在python程序中发现2位快乐数字的问题(卡在循环中)

时间:2018-12-03 23:29:02

标签: python loops numbers

我是python的初学者,我刚刚编写了一个程序来查找两位数的happy numbers。我们应该给它一个2位数的数字,然后如果它是一个快乐的数字,它应该打印出它是一个快乐的数字,如果不是,它应该不包含1的循环中不断循环。

这是我的代码:

input_number = int(input("Please Enter a positive 2 digits number\n"))

digits = [int(i) for i in str(input_number)]

while input_number != 1:
    for i in range(len(digits)):
        sum_of_squares = digits[i]**2 + digits[i-1]**2
        input_number = sum_of_squares
    print(input_number)
    if input_number == 1:
        print("Happy ;)")
        break

我的问题是我的程序永远不会离开循环,例如49是一个快乐的数字,但是当我输入它时,它会无休止地打印97。 我的代码有什么问题?

3 个答案:

答案 0 :(得分:0)

在循环内,您需要更改digits的值。另外,由于它是2位数字,因此您只能使用0和1的列表索引。

input_number = input()

digits = [int(i) for i in input_number]
while input_number != 1:
    sum_of_squares = digits[0]**2 + digits[1]**2
    digits = [int(i) for i in str(sum_of_squares)]
    input_number = sum_of_squares
    print(input_number)
    if input_number == 1:
        print("Happy ;)")
        break

答案 1 :(得分:0)

@ joyal-mathew的答案略有不同。这适用于任何数字

input_number = int(input("Please Enter a positive number\n"))

while input_number != 1:
    digits = [int(i) for i in str(input_number)]
    digit_squares = [i*i for i in digits]
    sum_of_squares = sum(digit_squares)
    input_number = sum_of_squares
    print(input_number)
    iter_count+=1
    if input_number == 1:
        print("Happy ;)")
        break

答案 2 :(得分:0)

递归和冗长的解决方案:

def is_happy(int_tc, seen = None):
    """checks if the number is a happy number"""
    if seen is None:
        seen = [int_tc]

    sum_squares = sum_of_squares_of_all_digits(seen[-1])

    if sum_squares == 1:
        return True
    elif sum_squares in seen: # check if the numbers are repeating infinitely
        return False
    else:
        seen.append(sum_squares)

    return is_happy(int_tc, seen)

def sum_of_squares_of_all_digits(number):
    """return sum of square of all digits"""
    return sum([digit ** 2 for digit in get_all_digits(number)])


def get_all_digits(number):
    """gets all the digits from the number right to left one bye one(yield)"""
    while(number > 0):
        yield number % 10
        number = (number - number % 10) / 10