## Python Homework Problems

In 2007 we switched our CS1 course to Python from C++. In 2012 we switched from Python2 to Python3. We have now accumulated many programming projects (over 100 at last count), and thought that it would benefit the CS1 Python community to share them. A great resource for programming projects is NCWIT's EngageCSEdu project—a set of peer-reviewed programmig projects.

This archive is organized on the order that we cover topics. File reading is built into projects early. Our programming projects generally take one week so we do ten or eleven in a semester—skipping exam weeks.

If you find problems with this page, email us.

William Punch and Richard Enbody, The Practice of Computing Using Python, 3rd. Ed

- Beginnings: a set of simple projects when you have little to work with.
- First Steps -- little to work with.
- Canoe Portage: Input some numbers, do some simple arithmetic, output results.(Python3)
- Richter Scale: Input some numbers, do some simple arithmetic, output results.(Python3)
- Windchill: Input some numbers, do some simple arithmetic, output results.(Python3)
- Arithmetic: Input some numbers, do some simple arithmetic, output results.
- Gasoline: Input some numbers, do some simple arithmetic on gas and oil quantities, output results.
- Measurement: Input some numbers, do some simple arithmetic to do silly conversions such as furlongs/fortnight, output results.
- Population: Input some numbers, do some simple arithmetic to estimate today's U.S. population, output results.
- Time Travel: Input some numbers, do some simple arithmetic to calculate travel time between stars, output results.
- Debt : Calculate the height of a stack of bills based on the national debt. .
- Simple Programs.
- Number Puzzle: Slayer: Check solutions for a number-word puzzle.
- Garden,Garden2: Calculate plantings and mulch for a garden. (Python3)
- Einstein: Solve a simple number puzzle attributed to Einstein.
- MacArthur: Solve a simple number puzzle attributed to MacArthur.
- Tones: Calculate frequencies to generate tones on a computer speaker.
- Turtle Graphics Angles: Use Turtle Graphics to draw two lines and the calculate the angle between them.
- NinetyNine : Simple number game.
- Control: With selection and repetition we can begin to do something.
- Draw : Draw regular patterns using TurtleGraphics. (Python3)
- Making Change : Making change.
- Number Puzzle: SplitNumber: Split numbers into increasing sequences, e.g. 154152 -> 15, 41, 52. (Python3)
- WaterBilling: Calculate water bills based on category and useage. (Python3)
- CarRental: Calculate rates for a car rental agency based on category and mileage. (Python3)
- Trig: Implement basic trigonometric functions using power series. (Python3)
- LatinSquares: Input two numbers: order and start. Build a Latin square of that order with that starting number.
- Number Theory: Persistence: Numbers can have interesting properties. Here we look at additive persistence where you sum the digits of a number and then sum the digits of the sum—continue until you get a single digit.
- Number Theory: Pologinal: The ancient Greeks found number properties to be interesting. A pologinal number is a particular geometric arrangement of a number of balls. Here we find two triangular number that form a given square number.
- Ancient Egyptian Multiplication: Weird Multiplication: To muliply A by B repeatedly multiply A by 2 while dividing B by 2 until the division has a remainder. If B becomes odd, add A to it. Sum the resulting A and B.
- Calculator: Make a simple, basic arithmetic calculator. Accept an expression in the form "number operator number", and calculate the result.
- Bank File Processing: Read a file of banking transactions and keep a ledger. (Python3)
- Working With Strings.
- Gibberish : Generate gibberish from English according to a particular pattern. (Python3)
- WHO_Measles : Given a file of World Health Organization raw data, answer queries such as "what is the vaccination level for Measles in Africa?" (Python3)
- Matching DNA : Simple DNA sequence matching.
- Palindomic Integers: Use the 196-algorithm to construct palindomic integers starting from any integer.
- Number-Guessing Game: Create a number-guessing game that provides hints on the number and position of correct digits in the guess (similar to Mastermind).
- Hangman: Create a hangman game (without the graphics of the hangman itself).
- Mastermind: Create a Mastermind game.
- Caesar Cypher: Encode and decode strings using a Caesar cypher.
- Shannon's Throbac: For fun Claude Shannon built a machine to do Roman Numeral arithmetic. We simulate it.
- Rock Paper Scissors: Create a game of Rock-Paper-Scissors.
- Functions (simple)
- Password_Cracking: Password Cracking. (Python3)
- Flag: Draw the American flag using TurtleGraphics. (Python3)
- Tesselations: Tile a plane using TurtleGraphics.
- StringLibrary: Implement a library of string functions (not using the built-in string functions). (Python3)
- WeFeelFine: Use functions from a module to gather data for analysis from the "We Feel Fine" page. The result is a collection of people's feelings scraped from blogs.
- GDP vs. Employment: Using GDP and employment data from the web, prompt for a year and provide the data for that year.
- Scrambled Words: Research shows that scrambled words can be read if the first and last letter are not changed, e.g. "Elingsh uinervtisy." Read in a file and scramble the words except first letters, last letters, and punctuation.
- Cracking a Caesar Cipher: Decrypt Caesar Ciphers using letter frequencies.
- Lists and Tuples
- Facebook: Suggest Facebook friends using real, but heavily anonymised data. (Python3)
- Bestsellers: Answer queries about bestsellers such as "What were the bestsellers in 2008?". (Python3)
- Venus: Determine suitable craters for mining on Venus using NASA data. (Python3)
- Baseball: Answer queries about a baseball season such as "list the players with the top 8 batting averages." (Python3)
- Apple Stock : Given a log file of Apple stock prices, calculate some simple statistics.
- Scrambled English: Scramble English words into a scrambled, but readable, form. (Python3)
- Basketball: Who is best basketball player in the NBA? Get data from the web and analyze it.
- Latin: Search for Latin roots, suffixes, and prefixes in a file.
- Anagrams: Given a word find all the anagrams of that word in a word list.
- Data Mining: Data Mining of online Google stock data.
- Build Query to Search Files: Build a simple query to search files ignoring stop words.
- Equity: Calculate Return on Equity (ROE) for stocks in a data file.
- Build HTML: Build HTML files from a database of information.
- Sunspots: Using NOAA data from the web analyze sunspot data to predict the next sunspot peak.
- Pascal's Triangle: Construct Pascal's Triangle to a specified depth.
- Auto Mileage: Using online data on automobiles, gather engine size and mileage data. Use least squares to find a linear regression and correlation. Graph it.
- Packaging: Minimize the amount of cardboard used to box a set of glasses with specified dimensions.
- Dictionaries and Sets
- GDP and Income: Who are the 1%? Use real GDP and income data to answer income questions. (Python3)
- Co-Occurrence: Build Dictionaries of Sets for Co-Occurrence. (Python3)
- Document Retrieval: Build a simple document retrieval system. (Python3)
- Poverty: Use US Census county data for MI to answer queries such as what is the poverty rate for children in a particular county. (Python3)
- Wikipedia: Parse a Wikipedia log file and respond to queries such as "who edited the most articles?" (Python3)
- TagCloud2: Build a tag cloud of a 2012 presidential debate. (Python3)
- WordCompletion: Simple word completion.
- TagCloud: Build a tag cloud of the 2008 vice-presidential debates.
- Movies & Actors: Using the online Internet Movies DataBase build a dictionary of movies and actors. Given two movies find all the actors in the movies (AND), find the common actors in the movies (OR), find the actors in either movie but not both (EXCLUSIVE_OR). Given an actor, find all the co-actors that actor has acted with.
- BMI: Body Mass Index: Using real data from the Internet on a set of people, calculate their BMI, and then use least squares to find a linear regression and correlation. Extra credit: graph it.
- Breast Cancer Classifier: Build a cancer classifier from breast cancer study data to predict if a given cancer is malignant or not.
- Income Classifier: Build an income classifier from individuals' characteristics (over 30K records from the Internet) to predict if the individual's income will be greater than $50K or not.
- Vocabulary Quiz: Build a vocabulary quiz program.
- Concordance: Build a simple concordance.
- Sunspots: Determine cycles in sunspot data (data goes back to 1749).
- SpellCheck: Build a file spell checker that includes suggestions.
- Natural Language Processing: Calculate unigrams and bigrams in a text file.
- Natural Language Processing II: Create Markov chains from a given text and then use the chains to create new text.
- Jobs: Grab data from data.gov and analyze private and public employment under different presidents.
- Classes: using instructor-designed classes to prepare for designing classes. We have found solitaire to be an excellent medium: we provide card and deck classes; students build a game. There are numerous variations on solitaire: e.g. World Of Solitaire.
- Class Design
- Adjacency : Given some rooms, what is the minimum number of TAs that can cover all rooms? (Python3)
- Currency : Currency calculator based on queries to Google for the latest rates. (Python3)
- GoogleMap : Query Google Maps to get a route between cities. (Python3)
- TurtleSnowPeople : Create a set of classes of graphical components for snow people. (Python3)
- Flags : Create a set of classes of graphical components for Flags. (Python3)
- Quadrilaterals : Given an outline of a class, fill in the details. (Python3)
- YouTube : Design classes to support using the Google API to make queries on YouTube.
- Triangles : Given an outline of a class, fill in the details. (Python3)
- Elevator Simulator: Create three classes (Building, Elevator, and Customer) to use in simulating an elevator.
- Face Drawing Program: Create five classes of facial features (using Turtle Graphics) and build a face drawing tool around them.
- Minesweeper: Create a Minesweeper class and design a Minesweeper game around it.
- Protein Transcription: Create a transcriber class so you can take in a sequence of DNA bases, use a mapping of amino acids to codons, and yield a sequence of amino acids.
- Queue Simulation: There are four ATM machines in the student union. Should students form one queue or four? Create an event class and build an event-driven simulation around that class. Use the simulator to answer the question.
- Game of Life: Create a class for the Game of Life and then build the game around it.
- Traveler's Dilemma: Write a program that plays the Travler's Dilemma using at least one class and one exception. Test your game with ten different pairs of people. Analyze the results.
- Dilbert's Carpet Fishing: A Dilbert cartoon has him playing an office game he calls "Carpet Fishing." Using at least one class, write the game.
- Turtle Classes: Create a set of classes of graphical components of your own design for use in creating a TurtleGraphics picture of your own design.
- Dating Service : Create a dating service with your own matching algorithm supported by classes of your own design.
- Dominos: Create a Dominos game supported by classes of your own design.
- TurtleCar: Create a library of classes to support drawing a car using Turtle graphics.

