我只是在练习 Python 并正在回答这个问题:
信息:有一个数的位数的平方反复求和得到的序列。如果序列在不到 15 步内收敛到 1,则该数字被认为是快乐数字。
问题:制作一个允许用户输入数字的程序,它会告诉他们输入的数字是否是快乐的数字。用户应该能够继续输入数字,直到输入 -1 以退出程序。
我试过这个问题,但有一个错误说
File "string", line 43, in fragment
TypeError: 'int' object is unsubscriptable
我知道错误是sequence_num += int(num[i]) ** 2
我不明白为什么,因为在此之前,我将 num 转换为字符串,然后由于(num[i])
在括号中,程序应该先运行,然后再将其转换为整数。知道为什么会发生这种情况和/或如何解决它。多谢你们。
#Constant to determine if number is happy
MAX_STEPS = 14
#Constants to signal end of sequences or program
END_SEQUENCE_NUM = 1
END_PROGRAM_NUM = -1
#Variable to count number of steps and digit number
steps = 0
i = 0
#Variable for sequence number
sequence_num = 0
#Loops until user inputs -1
while True:
#Gets values from user
num = input("\nPlease input a number: ")
#Checks if user entered -1 to end program
if num == END_PROGRAM_NUM:
#Ends program
break
#Checks if user inputted a number besides -1
else:
#Loops until the sequence converges to 1 or number of steps is greater than 15
while num != END_SEQUENCE_NUM and steps < MAX_STEPS:
#Counts number of steps
steps += 1
#Concatenates user's number into a string
num = str(num)
#Gets number of digits of user's number
num_digits = len(num)
#Squares each digit and adds the product
while i != num_digits:
sequence_num += int(num[i]) ** 2
i += 1
num = sequence_num
#Checks if number is happy
if num == END_SEQUENCE_NUM:
num_type = "happy"
else:
num_type = "not happy"
print "This is a", num_type, "number."