Python学习笔记(1)

1. 求50到100之间的素数

import math

for i in range(50,100+1):
    for j in range(2,int(math.sqrt(i))+1):
        if i%j==0:
            break
    else:
        print(i)
View Code

2. 求一元二次方程的解:ax2+bx+c=0

import math
def quad(a,b,c):
    if not isinstance(a,(int,float)) and isinstance(b,(int,float)) and isinstance(c,(int,float)):
        raise TypeError('bad operand type')
        return 'ABC\'re Error'
    else:
        if a==0 and b!=0:
            return (-c)/b
        elif a==0 and b==0:
            return 'ABC\'re Error'
        else:
            m=b*b-4*a*c
            if m>=0:
                x1=(-b+math.sqrt(m))/(2*a)
                x2=(-b-math.sqrt(m))/(2*a)
                if x1==x2:
                    return x1
                else:
                    return x1,x2
            else:
                return complex((-b)/(2*a),(math.sqrt(-m))/(2*a)),complex((-b)/(2*a),-(math.sqrt(-m))/(2*a))

a=int(input('plz input a:'))
b=int(input('plz input b:'))
c=int(input('plz input c:'))
s=quad(a,b,c)
print(s)
View Code

3. 关于输入函数【input()】的一些转化

 (python3.x的input(prompt)返回的是一个字符串,涉及计算的时候就会出错)

a=input('plz input a number:')
print(a) #you will see a string,even....!

a=int(input('plz input a number:'))
print(a) #you will see an integer!

a=float(input('plz input a number:'))
print(a) #you will see a float!

a=eval(input('plz input a number:'))
print(a) #you will see a number!
View Code

针对eval()的利弊,参见

4. 解决汉诺塔的递归函数

1 def move(n,a,b,c):
2     if n==1:
3         print(a,'--->',c)
4     else:
5         move(n-1,a,c,b)
6         move(1,a,b,c)
7         move(n-1,b,a,c)
8 n=input('enter the number:')
9 move(int(n),'A','B','C')
View Code

 5. List、tuple、String的切片操作

可以这样理解切片的位置与数量:

L[n:m]=[L[n],L[n+1],L[n+2],……,L[m-1]],数量是m-n个。例如:L[-2:-1]=[ L[-2] , L[-1-1]]=L[-2], 数量就是-1-(-2)=1个。

 1 L = list(range(1,100+1))
 2 print(L)
 3 print(L[10])
 4 print(L[0:10])
 5 print(L[2:10])
 6 print(L[10:20])
 7 print(L[-10:])
 8 print(L[-10:0])
 9 print(L[-10:-1])
10 print(L[0:10:2])
11 print(L[0:99:5])
12 print(L[::5])
13 print(L[:])
14 print('='*10)
15 print((0,1,2,3,4)[:3])
16 print('ABCDEF'[:3])
17 print('ABCDEF'[::2])
View Code

6. 斐波拉契数列

 1 def fib(max):
 2     n,a,b=0,0,1
 3     L=[]
 4     while n<max:
 5         L.append(b)
 6         a,b=b,a+b
 7         n=n+1
 8     return L
 9 
10 print(fib(10))
View Code

7. 【杨辉三角】列表生成器

def Ytriangles():
    a=[1]
    while True:
        yield a
        a=[sum(i) for i in zip([0]+a,a+[0])]
n=1
for t in Ytriangles():
    print(t)
    n=n+1
    if n==10:
        break
View Code

 8.(数字型)字符串转化为整数

 1 from functools import reduce
 2 
 3 def str2int(s):
 4     def fn(x,y):
 5         return x*10+y
 6     def char2num(s):
 7         return {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,}[s]
 8     return reduce(fn,map(char2num,s))
 9 
10 print(str2int('1234'))
11  
View Code

 

posted on 2015-06-12 23:07  那然那佛  阅读(235)  评论(0编辑  收藏  举报

导航