@@ -20,10 +20,10 @@ def factorial(n):
20
20
"""Return the factorial of a positive integer.
21
21
n -- The positive integer whose factorial is computed.
22
22
"""
23
- total = 1
23
+ result = 1
24
24
for i in range (2 , n + 1 ):
25
- total *= i
26
- return total
25
+ result *= i
26
+ return result
27
27
28
28
# The return statement at the end of the function is used to
29
29
# tell what the function gives back to whoever calls it. Now
@@ -33,44 +33,43 @@ def factorial(n):
33
33
34
34
35
35
# All right, that out of the way, let's write some more functions that
36
- # operate on lists. First, find the largest element in the list. We do
37
- # this first by explicitly iterating over the elements of the list .
36
+ # operate on lists. First, find the largest element in the list, same
37
+ # as the Python built-in function max .
38
38
39
39
40
40
def maximum (items ):
41
41
""" Return the largest item in the given items."""
42
42
if not items : # Testing whether the sequence is empty
43
- # This is how you make a function crash when its arguments are invalid .
43
+ # This is how you make a function crash for invalid arguments.
44
44
raise ValueError ("Empty list has no maximum" )
45
45
king = None
46
- for x in items :
47
- if king is None or x > king :
48
- king = x
46
+ for e in items :
47
+ if king is None or e > king :
48
+ king = e
49
49
return king
50
50
51
51
52
52
# Next, a function that creates and returns another list where
53
53
# each element equals the sum of the elements in the original
54
54
# list up to that index.
55
55
56
- def accumulate (seq ):
57
- result = []
58
- total = 0
59
- for x in seq :
60
- total += x
56
+ def accumulate (items ):
57
+ result , total = [], 0
58
+ for e in items :
59
+ total += e
61
60
result .append (total )
62
61
return result
63
62
64
63
65
64
# Select precisely the elements that are larger than their predecessor.
66
65
67
- def select_upsteps (seq ):
68
- prev = None
69
- result = []
70
- for x in seq :
71
- if prev is None or x > prev :
72
- result . append ( x )
73
- prev = x
66
+ def select_upsteps (items ):
67
+ prev , result = None , []
68
+ for e in items :
69
+ if prev is None or e > prev :
70
+ result . append ( e )
71
+ # The current element becomes previous element for the next round.
72
+ prev = e
74
73
return result
75
74
76
75
@@ -130,10 +129,10 @@ def fizzbuzz_translate(n):
130
129
return str (n )
131
130
132
131
133
- def fizzbuzz (start = 1 , end = 100 ):
134
- """Play the game of fizzbuzz from start to end, inclusive ."""
132
+ def fizzbuzz (start = 1 , end = 101 ):
133
+ """Play the game of fizzbuzz from start to end, exclusive ."""
135
134
result = []
136
- for n in range (start , end + 1 ):
135
+ for n in range (start , end ):
137
136
result .append (fizzbuzz_translate (n ))
138
137
result = ", " .join (result )
139
138
return result
0 commit comments