[Python] A simple code to find the number of daffodils

Without further ado, go straight to the code:

def find_narcissistic_numbers(n):
    narcissistic_numbers = []
    for num in range(10**(n-1), 10**n):
        temp = num
        sum = 0
        while temp > 0:
            digit = temp % 10
            sum += digit ** n
            temp //= 10
        if sum == num:
            narcissistic_numbers.append(num)
    return narcissistic_numbers

while True:
    n=input("请输入您要寻找的水仙花数位数:")
    if n=="exit":
        break;
    elif n.isdigit():
        n=int(n);
        narcissistic_numbers = find_narcissistic_numbers(n)
        print(str(n) + "位水仙花数:", narcissistic_numbers)
    else:
        print("输入有误,请重新输入")

The above code implements a function, which is to find the number of daffodils corresponding to the number of digits n and print it out.

First, a function find_narcissistic_numbers(n) is defined, which accepts a parameter n, which represents the number of narcissus numbers to be found. Internally, the function traverses all numbers from 10 to the (n-1) power to 10 to the n power through a loop, that is, the range is [10^(n-1), 10^n). For each number num, in an inner loop, take out each digit of num, calculate the nth power of each digit and accumulate it into the sum variable. Finally, if sum equals num, then num is a narcissus number and is added to the narcissistic_numbers list. The function returns a list of the number of daffodils found.

What follows is an infinite loop that continually asks the user to enter the number of digits in the number of daffodils they are looking for. The user can enter a digit n or type "exit" to exit the program. The program executes different logic by judging the user's input:

  1. 1. If the user enters "exit", the loop will be jumped out and the program will end.
  2. 2. If the user inputs a number, determine whether the input is a pure number by calling the isdigit() method, then convert it to an integer type, and call the find_narcissistic_numbers(n) function to find the narcissus number of the corresponding digits, and print the output .
  3. 3. If the user input is neither "exit" nor a number, it will prompt that the input is incorrect and require re-entering.

Through the above code, the user can repeatedly enter the number of daffodils in different digits to search, and get the corresponding result output. If the input digits are invalid or not a number, corresponding error processing will be performed.

Specific renderings:

Guess you like

Origin blog.csdn.net/zhangawei123/article/details/130910776