This work is licensed under a Creative Commons Attribution-Share Alike 3.0 United States License.

## Homework 1: Welcome to Python

**Due**: Part I due at 11pm on Wednesday, January 9 (nothing to turn in).**Due**: Part II due at 11pm on Friday, January 11. Submit via this turnin page.

This assignment will familiarize you with the Python programming language and the IDLE editor, which you will use throughout the quarter.

Python is an easy-to-use but powerful programming language that is particularly well-suited to quickly creating small programs.

IDLE is more than just an editor; it is a simple but powerful IDE, or "integrated development environment", which lets you edit, run, navigate, and debug Python code.

## Part I: Get started with Python

Follow the CSE 140 instructions for installing Python. Do this even if you already have a version of Python installed on your computer — for CSE 140, you will want a specific Python installation, namely Enthought Python Distribution.

Read (and follow along with!) a short tutorial for IDLE. (You could also try another short tutorial for IDLE, but that is optional.)

Optionally, follow the first parts of a Python tutorial.

There is nothing to turn in for Part I of the assignment.

## Part II: Programming exercises

Download the file .

For problems in this homework, you will edit your local copy of the file. You may do your work by editing and running (we recommend this approach), or by typing code at the Python interpreter and copying it into the appropriate part of when you are satisfied with it. When you have completed this homework, running the file should compute and print the answers to all the problems.

Don't forget to include documentation (source code comments, on a line starting with ) as appropriate in file .

## Problem 1: Roots

Compute and print both roots of the quadratic equation x^{2}-5.86 x+ 8.5408.

Hint: recall that the roots of a quadratic equation ax^{2}+bx+c are x=

−b ± √ b2 − 4ac |

2a |

Hint: use the function to compute the square root. (If you are using the Python interpreter, you need to first do . This already appears in the file that you will be editing, so everything is already set up for you if you are working within that file.)

## Problem 2: Reciprocals

Use a loop to print the decimal representations of 1/2, 1/3, ..., 1/10, one on each line.

## Problem 3: Triangular numbers

Use a loop to compute the 10th triangular number. The *n*th triangular number is defined as 1+2+3+...+*n*. (You can also compute the *n*th triangular number as *n**(*n*+1)/2. Use this formula to double-check that your loop is correct.)

Hint: This outline is an almost-complete solution. You only have to replace each ellipsis by an expression.

n = 10 triangular = 0 for i in ...: triangular = ... print "Triangular number", n, "via loop:", triangular print "Triangular number", n, "via formula:", n*(n+1)/2Your solution must not mention the number 10, except in the line. Your solution can use , but not . In other words, your code (after the line) should work for any value of .

## Problem 4: Factorial

Use a loop to compute 10!, the factorial of 10. Recall that the factorial of n is 1*2*3*...*n.

The first line of your solution will be . After that, your solution should not use again, though your solution will use . In other words, your code (after the line) should work for any value of .

Hint: Your answer will be similar to your answer to "Problem 3: Triangular numbers".

## Problem 5: Multiple factorials

Write code to print the first 10 factorials, in reverse order. In other words, write code that prints 10!, then prints 9!, then prints 8!, ..., then prints 1!. Its literal output will be:

3628800 362880 40320 5040 720 120 24 6 2 1The first line of your solution should assign a variable to , and then the rest of your solution must not use anywhere.

Hint: Use two nested loops.

The outer loop sets the value of to the values , , , ..., , in succession.

Then, the body of that loop is itself a loop — exactly your solution to "Problem 4: Factorial", without the first line that hard-codes the value of .

## Problem 6: Sums of reciprocals of factorials

Compute the following value:

1 + 1/1! + 1/2! + 1/3! + 1/4! + ... + 1/10!

The value should be close to *e* (≈ 2.71828), the base of the natural logarithms.

Hint: The easiest way to solve this is with two nested loops. It is possible, but tricky, to compute this using only one for loop. That is not necessary for this assignment.

Hint: Copy your solution to "Problem 5: Multiple factorials", then modify it. Rather than printing the factorials, you will add their reciprocals to a running total, then print that total at the end.

Hint: don't try to work the very first "1 +" into your loop; do it outside the loops (either at the very beginning or the very end of the outer loop).

## Submit your work

You are almost done!

Double-check that running your entire file produces output for each problem in the assignment, and that you have commented out any extraneous output (which you may have used for debugging, for example).

At the bottom of your file, state which students or other people (besides the course staff) helped you with the assignment, or that no one did.

At the bottom of your file, in the "Reflection" part, reflect on this assignment. What did you learn from this assignment? What do you wish you had known before you started? What would you do differently? What advice would you offer to future students?

Submit the following files via this turnin page.

Answer a survey about how much time you spent on this assignment.

## One thought on “Python Homework Problems”