Last active
December 7, 2017 10:30
-
-
Save dimnikolos/eefb44c8fce1d98a34ad1256914d6b38 to your computer and use it in GitHub Desktop.
This file contains 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
""" | |
computing partial sums | |
for a multiplication | |
""" | |
def updict(v,p,d): | |
if p in d: | |
d[p].append(v) | |
else: | |
d[p] = [v] | |
return(d) | |
def computedict(d): | |
ret = [] | |
carry = 0 | |
for p in sorted(d.keys()): | |
thisValue = sum(d[p]) + carry | |
digit = thisValue % 10 | |
ret.append(str(digit)) | |
carry = (thisValue - digit) // 10 | |
if carry>0: | |
ret.append(str(carry)) | |
return(''.join(reversed(ret))) | |
strinputa = input() | |
strinputb = input() | |
resultLen = len(strinputb) + len(strinputa) + 1 | |
print(strinputa.rjust(resultLen)) | |
print(('x'+strinputb).rjust(resultLen)) | |
print('-'*resultLen) | |
partialSums = {} | |
for i,x in enumerate(reversed(strinputb)): | |
try: | |
intx = int(x) | |
digitSum = {} | |
for j,y in enumerate(reversed(strinputa)): | |
inty = int(y) | |
print(str(intx*inty).rjust(resultLen-(i+j))) | |
partialSums = updict(intx*inty,i+j,partialSums) | |
digitSum = updict(intx*inty,i+j,digitSum) | |
digitRes = computedict(digitSum) | |
print('-'*resultLen) | |
print(digitRes.rjust(resultLen-i)+i*'0') | |
print('-'*resultLen) | |
except ValueError: | |
print('Give positive integers') | |
result = computedict(partialSums) | |
print(result.rjust(resultLen)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment