def fib(max):
a, b = 0, 1 ①
while a < max:
yield a ②
a, b = b, a + b ③
- , . 0 1, , . , : 0, b 1.
- a , .
- b , a, (a + b) b . , . a 3, b 5, a, b = b, a + b a 5 ( b) b 8 ( a b).
. , , . , for.
->yield , next()
>>> from fibonacci import fib
>>> for n in fib(1000): ①
... print(n, end=' ') ②
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> list(fib(1000)) ③
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
- fib() for . for next() fib() for n.
- for , n yield fib(), . fib() (a , max, 1000), for .
- : list(), ( , for ) .
A Plural Rule Generator
plural5.py plural().
def rules(rules_filename):
with open(rules_filename, encoding='utf-8') as pattern_file:
for line in pattern_file:
pattern, search, replace = line.split(None, 3) ①
yield build_match_and_apply_functions(pattern, search, replace) ②
def plural(noun, rules_filename='plural5-rules.txt'):
for matches_rule, apply_rule in rules(rules_filename): ③
if matches_rule(noun):
return apply_rule(noun)
raise ValueError('no matching rule for {0}'.format(noun))
- . , , , line.split(None, 3) .
- yield. ? , , build_match_and_apply_functions(), . , rules() , .
- rules() , for . for , rules(), , , , . loop , , rules() ( for line in pattern_file ). , ( ), , .
4? . 4 plural4, , plural(). : , .
|
|
? ! plural(), rules() .
: ( import) ( ). , - ( , ), , .
, . , Python.