簡體   English   中英

如何將數字的總和除以數字?

[英]how to divide sum of number by digit on number?

如何將位數除以位數?

例如: 4228為真,因為4+2+2+8=16可以除以4 , 2 , 8

3425 false 因為3+4+2+5=14不能除以3 , 4 , 2 , 5

numbers = int(input('input number : '))
result = 0

# NUM of digit
while numbers > 0 :
    digit = numbers % 10
    result = result + digit
    numbers = numbers // 10

factors = result

#factors of "NUM of digit"
for factor_result in range(1,factors + 1) :
    if factors % factor_result == 0 :
        print(factor_result)

請幫我;(

十分感謝:))

num = 4220
res = [int(x) for x in str(num)]

can_devided = True
for r in res:
    if r == 0:
        continue
    if sum(res) % r != 0:
        can_devided = False
        

print (can_devided)

根據您的描述,您似乎想要這樣的 function

# determine if sum of integers comprising an integer is divisible by its part
def divisor_check(num):
    # check that input num is integer 
    if not isinstance(num,int):
       print('warning: input is not an integer')
       return False

    # break num into component integers by convert to string first
    stringafied_num = str(num)
    
    # split the string-afied num to get component integers
    components = [*stringafied_num]
    
    # evaluate the components to get integers back
    components = [eval(v) for v in components]
    
    # sum components
    total=sum(components)
    
    # try dividing total by each component 
    for c in components:
        if total%c != 0:
            return False
    return True

此 function 將輸入分解為其分量整數,對它們求和,並計算所需的除數檢查。

如果您為您的示例評估此 function,您將獲得所需的結果

divisor_check(4228) --> True

divisor_check(3425) --> False

一種簡單的方法是計算數字的總和,然后檢查模數是否為 0。

在 python 中,我們可以將數字解析為 str,然后將每個數字(單個字符)轉換回 int 並創建這些數字的列表

input_numbers = int(input('input number : '))

# parse the number to a str, then map each char back to an integer
# and create a list of int for each digit
numbers = list(map(int, str(input_numbers )))    

現在,只需使用內置的sum()方法即可獲得您想要的結果。 下一部分只是對數字列表中的每個數字進行循環並檢查模塊。

result = sum(numbers)

is_divisible = True
for number in numbers:
  if number == 0 or result % int(number) != 0:
    is_divisible = False
print(is_divisible)

暫無
暫無

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

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