updated taxi simulator

This commit is contained in:
Luciano Ramalho
2015-02-10 19:08:24 -02:00
parent c6df60bb66
commit 7ec5f62376
7 changed files with 265 additions and 4 deletions

42
control/adder/adder.py Normal file
View File

@@ -0,0 +1,42 @@
import sys
def ask():
prompt = '>'
while True:
response = input(prompt)
if not response:
return 0
yield response
def parse_args():
yield from iter(sys.argv[1:])
def fetch(producer):
gen = producer()
next(gen)
yield from gen
def main(args):
if args:
producer = parse_args
else:
producer = ask
total = 0
count = 0
gen = fetch(producer())
while True:
term = yield from gen
term = float(term)
total += term
count += 1
average = total / count
print('total: {} average: {}'.format(total, average))
if __name__ == '__main__':
main(sys.argv[1:])

View File

@@ -0,0 +1,37 @@
"""
Closing a generator raises ``GeneratorExit`` at the pending ``yield``
>>> adder = adder_coro()
>>> next(adder)
>>> adder.send(10)
>>> adder.send(20)
>>> adder.send(30)
>>> adder.close()
-> total: 60 terms: 3 average: 20.0
Other exceptions propagate to the caller:
>>> adder = adder_coro()
>>> next(adder)
>>> adder.send(10)
>>> adder.send('spam')
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
"""
def adder_coro(initial=0):
total = initial
num_terms = 0
try:
while True:
term = yield
total += term
num_terms += 1
except GeneratorExit:
average = total / num_terms
msg = '-> total: {} terms: {} average: {}'
print(msg.format(total, num_terms, average))

View File

@@ -0,0 +1,47 @@
import sys
import collections
Result = collections.namedtuple('Result', 'total average')
def adder():
total = 0
count = 0
while True:
term = yield
try:
term = float(term)
except (ValueError, TypeError):
break
else:
total += term
count += 1
return Result(total, total/count)
def process_args(coro, args):
for arg in args:
coro.send(arg)
try:
next(coro)
except StopIteration as exc:
return exc.value
def prompt(coro):
while True:
term = input('+> ')
try:
coro.send(term)
except StopIteration as exc:
return exc.value
def main():
coro = adder()
next(coro) # prime it
if len(sys.argv) > 1:
res = process_args(coro, sys.argv[1:])
else:
res = prompt(coro)
print(res)
main()