当提供条件时,While循环未按预期工作

2024-06-28 21:00:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python初学者,通过the following challenge工作:

Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

下面是我的代码:

n = 132189

def kata(num):
    
    import re
    
    total = 0
    
    while total >= 0 and total < 10:
    
        for i in str(num).split():
        
            if int(i) > 9:
                split_num = (" ".join(str(i)))
                running_list = []
                running_list.append(split_num)
    
        num_list = re.findall(r'\d+', str(running_list))
    
        for i in num_list:
            if i.isdigit():
                total += int(i)
        print(total)
        
kata(n)

为什么我的代码没有循环回for循环并继续分解两位数的值


Tags: ofthe代码inreforifrunning
3条回答
def main():
n = 132189
l = []
total = 0
for i in range((len(str(n)))):
    g = str(n)
    #print(int(g[i]))
    total += int(g[i])

tot = 0 
for j in range(len(str(total))):
    f = str(total)
    #print(int(f[j]))
    tot += int(f[j])
    if tot > 9:
        continue
    else:
        l.append(tot)
        #print(tot,'tot')


print(l[-1]) # print(max(l))
print(l,end='') # not the best, but it works.

main()

你的代码有很多问题。我将在下面评论这些问题并提供一个简单有效的解决方案

代码分析

n = 132189


def kata(num):
    import re

    total = 0

    while total >= 0 and total < 10:

        # str(num).split() does nothing since split() will try to separate a string by whitespaces
        # and num has no whitespaces, so you will get an array with the whole number: ['132189']
        # A neat trick to separate a number by it's digits is using python's ability to iterate over strings:
        # split_num = [digit for digit in str(num)]
        # ^this creates a list with digits: ['1','3','2','1','8','9']
        for i in str(num).split():

            # since str(num).split() is ['132189'], this will run only once and i will be '132189'
            if int(i) > 9:
                # this line attempts to join i with whitespaces, making it '1 3 2 1 8 9'
                split_num = (" ".join(str(i)))
                # here you set running_list to an empy list
                # so you are resetting a list everytime before appending to it
                # which defeats the purpose of using a separate variable - 
                # you could just pass split_num to the findall
                running_list = []
                # and here you put '1 3 2 1 8 9' inside running_list, making it ['1 3 2 1 8 9']
                running_list.append(split_num)

        # this line grabs all the digits and sets num_list to ['1', '3', '2', '1', '8', '9']
        num_list = re.findall(r'\d+', str(running_list))

        # for each digit in numlist
        for i in num_list:
            # if it is a digit (which happens everytime in ['1', '3', '2', '1', '8', '9'])
            if i.isdigit():
                # add to the total
                # so total is 1+3+2+1+8+9 which is 24
                total += int(i)
        # then prints the total, which is 24
        print(total)
        # since total is 24 and 24 > 10, the loop will not run again because the condition is while total < 10.


kata(n)

溶液

n = 132189


def kata(num):
    # we will store the current digit sum inside num
    # so we want to keep going while the sum is greater than 9
    while num > 9:
        # create an array with every digit in the number
        split_num = [digit for digit in str(num)]
        # set num to zero, don't worry because the original number is saved inside split_num
        num = 0
        # for each digit in split_num
        for i in split_num:
            # convert the digit to int and add it to num
            num += int(i)
        print(num)
        # if we get here and num is > 9, the loop will run again with the new num


kata(n)

此解决方案将在每次迭代中打印总数,以便您可以检查它在做什么。
1+3+2+1+8+9=24,然后2+4=6
所以它应该打印24,然后打印6

def kata(num):
    running_list = []
    total = 0
    num_list  = [int(d) for d in str(num)]
    Sum = sum(num_list)
    while Sum > 9:
            num_list = [int(d) for d in str(Sum)]
            Sum = sum(num_list)
    print(Sum)

卡塔(132189); 产出:6

编辑:我不知道为什么我不能在这里正确缩进我的代码,但是你得到了答案,也试着学习如何调试,这样你就可以发现你的代码出了什么问题

相关问题 更多 >