[英]Adding large numbers on python with an algorithm, not with standard calculating
我的老師給我做了一個作業,來做一個python程序,該程序會添加大量數字並使用標准的添加算法。 (我知道Python 3.x本身可以添加大量數字,但是我需要添加方法)
這是標准算法的示例: 如何使用列加法添加大數
我試圖做一個程序,但是我做不到。 我沒有從StackOverflow找到任何令我滿意的答案。 這是我的越野車,還沒有完全嘗試,只能添加相等房間的數字(例如12和45、444和765,而不是1和134)。
n=str(raw_input("n:"))
m=str(raw_input("m:"))
k=0
res=''
if m>n:
m,n=n,m
k=0
for i in range(len(n)-1,-1,-1):
a=float(n[i])
try:
b=float(m[i])
except:
b=float(0)
k=float(k)
res+=str(int((a+b+k)%10))
if a+b+k>9:
k=1
else:
k=0
print(res[::-1])
PS我是Python的初學者,對您的幫助將不勝感激。
您可以在m
的開頭加上零,代碼也可以正常工作,因為要添加整數,則應使用int()
而不是float()
並且需要在for循環之后將進位添加到結果中,然后檢查此代碼
n=raw_input("n:")
m=raw_input("m:")
k=0
res=''
if len(m)>len(n):
n,m = m,n #this will swap
k=0
m = "0" * (len(n)-len(m)) + m #append zeroes to m at the begining
for i in range(len(n)-1,-1,-1):
a=int(n[i])
b = int(m[i])
k=int(k)
res+=str(int((a+b+k)%10))
if a+b+k>9:
k=1
else:
k=0
#add the remainder
if (k !=0) :
res += str(k)
print(res[::-1])
Python具有izip_longest
函數,用於填充缺失的0
s:
from itertools import izip_longest
n = raw_input("n:")
m = raw_input("m:")
k = 0
res = ''
for a, b in izip_longest(reversed(n), reversed(m), fillvalue='0'):
k, z = divmod(int(a)+int(b)+k, 10)
res = str(z) + res
if k:
res = str(k) + res
print res
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.