Python123-练习题

三角形周长及面积

输入的三角形的三条边a、b、c 的长度,计算并依次输出三角形的周长和面积,结果严格保留2位小数。测试用例的数据保证三角形三边数据可以构成三角形。
输入格式: 分三行输入 3 个浮点数,表示三角形的三个边长
输出格式: 三角形的周长和面积,格式参考示例

import math
a, b, c = float(input()), float(input()), float(input())
print('周长={:.2f}'.format(a + b + c))
s = (a + b + c)/2.0
print('面积={:.2f}'.format(math.sqrt(s * (s - a) * (s - b) * (s - c))))

a除以b

计算a除以b,结果四舍五入,保留2位小数。
输入格式: 输入包括两行, 每行一个实数, b不能等于0
输出格式: 正常计算结果为一个实数,当用户输入b为0时输出"除零错误"

a, b = int(input()), int(input())
if b == 0:print('除零错误')
else:print(round(a / b, 2))

2的n次方

计算2的n次方,n由用户输入
输入格式: 输入一个正整数

print(2 ** int(input()))

计算阶乘

输入一个正整数,输出其阶乘值。
输入格式: 输入一个正整数
输出格式: 输出阶乘结果

def s(n):if n == 1:return 1return n * s(n -1 )
print(s(int(input())))

无空隙回声输出

输入:"Python 是 一个 通用语言"
输出:"Python是一个通用语言"
print(input().replace(' ', ''))

字符串分段组合

输入:"Alice-Bob-Charis-David-Eric-Flurry"
输出:"Alice+Flurry"
ls = input().split('-')
print(ls[0] + '+' + ls[-1])

字符串格式化输出

a = input("")
s = "PYTHON"
print("{:{}^30}".format(s,a))

求所有素数

import math
for i in range(1, 101):for j in range(2, int(math.sqrt(i)) + 1):if i % j == 0:breakelse: print(i, end=' ')

数字不同数之和

获得用户输入的一个整数N,输出N中所出现不同数字的和。‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬
例如:用户输入 123123123,其中所出现的不同数字为:1、2、3,这几个数字和为6。

li, res = list(map(int, set(input()))), 0
for i in li:res += i
print(res)

验证码较验

if input().lower() == 'Qs2X'.lower():print('验证码正确')
else:print('验证码错误,请重新输入')

大小写转换

import string
for i in input():if i in string.ascii_lowercase:print(i.upper(), end='')elif i in string.ascii_uppercase:print(i.lower(), end='')else:print(i, end='')

查找指定字符

a, b= input(), input()
print('index = {}'.format(b.rfind(a))) if a in b else print('Not Found')

凯撒加密

import string
a, b = input(), int(input())
letter = string.ascii_letters
low, upp = string.ascii_lowercase, string.ascii_uppercase
after = low[b:] + low[:b] + upp[b:] + upp[:b]
print(a.translate(''.maketrans(letter, after)))

身份证号处理

ids = input()
year = ids[6:10]
sex = '女' if int(ids[16]) % 2 == 0 else '男'
print('你出生于{}年{}月{}日'.format(year, ids[10:12], ids[12:14]))
print('你今年{}周岁'.format(2020- int(year)))
print('你的性别为{}'.format(sex))

快乐的数字

import time
num, start = int(input()), time.perf_counter()
while num != 1:if time.perf_counter() - start > 1.9:breakli, num = list(str(num)), 0for i in li:num += int(i) ** 2
print(True) if num == 1 else print(False)

列表插入

输入一个字符串 s 和一个非负整数 i, 列表 ls = [‘2’, ‘3’, ‘0’, ‘1’, ‘5’],在指定的位置 i 和 列表末尾分别插入用户输入的字符串 s。当 i >=5 时,相当于在列表末尾插入两次字符串 s 。
输入格式:
第一行输入一个字符串‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬
第二行输入一个非负整数
输出格式: 插入新数据后的列表

ls = ['2', '3', '0', '1', '5']
n, i = input(), int(input())
if i >= 0:ls.insert(i,n)ls.append(n)
print(ls)

列表排序

ls = list(input())
ls.sort()
print(ls)

生成随机密码

import random
random.seed(0x1010)
pw = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*'
e = ''
while len(e) < 10:val = ''while len(val) < 10:val += random.choice(pw)if val[0] in e:continueelse:e += val[0]print(val)

杨辉三角形

