您的位置:首页 > 编程语言 > Python开发

Python Function Note

2016-01-14 19:05 435 查看

Python Function Note

#汉诺塔问题Python实现
def my_move(n, a, b, c):
if n == 1:
print(a + ' --> ' + c)
else:
my_move(n-1, a, c, b)#将前n-1个盘子从a放到b
my_move(1, a, b, c)#将最下面的盘子从a放到c
my_move(n-1, b, a, c)#将b上的n-1个盘子放到c上
return


#杨辉三角Python实现
def my_triangles(max):
i = 1
now = [1]
while i <= max:
yield now#保存当前list
now = [1] + [now
+now[n+1] for n in range(len(now)-1)] + [1]#构建下层list
i+=1
print('done')


#实现将‘123.456’转换成123.456,即函数float的实现
def my_float(s):
def my_front(x, y):
return x*10+y
def my_behind(x, y):
return x*0.1+y

front = s.split('.')[0]
behind = s.split('.')[1]
return reduce(my_front, map(int, front)) + 0.1*reduce(my_behind, map(int, behind))


#利用埃氏筛法筛选出素数
#产生无限的奇数
def my_productNumber():
n = 1
while 1:
n += 2
yield n

#返回判断是否是素数的函数
def my_isPrime(n):
return lambda x: x % n > 0

#素数发生器
def my_Primes():
yield 2
it = my_productNumber()
while 1:
n = next(it)
yield n
it = filter(my_isPrime(n), it)

for n in my_Primes():
if n < 100:
print(n)
else:
break


#判断一个数是否回文
def my_isPalindrome(n):
return str(n)[::-1] == str(n)
print(filter(my_isPalindrome, range(1, 1000)))


#关于装饰器
import functools

def log(text=None):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
if text == None:
# print('call %s()' % func.__name__)
pass
else:
# print('%s %s()' % (text, func.__name__))
pass
print('Begin Func↓')
temp = func(*args, **kw)
print('End Func↑')
return temp
return wrapper
return decorator

@log('call')  #相当于now = log('hahaha')(now)
def now(t):
print("2015")
return t
now(4)
print(now.__name__)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: