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?
Analysis Of The Test Run ResultA dictionary is 6.6 times faster than a list when we lookup in 100 items.
In Python dictionary, it is an unordered and immutable data type and can be used as a keys element. To create a dictionary of lists, first, we insert key-value within the curly brackets and to obtain the values of a dictionary, and then use the key name within the square brackets.
To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.
To convert a list to dictionary, we can use list comprehension and make a key:value pair of consecutive elements. Finally, typecase the list to dict type.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With