Python学习笔记 5

来源:互联网 发布:网络棋牌信息 编辑:程序博客网 时间:2024/06/07 12:49

1. 判断一个对象是否是可迭代

>>>from collections import Iterable>>>isinstance(1,Iterable)

这里写图片描述

2. 列表生成式/推导式

列表推导式是在给定列表的基础上做一些操作然后得到一个新列表的方式,类似于 for 循环,但是比 for 循环简洁很多。

一般的列表推导式格式:

[表达式 for 变量 in 列表]    或者  [表达式 for 变量 in 列表 [if 条件]|[for 循环]]

示例:

print [x*y for x in [1,2,3] for y in  [1,2,3]]结果:[1, 2, 3, 2, 4, 6, 3, 6, 9]print dict([(x,x*10) for x in range(1,10)])结果:{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60, 7: 70, 8: 80, 9: 90}

演练一下:求给定范围内和等于某个值的所有质数对及其个数(利用列表推导式)

def is_prime(num):    if num == 1:        return False    for i in range(2,num):        if num%i == 0:            return False    return Truedef primeComb(num,result):    resultlst = [(x,y) for x in range(2,num+1)if is_prime(x)  for y in range(x,num+1) if is_prime(y) and x+y == result]    print len(resultlst)    print resultlst

3. 关于 range 与 xrange

range(…)#所传递的参数一定要是整数

range(stop) -> 等同于 range(0,stop)range(start, stop[, step]) -> 列出某个范围内的整数,如果有步长,则列出步长间隔的所有整数返回一列包含一个整数算术数列range(i, j) 返回 [i, i+1, i+2, ..., j-1]; 起始位默认是0.当步长给定,则指明了递增规则或者递减规则例如:range(4) 返回 [0, 1, 2, 3]. 结束位4被忽略(左闭右开)!如果需要输出递减的数列,则需要指定步长为负数,例如range(10,1,-1)In [124]: range(10,1,-1)Out[124]: [10, 9, 8, 7, 6, 5, 4, 3, 2]

class xrange(object)

 |  xrange(stop) -> xrange对象 |  xrange(start, stop[, step]) -> xrange对象 |   |  类似range(),但是xrange()返回的是一个产生给定范围数字的对象,对于循环,这种操作比range()快很多,而且内存效率很高 |   |  定义的方法有以下: |   |  __getattribute__(...) |      x.__getattribute__('name') <==> x.name |   |  __getitem__(...) |      x.__getitem__(y) <==> x[y] |   |  __iter__(...) |      x.__iter__() <==> iter(x) |   |  __len__(...) |      x.__len__() <==> len(x) |   |  __reduce__(...) |   |  __repr__(...) |      x.__repr__() <==> repr(x) __reversed__(...) |      Returns a reverse iterator. |   |  ---------------------------------------------------------------------- |  数据和其他的属性定义如下: |   |  __new__ = <built-in method __new__ of type object> |      T.__new__(S, ...) -> a new object with type S, a subtype of T(END)

4. python 高阶函数

4.1 map

In [190]: map(str,range(1,6))Out[190]: ['1', '2', '3', '4', '5']In [191]: 

4.2 reduce

求阶乘:

In [187]: def mul(x,y):   .....:     return x*y   .....: In [188]: reduce(mul,range(1,6))Out[188]: 120

4.3 filter

filter(is_prime,range(100))#求100以内的质数

4.4 sorted

In [194]: sorted([1,345,657,323,4,6,687])Out[194]: [1, 4, 6, 323, 345, 657, 687]

借助列表实现字典元素的批量添加

In [8]: lst=['a','sd','sdf','re','oo']In [9]: userDict.fromkeys(lst,'halo')Out[9]: {'a': 'halo', 'oo': 'halo', 're': 'halo', 'sd': 'halo', 'sdf': 'halo'}

字典的枚举:
枚举只能返回返回两个值,一个是索引下标,一个是迭代的元素;

d = {1:"a",2:"b"}for i,j in enumerate(d):    print i,j,d[j]

创建生成器的方法:

  • 将列表生成式的[]改为();
  • 在定义的函数中加入yield关键字;

查看生成器元素的方式:
- 使用生成器的next方法;(不常用);注意python3中为__next()__
- 生成器是可迭代的对象,直接通过for循环查看;