ls = []
for i in range(10):if i == 0:ls.append([1])elif i == 1:ls.append([1, 1])else:temp = []for j in range(i + 1):if j == 0 or j == i:temp.append(1)else:temp.append(ls[i - 1][j] + ls[i - 1][j - 1])ls.append(temp)
for i in ls:for j in i:print(j,end=' ')print()

分期付款计算器

loan, num, ty, rate = float(input()), int(input()), input(), float(input())
ls = []
if ty == 'ACPI':res = loan * rate * (1 + rate) ** num / ((1 + rate) ** num - 1)print(round(res, 2))
elif ty == 'AC':total = 0for i in range(num):res = loan / num + (loan - total) * ratels.append(round(res, 2))total += loan / numprint(ls)
else:print('还款方式输入错误')

模拟布朗运动

import math
import random
random.seed(int(input()))
ls, x, y = [(0,0)], 0, 0
dm, hm = [1, -1], [i for i in range(1, 11)]
for i in range(5):dx = random.choice(dm)hx = random.choice(hm)dy = random.choice(dm)hy = random.choice(hm)x += dx * hxy += dy * hyls.append((x, y))
print(ls)
res, x, y = 0, 0, 0
for a, b in ls[1:]:res += math.sqrt((a - x) ** 2 + (b - y) ** 2)x, y = a, b
print(round(res, 2))

排序输出字典中数据

输入格式: 输入一个正整数n
输出格式: 输出指定个数的排序后的元素

dic1 = {'Tom':21,'Bob':18,'Jack':23,'Ana':20}
dic2 = {'李雷':21,'韩梅梅':18,'小明':23,'小红':20}
def printMsg(dic, n):if n >= len(dic):print(dic)else:print(dic[:n])
n = int(input())
printMsg(sorted(dic1.keys(), key=lambda x: x[0], reverse=False), n)
printMsg(sorted(dic2.items(), key=lambda x: x[1], reverse=False), n)

用户转账

dic={"aaa":["123456",10000],"bbb":["888888",5000],"ccc":["333333",3000]}
name = input()
target = dic.get(name)
self_ = dic.get('aaa')
if target is None:print('Wrong User')
else:value = int(input())if value > target[1]:print('Insufficient Funds')else:print('Tranfer Success')self_[1] -= valuetarget[1] += valueprint('aaa:' + str(self_[1]))print(name + ':' + str(target[1]))

用户登录(字典)

dic={"aaa":["123456",10000],"bbb":["888888",5000],"ccc":["333333",3000]}
target = dic.get(input())
if target is None:print('Wrong User')
else:for i in range(3):pwd = input()if target[0] == pwd:print('Success')breakelse:if i < 2:print('Fail,{} Times Left'.format(2 - i))else:print('Login Denied')

走马灯数

for i in range(123456, 987655):if len(set(str(i))) < 6:continuefor j in range(1, 7):if set(str(i)) - set(str(i * j)):breakelse:print(i)

集合元素删除

s = set(list(map(int,input().split())))
if max(s) > 30 or min(s) < 0 or len(s) == 0:exit()
for i in range(int(input())):try:ins = input().split()if ins[0] == "pop":s.pop()if ins[0] == "remove":s.remove(int(ins[1]))if ins[0] == "discard":s.discard(int(ins[1]))except:pass
else:print(sum(s))

罗马数字转换

dic = {"I": 1, "V": 5,"X": 10, "L": 50,"C": 100,"D": 500,"M": 1000}
str, sum = input(), 0
for i in range(len(str) - 1):if dic[str[i]] < dic[str[i + 1]]:sum -= dic[str[i]]else:sum += dic[str[i]]
sum += dic[str[-1]]
print(sum)

查找特征数(集合/列表)

li, res = list(map(int, input().split())), -1
for i in set(li):if i == li.count(i) and i > res:res = i
print(res)

各位数字之和为5的数

for i in range(int(input()) + 1):if sum(map(int, list(str(i)))) == 5:print(i, end=' ')

月份缩写(一)

i = int(input())
months = "Jan.Feb.Mar.Apr.May.Jun.Jul.Aug.Sep.Oct.Nov.Dec."
if 1<= i <= 12:print("{}.".format(months.split('.')[i - 1]))

字符串加密

import string
ls = list(input())
low = string.ascii_lowercase
upp = string.ascii_uppercase
i = 0
for char in ls:if char.isalpha():if char.islower():ls[i] = low[(low.find(char) + 3) % len(low)]if char.isupper():ls[i] = upp[(upp.find(char) + 5) % len(upp)]i += 1
print(''.join(ls))

念数字

输入一个整数,输出每个数字对应的拼音。当整数为负数时,先输出fu字

ls = ['ling', 'yi', 'er', 'san', 'si', 'wu', 'liu', 'qi', 'ba', 'jiu', 'fu']
res = []
for i in input():if i.isdigit():res.append(ls[int(i)])else:res.append(ls[-1])
print(' '.join(res))

判断火车票座位

a = input()
if 2 <= len(a) <= 3:  if a[:-1].isdigit() == 1 and 1 <= int(a[:-1]) <= 17:  if a[-1].lower() in ['a', 'f']: print("窗口")elif a[-1].lower() in ['c', 'd']: print("过道")elif a[-1].lower() == 'b': print("中间")else:print("输入错误")else:print("输入错误")
else:print('输入错误')

身份证号校验

ls = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
ids, res = input().strip(), 0
for i in range(len(ls)):res += int(ids[i]) * ls[i]
if ids[-1] == 'X':if res % 11 == 2:print('身份证号码校验为合法号码!')else:print('身份证校验位错误!')
elif (res % 11 + int(ids[-1])) % 11 == 1:print('身份证号码校验为合法号码!')
else:print('身份证校验位错误!')

个人数据脱敏

n = int(input())
if n <= 0:print('ERROR')
else:ls = [input().split() for i in range(n)]for i in ls:i[0] = i[0][:4] + '*' * 7 + i[0][11:]i[1] = i[1][:1] + '*' + i[1][2:]i[2] = i[2][:3] + '*' * 4 + i[2][7:] print(ls)

反素数

def prime(n):if n <= 1:return 0for i in range(2, int(n ** (1/2)) + 1):if n % i == 0:return 0return 1n, count, i = int(input()), 0, 2
while True:if prime(i) and prime(int(str(i)[::-1])) and str(i) != str(i)[::-1]:print(i, end=' ')count += 1if count == n:breaki += 1

编写函数输出自除数

def func(right):for num in range(1, right + 1):if '0' in str(num):continuefor i in str(num):if num % int(i) != 0:breakelse:print(num, end=' ')func(int(input()))

任意累积

# 请在...补充一行或多行代码def cmul(*s):sum = int(s[0])for i in s[1:]:sum *= int(i)return sumprint(eval("cmul({})".format(input())))

贪心的交易(函数)

import random
def f(prices):print(prices)i, res = 0, 0while i + 1 < len(prices):if prices[i + 1] > prices[i]:res += prices[i + 1] - prices[i]i += 1return res#下方实现代码,输入列表长度以及随机种子参数,并设定随机种子
n = int(input())
random.seed(int(input()))ls=[random.randint(1,100) for i in range(0,n)]   #构造价格列表,本行无需修改,
print(f(ls))               #输出结果,本行无需修改

统计文件中的中文字数

with open(input(), 'r',encoding='utf-8') as fp:count = 0for i in fp:for ch in ',。?!@#¥%……&*;(:; ) ——+|、·:“”’‘\n':i = i.replace(ch, '')count += len(i)print(count)

文件中数据转列表

with open('xrdfile.txt','r',encoding='utf-8') as fp:ls = [list(map(int,map(float,i.strip().split('\t')))) for i in fp]print(ls[:int(input())])

利用数据文件统计成绩

data = open('成绩单.csv','r', encoding='utf-8')
total, n = [0 for i in range(6)], int(input())
score = sorted([i.strip().split(',') for i in data.readlines()], key=lambda x:float(x[-1]))
print('最低分{}分,最高分{}分'.format(score[0][-1], score[-1][-1]))
if n > len(score):n = len(score)
print(score[:n])
print(score[-n:])
for i in range(len(total)):for j in score:total[i] += float(j[i + 3])
print(list(map(lambda i: round(i / len(score), 2), total)))data.close()

文本分析与加密

def change(ch, n):tem = ord('a')if ch.isupper():tem = ord('A')return chr(tem + (ord(ch) - tem + n) % 26)count = 0
for i in input():count = (ord(i) + count) % 26
with open('mayun.txt', 'r', encoding='utf-8') as fp:content, val = fp.readlines(), ''upp = low = num = space = other = words = 0for i in content:for j in i:if j.isalpha():val += change(j, count)if j.isupper():upp += 1else:low += 1else:val += jif j.isdigit():num += 1elif j.isspace():space += 1else:other += 1words += len(i.replace(',','').replace('.','').replace("'",'').split())print(upp, low, num, space, other)print('共有{}单词'.format(words + 1))print(count)print(val)

身份证号批量升位

# 模板仅供参考,可不按些模板写代码def id15218(id15):# 在这里写你的代码li = '7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2'.split(' ')ecc = '1 0 X 9 8 7 6 5 4 3 2'.split(' ')sum, j = 0, 0id17 = id15[:6] + '20' + id15[6:]if int(id15[6:8]) >= 5:id17 = id15[:6] + '19' + id15[6:]for i in id17:sum += int(i) * int(li[j])j += 1id18 = id17 + ecc[sum % len(ecc)]return id18n = int(input())
with open('id15.txt','r',encoding='utf-8') as file:for i in range(n):line = file.readline()   # line 的内容是文件中的一行,字符串类型# 在这里写你的代码print(line.replace(line[:15], id15218(line[:15])).strip())

手机销售统计

f18 = open('sale2018.csv','r',encoding='utf-8')
f19 = open('sale2019.csv','r',encoding='utf-8')
f18 = sorted(list(map(lambda x:x.split(',')[0],f18.read().splitlines())))
f19 = sorted(list(map(lambda x:x.split(',')[0],f19.read().splitlines())))
n = int(input())
if n == 1:print(f19)print(f18)
elif n == 2:res = list(set(f19).intersection(f18))res.sort()print(res)
elif n == 3:res = list(set(f19).union(f18))res.sort()print(res)    
elif n == 4:res = list(set(f19).difference(f18))res.sort()print(res)
elif n == 5:re = list(set(f19).difference(f18))re.extend(list(set(f18).difference(f19)))print(re)

一道题练会加减乘除和乘方

import mathn1 = input()
n2 = input()
print("{}+{}={}".format(n1, n2, eval(n1) + eval(n2)))
print("{}-{}={}".format(n1, n2, eval(n1) - eval(n2)))
print("{}*{}={}".format(n1, n2, eval(n1) * eval(n2)))
print("{}/{}={:.2f}".format(n1, n2, eval(n1) / eval(n2)))
print("{}除以{}的整数商={}".format(n1, n2, int(eval(n1) / eval(n2))))
print("{}除以{}的余数为={}".format(n1, n2, eval(n1) % eval(n2)))
print("{}的{}次方={}".format(n1, n2, int(math.pow(eval(n1), eval(n2)))))

输入3个数字,由小到大输出

ls = []
while len(ls) < 3:ls.append(input())
ls.sort(key=lambda x: eval(x), reverse=False)
for i in ls:print(i)

整数逆位运算

n = input()
if eval(n) >= 0:print(int(n[::-1]))
else:print(int('-' + n[1:][::-1]))

找数字,做加法

ls = ['', '']
for i in range(2):for j in input():if j.isnumeric():ls[i] += j
print(eval(ls[0]) + eval(ls[1]))

数字不同数之和

print(sum(list(set(map(int,input())))))

鸡兔同笼B

ls = []
for i in range(int(input())):feet = eval(input())if feet<=0 or feet%2 != 0:min = max = 0else:l = feet / 4;f = feet % 4 / 2min = l + fmax = feet/2ls += [(min, max)]
for a,b in ls:print(int(a),int(b))

侯先生爬楼梯

a, b = 0, 1
for i in range(int(input())):a, b = b, a + b
print(b)

字符串分段组合

s = input().split('-')
print(s[0] + '+' + s[-1])

103

参照代码模板完善代码,实现下述功能。文件 data.txt 文件中有多行数据,打开文件,读取数据,并将其转化为列表。统计读取的数据,计算每一行的总和、平均值,在屏幕上输出结果。
文件内容示例如下:‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬
Chinese: 80,Math:85,English:92, Physical: 81,Art:85,Chemical:88‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬
屏幕输出结果示例如下:‪‬‪‬‪‬‪‬‪‬‮‬‫‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‭‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‭‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‮‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬总和是:511.0,平均值是:85.17

#请在...上填写多行代码
#可以修改其他代码fi = open("data.txt", 'r')
for l in fi:l = l.split(',')s = 0.0n = len(l)for item in l:ll = item.split(":")s += float(ll[1])print("总和是:{},平均值是:{:.2f}".format(s,s/n))
fi.close()

Published by

风君子

独自遨游何稽首 揭天掀地慰生平