Demo01 摄氏温度转化为华氏温度
celsius = int(input("输入摄氏温度:\n\n"))
print()
fahrenheit = (9/5)*celsius + 32
print(f"输出:\n\n{fahrenheit}")
Demo02 计算圆柱体的体积
radius, length = input("输入:\n\n").split() # 输入两个数,并以空格隔开
radius = float(radius)
length = float(length)
print()
pi = 3.14
area = round(radius*radius*pi, 2) #round保留两位小数
volume = round(area*length, 2)
print(f"输出:\n\n{area}\n\n{volume}")
Demo03 将英尺数转换为米数
foot = float(input("输入:\n\n"))
meter_ruler = round(foot*0.305, 4)
print(f"输出:\n\n{meter_ruler}")
Demo04 计算小费
subtotal, Honorarium_rate = input("输入:\n\n").split()
subtotal = float(subtotal)
Honorarium_rate = float(Honorarium_rate)
Honorarium_rate = Honorarium_rate*0.01
tip = round(subtotal*Honorarium_rate, 2)
Total_amount =round(tip + subtotal, 2)
print(f"输出:\n\n{tip}\n\n{Total_amount}")
Demo05 对一个整数中的各位数字求和
while True:
num = int(input("输入:\n\n"))
if num < 0 or num > 1000:
print()
print("ERROR!\n")
else:
a = num // 100
b = (num - a*100) // 10
c = num % 10
sum = a + b + c
break
print(f"\n输出:\n\n{sum}\n")
print(f"解释:\n\n{num}各位数之和为:{a} + {b} + {c} = {sum}")
Demo06 计算年数和天数
minute = int(input("输入:\n\n"))
day = int(minute / 60 / 24)
year = day // 365
day = day % 365
print(f"输出:\n\n{year}\n\n{day}")
Demo07 计算能量
M = float(input("输入:\n\n"))
print()
initialTemperature = float(input())
print()
finalTemperature = float(input())
Q = round(M * (finalTemperature - initialTemperature) * 4184, 1)
print(f"输出:\n\n{Q}")
Demo08 分割数字
num = int(input("输入:\n\n"))
print()
if num >= 10000 or num <= 999:
print("ERROR!")
a = num % 10
b = num % 100 // 10
c = num % 1000 // 100
d = num // 1000
print(f"输出:\n\n{a}\n\n{b}\n\n{c}\n\n{d}")
Demo09 计算三角形的面积
import math
def calculate_triangle_area(x1, y1, x2, y2, x3, y3):
"""
计算三角形面积
参数:
x1, y1: 第一个顶点坐标
x2, y2: 第二个顶点坐标
x3, y3: 第三个顶点坐标
返回值:
三角形的面积
"""
side1 = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
side2 = math.sqrt((x3 - x2)**2 + (y3 - y2)**2)
side3 = math.sqrt((x1 - x3)**2 + (y1 - y3)**2)
s = (side1 + side2 + side3) / 2
area = math.sqrt(s * (s - side1) * (s - side2) * (s - side3))
return round(area, 1)
# 输入三角形的三个顶点坐标
print("输入:\n")
x1, y1, x2, y2, x3, y3 = map(float, input().split())
# 计算三角形的面积并输出
print("\n输出\n")
print(calculate_triangle_area(x1, y1, x2, y2, x3, y3))
Demo10 显示当前时间
import datetime
def get_adjusted_time(timezone):
# 获取当前时间
current_time = datetime.datetime.utcnow()
# 根据时区调整时间
adjusted_time = current_time + datetime.timedelta(hours=timezone)
return adjusted_time.strftime("%H:%M:%S")
# 输入时区
timezone = int(input("请输入时区:"))
# 获取调整后的时间
adjusted_time = get_adjusted_time(timezone)
# 输出调整后的时间
print(adjusted_time)
Demo11 计算三角形的三个角
import math
def calculate_angles(x1, y1, x2, y2, x3, y3):
# 计算三条边的长度
a = math.sqrt((x2 - x3)**2 + (y2 - y3)**2)
b = math.sqrt((x1 - x3)**2 + (y1 - y3)**2)
c = math.sqrt((x1 - x2)**2 + (y1 - y2)**2)
# 计算三个角度
angle_a = math.degrees(math.acos((a**2 - b**2 - c**2) / (-2 * b * c)))
angle_b = math.degrees(math.acos((b**2 - a**2 - c**2) / (-2 * a * c)))
angle_c = math.degrees(math.acos((c**2 - b**2 - a**2) / (-2 * a * b)))
return angle_a, angle_b, angle_c
# 输入三个顶点坐标
x1, y1, x2, y2, x3, y3 = map(float, input("请输入三个顶点的坐标:").split())
# 计算三个角度
angle_a, angle_b, angle_c = calculate_angles(x1, y1, x2, y2, x3, y3)
# 输出结果
print("角A的度数:{:.2f}".format(angle_a))
print("角B的度数:{:.2f}".format(angle_b))
print("角C的度数:{:.2f}".format(angle_c))
Demo12 最小数量的硬币
def coin_exchange():
total_amount = float(input("请输入总金额:"))
coin_values = [100, 25, 10, 5, 1] # 硬币面值,单位为分
coin_counts = [0] * len(coin_values) # 硬币数量
total_amount_in_cents = int(total_amount * 100) # 将总金额转换为分
for i in range(len(coin_values)):
coin_counts[i] = total_amount_in_cents // coin_values[i] # 计算每种硬币的数量
total_amount_in_cents %= coin_values[i] # 更新剩余金额
print("兑换结果:")
for i in range(len(coin_values)):
print(f"{coin_counts[i]}个{get_coin_name(i)}硬币")
def get_coin_name(index):
coin_names = ["一元", "两角五分", "一角", "五分", "一分"]
return coin_names[index]
coin_exchange()
Demo13 正多边形的面积
import math
def calculate_polygon_area(n, s):
area = (n * s**2) / (4 * math.tan(math.pi / n))
return round(area, 2)
n, s = map(float, input("请输入边的个数和边的长度(以空格分隔):").split())
result = calculate_polygon_area(n, s)
print("正{}多边形的面积为:{:.2f}".format(int(n), result))
Demo14 计算身体质量指数
def calculate_bmi(weight, height):
bmi = weight / (height ** 2)
return bmi
weight, height = map(float, input("请输入体重(kg)和身高(m)(以空格分隔):").split())
bmi = calculate_bmi(weight, height)
if bmi < 18.5:
result = "超轻"
elif bmi < 25.0:
result = "标准"
elif bmi < 30.0:
result = "超重"
else:
result = "肥胖"
print("BMI指数结果:", result)
Demo15 判定闰年
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
return "Yes"
else:
return "No"
year = int(input("请输入一个年份:"))
result = is_leap_year(year)
print(result)
Demo16 中彩票
import random def lottery(guess): random_num = random.randint(10, 99) print("随机产生的两位数:", random_num) if guess == random_num: return 10000 elif sorted(str(guess)) == sorted(str(random_num)): return 3000 elif str(guess)[0] == str(random_num)[0] or str(guess)[1] == str(random_num)[1]: return 1000 else: return 0 guess = int(input("请输入一个两位数:")) prize = lottery(guess) print("用户的奖金:", prize)
Demo17 解一元二次方程
import math
def solve_quadratic_equation(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
return root1, root2
elif discriminant == 0:
root = -b / (2*a)
return root
else:
return "无实数解"
a, b, c = map(float, input("请输入a、b、c的值(以空格分隔):").split())
result = solve_quadratic_equation(a, b, c)
if isinstance(result, tuple):
print("{:.2f}".format(result[0]))
print("{:.2f}".format(result[1]))
else:
print(result)
Demo18 解2×2线程方程
def solve_linear_equations(a, b, c, d, e, f):
determinant = a * d - b * c
if determinant != 0:
x = (e * d - b * f) / determinant
y = (a * f - e * c) / determinant
return x, y
else:
return "无解"
a, b, c, d, e, f = map(float, input("请输入a、b、c、d、e、f的值(以空格分隔):").split())
result = solve_linear_equations(a, b, c, d, e, f)
if isinstance(result, tuple):
print("{:.1f}".format(result[0]))
print("{:.1f}".format(result[1]))
else:
print(result)
Demo19 未来是周几
def calculate_future_day(today, days):
future_day = (today + days) % 7
return future_day
day_of_week = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
today, days = map(int, input("请输入今日星期几的数字和未来某天的天数(以空格分隔):").split())
future_day = calculate_future_day(today, days)
print(day_of_week[future_day])
Demo20 本年中的第几天
def calculate_day_of_year(year, month, day):
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
# 判断是否是闰年,如果是闰年则将二月的天数设为29
if is_leap_year(year):
days_in_month[1] = 29
day_of_year = sum(days_in_month[:month-1]) + day
return day_of_year
def is_leap_year(year):
if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0):
return True
else:
return False
year, month, day = map(int, input("请输入年、月、日(以空格分隔):").split())
day_of_year = calculate_day_of_year(year, month, day)
print(day_of_year)
Demo21 剪刀石头布I
import random
def rock_paper_scissors(user_choice):
computer_choice = random.randint(0, 2)
choices = ["剪刀", "石头", "布"]
print("计算机出的:", choices[computer_choice])
print("用户出的:", choices[user_choice])
if user_choice == computer_choice:
return "平局"
elif (user_choice == 0 and computer_choice == 1) or (user_choice == 1 and computer_choice == 2) or (user_choice == 2 and computer_choice == 0):
return "计算机赢"
else:
return "用户赢"
user_choice = int(input("请输入数字0、1或2(分别代表剪刀、石头、布):"))
result = rock_paper_scissors(user_choice)
print(result)
Demo22 三角形的周长
def calculate_triangle_perimeter(a, b, c):
if a + b > c and a + c > b and b + c > a:
perimeter = a + b + c
return perimeter
else:
return "非法"
a, b, c = map(float, input("请输入三角形的三边长度(以空格分隔):").split())
result = calculate_triangle_perimeter(a, b, c)
print(result)
Demo23 一周的星期几
def calculate_day_of_week(year, month, day):
if month < 3:
month += 12
year -= 1
j = year // 100
k = year % 100
h = (day + (26 * (month + 1) // 10) + k + (k // 4) + (j // 4) + (5 * j)) % 7
day_of_week = ["星期六", "星期天", "星期一", "星期二", "星期三", "星期四", "星期五"]
return day_of_week[h]
year, month, day = map(int, input("请输入年、月、日(以空格分隔):").split())
result = calculate_day_of_week(year, month, day)
print(result)
Demo24 直线的交点
def calculate_intersection(x1, y1, x2, y2, x3, y3, x4, y4):
denominator = (y1 - y2) * (x3 - x4) - (x1 - x2) * (y3 - y4)
if denominator == 0:
return "两条直线平行"
else:
x = ((y1 - y2) * (x1 - x3) * (x4 - x3) + y3 * (x2 - x1) * (x4 - x3) - y1 * (x4 - x3) * (x2 - x1)) / denominator
y = ((y1 - y2) * (y3 - y1) * (x2 - x1) + x1 * (y2 - y1) * (x2 - x1) - y1 * (x2 - x1) * (x3 - x4)) / denominator
return x, y
x1, y1, x2, y2, x3, y3, x4, y4 = map(float, input("请输入x1 y1 x2 y2 x3 y3 x4 y4的值(以空格分隔):").split())
result = calculate_intersection(x1, y1, x2, y2, x3, y3, x4, y4)
print(result)
Demo25 回文数
def is_palindrome_number(number):
number_str = str(number)
reversed_number_str = number_str[::-1] # 将字符串反转
if number_str == reversed_number_str:
return "Yes"
else:
return "No"
number = int(input("请输入一个三位整数:"))
result = is_palindrome_number(number)
print(result)
Demo26 两个矩形
def calculate_rectangle_relation(x1, y1, w1, h1, x2, y2, w2, h2):
left1 = x1 - w1 / 2
right1 = x1 + w1 / 2
top1 = y1 + h1 / 2
bottom1 = y1 - h1 / 2
left2 = x2 - w2 / 2
right2 = x2 + w2 / 2
top2 = y2 + h2 / 2
bottom2 = y2 - h2 / 2
if left1 > right2 or left2 > right1 or bottom1 > top2 or bottom2 > top1:
return "相离"
elif left1 == left2 and right1 == right2 and bottom1 == bottom2 and top1 == top2:
return "包含"
else:
return "重叠"
x1, y1, w1, h1 = map(float, input("请输入第一个矩形的中心坐标x、y和宽、高(以空格分隔):").split())
x2, y2, w2, h2 = map(float, input("请输入第二个矩形的中心坐标x、y和宽、高(以空格分隔):").split())
result = calculate_rectangle_relation(x1, y1, w1, h1, x2, y2, w2, h2)
print(result)
第二部分 循环语句
Demo27 打印数字I
def print_pattern_a(n):
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=' ')
print()
def print_pattern_b(n):
for i in range(n, 0, -1):
for j in range(1, i+1):
print(j, end=' ')
print()
def print_pattern_c(n):
for i in range(1, n+1):
for j in range(n-i, 0, -1):
print(' ', end=' ')
for j in range(i, 0, -1):
print(j, end=' ')
print()
def print_pattern_d(n):
for i in range(n, 0, -1):
for j in range(n-i):
print(' ', end=' ')
for j in range(1, i+1):
print(j, end=' ')
print()
n = int(input("请输入一个整数:"))
print("模式A")
print_pattern_a(n)
print("模式B")
print_pattern_b(n)
print("模式C")
print_pattern_c(n)
print("模式D")
print_pattern_d(n)
Demo28 打印数字II
def print_pattern(n):
for i in range(1, n+1):
for j in range(n-i, 0, -1):
print(' ', end=' ')
for j in range(i, 0, -1):
print(j, end=' ')
for j in range(2, i+1):
print(j, end=' ')
print()
n = int(input("请输入一个整数:"))
print_pattern(n)
Demo29 打印数字III
def print_pattern(n):
for i in range(0, n):
for j in range(0, n-i-1):
print(" ", end=" ")
num = 1
for j in range(0, i+1):
print(num, end=" ")
num *= 2
num //= 2
for j in range(0, i):
num //= 2
print(num, end=" ")
print()
n = int(input("请输入一个整数:"))
print_pattern(n)
Demo30 打印菱形I
def print_diamond(n):
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for j in range(i+1):
print("* ", end="")
print()
for i in range(n-1, 0, -1):
for j in range(n-i):
print(" ", end="")
for j in range(i):
print("* ", end="")
print()
n = int(input("请输入菱形的高度(奇数):"))
print_diamond(n)
Demo31 打印菱形II
def print_hollow_diamond(n):
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for j in range(i*2+1):
if j == 0 or j == i*2:
print("*", end="")
else:
print(" ", end="")
print()
for i in range(n-2, -1, -1):
for j in range(n-i-1):
print(" ", end="")
for j in range(i*2+1):
if j == 0 or j == i*2:
print("*", end="")
else:
print(" ", end="")
print()
n = int(input("请输入一个正整数:"))
print_hollow_diamond(n)
Demo32 打印菱形III
def print_diamond(n):
for i in range(n):
for j in range(n-i-1):
print(" ", end="")
for j in range(i*2+1):
print("*", end="")
print()
for i in range(n-2, -1, -1):
for j in range(n-i-1):
print(" ", end="")
for j in range(i*2+1):
print("*", end="")
print()
n = int(input("请输入一个奇数:"))
print_diamond(n)
Demo33 猜数字
import random
def guess_number():
random_number = random.randint(0, 100)
guess = -1
while guess != random_number:
guess = int(input("请输入一个整数:"))
if guess > random_number:
print("高了")
elif guess < random_number:
print("低了")
else:
print("猜中了!答案就是", random_number)
guess_number()
Demo34 最大公约数I
def calculate_gcd(a, b):
while b != 0:
a, b = b, a % b
return a
a, b = map(int, input("请输入两个正整数:").split())
gcd = calculate_gcd(a, b)
print(gcd)
Demo35 判断素数
def is_prime_number(number):
if number <= 1:
return "No"
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return "No"
return "Yes"
number = int(input("请输入一个大于1的正整数:"))
result = is_prime_number(number)
print(result)
Demo36 最小公倍数
def calculate_least_common_multiple(a, b):
if a == 0 or b == 0:
return 0
else:
gcd = calculate_greatest_common_divisor(a, b)
lcm = (a * b) // gcd
return lcm
def calculate_greatest_common_divisor(a, b):
while b != 0:
a, b = b, a % b
return a
a, b = map(int, input("请输入两个正整数:").split())
result = calculate_least_common_multiple(a, b)
print(result)
Demo37 整数的素因子
def find_prime_factors(n): factors = [] i = 2 while i <= n: if n % i == 0: factors.append(i) n = n // i else: i += 1 return factors n = int(input("请输入一个正整数:")) prime_factors = find_prime_factors(n) for factor in prime_factors: print(factor, end=' ')
Demo38 完全数
def is_perfect_number(n):
factors_sum = 0
for i in range(1, n):
if n % i == 0:
factors_sum += i
if factors_sum == n:
return "Yes"
else:
return "No"
n = int(input("请输入一个正整数:"))
result = is_perfect_number(n)
print(result)
Demo39 前50个素数
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
count = 0
num = 2
while count < 50:
if is_prime(num):
print(num, end=' ')
count += 1
if count % 10 == 0:
print()
num += 1
Demo40 计算π
def calculate_pi(n):
pi = 0
sign = 1
for i in range(1, n+1):
term = 1 / (2*i - 1)
pi += sign * term
sign *= -1
pi *= 4
return pi
n = int(input("请输入要计算π的项数:"))
result = calculate_pi(n)
print(result)
Demo41 计算e
def calculate_e(n):
e = 1
factorial = 1
for i in range(1, n+1):
factorial *= i
e += 1 / factorial
return e
n = int(input("请输入要计算e的项数:"))
result = calculate_e(n)
print(result)
Demo42 剪刀石头布II
import random
def rock_paper_scissors():
choices = ["剪刀", "石头", "布"]
computer_score = 0
player_score = 0
while computer_score < 3 and player_score < 3:
computer_choice = random.choice(choices)
player_choice = input("请输入数字0、1或2(分别代表剪刀、石头、布):")
print("计算机出的:", computer_choice)
print("玩家出的:", choices[int(player_choice)])
if player_choice == "0" and computer_choice == "石头":
computer_score += 1
elif player_choice == "1" and computer_choice == "布":
computer_score += 1
elif player_choice == "2" and computer_choice == "剪刀":
computer_score += 1
elif computer_choice == "0" and player_choice == "石头":
player_score += 1
elif computer_choice == "1" and player_choice == "布":
player_score += 1
elif computer_choice == "2" and player_choice == "剪刀":
player_score += 1
if computer_score == 3:
return "计算机是终极胜利者"
else:
return "玩家是终极胜利者"
result = rock_paper_scissors()
print(result)
Demo43 组合问题I
def combination():
count = 0
for i in range(1, 7):
for j in range(i+1, 8):
print("组合({},{})".format(i, j))
count += 1
return count
total_count = combination()
print("所有组合的个数:", total_count)
Demo44 组合问题II
def combination():
count = 0
combinations = []
for i in range(1, 5):
for j in range(1, 5):
for k in range(1, 5):
if i != j and i != k and j != k:
count += 1
combinations.append(i * 100 + j * 10 + k)
return count, combinations
total_count, combinations = combination()
print("能组成的互不相同且无重复数字的三位数的个数:", total_count)
print("具体的数字组合:", combinations)
Demo45 水仙花数
def find_armstrong_numbers():
armstrong_numbers = []
for number in range(100, 1000):
digit1 = number // 100
digit2 = (number % 100) // 10
digit3 = number % 10
if number == (digit1 ** 3 + digit2 ** 3 + digit3 ** 3):
armstrong_numbers.append(number)
return armstrong_numbers
numbers = find_armstrong_numbers()
print("所有的水仙花数:", numbers)
Demo46 青蛙跳台阶
def calculate_frog_jump(n):
if n <= 0:
return 0
elif n == 1:
return 1
elif n == 2:
return 2
else:
dp = [0] * (n+1)
dp[1] = 1
dp[2] = 2
for i in range(3, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]
n = int(input("请输入台阶的数量:"))
result = calculate_frog_jump(n)
print("不同的跳法数量:", result)
Demo47 堆叠相加
def calculate_stacked_sum(a, n):
sum = 0
curr = a
for i in range(n):
sum += curr
curr = curr * 10 + a
return sum
a, n = map(int, input("请输入数字a和组数n(以空格分隔):").split())
result = calculate_stacked_sum(a, n)
print(result)
Demo48 十进制转二进制
def decimal_to_binary(n):
binary = ""
while n > 0:
binary = str(n%2) + binary
n = n // 2
return binary
n = int(input("请输入一个十进制正整数:"))
binary = decimal_to_binary(n)
print(binary)
Demo49 二进制转十进制
def binary_to_decimal(binary):
decimal = 0
power = len(binary) - 1
for digit in binary:
decimal += int(digit) * (2 ** power)
power -= 1
return decimal
binary = input("请输入一个二进制字符串:")
decimal = binary_to_decimal(binary)
print(decimal)
Demo50 十进制转十六进制
def decimal_to_hexadecimal(decimal):
hexadecimal = hex(decimal)[2:]
return hexadecimal
decimal = int(input("请输入一个十进制正整数:"))
hexadecimal = decimal_to_hexadecimal(decimal)
print(hexadecimal)
Demo51 十六进制转十进制
def hexadecimal_to_decimal(hexadecimal):
decimal = int(hexadecimal, 16)
return decimal
hexadecimal = input("请输入一个十六进制字符串:")
decimal = hexadecimal_to_decimal(hexadecimal)
print(decimal)
Demo52 最长公共前缀
def longest_common_prefix(s1, s2):
prefix = ""
min_len = min(len(s1), len(s2))
for i in range(min_len):
if s1[i] == s2[i]:
prefix += s1[i]
else:
break
return prefix
s1 = input("请输入字符串s1:")
s2 = input("请输入字符串s2:")
result = longest_common_prefix(s1, s2)
print(result)
Demo53 子串出现的次数
def count_substring(s1, s2):
count = 0
start = 0
while True:
index = s1.find(s2, start)
if index == -1:
break
count += 1
start = index + len(s2)
return count
s1 = input("请输入字符串s1:")
s2 = input("请输入字符串s2:")
result = count_substring(s1, s2)
print(result)
Demo54 最长公共子串
def longest_common_substring(s1, s2):
m = len(s1)
n = len(s2)
dp = [[0] * (n+1) for _ in range(m+1)]
max_length = 0
end_index = 0
for i in range(1, m+1):
for j in range(1, n+1):
if s1[i-1] == s2[j-1]:
dp[i][j] = dp[i-1][j-1] + 1
if dp[i][j] > max_length:
max_length = dp[i][j]
end_index = i
return s1[end_index-max_length:end_index]
s1 = input("请输入字符串s1:")
s2 = input("请输入字符串s2:")
result = longest_common_substring(s1, s2)
print(result)
Demo55 检测密码
def check_password(password):
if len(password) < 8:
return "No"
count_digit = 0
count_upper = 0
for char in password:
if not char.isalnum():
return "No"
if char.isdigit():
count_digit += 1
if char.isupper():
count_upper += 1
if count_digit < 2 or count_upper < 2:
return "No"
return "Yes"
password = input("请输入密码:")
result = check_password(password)
print(result)
Demo56 回文素数
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def is_palindrome(n):
return str(n) == str(n)[::-1]
count = 0
num = 2
print("前100个回文素数:")
while count < 100:
if is_prime(num) and is_palindrome(num):
print(num, end=' ')
count += 1
if count % 10 == 0:
print()
num += 1
Demo57 反素数
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def is_reverse_prime(n):
reverse_n = int(str(n)[::-1])
return is_prime(n) and is_prime(reverse_n)
count = 0
num = 2
print("前100个反素数:")
while count < 100:
if is_reverse_prime(num):
print(num, end=' ')
count += 1
if count % 10 == 0:
print()
num += 1
Demo58 双素数
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def find_twin_primes(limit):
twin_primes = []
for num in range(2, limit):
if is_prime(num) and is_prime(num + 2):
twin_primes.append((num, num + 2))
return twin_primes
limit = 1000
print("小于1000的双素数:")
twin_primes = find_twin_primes(limit)
for twin_prime in twin_primes:
print(twin_prime[0], twin_prime[1])
Demo59 梅森素数
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def find_mersenne_primes():
mersenne_primes = []
for p in range(2, 32):
num = 2**p - 1
if is_prime(num):
mersenne_primes.append((p, num))
return mersenne_primes
print("p ≤ 31的所有梅森素数:")
mersenne_primes = find_mersenne_primes()
for mersenne_prime in mersenne_primes:
print("p =", mersenne_prime[0], ", 梅森素数 =", mersenne_prime[1])
Demo60 平方根的近似求法
def sqrt_approximation(n):
last_guess = 1
next_guess = (last_guess + n / last_guess) / 2
while abs(next_guess - last_guess) > 0.0001:
last_guess = next_guess
next_guess = (last_guess + n / last_guess) / 2
return next_guess
n = float(input("请输入一个数:"))
approximation = sqrt_approximation(n)
print("平方根的近似值:", approximation)
不死兔子
def immortal_rabbit(n):
if n == 0 or n == 1:
return 1
else:
return immortal_rabbit(n-1) + immortal_rabbit(n-2)
n = int(input("请输入月份:"))
result = immortal_rabbit(n)
print("第", n, "个月的兔子数量为:", result)
英雄联盟商城注册、登入、购买系统
import os
import time
class Hero:
def __init__(self, name, price):
self.name = name
self.price = price
class User:
def __init__(self, username, password):
self.username = username
self.password = password
self.shopping_cart = ShoppingCart()
self.create_user_info_file()
def create_user_info_file(self):
filename = f"{self.username}.txt"
with open(filename, 'w') as file:
file.write(f"Username: {self.username}\nPassword: {self.password}")
def login(self, username, password):
if self.username == username and self.password == password:
print("登录成功!")
return True
else:
print("用户名或密码错误!")
return False
def buy_hero(self, hero):
self.shopping_cart.add_item(hero)
print(f"{hero.name} 已添加到购物车")
def check_gold(self):
total_price = self.shopping_cart.calculate_total_price()
print(f"当前金币余额:{self.calculate_gold()},购物车总价格:{total_price}")
if self.calculate_gold() >= total_price:
return True
else:
print("金币不足,无法结算!")
return False
def calculate_gold(self):
# 假设用户的金币余额为10000
return 10000
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, item):
self.items.append(item)
def remove_item(self, item):
self.items.remove(item)
def calculate_total_price(self):
total_price = 0
for item in self.items:
total_price += item.price
return total_price
def main():
heroes = [
Hero("亚索", 6300),
Hero("盖伦", 4500),
Hero("艾希", 4800),
Hero("劫", 6300),
Hero("瑞兹", 4800),
Hero("阿卡丽", 4800),
Hero("易", 4500),
Hero("卡特琳娜", 4800)
]
print("欢迎来到英雄联盟商城购买系统")
while True:
print("请选择操作:")
print("1. 注册")
print("2. 登录")
choice = input("请输入操作编号:")
if choice == "1":
username = input("请输入用户名:")
password = input("请输入密码:")
user = User(username, password)
print("注册成功!")
continue
elif choice == "2":
username = input("请输入用户名:")
password = input("请输入密码:")
user = User(username, password)
login_attempts = 0
while login_attempts < 3:
if user.login(username, password):
while True:
print("请选择操作:")
print("1. 购买英雄")
print("2. 查看购物车")
print("3. 结算")
choice = input("请输入操作编号:")
if choice == "1":
print("可购买的英雄列表:")
for i, hero in enumerate(heroes):
print(f"{i+1}. {hero.name:<10} - 价格:{hero.price}")
hero_choice = int(input("请输入要购买的英雄编号:"))
user.buy_hero(heroes[hero_choice-1])
continue
elif choice == "2":
print("购物车中的英雄:")
for i, item in enumerate(user.shopping_cart.items):
print(f"{i+1}. {item.name}")
continue
elif choice == "3":
if user.check_gold():
total_price = user.shopping_cart.calculate_total_price()
print(f"总价格:{total_price}")
print("购买成功!感谢您的购买!")
return
else:
login_attempts += 1
print(f"登录失败!还剩 {3 - login_attempts} 次尝试机会")
if login_attempts == 3:
print("登录失败次数过多,请等待五分钟再进行登录")
time.sleep(300) # 等待五分钟
else:
username = input("请输入用户名:")
password = input("请输入密码:")
break
if __name__ == "__main__":
main()