hw05.py - def make_counter"Return a counter function > c = make_counter > c'a 1 > c'a 2 > c'b 1 > c'a 3 > c2 = make_counter > c2'b 1 > c2'b 2 > c'b c2'b

hw05.py - def make_counter"Return a counter function > c =...

• Homework Help
• 5
• 50% (2) 1 out of 2 people found this document helpful

This preview shows page 1 - 3 out of 5 pages.

def make_counter(): """Return a counter function. >>> c = make_counter() >>> c('a') 1 >>> c('a') 2 >>> c('b') 1 >>> c('a') 3 >>> c2 = make_counter() >>> c2('b') 1 >>> c2('b') 2 >>> c('b') + c2('b') 5 """ count = {} def counter(string): nonlocal count count[string]= count.get(string,0) + 1 return count[string] return counter def make_fib(): """Returns a function that returns the next Fibonacci number every time it is called. >>> fib = make_fib() >>> fib() 0 >>> fib() 1 >>> fib() 1 >>> fib() 2 >>> fib() 3 >>> fib2 = make_fib() >>> fib() + sum([fib2() for _ in range(5)]) 12 """ first = 0 second = 1 def func(): nonlocal first, second total = first first, second = second, first + second return total return func def make_withdraw(balance, password): """Return a password-protected withdraw function. >>> w = make_withdraw(100, 'hax0r') >>> w(25, 'hax0r') 75 >>> error = w(90, 'hax0r') >>> error 'Insufficient funds' >>> error = w(25, 'hwat')
>>> error 'Incorrect password' >>> new_bal = w(25, 'hax0r') >>> new_bal 50 >>> w(75, 'a') 'Incorrect password' >>> w(10, 'hax0r') 40 >>> w(20, 'n00b') 'Incorrect password' >>> w(10, 'hax0r') "Your account is locked. Attempts: ['hwat', 'a', 'n00b']" >>> w(10, 'l33t') "Your account is locked. Attempts: ['hwat', 'a', 'n00b']" >>> type(w(10, 'l33t')) == str True """ count = 0 guesses = [] def withdraw(amount,guess): nonlocal balance, password, count, guesses if guess == password: if count == 3 : return "Your account is locked. Attempts: " + str(guesses) if amount > balance: return 'Insufficient funds' else: balance = balance - amount return balance if count == 3 :

You've reached the end of your free preview.

Want to read all 5 pages?

• Spring '14
• BERRY,ME

What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern