Homework for Week 9
After this week you can
- Create lists by adding elements
- Select elements form a list by index
- Loop through a list
- Split a string into a list of strings
Lists
A list is a data structure that allows the program to process a sequence of similar values in a uniform way. The elements in a list have a fixed order, and each element has a unique index inside the list. A list variable refers to the whole list; the values inside have no names and can be accessed by index. A convenient way to go through all elements of a list is a definite (for) loop. In many respects, lists are a generalization of strings, and as with strings, there are many standard functions that operate on lists.
Watch the videos:
Slides in English
Textbook in English
Quiz
Go to Moodle and solve the quiz on the video lectures.
Examples
List of shoe sizes
The following program reads the foot lengths from the file footlengths.txt, calculates shoe sizes for all numeric foot lengths, and prints the shoe sizes, adding the results in a list. After the file is read, the program prompts the user for shoe size, counts how many people in the list have the same shoe size as the size entered, and prints the result.
fh = open("footlengths.txt") shoesizes = [] for foot in fh: try: f = float(foot) except: print("Invalid input:", foot.strip()) else: size = int(round(3/2 * f + 2)) print("Foot length:", f, "- Suitable shoe size is", size) shoesizes.append(size) while True: try: size = int(input("Please enter shoe size: ")) except: print("Please enter a number") else: number = shoesizes.count(size) print(number, "people have the same shoe size") break
The first loop reads the shoe sizes from the file into a list. The second loop performs a lookup in the list, prompting the user for a number until the user enters a suitable value.
Days of the week
The next program repeatedly asks for the number of the day of the week and prints the name of the day until the user enters 'done' instead of a number.
def day_of_week(n): days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return days[n-1] while True: line = input("Enter number of day of the week or word 'done': ") if line == 'done': break try: number = int(line) except: print("Please enter a number") else: if number < 1 or number > 7: print("The number of the day of the week must be in the range 1-7") else: print("The name of this day of the week is", day_of_week(number))
A list is a convenient place to store different values that are naturally ordered (like month names). Then we can retrieve the values from the list by index.
Exercises
1. Calculation of sales prices
Write a function calculate_prices, which takes a sequence of prices and markup percentage as its arguments. All prices and the percentage are floating-point numbers.
The function returns a new sequence of prices of the same length, where the initial prices have been increased by the markup percentage, and after that, 20% VAT is added to all prices.
Example
>>> calculate_prices([100.0, 1200.0], 10.0)
[132.0, 1584.0]
Explanation. Add the markup percentage: 100.0 + 10% = 110.0. Add the VAT: 110.0 + 20% = 132.0.
2. Number of boys and girls
Write a function boys_and_girls that has one argument: a list of strings where each element is the first name (which may consist of several names) and gender (B for boys, G for girls) of a person, separated by a space. The function should return a two-element list, where the first and second elements denote the numbers of boys and girls in the list, respectively.
Example
>>> boys_and_girls(['Mark B', 'Ella G', 'Robert Hugo B', 'Ralf B', 'Veronika G'])
[3, 2]
3. Selecting the trip
A travel agency has written all its trips in the file trips.txt, where every line contains the name of the trip and its price in euros, separated by a comma. For example, the content of the file trips.txt may be:
Day cruise to Helsinki,29 Hike in the mountains of Tokyo,700 Romantic weekend in Haapsalu,150 Prague pub crawl,400
First, create a function list_trips, which takes filename and budget size as its arguments. The function should find all trips in the file that fit into the budget and return the list of the names of such trips.
For example, with the sample file above, the function should behave as follows:
>>> list_trips('trips.txt', 200)
['Day cruise to Helsinki', 'Romantic weekend in Haapsalu']
Next, write a program that asks the user to enter the budget size and, using the function list_trips, selects all trips from the file trips.txt that cost less than the budget size entered.
Example of the output:
Enter trip budget: 200
Suitable trips are:
Day cruise to Helsinki
Romantic weekend in Haapsalu
Submit your solutions
Go to Moodle and submit your solutions of exercises as files home1.py, home2.py, home3.py.
Advice
Always stick to one task at a time.