首页 > 解决方案 > 提供条件时,While 循环未按预期工作

问题描述

我是 python 的初学者,正在应对以下挑战

给定n,取n的位数之和。如果该值超过一位,则继续以这种方式减少,直到产生一位数。输入将是一个非负整数。

下面是我的代码:

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 循环并继续分解两位数的值?

标签: pythonpython-3.x

解决方案


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

代码分析

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。


推荐阅读