Last active
August 16, 2019 20:31
-
-
Save svmihar/bb424447588c8fb9eafa0c77765394d1 to your computer and use it in GitHub Desktop.
solution to: https://www.youtube.com/watch?v=W2Nz3733mCw&lc=z222zbry0m3ogrpj404t1aokg0k1ngnhw55naycpr2chbk0h00410.1565984354643611
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
""" author: svmihar | |
problem source: https://www.youtube.com/watch?v=W2Nz3733mCw&lc=z222zbry0m3ogrpj404t1aokg0k1ngnhw55naycpr2chbk0h00410.1565984354643611 | |
""" | |
# problem1 | |
# adder(5)(3) --> 8 | |
def adder(x): | |
def wrapper(y): | |
return x+y | |
return wrapper | |
print('problem 1') | |
print(adder(5)(3)) | |
# problem2 | |
# partial(add,1)(3) --> 4 | |
def add(n,m): | |
return (n+m) | |
def partial(fn,x): | |
def wrapper(y): | |
return fn(x,y) | |
return wrapper | |
print('problem 2') | |
print(partial(add, 1)(3)) | |
# problem 3 | |
# summator = make_summator() | |
# summator(1) --> 1 | |
# summator(3) --> 4 | |
# summator(4) --> 8 | |
def summator(): | |
x = 0 | |
def sabi(n): | |
nonlocal x | |
x += n | |
return x | |
return sabi | |
sedap = summator() | |
print('problem 3') | |
sedap(1) | |
sedap(3) | |
print(sedap(4)) | |
# problem 4 | |
# @cache | |
# add(5,3) --> 8 | |
# add(1,2) --> 8 | |
# add(4,6) --> 8 | |
def cache1(function): | |
# solution 1: with if | |
asu = [] | |
def wrapper(*args): | |
if function(*args) in asu: | |
return asu[0] | |
else: | |
asu.append(function(*args)) | |
return asu[0] | |
return wrapper | |
def cache2(fn): | |
# solution 2: assigning the function on nonlocal variable | |
asu = [] | |
def wrapper(*args): | |
asu.append(fn(*args)) | |
return asu[0] | |
return wrapper | |
@cache1 | |
def add(a, b): | |
return a+b | |
@cache2 | |
def add_(a,b): | |
return a+b | |
print('problem 4') | |
add(1, 3) | |
add(2, 4) | |
print(add(3, 5)) | |
print(add(3, 9)) | |
print(10*'=') | |
add_(1, 3) | |
add_(2, 4) | |
print(add_(3, 5)) | |
print(add_(3, 9)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment