學習編程、學習Python最好的方式就是練習,哪怕是新手,只要不斷地敲代碼輸出,肯定會有神效。
Python的練手項目很多,特別是Github上,建議不管新手、老司機都去看看。
這裡推薦給大家兩個Github上練習的項目,算法倉庫-algorithms和腳本倉庫-Python master。
後文會有相應源代碼集打包下載,給需要的小伙伴。
首先來看看算法倉庫-algorithms。
這裡面集合眾多核心算法的Python實現,比如排序、圖計算、回溯、隊列、流計算、堆、搜索、壓縮等等。
該倉庫支持第三方庫安裝,在python中進行調用,非常方便。
首先使用pip進行安裝:
pip3 install algorithms
然後導入相關模塊進行調用,比如sort模塊裡的merge_sort歸並排序算法。
from algorithms.sort import merge_sort
if __name__ == "__main__":
my_list = [1, 8, 3, 5, 6]
my_list = merge_sort(my_list)
print(my_list)
個人感覺這個倉庫裡的算法很齊全,適合做練習,小伙伴們可以試試。
所有算法腳本已經打包好,獲取步驟如下:
1,點擊下方公眾號 數據STUDIO 名片
2,關注 數據STUDIO後,在消息後台回復 b
▲點擊關注「數據STUDIO」回復b
另外,@公眾號:數據STUDIO 還為大家整理和篩選了大量火爆全網的Python數據科學學習資料,全部資料按需自助免費獲取!直接點擊鏈接:
火爆全網的Python數據科學手冊,太有用了
復旦學子《可解釋機器學習》中文版完整PDF下載!
700頁的機器學習筆記火了!完整版開放下載
另外還有一個很好的練手項目,腳本倉庫-Python master。
這個項目收集了作者平時工作用到的幾千個實用小腳本,作者雖然不是程序員,但他這種用代碼解決問題的習慣會極大的提升效率,也會迸發出更多的創新思維。
我覺得這樣的代碼每個人都可以寫出來,只要慢慢積累多練習就可以。
舉一個簡單的例子,作者寫了一個創建二維碼的腳本,可以自動將url轉化為二維碼。
import pyqrcode
import png
from pyqrcode import QRCode
# Text which is to be converted to QR code
print("Enter text to convert")
s = input(": ")
# Name of QR code png file
print("Enter image name to save")
n = input(": ")
# Adding extension as .pnf
d = n + ".png"
# Creating QR code
url = pyqrcode.create(s)
# Saving QR code as a png file
url.show()
url.png(d, scale=6)
除此之外,該倉庫中還有很多這樣實用的腳本文件。
所有算法腳本已經打包好,獲取步驟如下:
1,點擊下方公眾號 數據STUDIO 名片
2,關注 數據STUDIO後,在消息後台回復 d
▲點擊關注「數據STUDIO」回復d
另外,@公眾號:數據STUDIO 還為大家整理和篩選了大量火爆全網的Python數據科學學習資料,全部資料按需自助免費獲取!直接點擊鏈接:
火爆全網的Python數據科學手冊,太有用了
復旦學子《可解釋機器學習》中文完整PDF下載!
700頁的機器學習筆記火了!完整版開放下載
接下來,展示一些更多的代碼案例,供大家參考。
# extract text from a img and its coordinates using the pytesseract module
import cv2
import pytesseract
# You need to add tesseract binary dependency to system variable for this to work
img = cv2.imread("img.png")
# We need to convert the img into RGB format
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
hI, wI, k = img.shape
print(pytesseract.image_to_string(img))
boxes = pytesseract.image_to_boxes(img)
for b in boxes.splitlines():
b = b.split(" ")
x, y, w, h = int(b[1]), int(b[2]), int(b[3]), int(b[4])
cv2.rectangle(img, (x, hI - y), (w, hI - h), (0, 0, 255), 0.2)
cv2.imshow("img", img)
cv2.waitKey(0)
def is_leap(year):
leap = False
if year % 4 == 0:
leap = True
if year % 100 == 0:
leap = False
if year % 400 == 0:
leap = True
return leap
year = int(input("Enter the year here: "))
print(is_leap(year))
def jpeg_res(filename):
""""This function prints the resolution of the jpeg image file passed into it"""
# open image for reading in binary mode
with open(filename,'rb') as img_file:
# height of image (in 2 bytes) is at 164th position
img_file.seek(163)
# read the 2 bytes
a = img_file.read(2)
# calculate height
height = (a[0] << 8) + a[1]
# next 2 bytes is width
a = img_file.read(2)
# calculate width
width = (a[0] << 8) + a[1]
print("The resolution of the image is",width,"x",height)
jpeg_res("img1.jpg")
def bucket_sort(arr):
''' Bucket Sort
Complexity: O(n^2)
The complexity is dominated by nextSort
'''
# The number of buckets and make buckets
num_buckets = len(arr)
buckets = [[] for bucket in range(num_buckets)]
# Assign values into bucket_sort
for value in arr:
index = value * num_buckets // (max(arr) + 1)
buckets[index].append(value)
# Sort
sorted_list = []
for i in range(num_buckets):
sorted_list.extend(next_sort(buckets[i]))
return sorted_list
def next_sort(arr):
# We will use insertion sort here.
for i in range(1, len(arr)):
j = i - 1
key = arr[i]
while arr[j] > key and j >= 0:
arr[j+1] = arr[j]
j = j - 1
arr[j + 1] = key
return arr
import math
def distance(x,y):
"""[summary]
HELPER-FUNCTION
calculates the (eulidean) distance between vector x and y.
Arguments:
x {[tuple]} -- [vector]
y {[tuple]} -- [vector]
"""
assert len(x) == len(y), "The vector must have same length"
result = ()
sum = 0
for i in range(len(x)):
result += (x[i] -y[i],)
for component in result:
sum += component**2
return math.sqrt(sum)
def nearest_neighbor(x, tSet):
"""[summary]
Implements the nearest neighbor algorithm
Arguments:
x {[tupel]} -- [vector]
tSet {[dict]} -- [training set]
Returns:
[type] -- [result of the AND-function]
"""
assert isinstance(x, tuple) and isinstance(tSet, dict)
current_key = ()
min_d = float('inf')
for key in tSet:
d = distance(x, key)
if d < min_d:
min_d = d
current_key = key
return tSet[current_key]
# Implement the encode and decode methods.
def encode(strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
res = ''
for string in strs.split():
res += str(len(string)) + ":" + string
return res
def decode(s):
"""Decodes a single string to a list of strings.
:type s: str
:rtype: List[str]
"""
strs = []
i = 0
while i < len(s):
index = s.find(":", i)
size = int(s[i:index])
strs.append(s[index+1: index+1+size])
i = index+1+size
return strs
def get_histogram(input_list: list) -> dict:
"""
Get histogram representation
:param input_list: list with different and unordered values
:return histogram: dict with histogram of input_list
"""
# Create dict to store histogram
histogram = {}
# For each list value, add one to the respective histogram dict position
for i in input_list:
histogram[i] = histogram.get(i, 0) + 1
return histogram
個人感覺這兩個倉庫裡的算法和腳本很齊全,適合做練習,小伙伴們可以試試。
所有算法腳本已經打包好,獲取步驟如下:
1,點擊下方公眾號 數據STUDIO 名片
2,關注 數據STUDIO後,在消息後台回復 b 或者 d
▲點擊關注「數據STUDIO」回復b 或者 d
另外,@公眾號:數據STUDIO 還為大家整理和篩選了大量火爆全網的Python數據科學學習資料,全部資料按需自助免費獲取!直接點擊鏈接:
火爆全網的Python數據科學手冊,太有用了
復旦學子《可解釋機器學習》中文完整PDF下載!
700頁的機器學習筆記火了!完整版開放下載