python中的加法和乘法持久化

时间:2016-02-24 00:20:32

标签: python math persistence

我的代码遇到了一些麻烦。我必须找到一个数字的加法和乘法持久性。到目前为止,我只能找到持久性一次,但它必须保持循环,以便答案小于9。 结果如下:

type a number thats greater than 9: 1234
additive persistence result:  10
multiplicative persistence result:  240
Press enter to exit

然而,这是错误的,因为它应该分解10和240.它应该做1 + 0 = 1和2 * 4 * 0 = 0。我知道我可能需要一个循环来完成这个,它只是我不知道如何。这是我的CS课程,甚至我的老师也不知道该怎么做。 这是我的代码:

a=raw_input("type a number thats greater than 9: ")

sum_1=0

for element in a:
    sum_1+=int(element)
print "additive persistence result: ",sum_1


for element in a:
    sum_1*=int(element)
print "multiplicative persistence result: ",sum_1
print"Press enter to exit"
raw_input()

3 个答案:

答案 0 :(得分:2)

我会让你开始第一个:

while len(a) > 1:
    sum_1 = 0
    for element in a:
        sum_1+=int(element)
    a = str(sum_1)

答案 1 :(得分:0)

这是reduce()函数的一个很好的用例:

def persistence(num, op):
    while True:
        digits = list(map(int, str(num)))
        if len(digits) == 1:
            return digits[0]
        num = reduce(op, digits)

您可以将op operator.addoperator.mul称为

>>> persistence(1234, operator.add)
1
>>> persistence(1234, operator.mul)
8

答案 2 :(得分:0)

您如何尝试以下代码:

#Multiplicative Persistence

from functools import reduce  # omit on Python 2
import operator

#Q_num is used for asking the input of the number
Q_num = int(input('What is the input number: '))

#D_num is used to seperated the number from Q_num and put them in the list
D_num = ([int(A_num)for A_num in str(Q_num)])
print(D_num)

#Multiply is used to convert function to D_num(numbers that already being seperated)
Multiply = reduce(operator.__mul__, D_num)
print(Multiply)

#D_mulF is used to seperated the number from Multiply and put them in the list
D_mulF = ([int(B_num)for B_num in str(Multiply)])
print(D_mulF)

#Multiplier is used to convert function to D_mulF(numbers that already being seperated)
Multiplier = reduce(operator.__mul__, D_mulF)
print(Multiplier)


#Additive Persistence
#Q_num is used for asking the input of the number
Q_num = int(input('What is the input number: '))

#D_num is used to seperated the number from Q_num and put them in the list
D_num = ([int(A_num)for A_num in str(Q_num)])
print(D_num)

#D_sum is used to convert the sum() function to D_num(numbers that already being seperated)
D_sum = (sum(D_num))  # Add all of the number in the list
print(D_sum)

#Answer is used to seperated the number from D_sum and put them in the list
Answer = ([int(A_num2)for A_num2 in str(D_sum)])
print(Answer)

#F_ans is used to convert function to Answer(numbers that already being seperated)
F_ans = (sum(Answer))
print(F_ans)