Python 笔记

Python 笔记

basics

>>> 4
4

>>> print 4
4

>>> type (4)
<type 'int'>

>>> type ('hehe')
<type 'str'>

>>> print 1,000,000
1 0 0

>>>a,b = 1,2
>>>a
1
>>>b
2

>>> [a, b] = 1, 2
>>> a
1
>>> b
2

types of variables
int, str, float, bool, long

int 之间的计算结果如果超过 int 极限, 则 Python 自动返回一个 long 结果


how to assign values

>>> s= 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897932

>>> message = 'nihao123'
>>> print message
nihao123

Python has 31 keywords

and       del       from      not       while    
as        elif      global    or        with     
assert    else      if        pass      yield    
break     except    import    print              
class     exec      in        raise              
continue  finally   is        return             
def       for       lambda    try

运算符号

+
-
*
/
**   #次方

可以对 string 使用的运算符号

+  # concatenation
*  # 表示重复几次

>>> message = 'nihao'
>>> print message * 2
nihaonihao

indentation

一行只能写一个 statement
不需要用 ; 来结尾
用 indentation (四个空格) 来表示 grouping

if s == 1: 
	s = s + 1 
	a = a - 10 
else:
	s = s + 10
	a = a + 10

如果一行写不完一个 statement, 就用 \ 把两行连起来

aReallyLongVariableNameThatMakesMyLinesLong = \
	aReallyLongVariableNameThatMakesMyLinesLong + 1

类型转换

int(xxx)
float(xxx)
str(xxx)

>>> int('33')
33
>>> int('hehe')
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    int('hehe')
ValueError: invalid literal for int() with base 10: 'hehe'
>>> 

检查类型

bool result = isinstance(n, int)

import

>>> import math

>>> print math
<module 'math' from '/usr/lib/python2.5/lib-dynload/math.so'>

>>> ratio = signal_power / noise_power
>>> decibels = 10 * math.log10(ratio)

>>> radians = 0.7
>>> height = math.sin(radians)

>>> math.pi
3.1415926535897931

代码练习1: factorial

def factorial(n):
    if n == 0:
        return 1
    elif not isInstance(n, int):
    	return None
    elif n < 0:
    	return None	
    else:
        recurse = factorial(n-1)
        result = n * recurse
        return result

代码练习2: fibonacci

def fibonacci (n):
    if n == 0:
        return 0
    elif  n == 1:
        return 1
    else:
        return fibonacci(n-1) + fibonacci(n-2)

代码练习3: ackermann

The Ackermann function, A(m, n), is defined3:
      	
A(m, n) = 	
              n+1	if  m = 0 
        A(m−1, 1)	if  m > 0  and  n = 0 
A(m−1, A(m, n−1))	if  m > 0  and  n > 0.
	 	 	    
Write a function named ack that evaluates Ackerman’s function. 
Use your function to evaluate ack(3, 4), which should be 125. 
What happens for larger values of m and n?

答案

def ackermann(m, n):
    if m < 0 or n < 0:
		print 'illegal argument!!!'
	    return None
	if m == 0:
	    return n+1
	if m > 0 and n == 0:
		return ackermann(m-1, 1)
	if m > 0 and n > 0:
		return ackermann(m-1, ackermann(m, n-1))

pass

表示这一行啥也不干, 没有任何作用
可以用来占位儿, 以后再填上需要的代码

if a > 500:
    pass
else:
    b = b + 10    

获取键盘输入

>>> s = raw_input()
我就是左轮山猫

>>> print s
我就是左轮山猫
>>> s = raw_input('Who are the patriots?\n')   # 不使用 \n 的话就得在同一行上输入了, 会很难受
Who are the patriots?
laliluleilo

>>> s
'laliluleilo'
>>> s = raw_input('康美丽的代表数字是什么?\n')
康美丽的代表数字是什么?
2

>>> int(s)
2

while break

while True:
    line = raw_input('> ')
    if line == 'done':
        break
    print line

for loop

s = '0123'
for letter in s:
	print letter,
	
0 1 2 3
numbers = ['a', 'b', 'c']
for i in range(len(numbers)):
    numbers[i] = numbers[i] + ' hahaha'
    print numbers[i]

range()
用来进行指定次数的 for loop iteration
end exclusive

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4

list comprehension
一种更简洁的写 list 的表达式
结构: [expr for var in list]
也可以加入 if 判断

>>> [x/2.0 for x in [4, 5, 6]]
[2.0, 2.5, 3.0]

>>> [y**2 + 3 for y in [1, 10, 1000]][
4, 103, 1000003]

