python求解水仙花数的方法
作者:上大王 时间:2023-10-08 12:07:28
本文实例讲述了python求解水仙花数的方法。分享给大家供大家参考。具体如下:
一个N位的十进制正整数,如果它的每个位上的数字的N次方的和等于这个数本身,则称其为花朵数。
#!/usr/bin/python
def get_flower(n, ofile):
D_pow=[pow(i,n) for i in range(0,10)]
V_min=1*pow(10,n-1)
V_max=sum((9*pow(10,x) for x in range(0,n)))
T_count=0
print D_pow, V_max, V_min
nums=[1]+[0]*(n-1)
print 'Start:', nums
idx=n-1
tmp_l=[0]*10
while True:
nums[idx]+=1
if nums[idx]<10:
j=idx+1
while j<n:
nums[j]=nums[idx] # reset
j+=1
v=sum((D_pow[x] for x in nums))
if v<=V_max and v>=V_min:
T_count+=1
#test if is flower
#print 'do test:', ''.join(map(str,nums))
k=0
while k<10:
tmp_l[k]=0
k+=1
N=0
for k in nums:
tmp_l[k]+=1
N+=1
while N>0:
p=v%10
if tmp_l[p]>0:
tmp_l[p]-=1
N-=1
else:
break
v/=10
if N==0:
print >>ofile, 'hit', sum((D_pow[x] for x in nums))
idx=n-1
elif idx==0:
print 'done'
break
else:
idx-=1
print 't_count', T_count
if __name__ == '__main__':
with file('./f.txt', 'wb') as o:
get_flower(21, o)
#get_flower(3, o)
希望本文所述对大家的Python程序设计有所帮助。
标签:python,水仙花数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Dreamweaver 4.0使用技巧集锦
2007-11-08 12:47:00
wxPython中wx.gird.Gird添加按钮的实现
2021-07-05 15:13:19
![](https://img.aspxhome.com/file/2023/9/86269_0s.png)
python图形界面教程Tkinter详解
2021-01-08 04:27:47
python实现图片素描效果
2022-06-10 21:00:40
![](https://img.aspxhome.com/file/2023/1/91841_0s.png)
Python tkinter之ComboBox(下拉框)的使用简介
2021-11-10 02:40:29
![](https://img.aspxhome.com/file/2023/3/127813_0s.png)
Elasticsearch属性单词常用解析说明
2023-06-12 14:47:36
如何将python文件打包成exe可运行文件
2022-06-29 19:01:17
![](https://img.aspxhome.com/file/2023/9/82649_0s.png)
浏览器事件循环与vue nextTicket的实现
2024-05-09 09:25:26
![](https://img.aspxhome.com/file/2023/5/128875_0s.png)
五个有趣的Python整蛊小程序合集
2022-10-27 12:34:10
![](https://img.aspxhome.com/file/2023/0/86150_0s.png)
Python可视化神器pyecharts绘制雷达图
2021-09-30 14:50:48
![](https://img.aspxhome.com/file/2023/3/102953_0s.png)
Jenkins配置maven项目之打包、部署、发布的全过程
2023-08-07 19:14:29
![](https://img.aspxhome.com/file/2023/1/61841_0s.jpg)
Vue Cli3 创建项目的方法步骤
2024-05-21 10:16:53
![](https://img.aspxhome.com/file/2023/8/125288_0s.png)
MySQL动态修改varchar长度的方法
2024-01-17 22:27:10
轻松掌握SQL Server存储过程的命名标准
2009-01-15 13:14:00
Golang实现文件传输功能
2023-08-05 13:50:31
![](https://img.aspxhome.com/file/2023/8/90478_0s.jpg)
Python 查看文件的编码格式方法
2021-11-01 10:50:39
Python中.py文件打包成exe可执行文件详解
2023-06-10 19:11:00
![](https://img.aspxhome.com/file/2023/8/99448_0s.jpg)
js实现百度地图定位于地址逆解析,显示自己当前的地理位置
2024-05-08 10:12:04
Python利用正则表达式匹配并截取指定子串及去重的方法
2021-05-07 00:37:20
python读写ini配置文件方法实例分析
2022-10-09 22:02:28