2015-06-20 234 views
-1

我已經給出了Python語言中的一個任務,我應該將給定的數字分成2個半部分並且對2個半部分進行求和。例如:如何使用python拆分整數並對拆分後的整數求和?

input = 1234 
output must be 1 + 2 = 3 and 3 + 4 = 7. means 3 & 7. 

說明:我有給定的輸入1234被劃分到12和34

,然後我要總結1 + 2和3 + 4以及最終輸出將是37 PS:這是我自己試了一下。我是python的新手。

#T = int(raw_input()) 
#while T > 0 : 
# input = raw_input() 
# i = [] 
# i.append(input) 
+1

你有沒有嘗試自己解決呢? – vaultah

+0

沒有嘗試我不會來這裏。 – nasr18

+0

好的,顯示你的嘗試。 – dlask

回答

0
data = input() 
# Divide the list 
div = len(data)//2 
lst = [] 
# Add both halves to the list 
lst.append(data[:div]) 
lst.append(data[div:]) 
tot = "" 
# Loop through the list and add the sum as a string 
for i in lst: 
    tot += str(int(i[0])+int(i[1])) 
# Print the final string 
print(tot) 
+0

非常感謝。這正是我想要的。 – nasr18

+0

有什麼辦法可以檢查前半部分的總和是否等於後半部分的總和?我的意思是1 + 2 = 3等於3 + 4 = 7. – nasr18

+0

將tot更改爲列表並將整數添加到for循環中的列表中。然後檢查列表中的第一個元素是否等於第二個(tot [0] == tot [1]) –