[英]Need to add elements of an array iteratively in Python
您能否幫助我編寫一個python程序(使用Python 3.4)來迭代添加數字元素,直到總和達到一位數。 我的程序如下:
import random
import sys
import os
n = input('Please enter the number: ')
ar = list(map(int, str(n)))
sm = sum(ar)
ar_sm = list(map(int, str(sm)))
total_num = sum(ar_sm)
print(total_num)
我對這種邏輯不滿意,並且我相信有更好的方法可以做到這一點。
當需要第三次迭代時,您的邏輯不起作用。 例如,如果輸入為99999999999
,則結果為18
。 您需要一個循環:
n = input('Please enter the number: ')
while len(n) > 1: # If string length is 1, then stop
numlist = [int(x) for x in n] # Makes an integer list from all chars in the input string
n = str(sum(numlist)) # Sum and parse to string
print(n)
輸入:
99999999999
輸出:
9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.