Transcript 05-Lists

Lists
01024111 Computers and
Programming
Agenda
•
•
•
•
•
•
What is a list?
How to access elements in the list?
The for statement
Operations on lists
Looping with for statement
Examples
2
WHAT IS A LIST?
3
Test scores for 5 students
• We can use 5 variables for storing 5
numbers.
s1 = 10
s2 = 16
s1
10
s3 = 15
s2
16
s4 = 9
s3
15
s5 = 23
s4
9
program
s4
s5
9
23
4
Computing statistics
t
t
t
t
t
t
= 0
m = 0
What is the goal
+= s1
if s1
of this program?
+= s2
m
+= s3 The summation
if s2
+= s4
m
+= s5
if s3
The average
m
avg = t / 5
if s4
m
How about this?
if s5
m
And this?
The maximum
> m:
= s1
> m:
= s2
> m:
= s3
> m:
= s4
> m:
= s5
5
Side notes
• In the last slide, we use a new type of
operators: +=.
a = a + 1
a += 1
a = a * 2
a *= 2
6
Test scores for 50 students
• Suppose that now you have 50 students in
a class.
• How can you store all the scores?
7
50 variables
• We can use 50 variables to store 50
numbers
s1 = 10
s2 = 16
s3 = 15
s4 = 9
s5 = 23
…
…
…
Extremely
difficult
to deal with
8
Lists
• In Python, we have data types that can
keep many items in one place. One of
these is a list.
• An example of a list:
[10, 16, 15, 9, 23]
10
16
15
9
23
9
A list constant
• We write a list by enclosing all items in a
pair of brackets [ ], with a comma (,)
separating each pair of items.
• It is OK to have extra comma after the
last item.
10
Examples
• A list of numbers of days for each month
[31,28,31,30,31,30,
31,31,30,31,30,31]
• A list of names of days in a week
['sun','mon','tue','wed',
'thu','fri','sat']
11
Example
• A list of names
["somying", "somsak", "somchai"]
"somying"
"somsak"
"somchai"
12
A list is just another data
• We can assign a list to a variable. That
variable will refer to that list.
scores = [10, 16, 15, 9, 23]
scores
10
16
15
9
23
13
ACCESSING ITEMS IN A LIST
14
Indexing
• We can refer to an item in a list by
specifying its index in the list.
• The first item in the list has index 0; the
next one has index 1, and so on.
scores
10
16
15
9
23
scores[0]
scores[1]
scores[2]
scores[3]
scores[4]
15
Accessing items through
their indices
• Recall that the first item has index 0.
scores = [10, 16, 15, 9, 23]
print(scores[0])
>>> 10
print(scores[3])
>>> 9
print(scores[1] + scores[4])
>>> 39
16
Example
days
0
1
2
3
4
5
6
'sun'
'mon'
'tue'
'wed'
'thu'
'fri'
'sat'
>>> print(days[3])
wed
17
Thinking Corner
• Write a program that print all items in the
following list a. You are not allowed to
write "print" more than once.
a = [1,2,1,4,3,2,4,2,5,6,3,7]
• Note: there are 12 items in the list.
• Hint: try using the while statement.
18
Thinking Corner: solution
a = [1,2,1,4,3,2,4,2,5,6,3,7]
i = 0
while i <= 11:
print(a[i])
i = i + 1
19
Practice
• What is the output?
ps = [2,3,5,7,11]
i = 0
while i<5:
print(ps[i])
i = i + 2
2
5
11
20
More practice
• What is the output?
ps = [2,3,5,7,11,13]
nn = [1,2,1,1, 2, 1]
i = 0
while i<6:
print(ps[i])
i = i + nn[i]
2
3
7
11
21
Modifying data in a list
• As we can refer to items in the list, we can
assign new values to them.
>>> s = [10,20,30,40,50]
>>> s[2] = 5
>>> s
[10,20,5,40,50]
>>> s[4] += 7
>>> s
[10,20,5,40,57]
22
Practice
• What is the output?
ps = [1,2,1,3,1,4]
t = 0
j = 0
while j < 6:
if ps[j] > t:
t = ps[j]
else:
ps[j] = t
print(ps[j])
j += 1
1
2
2
3
3
4
23
Anything goes…
• A list can hold items with different types.
stinfo = ["dang", 20, 167, 78.5]
stinfo
"dang
20
167
78.5
stinfo[0]
stinfo[1]
stinfo[2]
stinfo[3]
24
An Empty List
• An empty list is also a list
>>> mylist = []
>>> a = mylist[0]
Traceback (most recent call
last): builtins.IndexError: list
index out of range
We get an error because we try to access
an item which is not there.
25
THE FOR-STATEMENT
26
The for statement
• We can use the for statement to iterate
through all items in a list
• Syntax:
for var in list:
statement
statement
For statement controls a block, so
make sure you have the same indent.
27
How does the for statement
work?
• The block inside the for statement is
executed as the variable iteratively refers
to each item in the list.
for x in [2,3,5,7,11]:
print(x)
2
3
5
7
11
x
x
x
x
2
3
5
7
11
x
28
Thinking Corner
• Write a program that computes the
summation of all items in the following
list.
a = [1,2,1,4,3,2,4,2,5,6,3,7]
a = [1,2,1,4,3,2,4,2,5,6,3,7]
total = 0
for x in a:
total = total + x
print(total)
29
This helps when processing
lists…
s = [10,16,15,9,13]
t = 0
for x in s:
t = t + x
m = 0
for x in s:
if x > m:
x = m
Computing
the
summation
Compute
the
maximum
30
... even when they contain
lots of data
s = [10,16,15,9,13,20,12,11,2,14,
6,7,13,4,6,7,14,18,9,12]
t = 0
Computing the sum
for x in s:
t = t + x
Nothing changes
m = 0
for x in s:
if x > m:
x = m
Computing the maximum
31
A quick summary on how to
access items in a list
Referring to each item
a
a[5]
Iterate through a list
a
for x in a:
c += x
32
OPERATIONS ON LISTS
33
Working with lists
• Operators on lists
• List functions
• Adding items to lists
34
Operators on lists (1)
• We can add two lists. The result is the
concatenation of the two lists.
>>> [1,2] + [5,10,15]
[1,2,5,10,15]
1
2
5
10
15
35
Operators on lists (2)
• We can multiply a list with an integer.
The result is the concatenation of copies
of the original list.
>>> [1,2] * 3
[1,2,1,2,1,2]
1
2
Very useful for
initializing lists.
36
Example for multiplying
with an integer
• If we want to create a list with 10 items all
of them are zero.
>>> [0] * 10
[0,0,0,0,0,0,0,0,0,0]
37
List functions
• Important functions are
names
len
objectives
Returns the
number of items
examples
results
len([1,2,5])
3
sum
Returns the
summation
sum([1,2,5])
8
max
Returns the
maximum
max([1,2,5])
5
min
Returns the
minimum
min([1,2,5])
1
38
Examples of usage
>>>
0
>>>
>>>
21
>>>
10
>>>
5
>>>
7
len([])
s = [1,2] + [3,5,10]
sum(s)
max(s)
len(s)
len(s + [1,6])
#=>[1,2,3,5,10,1,6]
39
Appending to lists
• We can add items to lists by using method
append as shown below.
>>> s = [1,2,5]
>>> s.append(10)
>>> s
[1,2,5,10]
40
EXAMPLE 1
41
Statistics
• We shall write a program that computes
data statistics


