程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

micropython優雅的兩個小功能塊

編輯:Python

雖然做調庫俠很爽,但是我還是建議大家盡可能寫一寫,看一看小的功能塊,對於提升自己的編程思維和能力非常有幫助,而且如果做得夠優雅是很爽快的!
功能1:
尋找兩個置頂字符串之間的字符
比如chars=‘sdf#1234,[email protected]’
只想提取#和,之間的1234,怎麼做?
萬能的正則表達式,一定能做到,也許有其他的庫也可以,但是何不嘗試自己寫一個呢?
上核心代碼:

clist=[]
mark=0
text='sdf#1234,[email protected]'
for ch in text:
if ch=='#':
mark+=1
elif ch==',':
mark-=1
else:
if mark:
clist.append(ch)
result=''.join(clist)

加個標志為,開始結尾拿捏,搞定!學到了
功能2:
求兩個坐標矩形相交的面積
聽上去是不像個有點復雜的數據問題?也許cv2或者某個庫裡有此功能,但自己嘗試寫一個真的很難嗎?
上代碼:

def Returns_Coordinates(left_1,right_1,left_2,right_2): # left_1 right_1 block
coord = []
left_h = 0
left_w = 0
right_h = 0
right_w = 0
height = min(right_1[0],right_2[0])-max(left_1[0],left_2[0])
width = min(right_1[1],right_2[1])-max(left_1[1],left_2[1])
if height > 0 and width > 0 :
if left_2[0] <= left_1[0] and left_2[1] <= left_1[1] :
left_h = 0
left_w = 0
elif left_2[0] >= left_1[0] and left_2[1] <= left_1[1] :
left_h = left_2[0] - left_1[0]
left_w = 0
elif left_2[0] >= left_1[0] and left_2[1] >= left_1[1] :
left_h = left_2[0] - left_1[0]
left_w = left_2[1] - left_1[1]
else :
left_h = 0
left_w = left_2[1] - left_1[1]
right_h = left_h + height
right_w = left_w + width
coord.append(left_h)
coord.append(left_w)
coord.append(right_h)
coord.append(right_w)
return coord

想通了就不難,就是個比較,然後進階想做一個,計算一個矩形跟多個矩形交集的總面積的,奧利給,動腦筋想就完了!


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved