Problem Solving with Python Challenges 3 – Lists, loops and ranges

Transcription

Problem Solving with Python Challenges 3 – Lists, loops and ranges
 Problem Solving with Python Challenges 3 – Lists, loops and ranges Contents 1 Lists ............................................................................................................................................................... 1 1.1 Example use of lists ....................................................................................................................... 2 1.2 Using if statements to tell the user the days of the week ............................................. 2 1.3 Using a list to tell the user the days of the week .............................................................. 2 2 A note on ranges and lists ................................................................................................................... 3 3 Using a list to improve the alternating colour spirograph ................................................... 4 4 Using the modulus operator to cycle through a list ................................................................. 5 5 Extra challenge: using a list to store a times table ................................................................... 7 5.1 Some more list operations ......................................................................................................... 7 5.2 Times table in a list ....................................................................................................................... 7 Appendix: lists in Scratch and Python ................................................................................................... 9 Remember you can write programs in Scratch that are equivalent to the programs in this set of challenges. 1 Lists Sometimes it is useful to be able to deal with collections of things (like a collection of cells in a row or column in Excel). One way to do this in a programming language is to use a data structure called a list. A list is an ordered collection of things (or items or elements). We use lists: •
•
•
To model collections, e.g. a shopping list, the days of the week To group things together To simplify algorithms 1 1.1 Example use of lists Type the following in a Python program called "listpractice.py". # create a list and access elements
numbers = [1, 2, 3, 4]
print(numbers)
print(numbers[0])
print(numbers[1])
print(numbers[2])
print(numbers[3])
numbers[0] = 5
print(numbers)
# print the length of a list
print('length of numbers: ', len(numbers))
# loop through a list
days = ['Sun', 'Mon', 'Tues', 'Wed', 'Thu', 'Fri', 'Sat']
for day in days:
print(day)
The above is an example of iterating through a list. The variable day is given the value days[0], then days[1], then days[2] up to days[6] ('Sat'). 1.2 Using if statements to tell the user the day of the week Start a new program as follows: answer = input('Enter a number for the day of the
week you want (0 is Sunday, 6 is Saturday): ')
day_number = int(answer)
if day_number < 0:
print('I can only accept a number between 0 and 6')
if day_number > 6:
print('I can only accept a number between 0 and 6')
Now add a sequence of if statements to complete the program so that: •
•
•
•
•
•
•
If the user enters 0, print "Sunday" If the user enters 1, print "Monday" If the user enters 2, print "Tuesday" If the user enters 3, print "Wednesday" If the user enters 4, print "Thursday" If the user enters 5, print "Friday" If the user enters 6, print "Saturday" 1.3 Using a list to tell the user the day of the week Write a new version of the program in challenge 1.2 that uses a list of the days of the week. The program should start the same way: answer = input('Enter a number for the day of the
week you want (0 = Sunday, 6 = Saturday): ')
day_number = int(answer)
2 if day_number <
print('I can
if day_number >
print('I can
0:
only accept a number between 0 and 6')
6:
only accept a number between 0 and 6')
To complete the program, use the number entered (day_number) to select a day of the week from a list of days. You will have to declare a list with the names of the days of the week. Can you see how the list simplifies the program? Can you improve the program by using an if/else statement? •
•
2 A note on ranges and lists Try typing the following in the Python shell: >>> range(10)
>>> list(range(10))
The Python range function creates a sequence of numbers. The most common use of the function is to specify the length of the sequence. So, range(10) creates a sequence of 10 numbers that starts with the number 0 and ends with the number 9. We can use the result of the range function like a list that we can iterate through. For example, try the following code: for counter in range(5):
print(counter)
It should result in the following output to the shell: 0
1
2
3
4
That is, the five numbers 0 to 4 inclusive. 3 3 Using a list to improve the alternating colour spirograph Lets look again at our alternating colour spirograph program: from turtle import *
answer = input('Enter length of polygon sides: ')
side_length = int(answer)
answer = input('Enter number of sides of polygon: ')
sides = int(answer)
angle = 360/sides
answer = input('Enter number of polygons: ')
polygons = int(answer)
rotation = 360/polygons
colour_index = 0
speed(0)
for polygon in range(polygons):
if colour_index == 0:
color('red')
if colour_index == 1:
color('green')
if colour_index == 2:
color('blue')
for side in range(sides):
forward(side_length)
right(angle)
colour_index = colour_index + 1
if colour_index == 3:
colour_index = 0
right(rotation)
As discussed previously, the problem with the above solution to drawing alternately coloured polygons is that the complexity increases with each new colour we add. For each new colour we need a new if statement before drawing a polygon and need to keep track of a different value for colour_index to reset after drawing a polygon. This approach is complex and error prone. Tasks 1. Instead of using if statements to select the pen colour, select the pen colour from a list of colours. 2. Experiment with adding new colours to your list (e.g. 'black' and 'magenta') and with different numbers of polygons in your spirograph. If you solve the problem correctly, then producing the following two spirographs of 7 polygons should simply be a matter of using the list of colours: 'red', 'green' and 'blue' for the first shape and adding 'black' and 'magenta' to the list for the second shape. 4 Hints •
•
•
You will still need an index position to select a colour from the list before drawing each polygon You will still have to increment the colour index after drawing each polygon Resetting the colour index should now be related to the length of the list Lesson We can often use a data structure to simplify algorithms. For example, if we have a program in which we repeatedly choose from a set of options, we may be able to simplify the program by storing the options in a list. In the next challenge we will see how to simplify the program further and remove the need to explicitly increment and reset the colour index position. 4 Using the modulus operator to cycle through a list 4.1 Lists and index positions Lists have a length (or size) and an index position for each item in the list. In Python, and most other programming languages, index positions start from 0 (like the floors of a building)*. This means that: •
•
0 is the position of the first item in a list len(my_list)-1 is the position of the last item in a list my_list Try typing the following in the Python shell and see if you can make sense of the output. names = ['Bob', 'Alice', 'Harry']
name = names[0]
print(name)
name = names[1]
print(name)
name = names[2]
print(name)
name = names[len(names) – 1]
print(name)
Now, what happens if you try to access names[3]? There is no list item at index position 3. * Except in Scratch. Index positions in Scratch start from 1. 5 4.2 The modulus operator The modulus operator (%) gives us the remainder after integer division. It has many useful applications. For two positive integers n and m, the modulus operator has the following property: n % m is in the range 0 to m–1 •
For example, for any positive number n: n % 2 is either 0 or 1 n % 3 is either 0, 1 or 2 n % 4 is either 0, 1, 2 or 3 •
•
•
and so on. That is, dividing one positive integer (n) by another (m) always leaves a remainder in the range 0 to m-­‐1 inclusive. Tasks 1. Create a new Python program testmodulus.py with the following code: for n in range(20):
mod = n % 10
print(n, '%', 10, 'is', mod)
Note the integers from 0 to 19 are "reduced" to their last digit (integers in range 0 to 9). 2. Try the above code with the divisors 5, 6 and 20 instead of 10. 3. The modulus is very useful when dealing with lists because we can use it to reduce an integer that is larger than the length of a list to an integer in the range: 0 to len(list) – 1
That is, an integer that can be used as a valid index position in the list. Modify the program in Challenge 3 to use the modulus to cycle through the list of colours. Hint Start by seeing what the following code does: colours = ['red', 'green', 'blue']
colour_index = 0
for counter in range(20):
colour_index = counter % len(colours)
print(colours[colour_index])
6 5 Extra challenge: using a list to store a times table We can use a list to store related information together. In this challenge you will store a times tables in a list, like storing it in a row of cells in Excel. First we will look at some more list operations. 5.1 Some more list operations # append to an existing list
numbers = [1, 2, 3, 4]
print(numbers)
numbers.append(6)
print(numbers)
# declare an empty list, and append to it
my_list = [ ]
my_list.append(200)
print(my_list)
print(my_list[0])
# search a list
guest_list = ['Tom', 'Dick', 'Harry']
if 'Tom' in guest_list:
print('Tom is on guest_list')
else:
print('Tom is not on guest_list')
if 'Bob' in guest_list:
print('Bob is on guest_list')
else:
print('Bob is not on guest_list')
5.2 Times table in a list Look at the following Python program. answer = input('Enter the times table you want: ')
number = int(answer)
for multiplier in range(12):
print(multiplier * number)
Can you predict the output for user input of 2? Create the above program in a new file and run it. Is the output as you expected? Can you explain the output? Tasks 1. Modify the program so that it calculates the times table correctly. Test your program for different times tables. 2. Modify your program to append each value it calculates to a times table list and then, once the list is complete, print out the table as a whole. Hint Start with an empty list and use the list append function to add values to the list as you calculate them. 7 6 Consolidation For extra practice and to consolidate some of the material covered so far, work through as much of sections 1, 2, 4, 5, 7, 8 and 3 as you can of Basics at the Python School web site: •
http://www.pythonschool.net/category/basics.html 8 Appendix: lists in Scratch and Python Scratch Python You will be asked for the name of the list and, like other variables, you can show and hide the list on the Scratch stage. # empty list
my_list = []
# list of numbers
numbers = [1, 2, 3]
# list of strings
names = ['Tom', 'Dick']
This creates slots in memory to store the list (like a collection of related cells in a row or column in Excel) item = my_list[0]
Select the item at position 1 in my list. Select the item at position 0 in my_list (assign my_list[0] to variable item). In Scratch, the first item in a list is at position 1. In Python (and most other programming languages), the first item in a list is at position 0 (like floors of a building). Specify a different position to select an item at a different position in the list. Specify a different position to select an item at a different position in the list 'thing' in my_list
True if the string 'thing' is in my_list True if my list contains 'thing' len(my_list)
The length of my_list (the number of items in the list) The length of my list my_list.append('thing')
Add/append string 'thing' to the end of my_list. Add thing to the end of my list. my_list[0] = 'thing'
Replace the item at position 0 of my_list with the string 'thing'.
Replace the item at position 1 of my list with That is, assign 'thing' to the first item thing. in the list. Specify a different position to replace an item at a different position in the list. 9 item = my_list.remove(0)
Remove the item at position 0 from my_list and assign the item removed to the variable item. Delete the item at position 1 of my list. Specify a different position to remove the item from a different position in the list. my_list.insert(0, 'thing')
Insert the string 'thing' at position 0 of my_list. Insert thing at position 1 of my list. Specify a different position to insert an item at a different position in the list. 10