Skip to content

Instantly share code, notes, and snippets.

@wardi
Created November 22, 2019 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wardi/4dbe4ddaf0bce94fc21e457a857579df to your computer and use it in GitHub Desktop.
Save wardi/4dbe4ddaf0bce94fc21e457a857579df to your computer and use it in GitHub Desktop.
"""
Answers to shopping list, generation, iteration, decoration exercises posted
"""
def shopping_list():
"""
Exercise: shopping list
using while True: and input() create a shopping list interface allowing a user to enter multiple items then type DONE to exit
add a command to delete the last item in the list
add a command to print the current list
add a commands to save the list to a file and load from a file
"""
items = []
def show():
print('\n'.join(items))
while True:
item = input('What to buy/DONE/DEL/SHOW/SAVE/LOAD? ')
if item == 'DONE':
break
elif item == 'DEL':
try:
del items[-1]
except IndexError:
print('nothing to delete')
elif item == 'SHOW':
show()
elif item == 'SAVE':
with open('shopping.txt', 'w') as f:
f.write('\n'.join(items))
elif item == 'LOAD':
with open('shopping.txt') as f:
items = f.read().split('\n')
else:
items.append(item)
show()
def number_sequence():
"""
Exercise: generation, iteration, decoration
create a generator that produces the sequence: 1, 2, 1, 2, 2, 1, 2, 2, 2, ⋯
"""
n = 1
while True:
yield 1
for i in range(n):
yield 2
n += 1
# NOTE: this generator never exits
def five_from_number_sequence():
"""
write code that will skip the first element of the generator above then print the next 5 elements
"""
seq = number_sequence()
next(seq)
for i in range(5):
print(next(seq))
def noisy_decorator(fn):
"""
create a decorator that will print all arguments passed to a function and its return value
"""
def wrapper(*args, **kwargs):
print('arguments passed to', fn.__name__, ':', args, kwargs)
rval = fn(*args, **kwargs)
print('return value:', rval)
return rval
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment