小练习
小练习:
读入一组数字,然后把每个数字加一后输出。比如说:123,输出之后是2、3、4
算法:
1 读入一组数据,纯数字,读入之后的类型是字符串
num = raw_input("input a number:")
2 将这个数字,拆成每个数字是个独立的元素,循环这个字符串,放到list1里
list1=[]
for i in num:
list1.append(i)
3 生成一个新的list2,存储结果
list2=[]
4 遍历list1的每一个元素,转换为数字类型,然后+1,转换为字符串类型,然后存到list2里面
for i in list1:
list2.append(str(int(i)+1))
5 这个时候List2里面存的都是字符串类型,然后拼接为最后的结果,结果也是字符串,
转化为int类型。
print int("".join(list2))
定义一个函数,生成一组随机密码,要求大小写组合+数字,10位以上
算法:
随机生成法,生成一个大的集合list,然后shuffle之后,取前几位
import random
import string
a=list(string.uppercase)
random.shuffle(a)
print a[:4]
str1=a
1 想办法生成4个随机大写字母的字符串
import random
import string
a=list(string.uppercase)
random.shuffle(a)
print a[:4]
str1=a
2 想办法生成3个随机小写字母的字符串
import random
import string
a=list(string.lowercase)
random.shuffle(a)
print a[:3]
str2=a
3 想办法生成3个随机数字的字符串
import random
import string
a=list(string.digits)
random.shuffle(a)
print a[:3]
str3=a
4 讲前三步的结果,拼接成一个10位的字符串
result =str1+str2+str3
5 封装到一个函数里面
封装
import random
import string
def get_random_elements(s,length):
a=list(s)
random.shuffle(a)
print a[:length]
return a[:length]
def get_random_password():
return "".join(get_random_elements(string.uppercase,4)+get_random_elements(string.lowercase,3)+get_random_elements(string.digits,3))
if __name__ == "__main__":
print get_random_password()
插曲1
>>> random.sample(list(string.uppercase),4)
['T', 'A', 'P', 'X']
>> print random.sample(["我","饿","你"],1)[0]
饿
>> a =["我"]
>> a
'\xce\xd2']
>> print a
'\xce\xd2']
>> print a[0]
我
>>
函数
查看内置函数:
>>> dir(sum)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__form
at__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__',
'__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduc
e_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subc
lasshook__']
函数文档注释:
>>> def print_add(a,b):
... '''加油'''
... return a + b
...
>>> print print_add.__doc__
加油
>>>
文件就是模块
b.py:
def add(a,b):
return a+b
def sub(a,b):
return a-b
a.py:
# encoding: utf-8
import b
print b.add(1,2)
print b.sub(20s,10)
小题:计算一个浮点相乘记录时间,并且还回时间
>>> def count_elapse_time():
... a=time.time()
... for i in range(10000):
... 1.1111*9.99999
... return time.time() - a
...
def print_flaod():
stat_time = time.time()
num = 0.1
for i in range(10000):
print num*i
print_flaod()
参数错误 参数顺序需要主要
>> add(1)
raceback (most recent call last):
File "<stdin>", line 1, in <module>
ypeError: add() takes no arguments (1 given)
>> def add(a,b):
.. pass
..
>> add()
raceback (most recent call last):
File "<stdin>", line 1, in <module>
ypeError: add() takes exactly 2 arguments (0 given)
吴老师(875821166) 12:01:48
SyntaxError: non-keyword arg after keyword arg
>>> "*"*20
'********************'
>>>
打印一个阶乘使用函数默认参数10
注意点:默认值要放到参数后面
def factorial(n=10):
if not isinstance(n,int):
raise TypeError("The input is not Int Type")
Result=1
for i in range(1,n+1):
Result*=i
return Result
print factorial(5)
print factorial("5")
print factorial()
非默认值
出错:因为位置不对!
def say( times = 1,message):
print message * times
say('gloryroad!')
say(u'万岁!', 3)
>>> def a():return
...
>>> print a()
None
1个函数,传一个字符串,奇数长度返回1,偶数长度返回0
def get_length_status(s):
if not isinstance(s,(str,unicode)):
return None
if len(s)%2 ==0:
return 0
else:
return 1
print get_length_status("abc")
print get_length_status(u"abc")
出一道题:写一个函数,可以设定不定个数的形参,将形参中的奇数,作为返回结果
def powersum( *args):
li=[]
for i in args:
if not isinstance(i,int):
continue
elif i%2<>0:
li.append(str(i))
return ",".join(li)
print powersum(2,3,"1")
print powersum(2,3,4,4,55,67,88)
print powersum(2,3,4,5,"p")
可变参数:*表示元组、**表示字典
def fun2(a,b=100,*args,**keys):
print "keys type=%s" % type(keys)
print "keys=%s" % str(keys)
print "name=%s" % str(keys['name'])
print "sex=%s" % str(keys['sex'])
sum=0
for i in args:
sum+=i
print sum+a+b
fun2(1,2,3,4,name="vp",age=19,sex="m")
练习:写一个函数,使用可变参数字典的形式,计算所以参数的key和value的长度并作为函数的结果返回
def count_arguments_length(**kw):
result =0
for k,v in kw.items():
result+=len(str(k))
result+=len(str(v))
return result
print count_arguments_length(name="wulaoshi")
print count_arguments_length(name="wulaoshi",sex="male",age=40)
小题:
def sum(a,*arg,**args):
sum=0
sum=sum+a
for i in arg:
sum=sum+int(i)
for i in args.values():
sum=sum+int(i)
return sum
print sum(1,2,3,4,b=5,c=6,d=7)
四剑客:lambda map filter reduce
Lambda函数
>>> a=lambda x,y,z:x+y+z
>>> a(1,2,3)
6
def make_repeater(n):
return lambda s: s*n
twice = make_repeater(2)
print twice('word')
print twice(5)
Map函数
>>> def x(s):return s+1
...
>>> map(x,[1,2,3])
[2, 3, 4]
>>> map(x,[1,2,3])
[2, 3, 4]
>>> map(x,(1,2,3))
[2, 3, 4] >>> map(lambda x:x.upper(),"abc")
['A', 'B', 'C']
题目:使用map函数,将一个字符串中的小写字母删除掉,例如:“AABBaabb”,
结果返回"AABB
def delete_lowercase(s):
if s>='a' and s<="z":
return ""
else:
return s
print "".join(map(delete_lowercase,"AABBaabb"))
张闻棋:
>>> "".join([i for i in map(lambda x:(re.match(r"[ACDEFGHIJKLMNOPQRSTUVWXYZ]*",x
).group()),"asdASD") if i!=""])
'ASD'、
讲解
>>> [i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> map(lambda x,y:x+y,[1,2,3],[10,20,30])
[11, 22, 33]
个数需要对上:如果不能对上出现下列错误
>>> map(lambda x,y:x+y,[1,2,3],[10,20])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
Filter函数
def delete_lowercase(s):
if s>='a' and s<="z":
return
else:
return s
print "".join(filter(delete_lowercase,"AABBaabb"))
小题:小于5的数据保留
def delete_numbere(s):
if int(s)>=5:
return True
print "".join(filter(delete_numbere,"123456789"))
Reduce函数:累加效果
>>> reduce(lambda x,y:x+y,[1,2,3,4])
10
>>> 1:1+2 2:3+3 3:6+4
1到100:
>>> reduce(lambda x,y:x+y,range(1,101))
5050
>>>
综合练习
#coding=utf-8
def fn(x, y):
return x * 10 + y
def char2num(s):
return {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}[s]
print reduce(fn, map(char2num, '13579'))
递归函数
# -*- coding: utf-8 -*- #
def recur_fibo(n):
"""递归函数
输出斐波那契数列"""
if n <= 1:
return n
else:
return (recur_fibo(n-1) + recur_fibo(n-2)),
#打印四项:
#n=4,return f(3)+f(2)
#n=3,return f(2)+f(1) 1+1 n=2,return f(1)+f(0) result=1
#n=2,,return f(1)+f(0) n=1,return 1
# 获取用户输入
nterms = int(raw_input("您要输出几项斐波那契数列? ".decode('utf-8').encode('gbk')))
# 检查输入的数字是否正确
if nterms <= 0:
print u"输入正数"
else:
print u"斐波那契数列:"
for i in range(nterms):
print recur_fibo(i)