程序设计实训(python)
python的一些基础练习,仅供参考。
寻找水仙花数
def narcissistic_number():
narcissistic_list = []
for number in range(100, 1000):
a = int(number / 100)
b = int(number / 10) % 10
c = number % 10
if a ** 3 + b ** 3 + c ** 3 == number:
narcissistic_list.append(number)
return narcissistic_list
print(narcissistic_number())
寻找完美数
def perfect_number(limit=1000):
if type(limit) != int or limit <= 0:
return 'Parameter Error.'
else:
num_list = []
for i in range(1, limit):
sum = 0
for j in range(1, i):
if i % j == 0:
sum = sum + j
if sum == i:
num_list.append(i)
return num_list
pass
百钱百鸡问题
def buy_chicken():
a = []
b = []
for i in range(0, 100):
for j in range(0, 100):
k = 100 - i - j
if k>=0 and k % 3 == 0 and 5 * i + 3 * j + k / 3 == 100:
b = [i, j, k]
a.append(b)
return a
print(buy_chicken())
pass
最大公约数和最小公倍数
def gcd(x, y):
gcd = []
if type(x) == int and type(y) == int and x > 0 and y > 0:
for i in range(1, x + 1):
if x % i == 0:
if y % i == 0:
gcd.append(i)
return gcd[-1]
else:
return ('Parameter Error.')
pass
def lcm(x, y):
if type(x) == int and type(y) == int and x > 0 and y > 0:
m = gcd(x, y)
n = (x * y) / m
return int(n)
else:
return ('Parameter Error.')
pass
回文数
def is_palindrome_number(num):
zhengxu = str(num)
daoxu = zhengxu[::-1]
if(zhengxu == daoxu):
return(True)
else:
return(False)
pass
素数
def is_prime_num(num):
if num <= 0 or type(num) != int:
return "Parameter Error."
else:
for i in range(2, num):
if num % i == 0:
return False
return True
约瑟夫环问题
def jose_prob(m, n):
if m >= n or not isinstance(n,int)\
or not isinstance(m,int)\
or m <= 0 or n <= 0:
return "Parameter Error."
flag = 9
jose_list = [1 for i in range(0, n)] # 1 live ;0 dead
start = 0
for i in range(0, n - m):
j = 0
k = 0
while j < flag :
if jose_list[(start+k) % n] != 0: # not dead
j += 1
k += 1
dead = (start+k-1)%n
jose_list[dead] = 0
start = dead + 1
return jose_list
pass
万年历
def calendar(year, month, day):
if type(day) == int and type(month) == int and type(year) == int and 0<=month<=12 and year>=1 and 0<=day<=31:
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
runnian = 1
else:
runnian = 0
month_30 = [4, 6, 9, 11]
if (month in month_30 and day == 31 ) or (month == 2 and (day > 29 if runnian else day > 28)):
return "Parameter Error."
month_day = [31,28,31,30,31,30,31,31,30,31,30,31]
sum = 0;
for i in range(0,month-1):
sum += month_day[i]
sum += day
if month > 2 and runnian==1:
sum += 1
return sum
else:
return "Parameter Error."
pass
两地之间距离计算
# 计算两点p1, p2之间的距离
# p1:(纬度、经度)
# p2: (纬度、经度)
def sphere_distance(p1, p2):
EARTH_RADIUS = 6371 # 地球平均半径,6371km
def wrong_parameter(p):
if len(p) == 2 and 0 <= p[0] <= 90 and 0 <= p[1] <= 180:
return 1
return 0
if not (wrong_parameter(p1) and wrong_parameter(p2)):
return "Parameter Error."
a = 2
rad = math.pi / 180
tmp_1 = [x * rad for x in p1]
tmp_2 = [x * rad for x in p2]
phi_1, lam_1 = tmp_1
phi_2, lam_2 = tmp_2
distance = math.sin((phi_2 - phi_1) / 2) ** 2 \
+ math.cos(phi_1) * math.cos(phi_2) * (math.sin((lam_2 - lam_1) / 2) ** 2)
distance = 2 * EARTH_RADIUS * math.asin(math.sqrt(distance))
return round(distance, a)
计算 Fibonacci 序列的值
# Fibonacci是1,1, 2,3,5, 8,13.....
# n1 = 1, n2 =2, n3 = n1+n2, n4 = n3+n2
import sys
def fibonacci_recursion(number):
if type(number) != int or number <= 0:
return "Parameter Error."
else:
if sys.getrecursionlimit() < number:
sys.setrecursionlimit(number)
if number == 1 or number == 2:
return 1
else:
return fibonacci_recursion(number - 2) + fibonacci_recursion(number - 1)
def fibonacci_loop(number):
if type(number) != int or number <= 0:
return "Parameter Error."
else:
if 1 == number or 2 == number:
return 1
a = 0
b = 1
c = 1
for i in range(number - 2):
a = b
b = c
c = a + b
return c
pass
摩斯码生成器
def morse_code(usr_str):
CODE = {'A': '. -', 'B': '- . . .', 'C': '- . - .',
'D': '- . .', 'E': '.', 'F': '. . - .',
'G': '- - .', 'H': '. . . .', 'I': '. .',
'J': '. - - -', 'K': '- . -', 'L': '. - . .',
'M': '- -', 'N': '- .', 'O': '- - -',
'P': '. - - .', 'Q': '- - . -', 'R': '. - .',
'S': '. . .', 'T': '-', 'U': '. . -',
'V': '. . . -', 'W': '. - -', 'X': '- . . -',
'Y': '- . - -', 'Z': '- - . .',
'0': '- - - - -', '1': '. - - - -', '2': '. . - - -',
'3': '. . . - -', '4': '. . . . -', '5': '. . . . .',
'6': '- . . . .', '7': '- - . . .', '8': '- - - . .',
'9': '- - - - .'
}
length = len(usr_str)
count = 0
s = ''
usr_str = usr_str.upper()
for item in usr_str:
count += 1
if item ==' ':
s += ' '
else:
if count == length:
s += CODE[item]
else:
s = s + CODE[item] + ' '
return s
pass
词频统计
def word_freq(path):
sight_word = "a and away big blue can come down find for funny go help here I in is it jump little look make me my not one play red run said see the three to two up we where yellow you all am are at ate be black brown but came did do eat four get good have he into like must new no now on our out please pretty ran ride saw say she so soon that there they this too under want was well went what white who will with yes after again an any ask as by could every fly from give going had has her him his how just know let live may of old once open over put round some stop take thank them then think walk were when always around because been before best both buy call cold does don't fast first five found gave goes green its made many off or pull read right sing sit sleep tell their these those upon us use very wash which why wish work would write your about better bring carry clean cut done draw drink eight fall far full got grow hold hot hurt if keep kind laugh light long much myself never only own pick seven shall show six small start ten today together try warm"
sight_word = sight_word.lower()
sight_word_list = sight_word.split()
with open(path) as f:
text = f.read()
lst = re.findall(r'[a-z\'0-9—“”]+', text.lower())
lst = [i.lower() for i in lst if i and i.lower() not in sight_word_list]
dic = {}
for i in lst:
if i in dic:
dic[i] += 1
else:
dic[i] = 1
result = sorted(dic.items(), key=lambda x:(x[1], x[0]), reverse=True)
return result[:10]
pass
C 程序文件处理
import os
def filter_c_file(dir_path):
# 遇到快注释的标志
sign = False
fp = os.listdir(dir_path)
new_fp = []
for item in fp:
if item.endswith('.c') or item.endswith('.cpp'):
new_fp.append(item)
for index, item in enumerate(new_fp):
# if not index:
# continue
result_list = []
with open(os.path.join(dir_path, item), encoding='gb18030',errors="ignore") as f:
for line in f:
if sign:
if '*/' in line:
sign = False
continue
l_index = line.find('"')
r_index = line.rfind('"')
# if l_index != -1 and r_index != -1:
if '#include' in line:
index = line.find('#include')
if l_index> index or index > r_index:
line = line[:index]
if '//' in line:
index = line.find('//')
if l_index > index or index > r_index:
line = line[:index]
if '/*' in line:
index = line.find('/*')
if l_index > index or index > r_index:
if '*/' not in line:
sign = True
line = line[:index]
result_list.append(''.join(line.strip().split()))
new_text = ''.join(result_list)
item_path = os.path.join(dir_path, item.split(".")[0] + ".txt")
with open(item_path, 'w') as f:
f.write(new_text)
敏感词过滤
def filter_words(user_input):
try:
sens_str = open(r'..\ProblemSets\RefCode\ExCode\testCase\testData\sensitive.txt').read()
except FileNotFoundError:
sens_str = ["哇哈哈","变态","可怕","gay","丽日御茶子","卓小由"]
j = 0
words = user_input
while (j < len(sens_str)):
n = len(sens_str[j])
m = re.sub(sens_str[j], '*' * n, words)
words = m
j += 1
return words
pass
Base64 编解码算法
import base64
from io import BytesIO
import math
import time
def b64en(path_in, path_out):
IM = open(path_in,'rb')
STRING = base64.b64encode(IM.read())
IM.close()
with open(path_out, 'wb') as OBJ:
OBJ.write(STRING)
def b64de(path_in, path_out):
base_64 = ['A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'+', '/']
with open(path_in,'r') as file:
STRING = file.read()
N = []
for k in STRING:
if k == '=':
continue
N.append(base_64.index(k))
BITES = []
for i in N:
bit = bin(i)
bit = bit.replace('0b','')
bit_new = bit.rjust(6,'0')
BITES.append(bit_new)
L = []
bite_0 = ''.join(BITES)
while len(bite_0) >= 8 :
UN = bite_0[0:8]
L.append(int(UN,2))
bite_0 = bite_0[8:]
bytes_L = bytes(L)
with open(path_out,'wb') as OBJ:
OBJ.write(bytes_L)
计算图形面积及周长
import math
class Shape(object):
def __init__(self):
self.perimeter = 0
self.area = 0
self.name = None
def cal_perimeter(self):
pass
def cal_area(self):
pass
def display(self):
print('名称:' + self.name)
print('面积:' + str(self.area))
print('周长:' + str(self.perimeter))
class Rectangle(Shape):
def __init__(self, n, a, b):
super().__init__()
self.name = n
self.a = a
self.b = b
def cal_area(self):
self.area = round(self.a * self.b, 2)
return self.area
def cal_perimeter(self):
self.perimeter = round(2 * (self.a + self.b), 2)
return self.perimeter
class Triangle(Shape):
def __init__(self, n, a, b, c):
super().__init__()
self.name = n
self.a = a
self.b = b
self.c = c
def cal_area(self):
self.cal_perimeter()
h = self.perimeter / 2
self.area = math.sqrt(h * (h - self.c) * (h - self.b) * (h - self.a))
self.area = round(self.area, 2)
return self.area
def cal_perimeter(self):
self.perimeter = self.a + self.b + self.c
self.perimeter = round(self.perimeter, 2)
return self.perimeter
class Circle(Shape):
def __init__(self, n, a):
super().__init__()
self.name = n
self.a = a
def cal_area(self):
self.area = round(3.14 * self.a ** 2, 2)
return self.area
def cal_perimeter(self):
self.perimeter = round(2 * 3.14 * self.a, 2)
return self.perimeter
XML 文件的生成与解析
import os
from xml.dom import minidom
try:
import xml.etree.cElementTree as et
except ImportError:
import xml.etree.ElementTree as et
# 题目:XML文件的生成和解析
def create_xml(path):
# 创建DOM树对象
dom = minidom.Document()
# 设置tilemap
tilemap = dom.createElement('tilemap')
dom.appendChild(tilemap)
tilemap.setAttribute('tilemapservice', 'http://tms.osgeo.org/1.0.0')
tilemap.setAttribute('version', '1.0.0')
# 设置title
title = dom.createElement('title')
title_text = dom.createTextNode('default')
title.appendChild(title_text)
tilemap.appendChild(title)
# 设置abstract
abstract = dom.createElement('abstract')
tilemap.appendChild(abstract)
# 设置srs
srs = dom.createElement('srs')
srs_text = dom.createTextNode('EPSG:4326')
srs.appendChild(srs_text)
tilemap.appendChild(srs)
# 设置vsrs
vsrs = dom.createElement('vsrs')
tilemap.appendChild(vsrs)
# 设置boundingbox
boundingbox = dom.createElement('boundingbox')
boundingbox.setAttribute('maxx', '180.0')
boundingbox.setAttribute('maxy', '90.0')
boundingbox.setAttribute('minx', '-180.0')
boundingbox.setAttribute('miny', '-90.0')
tilemap.appendChild(boundingbox)
# 设置origin
origin = dom.createElement('origin')
origin.setAttribute('x', '-180.0')
origin.setAttribute('y', '-90.0')
tilemap.appendChild(origin)
# 设置tileformat
tileformat = dom.createElement('tileformat')
tileformat.setAttribute('extension', 'tif')
tileformat.setAttribute('height', '17')
tileformat.setAttribute('mime-type', 'image/tiff')
tileformat.setAttribute('width', '17')
tilemap.appendChild(tileformat)
# 设置tilesets
tilesets = dom.createElement('tilesets')
tilesets.setAttribute('profile', 'global-geodetic')
pixel = ['10.588', '5.294', '2.647', '1.323', '0.661', '0.331']
for order in range(6):
tileset = dom.createElement('tileset')
tileset.setAttribute('href', '')
tileset.setAttribute('order', str(order))
tileset.setAttribute('units-per-pixel', pixel[order])
tilesets.appendChild(tileset)
tilemap.appendChild(tilesets)
with open(path, 'w') as fh:
dom.writexml(fh, indent='', addindent='\t', newl='\n')
def parse_xml(path):
tree = et.parse(path)
tilemap = tree.getroot()
tilemap_service = tilemap.attrib.get('tilemapservice')
for child in tilemap:
if child.tag == 'title':
title = child.text
elif child.tag == 'tilesets':
num = 0
max_order = None
for tileset in child:
num += 1
order = int(tileset.attrib.get('order'))
if max_order is None:
max_order = order
else:
if order > max_order:
max_order = order
return {'tilemap service': tilemap_service, 'title': title, 'tileset count': num, 'tileset max': max_order}
二进制数据报文构建与解析
def pack_message(data_dict):
try:
fmt = '>b b 16s i i b'
return struct.pack(fmt, data_dict['type'], data_dict['csum'],
data_dict['id'].encode('utf-8'), data_dict['dis1'],
data_dict['dis2'], data_dict['count'])
except:
return "Parameter Error."
def unpack_message(message):
try:
result = {}
fmt = '>b b 16s i i b'
result['type'], result['csum'], result['id'], result['dis1'], result[
'dis2'], result['count'] = struct.unpack(fmt, message)
result['id'] = result['id'].decode('utf-8')
return result
except:
return "Parameter Error."
实现数据库的操作
# 题目:实现数据库的操作
import sqlite3
import os
db_hw_db_path = "./test.db" # 全局变量,在create_db(path)时记录创建的数据库所在路径
def create_db(path):
global db_hw_db_path
db_hw_db_path = path
con = sqlite3.connect(path)
cur = con.cursor()
sql1 = """
CREATE TABLE Position
(POSITIONID VARCHAR PRIMARY KEY,
SALARY INTEGER NOT NULL);
"""
sql2 = """
CREATE TABLE Person
(NAME VARCHAR NOT NULL,
GENDER VARCHAR NOT NULL,
BIRTH VARCHAR NOT NULL,
ID VARCHAR PRIMARY KEY,
POSITIONID VARCHAR,
FOREIGN KEY (POSITIONID) REFERENCES Position(POSITIONID)
);
"""
sql3 = 'insert into Position values(?,?);'
try:
cur.execute(sql1)
cur.execute(sql2)
cur.executemany(sql3, [('A', 10000), ('B',6000), ('C', 3000), ('D', 1000)])
con.commit()
except Exception as e:
print(e)
return -1
else:
return 0
finally:
cur.close()
con.close()
# 使用Insert语句
def new_employee(person,level):
con = sqlite3.connect(db_hw_db_path)
cur = con.cursor()
sql = 'insert into Person values(?,?,?,?,?);'
try:
cur.execute(sql, person+(level,))
con.commit()
except Exception as e:
print(e)
return -1
else:
return 0
finally:
cur.close()
con.close()
# 使用Delete语句
def delete_employee(person):
con = sqlite3.connect(db_hw_db_path)
cur = con.cursor()
sql = f'delete from Person where ID={person};'
try:
cur.execute(sql)
con.commit()
except Exception as e:
print(e)
return -1
else:
return 0
finally:
cur.close()
con.close()
# 使用Update语句
def set_level_salary(level,salary):
if level not in ['A', 'B', 'C', 'D'] or not isinstance(salary, int):
return -1
con = sqlite3.connect(db_hw_db_path)
cur = con.cursor()
sql = f'update Position set SALARY={salary} where POSITIONID="{level}";'
try:
cur.execute(sql)
con.commit()
except Exception as e:
print(e)
return -1
else:
return 0
finally:
cur.close()
con.close()
# 使用Select查询语句
def get_total_salary():
con = sqlite3.connect(db_hw_db_path)
cur = con.cursor()
sql = 'SELECT SALARY from Person,Position where Person.POSITIONID = Position.POSITIONID;'
try:
cur.execute(sql)
ret = cur.fetchall()
except Exception as e:
print(e)
return -1
else:
return sum([i[0] for i in ret])
finally:
cur.close()
con.close()
if __name__ == "__main__":
create_db('./test.db')
new_employee(("tom","m","2018-09-01","123456789"),"A")
new_employee(("too","f","2017-09-01","123456788"),"B")
print(get_total_salary())
delete_employee("123456788")
print(get_total_salary())
print(set_level_salary("A",2))
print(get_total_salary())
爬虫
import time
import requests
from bs4 import BeautifulSoup
def crawler(book_list):
sort_list = []
for page in range(1, 6): # 目前排行榜只有5页
print(page)
url = f'https://www.qidian.com/rank/yuepiao?style=1&page={page}'
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.66 Safari/537.36'
}
ret = requests.get(url, headers=headers).text
soup = BeautifulSoup(ret, "html.parser")
books = soup.find_all(**{'data-eid': "qd_C40"})
for book in books:
book_name = book.get_text()
if book_name in book_list:
sort_list.append(book_name)
return {book_name:index+1 for index, book_name in enumerate(sort_list)}
if __name__ == '__main__':
book_list = ["三寸人间", "烂柯棋缘", "轮回乐园"]
print(crawler(book_list))