5. 求对数以及向下或者向上取整

import mathceil = math.ceil(math.log10(400))floor = math.floor(math.log10(400))

这里写图片描述

6.编程练习

6.1 输入一个正整数n,求n!(即阶乘)末尾有多少个0? 比如: n = 10; n! = 3628800,所以答案为2;

import math#第一种实现def lastZero1(num):    if 1<= num <= 1000:        count = 0        flag = 5        while flag < num+1:            flag += 5            count += 1            basicNum = 25;            while flag % basicNum == 0:                count += 1                basicNum *= 5        print(count)       else:        print('Number not within the range 1-1000 or not a number given!')#第二种实现def lastZero2(num):    count = 0;    temp=num/5;    while temp !=0 :         count+=math.floor(temp)        temp/=5    print(count)lastZero1(1000)lastZero2(1000)

这里写图片描述

6.2 设有n个正整数,将他们连接成一排,组成一个最大的多位整数。 如:n=3时,3个整数13,312,343,连成的最大整数为34331213。 如:n=4时,4个整数7,13,4,246连接成的最大整数为7424613。

#!/usr/bin/env python#coding:utf-8'''file:comBignum.pydate:8/31/17 9:04 AMauthor:lockeyemail:lockey@123.comdesc:'''def comBigNum(lst):    lststr = [str(item) for item in lst]    lstlen = len(lststr)    i = 0    while i < lstlen:        j = i+1        while j < lstlen:            if lststr[i] == lststr[j]:                j += 1                continue            int1 = lststr[i] + lststr[j]            int2 = lststr[j] + lststr[i]            if int(int1) < int(int2):                temp = lststr[j]                lststr[j] = lststr[i]                lststr[i] = temp            j += 1        i += 1    print ''.join(lststr)lst = [8,86,867,88,345,657,43,43545,6,5,43,1,2345,56,76]lst1 = [13,312,343]lst2 = [7,13,4,246]comBigNum(lst)comBigNum(lst1)comBigNum(lst2)

这里写图片描述

6.3 “回文串”是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串。花花非常喜欢这种拥有对称美的回文串,生日的时候她得到两个礼物分别是字符串A和字符串B。现在她非常好奇有没有办法将字符串B插入字符串A使产生的字符串是一个回文串。你接受花花的请求,帮助她寻找有多少种插入办法可以使新串是一个回文串。如果字符串B插入的位置不同就考虑为不一样的办法。

例如:
A = “aba”,B = “b”。这里有4种把B插入A的办法:
* 在A的第一个字母之前: “baba” 不是回文
* 在第一个字母‘a’之后: “abba” 是回文
* 在字母‘b’之后: “abba” 是回文
* 在第二个字母’a’之后 “abab” 不是回文
所以满足条件的答案为2

  • 输入描述:
    每组输入数据共两行。
    第一行为字符串A
    第二行为字符串B
    字符串长度均小于100且只包含小写字母

  • 输出描述:
    输出一个数字,表示把字符串B插入字符串A之后构成一个回文串的方法数

  • 示例1

- 输入    aba    b- 输出    2

程序示例

#!/usr/bin/env python#coding:utf-8'''file:palindrome.pydate:8/31/17 11:06 AMauthor:lockeyemail:lockey@123.comdesc:'''import mathdef if_Palindrome(str):#定义判断回文数的函数    strLen = len(str)-1    i = 0    if strLen %2 == 0:        halfstrLen = strLen/2    else:        halfstrLen = math.floor(strLen/2)    while i <= halfstrLen:        if str[i] != str[strLen-i]:            return False        i += 1    return Truedef com_Palindrome():#用户输入以及字符串拼接函数    total = 0    while True:        strA = raw_input('Please input string A:')        if not strA.isalpha() or len(strA) > 99:            print 'string A is not alpha string or out of range(within 100)'            return        strB = raw_input('Please input string B:')        if not strB.isalpha() or len(strB) > 99:            print 'string B is not alpha string or out of range(within 100)'            return        strA = strA.lower()        strB = strB.lower()        insertTimes = len(strA)        i = 0        while i <= insertTimes:            afterInsert = strA[0:i]+strB+strA[i:]            if if_Palindrome(afterInsert):                total += 1            i += 1        print total        total = 0com_Palindrome()

运行结果:
这里写图片描述