用 python 写一些常见的数学函数
来源:互联网 发布:java api中文文档 编辑:程序博客网 时间:2024/06/11 08:19
汉诺塔游戏
#汉诺塔steps = []def move(n, a="A", b="B", c="C"):if n == 1:step = a + "-->" + c #1个时,直接从A移到Csteps.append(step)else:move(n-1, a,c,b) #将n-1个借助C从A移到B 再把最大的从A移到Cstep = a + "-->" + csteps.append(step)move(n-1, b, a, c) #将n-1个借助A从B移到Cmove(3)print("移动次数为:%d \n操作步骤为:\n%s" % (len(steps),steps))
斐波那契数列
方法1
def fibonacci(n):a = 1L = [1,1]while a < n:x = L[-1] + L[-2]L.append(x)a = a + 1return Lprint(fibonacci(20))
方法2
def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1
使用生成器实现
def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done'
g = fib(6)while True:try:x = next(g)print('g:', x)except StopIteration as e:print('Generator return value:', e.value)break
杨辉三角
使用生成器实现
def triangles(): ret = [1] while True: yield ret for i in range(1, len(ret)): ret[i] = pre[i] + pre[i - 1] ret.append(1) pre = ret[:]
n = 0for x in triangles():print(x)n = n + 1if n == 10:break
使用列表生成式和生成器
def triangles(n):L = [1]m = 0while m < n:yield LL.append(0)L = [L[i - 1] + L[i] for i in range(len(L))]m = m + 1
l = triangles(10)for x in l:print(x)
质数
#定义一个从3开始的奇数序列 def _odd_iter(): n = 1 while True: n = n + 2 yield n
#定义一个筛选函数 过滤点可以被之前的数整除的数字def _not_divisible(n): return lambda x: x % n > 0
#定义一个生成器,不断返回下一个素数def primes(): yield 2 it = _odd_iter() # 初始序列 while True: n = next(it) # 返回序列的第一个数 yield n it = filter(_not_divisible(n), it) # 构造新序列
# 打印1000以内的素数:for n in primes(): if n < 1000: print(n) else: break
回数
def is_palindrome(n):return str(n) == str(n)[::-1]
通过筛选功能的高阶函数打印某范围内的回数
output = filter(is_palindrome, range(1, 1000))print(list(output))
阅读全文
1 0
- 用 python 写一些常见的数学函数
- python中常见的数学函数
- Python一些常见的字符串处理函数
- python 写函数的一些小细节
- 不常见的数学函数
- python 中常用不常见的一些函数
- 组合数学的一些常见公式
- Python自写的一些小函数(一)
- Python 自写的一些小函数(二)
- 用python写爬虫的一些技巧
- 用python写爬虫的一些技巧
- Python语言的数学函数
- python的一些常见用法
- SQL 的一些常见函数
- 一些常见函数的用法
- ORACLE的一些常见函数
- Tensorflow的一些常见函数
- DELPHI写ActiveForm常见的一些问题
- struts1于struts2的比较
- MySQL 命令行导出、导入Select 查询结果
- python-字典
- 【Java线程】锁机制:synchronized、Lock、Condition
- Unity Adroid串口Dll not found Exception : MonoPosixHelper第二种解决办法
- 用 python 写一些常见的数学函数
- Codeforces 734E Anton and Tree (dfs缩点+树的直径)
- Unity3D学习之路
- 如何打开pr_debug调试信息
- 1053. 住房空置率 (20)
- fork()和多线程
- 正则表达式复习--正则语法
- python重载和多态问题
- Python 最小聊天服务器&&客户端