python123部分编程题

python123部分编程题三位水仙花数ans=””foriinrange(100,1000):sum=0forjinstr(i):sum+=(eval(j))**3ifsum==i:ans+=”{},”.format(i)print(ans[:-1])猴子吃桃IIdefpeach(n):ifn==10:return1else:return(pe

三位水仙花数

在这里插入图片描述

ans = ""
for i in range(100, 1000):
    sum = 0
    for j in str(i):
        sum += (eval(j)) ** 3
    if sum == i:
        ans += "{},".format(i)
print(ans[:-1])

猴子吃桃 II

在这里插入图片描述

def peach(n):
    if n == 10:
        return 1
    else:
        return (peach(n + 1) + 1) * 2


for i in range(10, 0, -1):
    print("第{}天有{}只桃子".format(i, peach(i)))

侯先生爬楼梯

在这里插入图片描述

def climb(n):
    a, b = 1, 1
    for i in range(n):
        a, b = b, a + b
    return a


n = int(input())
print(climb(n))

编写函数输出自除数

在这里插入图片描述

def selfDivisor(num):
    t = str(num)
    if '0' in t:
        return 0
    for i in t:
        if num % int(i) != 0:
            return 0
    return 1


n = int(input())
ls = []
for i in range(1, n + 1):
    if selfDivisor(i):
        print(i, end=" ")

103

在这里插入图片描述

fi = open("data.txt", 'r')
for l in fi:
    l = l.split(',')
    s = 0.0
    n = len(l)
    for cours in l:
        items = cours.split(':')
        s += eval(items[1])
    print("总和是:{},平均值是:{:.2f}".format(s, s / n))
fi.close()

汉诺塔求解

在这里插入图片描述

steps = 0


def hanoi(src, des, mid, n):
    global steps
    if n == 1:
        steps = steps + 1
        print("[STEP{:>4}] {}->{}".format(steps, src, des))
    else:
        hanoi(src, mid, des, n - 1)
        steps = steps + 1
        print("[STEP{:>4}] {}->{}".format(steps, src, des))
        hanoi(mid, des, src, n - 1)


N = eval(input())
hanoi("A", "C", "B", N)

素数问题

在这里插入图片描述

def question_judge(question):
    """接收一个字符串为参数,根据参数值判断问题类型,调用合适的函数进行操作。"""
    if question == '素数':       # 如果输入”素数“,再输入一个正整数n,输出不大于n的所有素数
        n = int(input())
        output_prime(n)         # 输出素数
    elif question == '回文素数':
        n = int(input())
        palindromic_prime(n)   # 输出回文素数
    elif question == '反素数':
        n = int(input())
        reverse_prime(n)  # 输出反素数
    elif question == '哥德巴赫猜想':
        n = int(input())
        goldbach_conjecture(n)
    else:
        print('输入错误')



def is_prime(n):
    """判断素数的函数,接收一个正整数为参数,参数是素数时返回True,否则返回False 减小判定区间,减少循环次数,提升效率"""
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5 + 1)):
        if n % i == 0:
            return False
    else:
        return True




def output_prime(number):
    """接收一个正整数为参数,遍历从0到number之间的所有整数 在一行中输出不大于number的所有素数,函数无返回值"""
    for i in range(number+1):
        if is_prime(i):
            print(i,end=" ")



def palindromic(num):
    """接收一个数字为参数,判定其是否为回文数,返回布尔值。"""
    return str(num) == str(num)[::-1]


def palindromic_prime(number):
    """接收一个正整数参数number,遍历从0到number之间的所有整数, 若某个数是素数,且转为字符串后是回文字符串,则称其为回文素数 找出并在同一行中从小到大输出小于number的所有回文素数,各数字间用一个空格分隔, 函数无返回值"""
    for i in range(number + 1):
        if palindromic(i) and is_prime(i):
            print(i, end = ' ')



