1. 統計字串裏的字母個數:四種方法
string = "Hann Yang's id: boysoft2002"
print( sum(map(lambda x:x.isalpha(),string)) )
print( len([*filter(lambda x:x.isalpha(),string)]) )
print( sum(['a'<=s.lower()<='z' for s in string]) )
import re
print( len(re.findall(r'[a-z]', string, re.IGNORECASE)) )
2. 一行代碼求水仙花數
[*filter(lambda x:x==sum(map(lambda n:int(n)**3,str(x))),range(100,1000))]
增強型水仙花:一個整數各比特數字的該整數比特數次方之和等於這個整數本身。如:
1634 == 1^4 + 6^4 + 3^4 + 4^4
92727 == 9^5 + 2^5 + 7^5 + 2^5+7^5
548834 == 5^6 + 4^6 + 8^6+ 8^6+ 3^6 + 4^6
求3~7比特水仙花數,用了81秒:
[*filter(lambda x:x==sum(map(lambda n:int(n)**len(str(x)),str(x))),range(100,10_000_000))]
# [153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725, 4210818, 9800817, 9926315]
不要嘗試計算7比特以上的,太耗時了。我花了近15分鐘得到3個8比特水仙花數:
>>> t=time.time();[*filter(lambda x:x==sum(map(lambda n:int(n)**len(str(x)),str(x))),range(10_000_000,100_000_000))];print(time.time()-t)
[24678050, 24678051, 88593477]
858.7982144355774
3. 字典的快捷生成、鍵值互換、合並:
>>> dict.fromkeys('abcd',0) # 只能設置一個默認值
{'a': 0, 'b': 0, 'c': 0, 'd': 0}
>>> d = {}
>>> d.update(zip('abcd',range(4)))
>>> d
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
>>> d = dict(enumerate('abcd'))
>>> d
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}
>>> dict(zip(d.values(), d.keys()))
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
>>> dict([v,k] for k,v in d.items())
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
>>> d1 = dict(zip(d.values(), d.keys()))
>>>
>>> d = dict(enumerate('cdef'))
>>> d2 = dict(zip(d.values(), d.keys()))
>>> d2
{'c': 0, 'd': 1, 'e': 2, 'f': 3}
>>>
>>> {**d1, **d2}
{'a': 0, 'b': 1, 'c': 0, 'd': 1, 'e': 2, 'f': 3}
>>> {**d2, **d1}
{'c': 2, 'd': 3, 'e': 2, 'f': 3, 'a': 0, 'b': 1}
# 合並時以前面的字典為准,後者也有的鍵會被覆蓋,沒有的追加進來
4. 字典的非覆蓋合並: 鍵重複的值相加或者以元組、集合存放
dicta = {"a":3,"b":20,"c":2,"e":"E","f":"hello"}
dictb = {"b":3,"c":4,"d":13,"f":"world","G":"gg"}
dct1 = dicta.copy()
for k,v in dictb.items():
dct1[k] = dct1.get(k,0 if isinstance(v,int) else '')+v
dct2 = dicta.copy()
for k,v in dictb.items():
dct2[k] = (dct2[k],v) if dct2.get(k) else v
dct3 = {k:{v} for k,v in dicta.items()}
for k,v in dictb.items():
dct3[k] = set(dct3.get(k))|{v} if dct3.get(k) else {v} # 並集運算|
print(dicta, dictb, sep='\n')
print(dct1, dct2, dct3, sep='\n')
'''
{'a': 3, 'b': 20, 'c': 2, 'e': 'E', 'f': 'hello'}
{'b': 3, 'c': 4, 'd': 13, 'f': 'world', 'G': 'gg'}
{'a': 3, 'b': 23, 'c': 6, 'e': 'E', 'f': 'helloworld', 'd': 13, 'G': 'gg'}
{'a': 3, 'b': (20, 3), 'c': (2, 4), 'e': 'E', 'f': ('hello', 'world'), 'd': 13, 'G': 'gg'}
{'a': {3}, 'b': {3, 20}, 'c': {2, 4}, 'e': {'E'}, 'f': {'world', 'hello'}, 'd': {13}, 'G': {'gg'}}
'''
5. 三邊能否構成三角形的判斷:
# 傳統判斷: if a+b>c and b+c>a and c+a>b:
a,b,c = map(eval,input().split())
p = (a+b+c)/2
if p > max([a,b,c]):
s = (p*(p-a)*(p-b)*(p-c))**0.5
print('{:.2f}'.format(s))
else:
print('不能構成三角形')
#或者寫成:
p = a,b,c = [*map(eval,input().split())]
if sum(p) > 2*max(p):
p = sum(p)/2
s = (p*(p-a)*(p-b)*(p-c))**0.5
print('%.2f' % s)
else:
print('不能構成三角形')
6. Zen of Python的單詞中,詞頻排名前6的畫出統計圖
import matplotlib.pyplot as plt
from this import s,d
import re
plt.rcParams['font.sans-serif'] = ['SimHei'] #用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus'] = False #用來正常顯示負號
dat = ''
for t in s: dat += d.get(t,t)
dat = re.sub(r'[,|.|!|*|\-|\n]',' ',dat) #替換掉所有標點,縮略語算一個詞it's、aren't...
lst = [word.lower() for word in dat.split()]
dct = {word:lst.count(word) for word in lst}
dct = sorted(dct.items(), key=lambda x:-x[1])
X,Y = [k[0] for k in dct[:6]],[v[1] for v in dct[:6]]
plt.figure('詞頻統計',figsize=(12,5))
plt.subplot(1,3,1) #子圖的行列及序號,排兩行兩列則(2,2,1)
plt.title("折線圖")
plt.ylim(0,12)
plt.plot(X, Y, marker='o', color="red", label="圖例一")
plt.legend()
plt.subplot(1,3,2)
plt.title("柱狀圖")
plt.ylim(0,12)
plt.bar(X, Y, label="圖例二")
plt.legend()
plt.subplot(1,3,3)
plt.title("餅圖")
exp = [0.3] + [0.2]*5 #離圓心比特置
plt.xlim(-4,4)
plt.ylim(-4,8)
plt.pie(Y, radius=3, labels=X, explode=exp,startangle=120, autopct="%3.1f%%", shadow=True, counterclock=True, frame=True)
plt.legend(loc="upper right") #圖例比特置右上
plt.show()
matplotlib.pyplot.pie 參數錶
Python 在問答頻道中刷題積累到的小技巧(一)
https://hannyang.blog.csdn.net/article/details/124935045
Python 在問答頻道中刷題積累到的小技巧(二)
https://hannyang.blog.csdn.net/article/details/125026881
Python 在問答頻道中刷題積累到的小技巧(三)
https://hannyang.blog.csdn.net/article/details/125058178
Python 在問答頻道中刷題積累到的小技巧(四)
https://hannyang.blog.csdn.net/article/details/125211774
Python 在問答頻道中刷題積累到的小技巧(五)
https://hannyang.blog.csdn.net/article/details/125270812