首先打印n Happy Numbers – Python
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了首先打印n Happy Numbers – Python,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2727字,纯文字阅读大概需要4分钟。
内容图文
![首先打印n Happy Numbers – Python](/upload/InfoBanner/zyjiaocheng/789/2226fb1fe51f4a3dbb38f63c594dc73f.jpg)
我在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))
内容总结
以上是互联网集市为您收集整理的首先打印n Happy Numbers – Python全部内容,希望文章能够帮你解决首先打印n Happy Numbers – Python所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。