實現的簡單python例子
阿新 • • 發佈:2019-01-08
本人學python沒多久,不足的望指點
1.輸入三個變數,然後按小到大輸出
x = int(input('please input x:'))
y = int(input('please input y:'))
z = int(input('please input z:'))
if x > y :
x, y = y, x
if x > z :
x, z = z, x
if y > z :
y, z = z, y
print(x,y,z)
2.求101-200的素數from math import sqrt def isprime(n): k = int(sqrt(n)) for i in range(2,k+1): if n % i == 0: return 0 return 1 if __name__ == '__main__': for n in range(101, 201): if isprime(n) ==1: print(n, end = ' ')
版本二:
<pre name="code" class="python">n = int(input('please input n:'))
for i in range(2,n+1):
j = i
for j in range(2,n):
if i % j ==0:
break
if j == i :
print(i,end=' ')
3.水仙花
for i in range(100,1000): a = i%10 b = i%100//10 c = i//100 if a**3+b**3+c**3 == i: print(i, end=' ')
4.分解質因子
n=int(input('please input n:'))
result=[]
i=2
str1=str(n)+'='
while n>1:
if n%i==0:
n/=i
result.append(str(i))
i -= 1
i +=1
str1+='*'.join(result)
print(str1)
函式版def f(n): result=[] i=2 str1=str(n)+'=' while n>1: if n%i==0: n/=i result.append(str(i)) i -= 1 i +=1 str1+='*'.join(result) return str1 if __name__ == '__main__': for i in range(80,100): print(f(i))
5.統計字串字元個數,空格字元個數,數字字元個數,其他字元個數
import string
s=input('please input string:')
letters = 0
space = 0
digit = 0
others =0
for ch in s:
if ch.isalpha():
letters += 1
elif ch.isspace():
space += 1
elif ch.isdigit():
digit += 1
else:
others += 1
print(letters, space , digit, others)
6.lamba 實現兩數求最值
MAX = lambda x, y:(x>y)*x + (y>x)*y
MIN = lambda x, y:(x<y)*x + (y<x)*y
if __name__ == '__main__':
print('max={0} , min={1}'.format(MAX(10,2), MIN(10,2)))
7.輸入一個整數,如果為奇數那麼sum=1+1/3+.....+1/n
如果為偶數那麼 sum=1/2+1/4+....+1/n
def f(n):
sum=0.0
if n%2 == 1:
for i in range(1, n+1, 2):
sum += 1/i
else:
for i in range(2, n+1, 2):
sum += 1/i
return sum
if __name__ == '__main__':
n=int(input('please input n:'))
print(f(n))
8.查詢一個age最高的name
if __name__ == '__main__':
person = {'shao':23, 'wang':20, 'zhang':21, 'he':22}
flag = 1
maxk=''
for (k, v) in person.items():
if flag == 1:
maxk = k
flag = 0
else:
if person[maxk] < v:
maxk = k
print(maxk, person[maxk])
9.向檔案裡面輸入一串字元
if __name__ == '__main__':
string = input('please input string:')
with open('f:/test.txt', 'a') as file:
file.write(string)
file.close()
10.python 對檔案操作,兩個磁碟檔案A和B,各存放一行字母,要求把這兩個檔案中的資訊合併(按字母順序排序)
import string
if __name__ == '__main__':
with open('f:/A.txt', 'r') as file_A:
stringA=file_A.read()
with open('f:/B.txt', 'r') as file_B:
stringB=file_B.read()
stringA+=stringB
stringA=list(stringA)
stringA.sort()
stringA=''.join(stringA)
with open('f:/C.txt', 'a') as file_C:
file_C.write(stringA)
file_A.close()
file_B.close()
file_C.close()
11.python與json的轉換
class Person(object):
def __init__ (self, name, age):
self.name = name
self.age = age
def __repr__(self):
return 'Person Object name:{0}, age{1}'.format(self.name, self.age)
if __name__ == '__main__':
p=Person('peter', 22)
print(p)
import person
import json
p=person.Person('shao', 22)
def object2dict(obj):
d={}
d['__class__'] = obj.__class__.__name__
d['__module__'] = obj.__module__
d.update(obj.__dict__)
return d
def dict2object(d):
if '__class__ ' in d:
class_name = d.pop('__class__')
module_name = d.pop('__module__')
module = __import__ (module_name)
class_ =getattr(module, class_name)
args = dict((key.encode('ascii'), value) for key, value in d.items())
inst = class_(**args)
else:
inst = d
return inst
d=object2dict(p)
print(d)
o=dict2object(d)
print(o)
12. 正則表示式
好的博文:
計算字串中float資料之和
import re
teststring = '123.33sdhf3424.34fdg323.324'
pattern = re.compile(r'\d+.\d*')
s=pattern.findall(teststring)
print(s)
print(sum([float(var) for var in s]))
正則表示式匹配問題
>>> s = '<html><head><title>Title</title>'
>>> pattern = re.compile('<.*?>')
>>> pattern.findall(s)
['<html>', '<head>', '<title>', '</title>']
>>> re.match('<.*?>',s).span()
(0, 6)
搞清楚貪心匹配與非貪心匹配之間的關係
正則表示式,子串代替問題
import re
p = re.compile('(blue|white|red)')
print(p.sub('colout', 'blue socket and red shoes'))
print(p.sub('colout', 'blue socket and red shoes', count=1))
>>>
colout socket and colout shoes
colout socket and red shoes
13.刪除一個list重複的元素
List=list('sdfhskhdsssssdhkhk')
List.sort()
print(List)
for index in range(len(List)-1, 0, -1):
if List[index] == List[index-1]:
del(List[index])
print(List)
最簡單的
str = 'sdfhskdfsjdfljsdf'
list(set(str))
14.刪除重複的list
z=[ [1,2] , [3,4] , [1,2] , [5,6] , [7,8] , [9,0] , [3,4] , [1,2] , [7,8] ]
z =[ repr(x) for x in z]
z = set(z)
z = [ eval(x) for x in z]
print(z)