簡體   English   中英

python中的加法和乘法持久性

[英]Additive and multiplicative persistence in python


我的代碼有問題。 我必須找到一個數字的加法和乘法持久性。 到目前為止,我只能找到一次持久性,但它必須不斷循環才能使答案小於 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。 我知道我可能需要一個 while 循環來做到這一點,只是我不知道如何。 這是給我的 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()

我會讓你開始第一個:

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

這是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

你試試這些代碼怎么樣:

#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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM