Dowemo
0 0 0 0

1. Determine whether an object is an iteration.

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

这里写图片描述

2./derivation.

A list derivation is to do some operations on the basis of a given list and then get a new column table, similar to the for loop, but much simpler than the for loop.

General list derivation format:

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

Example:

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}

: to find all prime pairs and number of pairs in a given range and equal to a value ( using list derivation )

defis_prime(num):if num == 1:
 returnFalsefor i in range(2,num):
 if num%i == 0:
 returnFalsereturnTruedefprimeComb(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. About range and.

A parameter that's passed by the # range (. ) must be.

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]

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 high order functio &.

4. 1 map.

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

4. 2 reduce.

Calculate factorial:

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.

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

the bulk addition of dictionary elements by list

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'}

An enumeration of the dictionary:
Enumeration returns only return returns back to two values, one is index subscript, one of the iteration elements;

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

method to create a generator:

  • Change the list of [ ] to ( );
  • Add the yield keyword to the defined function;

The way to view the generator elements in a way:
- using the next method of the generator; ( not commonly used ); Note the next ( ) __ in python3.
- generator is an iterative object that's viewed directly through for;

5. Sum up the logarithm and down or down.

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

这里写图片描述

6. Programming exercises.

6. 1 input a positive integer n, finding how many 0 at the end of n! ( I. E. Factorial )? For example: n = 10; n! = 3628800, so the answer is 2;

import math#第一种实现deflastZero1(num):if1<= num <= 1000:
 count = 0 flag = 5while 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!')#第二种实现deflastZero2(num): count = 0;
 temp=num/5;
 while temp!=0 : 
 count+=math.floor(temp)
 temp/=5 print(count)
lastZero1(1000)
lastZero2(1000)

这里写图片描述

6. 2 is provided with n positive integers, and they're connected to a row to make up a maximum number of multiple integers. If: n = 3, 3 integer 13, 312, 343, connected maximum integer is 34331213. If: n = 4, 4 integer 7, 13, 4, HSPA join the maximum integer of 7424613.

#!/usr/bin/env python#coding:utf-8'''
file:comBignum.py
date:8/31/17 9:04 AM
author:lockey
email:lockey@123.com
desc:
'''defcomBigNum(lst): lststr = [str(item) for item in lst]
 lstlen = len(lststr)
 i = 0while i <lstlen:
 j = i+1while j <lstlen:
 if lststr[i] == lststr[j]:
 j += 1continue 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 += 1print''.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 'palindrome string 'is a and string, such as"level"or"noon", and so on is a palindrome string. is very like this palindrome string, and her birthday when she gets two gifts are string a and string b. Now she is very curious that there's a way to insert string b into string a so that the resulting string is a palindrome string. You accept a request to help her find a number of insertion methods that can make the string a palindrome string. If the location of the string b is inserted differently, consider the difference.

For example:
A = adl, b ="b". Here are 4 ways to insert b into a:
Before * 's first letter:"baba"isn't a palindrome.
After the first letter 'a ', ''is a palindrome.
After * 's"b":"abba"is a palindrome.
""isn't a palindrome after the second letter 'a '
So the answer is 2.

  • Enter description:
    Two rows of input data per group.
    First behavior string a
    Second behavior string b
    String length is less than 100 and contains only lowercase letters

  • Output description:
    Output a number that represents the number of methods to form a palindrome string after I insert string b

  • Example 1

- 输入 aba
 b
- 输出 2

Example example

#!/usr/bin/env python#coding:utf-8'''
file:palindrome.py
date:8/31/17 11:06 AM
author:lockey
email:lockey@123.com
desc:
'''import mathdefif_Palindrome(str):#定义判断回文数的函数 strLen = len(str)-1 i = 0if strLen %2 == 0:
 halfstrLen = strLen/2else:
 halfstrLen = math.floor(strLen/2)
 while i <= halfstrLen:
 if str[i]!= str[strLen-i]:
 returnFalse i += 1returnTruedefcom_Palindrome():#用户输入以及字符串拼接函数 total = 0whileTrue:
 strA = raw_input('Please input string A:')
 ifnot 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:')
 ifnot 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 = 0while i <= insertTimes:
 afterInsert = strA[0:i]+strB+strA[i:]
 if if_Palindrome(afterInsert):
 total += 1 i += 1print total
 total = 0com_Palindrome()

Run results:
这里写图片描述




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs