【Python程序设计】上机作业(西电)⼈类⾼质量代码(误)
西电《Python程序设计》上机作业
2021
有些代码是嫖的,但⼤部分代码尽⾃⼰可能尝试以最简单或是最有趣的⽅式实现。
Python课⾃然是没有听的,肯定有更好更规范的写法,欢迎讨论
⽬录
【Python】第⼀次上机报告
1)安装 Python,使⽤ Python 解释器。
$ python
2)简单的加减乘除运算,调⽤标准模块 math 中的数学函数。
>>>0.1+0.2
0.30000000000000004
>>>0.3-0.1
0.19999999999999998
>>>0.1*0.2
0.020000000000000004
>>>1/0
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
ZeroDivisionError: division by zero
>>>import math
>>> math.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
ValueError: math domain error
3)编写和运⾏ Python 脚本。
$ python a.py
4)编写程序,⽣成包含 1000 个 0 到 100 之间的随机整数,并统计每个元素的出现次数。
import random
x =[random.randint(1,100)for _ in range(1000)]
print({unt(i)for i in set(x)})
5)编写程序,⽣成包含 20 个随机数的列表,然后将前 10 个元素升序排列,后 10 个元素降序排列,并输出结果。
import random
x =[random.randint(1,100)for _ in range(20)]
print(sorted(x[:10])+sorted(x[11:],reverse=True))
6)编写程序,运⾏后⽤户输⼊ 4 位整数作为年份,判断其是否为闰年。如果年份能被400 整除,则为闰年;如果年份能被 4 整除但不能被 100 整除也为闰年。
使⽤了海象运算符赋值,故需python版本>=3.8
print('闰年'if((year:=int(input("请输⼊年份:")))%4==0and year%100!=0)or year%400==0else'平年')
或者使⽤calendar
trim函数实例import calendar
print('闰年'if calendar.isleap(int(input("输⼊年份:")))else'平年')
【Python】第⼆次上机报告
5⽉6号上机后的作业是“字符串1”中的例题,因为代码已给出,所以要求同学们写注释,验证代码是否有问题,写有关程序的思考(如初始看到题⽬,你是准备怎么实现的)。
例4-1 编写函数实现字符串加密和解密,循环使⽤指定密钥,采⽤简单的异或算法
添加注释:
def crypt(source, key):
from itertools import cycle
'''
(class) cycle(__iterable: Iterable):
Return elements from the iterable until it is exhausted.
Then repeat the sequence indefinitely.
'''
html好看的颜代码result =''
temp = cycle(key)
for ch in source:
'''
next(iterator[, default]):
Return the next item from the iterator.
If default is given and the iterator is exhausted,
it is returned instead of raising StopIteration.
'''
result = result +chr(ord(ch)^ord(next(temp)))
return result
source ='Xidian University'# 原⽂
key ='CS'# 秘钥
print('Before Encrypted:'+source)
encrypted = crypt(source, key)
print('After Encrypted:'+encrypted)
打开telnet功能decrypted = crypt(encrypted, key)
print('After Decrypted:'+decrypted)
使⽤zip()函数:
def crypt(source, key):
from itertools import cycle
'''
(class) cycle(__iterable: Iterable):
Return elements from the iterable until it is exhausted.
Then repeat the sequence indefinitely.
'''
result =''
temp = cycle(key)
for ch, key in zip(source, temp):
result = result +chr(ord(ch)^ord(key))
return result
source ='Xidian University'# 原⽂
key ='CS'# 秘钥
print('Before Encrypted:'+source)
encrypted = crypt(source, key)
print('After Encrypted:'+encrypted)
decrypted = crypt(encrypted, key)
print('After Decrypted:'+decrypted)
函数式编程的写法:
def crypt(source, key):
from itertools import cycle
func =lambda x, y:chr(ord(x)^ord(y))# 函数式编程
return''.join(map(func, source, cycle(key)))
source ='Beautiful is better than ugly.'
key ='Python'
print('Before Encrypted:'+source)
encrypted = crypt(source, key)
print('After Encrypted:'+encrypted)
decrypted = crypt(encrypted, key)
print('After Decrypted:'+decrypted)
优化代码,使⽤base64,使不可见字符可见
from base64 import b64encode
def crypt(source, key):
from itertools import cycle
func =lambda x, y:chr(ord(x)^ord(y))# 函数式编程
return''.join(map(func, source, cycle(key)))
source ='Beautiful is better than ugly.'
key ='Python'
print('Before Encrypted:'+source)
encrypted = crypt(source, key)
python基础代码作业print('After Encrypted (base64enc):')
print(b64encode(bytes(encrypted,encoding='utf8')))# base64编码
decrypted = crypt(encrypted, key)
print('After Decrypted:'+decrypted)
例4-2 编写程序,⽣成⼤量随机信息,这在需要获取⼤量数据来测试或演⽰软件功能的时候⾮常有⽤,不仅能真实展⽰软件功能或算法,还可以避免泄露真实数据或者引起不必要的争议。
import random
import string
import string
import codecs
# 常⽤汉字Unicode编码表(部分),完整列表详见配套源代码
StringBase ='\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba'
def getEmail():
# 常见域名后缀,可以随意扩展该列表
suffix =['','.org','','']
characters = string.ascii_letters+string.digits+'_'
username =''.join((random.choice(characters)
for i in range(random.randint(6,12))))
domain =''.join((random.choice(characters)
for i in range(random.randint(3,6))))
return username+'@'+domain+random.choice(suffix)
def getTelNo():
return''.join((str(random.randint(0,9))for i in range(11)))
def getNameOrAddress(flag):
'''flag=1表⽰返回随机姓名,flag=0表⽰返回随机地址'''
result =''
if flag ==1:
chrome浏览器最新版# ⼤部分中国⼈姓名在2-4个汉字
rangestart, rangeend =2,4
elif flag ==0:
# 假设地址在10-30个汉字之间
rangestart, rangeend =10,30
else:
print('flag must be 1 or 0')
return''
for i in range(random.randint(rangestart, rangeend)):
result += random.choice(StringBase)
return result
def getSex():
return random.choice(('男','⼥'))
def getAge():
return str(random.randint(18,100))
def main(filename):
with codecs.open(filename,'w','utf-8')as fp:
# 虽然内置的 open() 和相关联的 io 模块是操作已编码⽂本⽂件的推荐⽅式,# 但codecs.open也提供了额外的⼯具函数和类,
# 允许在操作⼆进制⽂件时使⽤更多各类的编解码器:
fp.write('Name,Sex,Age,TelNO,Address,Email\n')
# 随机⽣成200个⼈的信息
for i in range(200):
name = getNameOrAddress(1)
sex = getSex()
age = getAge()
tel = getTelNo()
address = getNameOrAddress(0)
email = getEmail()
line =','.join([name, sex, age, tel, address, email])+'\n'
fp.write(line)
def output(filename):
with codecs.open(filename,'r','utf-8')as fp:
while True:
line = fp.readline()
if not line:
return
line = line.split(',')
for i in line:
print(i, end=',')
print()
if __name__ =='__main__':
filename =''
main(filename)计算机视频教程全集
output(filename)
例4-3 检查并判断密码字符串的安全强度。这实际上是⼀个分类问题。
import string
def check(pwd):
# 密码必须⾄少包含6个字符
if not isinstance(pwd,str)or len(pwd)<6:
return'not suitable for password'
# 密码强度等级与包含字符种类的对应关系
d ={1:'weak',2:'below middle',3:'abov
e middle',4:'strong'}
# 分别⽤来标记pwd是否含有数字、⼩写字母、⼤写字母和指定的标点符号
r =[False]*4
for ch in pwd:
# 是否包含数字
if not r[0]and ch in string.digits:
r[0]=True
# 是否包含⼩写字母
elif not r[1]and ch in string.ascii_lowercase:
r[1]=True
# 是否包含⼤写字母
elif not r[2]and ch in string.ascii_uppercase:
r[2]=True
# 是否包含指定的标点符号
elif not r[3]and ch in',.!;?<>':
r[3]=True
# 统计包含的字符种类,返回密码强度
# get(key[, default]):
# 如果 key 存在于字典中则返回 key 的值,否则返回 default。
# 如果 default 未给出则默认为 None,因⽽此⽅法绝不会引发 KeyError。
(r.count(True),'error')
print(check('a2C233d'))
例4-4 编写程序,把⼀个英⽂句⼦中的单词倒置,标点符号不倒置,例如 I like beijing. 经过函数后变为:beijing. like I
添加了强制类型:
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论