The program reads data items from the user
until the user enter -1
Then the program reports the summation, the
average, the maximum, and the minimum.
42
Main program
data = read_input()
# read data as a list
total = _____________________
sum(data)
average = ___________________
total / len(data)
max = _______________________
max(data)
min = _______________________
min(data)
# display output
43
Thinking Corner
• Write function read_list that reads integers
from the user until the user enters -1, and
returns a list of the integers.
def read_list():
print("Enter list (-1 to end):")
data = []
x = int(input())
while x!=-1:
data.append(x)
x = int(input())
return data
44
FOR LOOPS
45
for Loops
• We can use the for statement to simplify
many of the loops written with the while
statement.
What is this program doing?
t = 1
for i in [1,2,3,4,5]:
t *= i
print(t)
46
Printing
months = ['Jan', 'Feb',
'May', 'Jun',
'Sep', 'Oct',
days = [31, 28, 31, 30,
31, 31, 30, 31,
'Mar', 'Apr',
'Jul', 'Aug',
'Nov', 'Dev']
31, 30,
30, 31]
for i in [0,1,2,3,4,5,6,7,8,9,10,11]:
print(months[i],days[i])
47
Function range
months = ['Jan', 'Feb',
'May', 'Jun',
'Sep', 'Oct',
days = [31, 28, 31, 30,
31, 31, 30, 31,
'Mar', 'Apr',
'Jul', 'Aug',
'Nov', 'Dev']
31, 30,
30, 31]
for i in range(12):
print(months[i],days[i])
48
Function range
• Function range returns a result that acts
like a list. Its usages are shown below.
usages
result
range(r)
a list from 0 to r-1
range(7) =>
[0,1,2,3,4,5,6]
range(a,b) a list from a to b-1
range(3,7) =>
[3,4,5,6]
49
Quick practice
• What does this program compute?
t = 0
for i in range(100):
t += i*i
print(t)
50
More quick practice
• What does this program compute?
t = 0
for i in range(200):
if i % 3 == 0:
t += i
print(t)
51
Practice
def is_prime(n):
Let's do it step by step
Prime numbers are positive integers having
exactly two positive factors.
Write function is_prime that returns True if
and only if n is a prime number.
52
Thinking Corner
def count_factors(n):
count = 0
for f in range(1, n + 1):
if n % f == 0:
count += 1
return count
Write function count_factors that
returns the number of positive integers that
divides n using for-statement.
53
Thinking Corner
def count_factors(n):
count = 0
range(n +n 1):
for f in range(1,
+ 1):
if n % f == 0:
count += 1
return count
What would happen if
we change to this?
Write function count_factors that
returns the number of
positive integers
that
ZeroDivisionError:
integer
division or modulo by zero
divides n using for-statement.
54
Comparison
def count_factors(n):
count = 0
for f in range(1, n+1):
if n % f == 0:
count = count + 1
return count
def count_factors(n):
count = 0
f = 1
while f <= n:
if n % f == 0:
count = count+1
f = f + 1
return count
55
Practice
def is_prime(n):
return count_factors(n)==2
Use that to write is_prime
Prime numbers are positive integers having
exactly two positive factors.
Write function is_prime that returns True if
and only if n is a prime number.
56
EXAMPLE 2
57
Counting votes
• In one election for student
representatives, there are 5 candidates,
numbers from 1 to 5.
• Write a program that reads a list of votes
and then finds out who wins the election.
58
How can we keep vote
counts?
• Since we have 5 candidates, we will use a
list that can keep 5 items.
• However, because the candidate numbers
start with 1, we will actually use a list with
6 items so that we can access items with
indices 1 to 5.
Does not use
0
0
0
0
0
For storing vote counts
0
59
Initialization
• Everyone starts with 0 votes.
scores = [0,0,0,0,0,0]
scores = [0] * 6
Much easier to
write when we
have more
candidates.
60
Read and update vote
counts
scores = [0] * 6
choice = int(input())
while choice != -1:
scores[choice] += 1
choice = int(input())
61
Report
scores = [0] * 6
choice
= int(input())
def
show_result(s):
def show_result(s):
while
choice
!= -1:
for
in range(5):
for i
cnum
in range(1,len(s)):
cnum
= i + 1
scores[choice]
+= 1
print(cnum,"gets",s[cnum],"votes")
print(cnum,"gets",s[cnum],"votes")
choice
= int(input())
show_result(scores)
62
Thinking Corner
• Write function freq(ls,x) that accepts
list ls and a item x, and returns the
number of times item x appears in the list.
• Example of usage:
a = [1,2,1,1]
print(freq(a,1))
print(freq(a,2))
print(freq(a,3))
3
1
0
63
Thinking Corner: solution
def freq(ls,x):
c = 0
for y in ls:
if y == x:
c += 1
return c
64