python快乐数字怎么表达_打印前n个快乐数字Python
我用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个数字。在
我试着在循环中使用计数器,但没有用。在
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
