adfgasda :
I have a program that takes 2 numbers and subtracts them and also tells us if the individual places i.e. ones, tens and hundreds are smaller than the number they are being subtracted from and if they need to borrow.
a=2345
b=1266
o=[int(d) for d in str(a)]
a=[int(d) for d in str(a)]
b=[int(d) for d in str(b)]
x=len(a)
y=len(b)
i=1
state=[]
c=[]
for n in range(x):
if a[x-i]<b[y-i]:
a[x-i]+=10
a[x-i-1]-=1
state.append(True)
else:
state.append(False)
i+=1
i=1
for m in range(x):
c.append(a[x-i]-b[y-i])
i+=1
c=c[::-1]
print(o) #before borrow
print(a) #after borrow
print(b) #number to subtract
print(c) #result
print(state) #if borrowed
And this is my output:
[2, 3, 4, 5]
[2, 2, 13, 15]
[1, 2, 6, 6]
[1, 0, 7, 9]
[False, False, False, False]
Here is my question: 1) I want to map the results to a list of dictionary for each place like below:
[{'initial_num': '5', 'after_borrow': '15', 'state': True, 'after_subtract': '9'},
{'initial_num': '4', 'after_borrow': '13', 'state': True, 'after_subtract': '7'}...]
How do I do this so that I have 4 dicts in the list each corresponding to a particular position?
Guy :
You can zip
the lists you are interested in to dict
s with list comprehension
l = [{'initial_num': x, 'after_borrow': y, 'state': z, 'after_subtract': k} for x, y, z, k in zip(o, a, state, c)]