def reverse_num(num):
    """接收一个整数,返回其逆序字符串对应的整数"""
    return int(str(num)[::-1])


def reverse_prime(number):
    """接收一个正整数参数,找出并在同一行内输出所有小于number的反素数,数字间用一个空格分隔。 反素数指某数i及其逆序数都是素数,但数i对应的字符串不是回文字符串 函数无返回值"""
    for i in range(number):
        if not palindromic(i) and is_prime(i) and is_prime(reverse_num(i)):
            print(i, end=" ")



def goldbach_conjecture(num):
    """ 哥德巴赫猜想, 接收一个不小于4的正整数为参数。 当参数为不小于4的偶数时,将其分解为两个素数的加和,按小数+数的格式输出。 有多种组合时全部输出,但不输出重复的组合,例如输出8=3+5,不输出8=5+3。 参数为奇数或小于4时,输出'Data error!' """
    if num %2==0 and num>=4:
        for i in range(2,(num//2)+1):
            if is_prime(i) and is_prime(num-i):
                print(f"{ 
     num}={ 
     i}+{ 
     num-i}")
    else:
        print("Data error!")




if __name__ == '__main__':
    problems = input()
    question_judge(problems)

回文素数

在这里插入图片描述

def isPrime(x):
    for i in range(2, int(x ** 0.5) + 1):
        y = x % i
        if y == 0:
            break
            return False
    else:
        return True


def palindrome(x):
    if str(x) == str(x)[::-1]:
        return True
    else:
        return False


n = int(input())
m = 0
i = 2
while m < n:
    if isPrime(i) and palindrome(i):
        print(i, end=' ')
        i = i + 1
        m = m + 1
    else:
        i = i + 1

统计文件中的中文字数

在这里插入图片描述

def read_file(file):
    with open(file, 'r', encoding='utf-8') as data:
        result = data.read()
        for i in result:
            if i in ',。?!@#¥%……&*;(:; ) ——+|、·:“”’‘\n':
                result = result.replace(i, "")
    return len(result)


if __name__ == '__main__':
    file = input()
    dic = read_file(file)
    print(dic)

文件中数据转列表

在这里插入图片描述

with open('xrdfile.txt', 'r', encoding='utf-8') as f:
    n = int(input())
    ls = []
    for i in f.readlines():
        ls.append(i.strip().split())
    for i in range(len(ls)):
        ls[i][0] = int(float(ls[i][0]))
        ls[i][1] = int(float(ls[i][1]))
    print(ls[:n])

利用数据文件统计成绩

在这里插入图片描述

data = open('成绩单.csv','r', encoding='utf-8')
score = []
n = int(input())
for line in data:
    line = line.replace('\n', '')
    score.append(line.split(','))
score.sort(key=lambda x: int(x[9]))
if n > len(score):
    n = len(score)

print("最低分{}分,最高分{}分".format(score[0][9], score[-1][9]))
print(score[:n])
print(score[-n:])

s = [0, 0, 0, 0, 0, 0]
for i in range(len(score)):
    for j in range(len(s)):
        s[j] = s[j] + int(score[i][j + 3])

for l in range(len(s)):
    s[l] = round(s[l] / len(score), 2)
print(s)

data.close()

文本分析与加密

在这里插入图片描述

def encrypating(character, n):
    if character.islower():
        temp = ord('a');character = chr(temp + (ord(character) - temp + n) % 26)
    else:
        temp = ord('A');character = chr(temp + (ord(character) - temp + n) % 26)
    return character


l = list(str(input()));
secret = 0
for i in l:
    secret = (secret + ord(i)) % 26

f = open("mayun.txt", "r")
content = f.readlines()
upperchr = lowerchr = num = space = others = 0
words = 1

for line in content:
    for i in line:
        if i.isupper():
            upperchr += 1
        elif i.islower():
            lowerchr += 1
        elif i.isspace():
            space += 1
        elif i.isdigit():
            num += 1
        else:
            others += 1
    str = line.replace('.', '')
    str = str.replace(',', '')
    str = str.replace("'", '')
    l = list(str.split(' '))
    words += len(l)
print("%d %d %d %d %d" % (upperchr, lowerchr, num, space, others))
print("共有%d单词" % words)
print("%d" % secret)

for line in content:
    ret = ""
    for char in line:
        if char.isalpha():
            ret += encrypating(char, secret)
        elif char != '\n':
            ret += char
    print(ret)

身份证号批量升位

在这里插入图片描述

def id15218(id15):
    a = id15
    id15 = a[:6] + '19' + a[6:]
    Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    s = 0
    for i in range(17):
        s = s + int(id15[i]) * int(Wi[i])
    Y = str(s % 11)
    if int(Y) < 10:
        before = '0 1 2 3 4 5 6 7 8 9'
        after = '1 0 X 9 8 7 6 5 4 3'
        table = ''.maketrans(before, after)
        Y = Y.translate(table)
    else:
        Y = '2'
    id18 = id15[:17] + Y + id15[17:]
    id18 = id18.replace(id18[18], ' ' * 1)
    return id18


n = int(input())
with open('id15.txt', 'r', encoding='utf-8') as file:
    for i in range(n):
        line = file.readline()
        print(id15218(line), end='')

手机销售统计

在这里插入图片描述

sale2018 = []
sale2019 = []
with open('sale2018.csv', 'r', encoding='utf-8') as data2018:
    for line in data2018:
        temp1 = line.split(',')
        sale2018.append(temp1)
with open('sale2019.csv', 'r', encoding='utf-8') as data2019:
    for line in data2019:
        temp2 = line.split(',')
        sale2019.append(temp2)
n = int(input())
set2018 = { 
   x[0] for x in sale2018}
set2019 = { 
   x[0] for x in sale2019}
if n == 1:
    ls2019 = list(set2019)
    ls2018 = list(set2018)
    ls2019.sort()
    ls2018.sort()
    print(ls2019)
    print(ls2018)
elif n == 2:
    set2 = set2019 & set2018
    ls = list(set2)
    ls.sort()
    print(ls)
elif n == 3:
    set3 = set2018 | set2019
    ls = list(set3)
    ls.sort()
    print(ls)
elif n == 4:
    set4 = set2019 - set2018
    ls = list(set4)
    ls.sort()
    print(ls)
elif n == 5:
    set5 = set2018 ^ set2019
    ls = list(set5)
    ls.sort()
    print(ls)

任意累积

在这里插入图片描述

def cmul(*num):
    sum = 1
    for i in [*num]:
        sum *= i
    return sum


print(eval("cmul({})".format(input())))

编写函数输出自除数

在这里插入图片描述

def selfDivisor(num):
    strNum = str(num)
    if '0' not in strNum:
        for i in strNum:
            if num % int(i) != 0:
                return False
        return True


n = int(input())
for i in range(1, n + 1):
    if selfDivisor(i):
        print(i, end=' ')

反素数

在这里插入图片描述

import math


def isPrime(x):
    for i in range(2, int(math.sqrt(x)) + 1):
        if x % i == 0:
            return False
    return True


def isPalindrome(x):
    a = int(x[::-1])
    if a != int(x) and (isPrime(a)):
        return True
    return False


n = int(input(""))
i, j = 0, 2
while i < n:
    if isPrime(j) and isPalindrome(str(j)):
        print(j, end=" ")
        i += 1
    j += 1

贪心的交易(函数)

在这里插入图片描述

import random


def f(prices):
    le = len(prices) - 1
    i = 0
    sum = 0
    while (i + 1) <= le:
        if prices[i] < prices[i + 1]:
            sum += prices[i + 1] - prices[i]
        i += 1
    return sum


n = int(input())
m = int(input())
random.seed(m)
ls = [random.randint(1, 100) for i in range(0, n)]
print(ls)
print(f(ls))

汉诺塔

在这里插入图片描述

def hanoi(n, a, b, c):
    if n == 1:
        print(a, '-->', c)

    else:
        hanoi(n - 1, a, c, b)
        print(a, '-->', c)
        hanoi(n - 1, b, a, c)


n = int(input(""))
temp = input("")
str1 = temp.split(" ")
hanoi(n, str1[0], str1[1], str1[2])

各位数字之和为5的数

在这里插入图片描述

def fun(a):
    d = str(a)
    if sum([int(j) for j in d]) == 5:
        print(d, end=' ')
        
a = eval(input())
for i in range(a + 1):
    fun(i)

月份缩写(一)

在这里插入图片描述

months = "Jan.Feb.Mar.Apr.May.Jun.Jul.Aug.Sep.Oct.Nov.Dec."
month = months.split('.')
a = int(input(''))
index = a - 1
print(month[index] + ".")

字符串加密

在这里插入图片描述

str1 = input()
for i in str1:
    if ord('A') <= ord(i) <= ord('Z'):
        print(chr(ord('A') + (ord(i) - ord('A') + 5) % 26), end='')
    elif ord('a') <= ord(i) <= ord('z'):
        print(chr(ord('a') + (ord(i) - ord('a') + 3) % 26), end='')
    else:
        print(i, end='')

念数字

在这里插入图片描述

n = input()
dic = { 
   0: "ling", 1: "yi", 2: "er", 3: "san", 4: "si", 5: "wu", 6: "liu", 7: "qi", 8: "ba", 9: "jiu"}
ss = ""
for i in str(n):
    if i.isdigit():
        ss += dic[int(i)] + " "
    else:
        print("fu", end=" ")
print(ss.rstrip())

判断火车票座位

在这里插入图片描述

import sys

lst = ["a", "b", "c", "d", "f"]
n = input()
num = n[:-1]
ch = n[-1].lower()
if num.isdigit():
    dig = int(num)
    if dig < 1 or dig > 17 or ch not in lst:
        print('输入错误')
        sys.exit()
else:
    print("输入错误")
    sys.exit()
if ch == "a" or ch == "f":
    print('窗口')
elif ch == 'c' or ch == 'd':
    print('过道')
elif ch == 'b':
    print('中间')

个人数据脱敏

在这里插入图片描述

import sys

lst = list()
n = input()
if n.count('.') == 1 or n.count('-') == 1 or not n.isdigit():
    print('ERROR')
    sys.exit()
else:
    n = int(n)

for i in range(0, n):
    mlst = list()
    n = input().split()
    s0 = list(n[0])
    for i in range(len(s0)):
        if i > 3 and i < 11:
            s0[i] = '*'
    a = ''.join(s0)
    mlst.append(a)

    s1 = list(n[1])
    for i in range(len(s1)):
        if i == 1:
            s1[i] = '*'
    b = ''.join(s1)
    mlst.append(b)

    s2 = list(n[2])
    for i in range(len(s2)):
        if i < 7 and i > 2:
            s2[i] = '*'
    c = ''.join(s2)
    mlst.append(c)

    lst.append(mlst)

print(lst)

排序输出字典中数据

在这里插入图片描述

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

用户转账

在这里插入图片描述

dic={ 
   "aaa":["123456",10000],"bbb":["888888",5000],"ccc":["333333",3000]}
ls = ["bbb","ccc"]
user = input()
if user not in ls:
    print("Wrong User")
else:
    zz = int(input())
    if zz > dic["aaa"][1]:
        print("Insufficient Funds")
    else:
        print("Tranfer Success")
        print("{}:{}".format("aaa",dic["aaa"][1] - zz))
        print("{}:{}".format(user,dic[user][1] + zz))

用户登录(字典)

在这里插入图片描述

dic={ 
   "aaa":["123456",10000],"bbb":["888888",5000],"ccc":["333333",3000]}
account = input()
if account not in dic.keys():
    print("Wrong User")
else:
    n = 0
    while n != 3:
        password = input()
        n=n+1
        if password == dic[account][0]:
            print("Success")
            break
        elif n <= 2:
            print("Fail,"+str(3-n)+" Times Left")
        else:
            print("Login Denied")

走马灯数

在这里插入图片描述

print(999999//7)

集合元素删除

在这里插入图片描述

s = set([int(x) for x in input().split()])
N = int(input())

for i in range(N):
    cmd = input().split(" ")
    if cmd[0] == 'pop':
        s.pop()
    elif cmd[0] == 'remove':
        if int(cmd[1]) in s:
            s.remove(int(cmd[1]))
    elif cmd[0] == 'discard':
        s.discard(int(cmd[1]))

print(sum(s))

罗马数字转换

在这里插入图片描述

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

列表插入

在这里插入图片描述

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

列表排序

在这里插入图片描述

s = input("")
sList = list(s)
sList.sort()
print(sList)

生成随机密码

在这里插入图片描述

from random import *
seed(0x1010)
s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*'
excludes = ''
ls = []
while len(ls) < 10:
    pmd = ''
    for i in range(10):
        pmd += choice(s)
    if pmd[0] in excludes:
        continue
    else:
        ls.append(pmd)
        excludes += pmd[0]
for i in ls:
    print(i)

杨辉三角形

在这里插入图片描述

lists = [[]for i in range(10)]
lists[0].append(1)
lists[1].append(1)
lists[1].append(1)
last = 2
for i in range(2, 10):
    last += 1
    for j in range(0, last):
        lists[i].append(1)
    for k in range(1, last - 1):
        lists[i][k] = lists[i - 1][k] + lists[i - 1][k - 1]
for i in range(0, len(lists)):
    for j in range(0, len(lists[i])):
        print(lists[i][j], end=" ")
    print("")

分期付款计算器

在这里插入图片描述

bj = float(input()) 
mon = int(input())
w = input()
l = float(input())
ls = []
yh = 0 
if w not in ['AC','ACPI']:
    print('还款方式输入错误')
elif w == 'AC':
    for i in range(mon):
        hk = bj/mon + (bj-yh)*l
        yh = yh + (bj/mon)
        hk=round(hk,2) 
        ls.append(hk)
    print(ls)
else:
    hk = (bj*l*(1+l)**mon)/((1+l)**mon-1) 
    hk = round(hk,2)
    print(hk)

模拟布朗运动

在这里插入图片描述

import random
import math
random.seed(int(input()))
tup1 = (0,0)
arr = list()
arr.append(tup1)
for i in range(5):
    Xold = arr[i][0]
    Dx = random.choice([1,-1])
    Hx = random.choice([1,2,3,4,5,6,7,8,9,10])
    Xnew = Xold + Dx * Hx
    Yold = arr[i][1]
    Dy = random.choice([1,-1])
    Vy = random.choice([1,2,3,4,5,6,7,8,9,10])
    Ynew = Yold + Dy * Vy
    tup1  = (Xnew,Ynew)
    arr.append(tup1)
print(arr)
sum = 0
for i in range(5):
    temp = math.sqrt((arr[i][0] - arr[i+1][0])**2 + (arr[i][1] -arr[i+1][1])**2)
    sum = sum + temp
print(round(sum,2))

求所有素数

在这里插入图片描述

for x in range(1, 100):
    for y in range(2, x):
        if x % y == 0:
            break
    else:
        print(x, end=" ")

数字不同数之和

在这里插入图片描述

n = input("")
s = set(n)
ans = 0
for i in s:
    ans += eval(i)
print(ans)

验证码较验

在这里插入图片描述

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

大小写转换

在这里插入图片描述

str1 = input("")
ans = ""
for i in str1:
    if 'a' <= i <= 'z': #i >= 'a' and i <= 'z':
        ans += i.upper()
    elif 'A' <= i <= 'Z': #i >= 'A' and i <= 'Z':
        ans += i.lower()
    else:
        ans += i
print(ans)

查找指定字符

在这里插入图片描述

str1 = input("")
str2 = input("")
index = str2.rfind(str1) #返回字符串最后一次出现的位置,如果没有匹配项则返回 -1。
if index == -1:
    print("Not Found")
else:
    print("index = " + str(index))

凯撒加密

在这里插入图片描述

#ascii 字符串中的某个字符 offset 偏移量 flag true为小写false为大写
def kaisa(ascii, offset, flag):
    if flag:
        if ord(ascii) + offset > 122:
            return chr(ord(ascii) + offset - 122 + 96)
    else:
        if ord(ascii) + offset > 90:
            return chr(ord(ascii) + offset - 90 + 64)
    return chr(ord(i) + offset)

str1 = input("")
offset = int(input(""))
ans = ""
for i in str1:
    if i.isalpha():
        ans += kaisa(i, offset, i.lower())
    else:
        ans += i
print(ans)

身份证号处理

在这里插入图片描述

import datetime

id = input("")
birthYear = id[6] + id[7] + id[8] + id[9]
birthMonth = id[10] + id[11]
birthDay = id[12] + id[13]
sex = "男" if int(id[16]) % 2 != 0 else "女"
print("你出生于{}年{}月{}日".format(birthYear, birthMonth, birthDay))
print("你今年{}周岁".format(2020 - int(birthYear)))
print("你的性别为{}".format(sex))

快乐的数字

在这里插入图片描述

import time

num = input("")
start = time.perf_counter()
temp = num
while True:
    if time.perf_counter() - start > 0.9:
        print("False")
        break
    else:
        ans = 0
        for i in temp:
            ans += int(i) ** 2
        if ans == 1:
            print("True")
            break
        else:
            temp = str(ans)

三角形周长及面积

在这里插入图片描述

a = float(input(""))
b = float(input(""))
c = float(input(""))
zc, mj, s = 0, 0, 0
zc = a + b + c
p = zc / 2
mj = (p * (p - a) * (p - b) * (p - c)) ** (1 / 2)
print("周长=%.2f" % zc)
print("面积=%.2f" % mj)

a除以b

在这里插入图片描述

a = float(input(""))
b = float(input(""))
if b == 0:
    print("除零错误")
else:
    c = a / b
    print("%.2f" % c)

2的n次方

在这里插入图片描述

import math

p = int(input(""))
print(int(math.pow(2, p)))

计算阶乘

在这里插入图片描述

n = int(input(""))
ans = 1
for i in range(1, n + 1):
    ans *= i
print(ans)

字符串分段组合

在这里插入图片描述

str1 = input("")
temp = str1.split("-")
print(temp[0] + "+" + temp.pop())

字符串格式化输出

在这里插入图片描述

a = input("")
s = "PYTHON"
temp = "{0:" + a + "^30}"
print(temp.format(s[0:30]))

无空隙回声输出

在这里插入图片描述

str1 = input("")
for i in str1:
    if i != " ":
        print(i, end="")

三位水仙花数

在这里插入图片描述

list = []
for i in range(100,1000):
    if pow(i // 100 , 3) + pow(i % 10 , 3) + pow(i // 10 % 10, 3) == i:
        list.append(i)
for i in range(0, len(list)):
    if (i == len(list) - 1):
        print(list[i])
    else:
        print(list[i], end=",")

字典翻转输出

在这里插入图片描述

s = input()
try:
    dic = eval(s)
    d = { 
   value:key for key,value in dic.items()}
    print(d)
except:
    print("输入错误")

中文词语逆序

在这里插入图片描述

import jieba
s = input()
s1 = list(jieba.lcut(s))
print("".join(s1[::-1]))

双一流高校及所在省份统计

在这里插入图片描述

d = { 
   "北京大学": "北京", "中国人民大学": "北京", "清华大学": "北京",
     "北京航空航天大学": "北京", "北京理工大学": "北京", "中国农业大学": "北京",
     "北京师范大学": "北京", "中央民族大学": "北京", "南开大学": "天津",
     "天津大学": "天津", "大连理工大学": "辽宁", "吉林大学": "吉林",
     "哈尔滨工业大学": "黑龙江", "复旦大学": "上海", "同济大学": "上海",
     "上海交通大学": "上海", "华东师范大学": "上海", "南京大学": "江苏",
     "东南大学": "江苏", "浙江大学": "浙江", "中国科学技术大学": "安徽",
     "厦门大学": "福建", "山东大学": "山东", "中国海洋大学": "山东",
     "武汉大学": "湖北", "华中科技大学": "湖北", "中南大学": "湖南",
     "中山大学": "广东", "华南理工大学": "广东", "四川大学": "四川",
     "电子科技大学": "四川", "重庆大学": "重庆", "西安交通大学": "陕西",
     "西北工业大学": "陕西", "兰州大学": "甘肃", "国防科技大学": "湖南",
     "东北大学": "辽宁", "郑州大学": "河南", "湖南大学": "湖南", "云南大学": "云南",
     "西北农林科技大学": "陕西", "新疆大学": "新疆"}
counts = { 
   }
for place in d.values():
    counts[place] = counts.get(place, 0) + 1
items = list(counts.items())
for i in range(0, len(items)):
    print(items[i][0] + ':' + str(items[i][1]))

文本词频统计 – Hamlet

在这里插入图片描述

def getText():
    txt = open("hamlet.txt", "r").read()
    txt = txt.lower()
    for ch in '!"$%&()*+,-./:;<=>?@[\\]^_{}|·`''':
        txt = txt.replace(ch, " ")
    return txt

hamletTxt = getText()
words = hamletTxt.split()
counts = { 
   }
for word in words:
    counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
items.sort(key=lambda x: x[1], reverse=True)
for i in range(10):
    word, count = items[i]
    print(word)

字符串拼接操作

在这里插入图片描述

char = input("")
nums = int(input(""))
date = input("")
dateList = date.split("/")
print(char * nums)
print(dateList[0] + "年" + dateList[1] + "月" + dateList[2] + "日")
print(char * nums)

自幂数

在这里插入图片描述

n = int(input(""))
list2 = []
for i in range(10 ** (n - 1), 10 ** n):
    str1 = str(i)
    sum1 = 0
    for j in str1:
        num = int(j)
        sum1 += num ** n
    if i == sum1:
        list2.append(i)
for i in list2:
    print(i)

回文判断

在这里插入图片描述

a = input("")
b = a[::-1]
if a == b:
    print("True")
else:
    print("False")

字符串连接

在这里插入图片描述

s = input()
print('.'.join(s.split(',')))

首字母大写

在这里插入图片描述

str = input("")
print(str.title())

字母查找2.0(函数)

在这里插入图片描述

def f(m,n):
    for i in m:
        if i not in n or len(m) > len(n):
            return 'NOT FOUND'
    return 'FOUND'

m=input()
if m.isalpha():
    n=input()
    print(f(m, n))
else:
    print('ERROR')

IP地址转换

在这里插入图片描述

str1 = input("")
for i in str1:
    if i != '0' and i != '1':
        print('data error!')
        exit()
if len(str1) != 32:
    print('data error!')
else:
    decimalIP = str(int(str1[0:8], 2))
    for i in range(1, 4):
        decimalIP = decimalIP + '.' + str(int(str1[i * 8:(i + 1) * 8], 2))
    print(decimalIP)

哥德巴赫猜想

在这里插入图片描述

n = int(input())


def isPrime(n):
    if n <= 1:
        return False
    for i in range(2, (int(n ** 0.5) + 1)):
        if n % i == 0:
            return False
    return True


if n % 2 != 0:
    print("Data error!")
else:
    for x in range(2, n):
        y = n - x
        if isPrime(x) == 1 and isPrime(y) == 1:
            print("{:d} = {:d} + {:d}".format(n, x, y))
            break

计算ID号

在这里插入图片描述

import math


def isPrime(n):
    if n == 2 or n == 3:
        return True
    else:
        for i in range(2, int(math.sqrt(n)) + 1):
            if n % i == 0:
                return False
            else:
                return True


def count(n, num):
    s = 0
    for i in range(len(str(n))):
        x = int(str(n)[-i - 1])
        s += n // 10 ** (i + 1) * 10 ** i
        if x == num:
            s += n % 10 ** i + 1
        if x > num:
            s += 10 ** i
    return s


a = int(input())
b = int(input())
for i in range(a):
    if isPrime(i) and a % i == 0 and isPrime(a // i):
        print("WHUT" + str(a // i) + str(i))
        break
print(count(int(str(a // i) + str(i)), b))

通讯录(文件读取)

在这里插入图片描述

f = open("info.csv", 'r', encoding='gbk')
l = []
for line in f:
    l.append(line.replace("\n", "").split(","))
d = { 
   }
for c in l:
    d[c[0]] = [c[1], c[2]]
f.seek(0)
s = input()
if s == 'A':
    for line in f:
        print(line.replace(",", " ").replace("\n", ""))
elif s == "D":
    print(d)
else:
    print("ERROR")
f.close()

传感器日志光照统计

在这里插入图片描述

f = open("sensor-data-1k.txt", "r")
avg, cnt = 0, 0
for line in f:
    ls = line.split()
    cnt += 1
    avg += eval(ls[4])
print("{:.2f}".format(avg / cnt))

十二星座

在这里插入图片描述

f = open("SunSign.csv", "r", encoding='utf-8')
ls = []
for line in f:
    line = line.replace("\n", "")
    ls.append(line.split(","))
f.close()

while True:
    str1 = input()
    str1.strip()
    flag = False
    if str1 == 'exit':
        break
    for line in ls:
        if str1 == line[0]:
            print("{}座的生日位于{}-{}之间".format(chr(eval(line[3])), line[1], line[2]))
            flag = True
    if not flag:
        print("输入星座名称有误!")

传感器采集数据

在这里插入图片描述

f = open("sensor-data.txt", "r") 
l = [] 
s = f.readline()
while s:
    l.append(float(list(s.split())[4]))
    s = f.readline()
print("最大值、最小值、平均值分别是:%.2f,%.2f,%.2f" % (max(l), min(l), sum(l) / len(l)))
f.close()

圣诞老人的礼物

在这里插入图片描述

boxes_list = []
n, w = map(int, input().split())
for i in range(n):
    temp = list(map(int, input().split()))
    value_rate = temp[0] / temp[1]
    temp.append(value_rate)
    boxes_list.append(temp)
boxes_list = sorted(boxes_list, key=lambda x: x[2], reverse=True)
totalW, totalV = 0, 0.0
for i in range(n):
    if totalW + boxes_list[i][1] <= w:
        totalW += boxes_list[i][1]
        totalV += boxes_list[i][0]
    else:
        totalV += (w - totalW) * boxes_list[i][2]
        break
print("%.1f" % totalV)

小马统计逆序对

在这里插入图片描述

n = int(input())
count = 0
str = input()
str_list = str.split()
num_list = [int(x) for x in str_list]
for i in range(n):
    for j in range(i + 1, n):
        if (num_list[i] > num_list[j]):
            count = count + 1
print(count![在这里插入图片描述](https://img-blog.csdnimg.cn/e6056d76985549ba93e0aae0a8fc1cb1.png)

今天的文章python123部分编程题分享到此就结束了,感谢您的阅读,如果确实帮到您,您可以动动手指转发给其他人。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/32341.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注