>>> [a[0] for a in [['Hal', 'Abelson'],['Jacob','White'],['Leslie','Kaelbling']]]
['Hal', 'Jacob', 'Leslie']

>>> [x*x for x in nums if x%2==1]
[1, 25, 9801, 10201, 1369, 10201]

>>>[first + last for (first, last) in zip ([’Hal’, ’Jacob’, ’Leslie’], [’Abelson’, ’White’, ’Kaelbling’])]
[’HalAbelson’, ’JacobWhite’, ’LeslieKaelbling’]

>>>[first + last for first in[’Hal’,’Jacob’,’Leslie’] \for last in [’Abelson’,’White’,’Kaelbling’]]
[’HalAbelson’,’HalWhite’,’HalKaelbling’,’JacobAbelson’,’JacobWhite’,’JacobKaelbling’,’LeslieAbelson’,’LeslieWhite’,’LeslieKaelbling’]

如何判断两个 float 是否相等

if abs(y-x) < epsilon:
        break
       
# epsilon has a value like 0.0000001        

eval

把一个 string 变成 python 代码, 并让 interpreter 来解析运行

>>> eval('1 + 2 * 3')
7

>>> import math
>>> eval('math.sqrt(5)')
2.2360679774997898

>>> eval('type(math.pi)')
<type 'float'>

string 的相关方法

strings are immutable

len(s)
获得 string 的长度

>>> fruit = 'banana'
>>> len(fruit)
6

string slice s[start:end]
start inclusive, end exclusive

>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
>>> fruit[:]
'banana'
>>> fruit = 'banana'
>>> fruit[0:5:2]   # step 2
'bnn'

>>> fruit[::-1]
'ananab'

.upper()
把 string 变成全大写

>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA

in
检查 string 是否包含 substring

>>> 'Py' in 'Python'
True

寻找 substring 在 string 中的 index, 找不到返回 -1
.find('x')

>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1

.strip(['x'])
没有参数: 去掉首尾空格
有参数: 去掉首尾中和参数一样的字母

>>> s = '0123456'
>>> s.strip('56789')
'01234'

.replace('old', 'new' [, index])
index 从 1 开始算

>>> s = '0a1a2a3a4a5a'

>>> s.replace('a','b')
'0b1b2b3b4b5b'

>>> s.replace('a','b',1)
'0b1a2a3a4a5a'

ord('A') 把 unicode character 变成数字
chr(65) 把数字变成 unicode character
A - 65
Z - 90
a - 97
z - 122

s.capitalize() 变大写

list()
把 string 变成 list of characters

>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']

split()
无参数: 把一个带空格的 string 按照空格拆分为单词 list
有参数: 按照指定的 delimiter 把 string 拆分为 list

>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']

join('')
使用 delimiter 把 list 串成一个 string
必须有参数, 也就是 delimiter

>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'

is operator
判断两个 variables 是不是指向同一个 object (是否为同一地址)

>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True

>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

Global Variable

放在方法外面的全局变量

primitive:
若想在方法内部调用, 则必须使用 global 关键字
若在方法内部不使用 global 关键字, 就变成在方法内创建一个局部变量了

object:
取值和修改属性值: 不需要任何关键字, 直接调用, 因为是 mutable 的
重新 reference 到另一个 object: 需要使用关键字 global

been_called = False

def example2():
    been_called = True         # WRONG 这只是一个局部变量

def example3():
    global been_called 
    been_called = True       # RIGHT

known = {0:0, 1:1}

def example4():
    known[2] = 1

def example5():
    global known
    known = dict()

max()
参数: 可以是一个list, 也可以是多个参数

>>> max(0,100,5,25,33)
100

>>> max(['a','c','d'])
'd'

enumerate(iterable, start=0)
循环该 iterable, 返回 index 和 element 对应的 tuples

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

>>> list(enumerate(seasons, start=1))
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

lambda expression
格式
lambda<var1>, ..., <varn> : <expr>

>>> f = lambda x: x*x 
>>> f 
<function <lambda> at 0x4ecf0> 
>>> f(4)
>16

>>> g = lambda x,y : x * y
>>> g(3, 4)
>12 

>>> (lambda x,y : x * y) (3, 4)
>12

reduce(function, iterable[, initializer])
把指定 function apply 到 iterable 的每一个 element 上, 最后合称为一个单一的 value
initializer:
   如果 iterable 是空的, 就会把它作为 default 返回
   计算时会把它加到 iterable 的每个 item 前面

reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
# 效果为: ((((1+2)+3)+4)+5)

def isSubset(a, b):
    return reduce(operator.and_, [x in b for x in a])
# 返回一个 boolean 值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值