程序设计实训(python)

  • 寻找水仙花数
  • 寻找完美数
  • 百钱百鸡问题
  • 最大公约数和最小公倍数
  • 回文数
  • 素数
  • 约瑟夫环问题
  • 万年历
  • 两地之间距离计算
  • 计算 Fibonacci 序列的值
  • 摩斯码生成器
  • 词频统计
  • C 程序文件处理
  • 敏感词过滤
  • Base64 编解码算法
  • 计算图形面积及周长
  • XML 文件的生成与解析
  • 二进制数据报文构建与解析
  • 实现数据库的操作
  • 爬虫

python的一些基础练习,仅供参考。

寻找水仙花数

def narcissistic_number():narcissistic_list = []for number in range(100, 1000):a = int(number / 100)b = int(number / 10) % 10c = number % 10if a ** 3 + b ** 3 + c ** 3 == number:narcissistic_list.append(number)return narcissistic_listprint(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 = 0for j in range(1, i):if i % j == 0:sum = sum + jif sum == i:num_list.append(i)return num_listpass

百钱百鸡问题

def buy_chicken():a = []b = []for i in range(0, 100):for j in range(0, 100):k = 100 - i - jif k>=0 and k % 3 == 0 and 5 * i + 3 * j + k / 3 == 100:b = [i, j, k]a.append(b)return aprint(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.')passdef lcm(x, y):if type(x) == int and type(y) == int and x > 0 and y > 0:m = gcd(x, y)n = (x * y) / mreturn 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 Falsereturn 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 = 9jose_list = [1 for i in range(0, n)] # 1 live ;0 deadstart = 0for i in range(0, n - m):j = 0k = 0while j < flag :if jose_list[(start+k) % n] != 0: # not deadj += 1k += 1dead = (start+k-1)%njose_list[dead] = 0start = dead + 1return jose_listpass

万年历

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 = 1else:runnian = 0month_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 += dayif month > 2 and runnian==1:sum += 1return sumelse:return "Parameter Error."pass

两地之间距离计算


# 计算两点p1, p2之间的距离
# p1:(纬度、经度)
# p2: (纬度、经度)
def sphere_distance(p1, p2):EARTH_RADIUS = 6371  # 地球平均半径,6371kmdef wrong_parameter(p):if len(p) == 2 and 0 <= p[0] <= 90 and 0 <= p[1] <= 180:return 1return 0if not (wrong_parameter(p1) and wrong_parameter(p2)):return "Parameter Error."a = 2rad = math.pi / 180tmp_1 = [x * rad for x in p1]tmp_2 = [x * rad for x in p2]phi_1, lam_1 = tmp_1phi_2, lam_2 = tmp_2distance = 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+n2import sysdef 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 1else: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 1a = 0b = 1c = 1for i in range(number - 2):a = bb = cc = a + breturn cpass

摩斯码生成器


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 = 0s = ''usr_str = usr_str.upper()for item in usr_str:count += 1if item ==' ':s += '    'else:if count == length:s += CODE[item]else:s = s + CODE[item] + '   'return spass

词频统计

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] += 1else:dic[i] = 1result = sorted(dic.items(), key=lambda x:(x[1], x[0]), reverse=True)return result[:10]pass

C 程序文件处理

import osdef filter_c_file(dir_path):# 遇到快注释的标志sign = Falsefp = 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:#     continueresult_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 = Falsecontinuel_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 = Trueline = 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 = 0words = user_inputwhile (j < len(sens_str)):n = len(sens_str[j])m = re.sub(sens_str[j], '*' * n, words)words = mj += 1return wordspass

Base64 编解码算法


import base64
from io import BytesIO
import math
import timedef 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 == '=':continueN.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 = 0self.area = 0self.name = Nonedef cal_perimeter(self):passdef cal_area(self):passdef 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 = nself.a = aself.b = bdef cal_area(self):self.area = round(self.a * self.b, 2)return self.areadef cal_perimeter(self):self.perimeter = round(2 * (self.a + self.b), 2)return self.perimeterclass Triangle(Shape):def __init__(self, n, a, b, c):super().__init__()self.name = nself.a = aself.b = bself.c = cdef cal_area(self):self.cal_perimeter()h = self.perimeter / 2self.area = math.sqrt(h * (h - self.c) * (h - self.b) * (h - self.a))self.area = round(self.area, 2)return self.areadef cal_perimeter(self):self.perimeter = self.a + self.b + self.cself.perimeter = round(self.perimeter, 2)return self.perimeterclass Circle(Shape):def __init__(self, n, a):super().__init__()self.name = nself.a = adef cal_area(self):self.area = round(3.14 * self.a ** 2, 2)return self.areadef cal_perimeter(self):self.perimeter = round(2 * 3.14 * self.a, 2)return self.perimeter

XML 文件的生成与解析


import os
from xml.dom import minidomtry:import xml.etree.cElementTree as et
except ImportError:import xml.etree.ElementTree as et# 题目:XML文件的生成和解析
def create_xml(path):# 创建DOM树对象dom = minidom.Document()# 设置tilemaptilemap = dom.createElement('tilemap')dom.appendChild(tilemap)tilemap.setAttribute('tilemapservice', 'http://tms.osgeo.org/1.0.0')tilemap.setAttribute('version', '1.0.0')# 设置titletitle = dom.createElement('title')title_text = dom.createTextNode('default')title.appendChild(title_text)tilemap.appendChild(title)# 设置abstractabstract = dom.createElement('abstract')tilemap.appendChild(abstract)# 设置srssrs = dom.createElement('srs')srs_text = dom.createTextNode('EPSG:4326')srs.appendChild(srs_text)tilemap.appendChild(srs)# 设置vsrsvsrs = dom.createElement('vsrs')tilemap.appendChild(vsrs)# 设置boundingboxboundingbox = 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)# 设置originorigin = dom.createElement('origin')origin.setAttribute('x', '-180.0')origin.setAttribute('y', '-90.0')tilemap.appendChild(origin)# 设置tileformattileformat = dom.createElement('tileformat')tileformat.setAttribute('extension', 'tif')tileformat.setAttribute('height', '17')tileformat.setAttribute('mime-type', 'image/tiff')tileformat.setAttribute('width', '17')tilemap.appendChild(tileformat)# 设置tilesetstilesets = 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.textelif child.tag == 'tilesets':num = 0max_order = Nonefor tileset in child:num += 1order = int(tileset.attrib.get('order'))if max_order is None:max_order = orderelse:if order > max_order:max_order = orderreturn {'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 resultexcept:return "Parameter Error."

实现数据库的操作


# 题目:实现数据库的操作
import sqlite3
import osdb_hw_db_path = "./test.db"  # 全局变量,在create_db(path)时记录创建的数据库所在路径def create_db(path):global db_hw_db_pathdb_hw_db_path = pathcon = 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 -1else:return 0finally: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 -1else:return 0finally: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 -1else:return 0finally: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 -1con = 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 -1else:return 0finally: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 -1else: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 BeautifulSoupdef 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).textsoup = 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))

【西北工业大学】程序设计实训(python)相关推荐

  1. 中北c语言程序设计,中北大学软件学2013届C语言程序设计实训题目.doc

    中北大学软件学2013届C语言程序设计实训题目 C语言程序课程设计题目 (孟龙)题目1:年历显示 功能要求: 输入一个年份,输出是在屏幕上显示该年的日历.假定输入的年份在1940-2040年之间. 输 ...

  2. 做python的心得体会_实训python的心得体会

    如何学习Python的一些总结 C++.Java乃至C#都可以看做是同一类型的语言:C++还算灵活,但纷繁复杂的语法使得生产效率低下,Java提高了生产效率,却损失了灵活性;C#算是在生产效率和灵活性 ...

  3. c语言程序设计中北大学,《中北大学软件学院2013届C语言程序设计实训题目.doc...

    <中北大学软件学院2013届C语言程序设计实训题目 C语言程序课程设计题目 (孟龙)题目1:年历显示 功能要求: 输入一个年份,输出是在屏幕上显示该年的日历.假定输入的年份在1940-2040年 ...

  4. c#程序设计实训报告心得体会_C#程序实际实训总结

    C# 程序设计实训总结 C# 课程今天为止就结束了,这门课程让我体会到了编程的乐趣,他编写 win 窗口的确 很有意思. C# 为期两天的实训,有兴趣却又很苦恼,因为编程本来就是一个需要思维的过 程, ...

  5. c语言程序设计项目实训总结,c语言程序设计实训总结.docx

    c语言程序设计实训总结C语言程序设计实训总结为加强学生的实践动手能力,为贯彻落实教学计划的要求,培养学生的实践技能,计算机系05级计算机网络工程与管理.计算机信息学管理.图形图像三个的学生于XX年6月 ...

  6. c语言程序设计实训太空战机,清华大学出版社-图书详情-《C程序设计实训教程(第2版)》...

    前 言 "C程序设计"是一门实践性很强的课程,学习本课程既要理解C语言的基本理论和基本知识,更要掌握应用理论知识编写程序的方法和技能.为此,编者基于长期从事"C程序设计& ...

  7. c语言程序设计实训教程刘涛夏启寿,C语言程序设计

    作者:夏启寿\刘涛 责编:赵丽欣\郭丽娜 出版社:科学出版社 ISBN书号:978-7-03-036128-8 发行号:TP-6139.0101 出版日期:2013-1-11 定价:36 内容简介: ...

  8. 创新实训-python爬虫多线程|解决中文乱码问题|卡片向上浮动效果|图文切换

    创新实训-python爬虫多线程|乱码问题|前端样式重新修改 考完毛概,把上周的工作总结一下.爬虫在第一周的时候只爬了一个就业指导这一个模块,这一次又加了招聘服务模块,所以就用了两个线程.前端首页一开 ...

  9. 单片机c语言程序设计实训报告,(整理)单片机C语言程序设计实训100例.doc

    (整理)单片机C语言程序设计实训100例.doc .单片机C语言程序设计实训100例基于8051Proteus仿真案例第 01 篇 基础程序设计01闪烁的LED/* 名称闪烁的LED说明LED按设定的 ...

最新文章

  1. 从入门到放弃的javaScrip——队列
  2. JAVA编程语言的基础知识(六)
  3. c语言实现天气预报步骤,天气预报是怎么预测天气的?天气预报制定需要哪些步骤...
  4. 自己实现一个和PYTHON的库一模一样的sha_256算法
  5. 人物角色群体攻击判定(一)
  6. 鸟哥的私房菜-基础篇学习-文件与目录管理-2-1
  7. Frenet Frame
  8. Chrome浏览器 显示 Flash不是最新版
  9. mapgis k9将wp、wl、wt转shp属性字段名乱码
  10. 企业邮箱地址格式是什么?企业邮箱地址类型汇总
  11. Android Startup实现分析
  12. 如何将pdf转换成jpg,转换达人教你一招搞定
  13. 解决Cannot delete or update a parent row: a foreign key constraint fails的mysql报错
  14. 【无标题】.NET?MemoryCache如何清除全部缓存学习通http://www.bdgxy.com/
  15. Android 关于Android权重的真正理解
  16. 粒子群优化算法和python代码_Python编程实现粒子群算法(PSO)详解
  17. 设置MyEclipse的编辑器和控制台为护眼色
  18. C++数据结构之单链表(henu.hjy)
  19. php psl标准,API 5L PSL1与PSL2标准的区别
  20. JS红宝书·读书笔记

热门文章

  1. Android 实现视屏播放器、边播边缓存功能、外加铲屎(IJKPlayer)
  2. [SRM] 10 CCZ的诗
  3. binarytree构建二叉树堆,python
  4. 浙江大学计算机学院各专业介绍ppt模板,浙大硕士论文答辩经典ppt模板(几乎涵盖各种ppt制作技巧).ppt...
  5. - TMS320C6748———EDMA简介及配置
  6. curl基本用法,curl和wget区别
  7. 【智慧地球】图新地球 | 如何将图新地球多要素KML进行分离输出
  8. zip/unzip 压缩
  9. 医学图像分割损失函数Dice
  10. 2018年数学建模国赛A题题目、解题思路、matlab代码(四)