Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help writing this in Python! Please make the code easy to understand! Tha

ID: 3709458 • Letter: I

Question

I need help writing this in Python! Please make the code easy to understand! Thanks!

Provide solutions for the first 5 problems in this tutorial using a functional programming approach: 1. Implement a function product to multiply 2 numbers recursively using + and -operators only 2. Write a function flatten dict to flatten a nested dictionary by joining the keys with character. >>> flatten, d?ct(('a': 1,'b': {x: 2, 'y: 3), 'c': 4)) 3. Write a function unflatten dict to do reverse of flatten dict. 4. Write a function treemap to map a function over nested list. >>teemap(lambda x: x*x, [1, 2, [3, 4, [51lI [1,4, [9, 16, [251I1 5. Write a function tres xeverse to reverse elements of a nested-list recursively. >>tee rexerse(1, 2], [3, [4, 5]1. 6

Explanation / Answer

def mul(x,y):
if y<0:
return mul(x,-y)#convert y to +ve
if y==0:#multiply by 0 is 0
return 0
return x + mul(x,y-1)#multiply x*y=x+x*(y-1)
#above recursion will eventually get y to be 0 and stop
#ex: 2*2 = 2+2*1 = 2+2+2*0 = 2+2+0 = 4

def flatten_dict(d):
res = {}
for k,v in d.items():
if type(v)==int:
v = int(v)
res[k] = v
else:# if v is a dict
v = flatten_dict(v)
for k1,v1 in v.items():
res[k+'.'+k1] = v1
return res

#used in unflatten_dict
def addk(res,karr,v):
if len(karr) == 1:
res[karr[0]] = v#entry was simple str:int
else:#entry was str:dict
kinit = karr[0]#root level key
karr = karr[1:]
try:#entries already exist in d[kinit]
res[kinit] = addk(res[kinit],karr,v)
except KeyError:#entries do not exist in d[kinit]
res1 = v
for k1 in karr:
res1 = {k1:res1}
res[kinit] = res1
return res

def unflatten_dict(d):
res = {}
for k,v in d.items():
karr = k.split('.')
res = addk(res,karr,v)
return res

def treemap(f,l):
res=[]
for e in l:
if type(e) == int:
res.append(f(e))
else:
res.append(treemap(f,e))
return res

def tree_reverse(l):
l.reverse()
res = []
for e in l:
if type(e) == list:
res.append(tree_reverse(e))
else:
res.append(e)
return res