gpt4 book ai didi

python - 打印前 n 个快乐数字 - Python

转载 作者:太空宇宙 更新时间:2023-11-03 10:52:00 25 4
gpt4 key购买 nike

我正在用 python 编写一段代码来检查给定数字是否快乐,即获取数字并将它们的平方和相加为 1,这是一个快乐数字或以永无止境的循环结束它定义了一个不快乐的数字。之后,我想列出前 n 个快乐数字。尽管草率地检查了快乐数字,但我似乎无法弄清楚列表部分。

def adder(num):
total=0
if len(str(num))>1: #check if given number is double digit or not
tens = int(str(num)[0]) # splitting the digits
ones = int(str(num)[1])
total = (tens**2)+(ones**2) # summing up the squares
#print (total)
return total
else: # if the given number is a single digit
total = (num**2)
#print (total)
return total

#adder(9)

def happynumber(num, counter):
N = adder (num) # storing the sum in a variable


#print ("value of n is {}".format(N))
if N == 1: #checks if the sum is 1
# print ("In just {} tries we found that {} is a happy number.".format(counter, number))
print (number)



else: # if the sum isn't 1, racalls the happynumber function
counter += 1 # keeps track of number of tries so that we don't end up in an infinite loop
if counter < 11: # setting the limit for number of tries
#print (counter)
happynumber (N, counter)
else:
#print ("it took us {} tries and found that the number {} is not a happy number".format(counter, number))
return False

counter = 0


for i in range(0,100): # listing all the happy numbers between 0 and 100
number = i
happynumber (number, counter)

此外,如果你们能回顾一下我的写作风格并给予一些指点,我会很高兴。

问题是,无论如何我都无法列出前 n 个数字。

我尝试在循环中使用计数器但无济于事。

最佳答案

如果您的主要问题是您希望将所有快乐数字放在一个列表中,您可以通过在递归循环之外定义一个列表来轻松解决这个问题。

def happynumber(num, counter):
N = adder(num)

if N == 1:
happyhappy.append(number) #new happy number into list
else:
...continue with your code

#-------main script-------------
happyhappy = [] #create a list to store your happy numbers
counter = 0
for i in range(100):
number = i
happynumber(number, counter)

print(happyhappy) #and retrieve the list

话虽如此,您的 adder() 函数效率低下。它最多只计算两位数。更糟糕的是,它必须从头开始对每个数字执行平方运算,这非常耗时。

更好的方法是预先计算平方并将它们存储在字典中:

square_dic = {str(i): i ** 2 for i in range(10)}  #create a dictionary of squares
def adder(num):
s = str(num) #make the number into an iterable string
x = [square_dic[i] for i in s] #look up the square of each digit
return sum(x) #and calculate the sum of squares

多亏了 Python 中的列表理解,我们可以让它变得更加敏捷

square_dic = {str(i): i ** 2 for i in range(10)}
def adder(num): #does exactly, what the other function did
return sum(square_dic[i] for i in str(num))

关于python - 打印前 n 个快乐数字 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com