略
略
pip list
year = 19
guess_age = int(input("请输入你猜的年龄:"))
if year == guess_age:
print("Yes,it is right!")
else:
print("No,you are wrong!")
【源程序】
###################################
<人名 1> 新年贺卡 <人名 2>
python0101.py
2015
###################################
name1 = input("Please enter a value for name1:")
name2 = input("Please enter a value for name2:")
print(f'''
###################################
# {name1} 新年贺卡 {name2}
# python0101.py
# 2015
###################################
''')
import math
r = float(input("Please enter a valur for radius:"))
surface = '%.10f' % round(4 * math.pi * r * r, 2)
volume = '%.10f' % round(4 / 3 * math.pi * (r ** 3), 2)
print(f"The surface area of sphere is {surface}")
print(f'The volume of sphere if {volume}')
str1 = "这是一个变量"
print("变量str1的值是:" + str1)
print("变量str1的地址是:%d" % (id(str1)))
str2 = str1
print("变量str2的值是:" + str2)
print("变量str2的地址是:%d" % (id(str2)))
str1 = "这是另一个变量"
print("变量str1的值是:" + str1)
print("变量str1的地址是:%d" % (id(str1)))
print("变量str2的值是:" + str2)
print("变量str2的地址是:%d" % (id(str2)))
x = 3
x += 3
print(x)
x -= 3
print(x)
x *= 3
print(x)
x /= 3
print(x)
list = [1, 2, 3, 4]
count = 0
for i in list:
for j in list:
for k in list:
if (i != j) and (i != k) and (j != k):
count += 1
print(f"{i}{j}{k}", end=" ")
print("")
print(f"The count is {count}")
year = int(input('year: '))
mouth = int(input('month:'))
day = int(input('day:'))
mouths = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if year % 400 == 0 or year % 4 == 0:
mouths[3] += 1
if 0 < mouth <= 12:
days = 0
for item in range(mouth):
sum = mouths[item]
days += sum
result = days + day
print(f'今天是今年的第{result}天')
else:
print('输入日期超出范围')
list = [int(input("Please input a value for x:")), int(input("Please input a value for y:")),
int(input("Please input a value for z:"))]
print(sorted(list))
print('\n'.join([' '.join([f"{j}x{i}={i * j}" for j in range(1, i + 1)]) for i in range(1, 10)]))
result = []
for i in range(101, 200):
for j in range(2, i - 1):
if i % j == 0:
break
else:
result.append(i)
print(f"素数一共有{len(result)}个")
print(result)
str = input("请输入一行字符:")
count_alpha = 0
count_space = 0
count_digit = 0
count_other = 0
for i in str:
if i.isalpha():
count_alpha += 1
if i.isspace():
count_space += 1
if i.isdigit():
count_digit += 1
else:
count_other += 1
print(f"{str}中的英文字母个数为:{count_alpha}")
print(f"{str}中的空格个数为:{count_space}")
print(f"{str}中的数字个数为:{count_digit}")
print(f"{str}中的其他字符个数为:{count_other}")
result = []
for i in range(1, 21):
num = 1
for j in range(1, i + 1):
num *= j
result.append(num)
print(sum(result))
d = {'wzr': '1', 'Lebron': 2, 'is': 3, 'GOAT': 4}
n = input("请输入键:")
print(d.get(n, "您输入的键不存在!"))
from random import choices
data = choices(range(100), k=20)
print(data)
data[:10] = sorted(data[:10])
data[10:] = sorted(data[10:], reverse=True)
print(data)
a.请将 a 字符串的数字取出,并输出成一个新的字符串。
b.请统计 a 字符串出现的每个字母的出现次数(忽略大小写,a 与 A 是同一个字母),并输出成一个字典。 例 {‘a’:3,‘b’:1}
c.请去除 a 字符串多次出现的字母,仅留最先出现的一个,大小写不敏感。例
‘aAsmr3idd4bgs7Dlsf9eAF’,经过去除后,输出 ‘asmr3id4bg7lf9e’
d.按 a 字符串中字符出现频率从高到低输出到列表,如果次数相同则按字母顺序排列。
a = "aAsmr3idd4bgs7Dlsf9eAF"
str_digit = ''
for i in a:
if i.isdigit():
str_digit += i
print(str_digit)
lower_a = a.lower()
c = {key: lower_a.count(key) for key in lower_a if key.isalpha()}
print(c)
result = []
for i in a:
if i not in result:
if ('A' <= i <= 'Z') and (i.lower() not in result):
result.append(i)
elif ('a' <= i <= 'z') and (i.upper() not in result):
result.append(i)
elif not i.isalpha():
result.append(i)
print("".join(result))
def isPalindrome(str):
rever_str = str[::-1]
if rever_str == str:
print(f"{str}是回文字符串!")
else:
print(f"{str}不是回文字符串!")
str = input(" ")
isPalindrome(str)
定义一个函数,实验给定任意字符串,查找其中每个字符的最后一次出现,并按每个字符最后一次出现的先后顺序依次存入列表。例如对于字符串’abcda’的处理结果为[‘b’, ‘c’, ‘d’, ‘a’],而字符串’abcbda’的处理结果为[‘c’, ‘b’, ‘d’, ‘a’]。测试函数的正确性。
List = list()
str1 = input("Please enter a value for str1:")
for i in str1:
if List.__contains__(i):
List.remove(i)
List.append(i)
else:
List.append(i)
print(List)
def factorization(n):
list = []
while n > 1:
for i in range(n-1):
k = i + 2
if n % k == 0:
list.append(k)
n = n//k
break
print(list)
factorization(20)
class VehicleClass:
def __init__(self, vehicle_name, num_wheels):
self.vehicle_name = vehicle_name
self.num_wheels = num_wheels
def drive(self):
if self.is_movable:
if self.is_motorized:
return f"{self.vehicle_name}正在启动引擎并行驶。"
else:
return f"{self.vehicle_name}正在踩踏脚踏板。"
else:
return f"{self.vehicle_name}无法行驶,可能需要维修。"
class BusClass(VehicleClass):
def __init__(self, vehicle_name):
super().__init__(vehicle_name, num_wheels=4)
class BicycleClass(VehicleClass):
def __init__(self, vehicle_name):
super().__init__(vehicle_name, num_wheels=2)
class CustomSet:
def __init__(self):
self.elements = []
def add(self, element):
if element not in self.elements:
self.elements.append(element)
def remove(self, element):
if element in self.elements:
self.elements.remove(element)
def union(self, other_set):
new_set = CustomSet()
new_set.elements = self.elements.copy()
for element in other_set.elements:
if element not in new_set.elements:
new_set.elements.append(element)
return new_set
def intersection(self, other_set):
new_set = CustomSet()
for element in self.elements:
if element in other_set.elements:
new_set.add(element)
return new_set
def symmetric_difference(self, other_set):
union_set = self.union(other_set)
intersection_set = self.intersection(other_set)
symmetric_diff_set = union_set.difference(intersection_set)
return symmetric_diff_set
def difference(self, other_set):
new_set = CustomSet()
for element in self.elements:
if element not in other_set.elements:
new_set.add(element)
return new_set
def display(self):
print(self.elements)
class CustomStack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return None
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def getDistance(self, other):
print(f"两点之间的距离为:{round(math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2),2)}")
point1 = Point(5, 1)
point2 = Point(6, 2)
point1.getDistance(point2)
class Rectangle:
def __init__(self, x, y):
self.x = x
self.y = y
def getArea(self):
print(f"长方形的面积为{self.x * self.y}")
def getGirth(self):
print(f"长方形的周长为{self.x * 2 + self.y * 2}")
rectangle1 = Rectangle(9, 10)
rectangle1.getArea()
rectangle1.getGirth()
rectangle2 = Rectangle(5, 5)
rectangle2.getArea()
rectangle2.getGirth()
class BankAccount:
def __init__(self, initial_balance=0.0, interest_rate=0.01):
self.balance = initial_balance
self.interest_rate = interest_rate
def get_balance(self):
return self.balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
return f"存款成功。当前余额:{self.balance}"
else:
return "存款金额必须大于0。"
def withdraw(self, amount):
if amount > 0 and self.balance >= amount:
self.balance -= amount
return f"取款成功。当前余额:{self.balance}"
elif amount <= 0:
return "取款金额必须大于0。"
else:
return "余额不足,无法取款。"
def get_interest_rate(self):
return self.interest_rate
def set_interest_rate(self, new_rate):
if new_rate >= 0:
self.interest_rate = new_rate
return f"利率已更新为 {self.interest_rate * 100}%。"
else:
return "利率不能为负数。"
# 创建银行帐户对象
account = BankAccount(initial_balance=1000.0, interest_rate=0.02)
# 查询余额
print("当前余额:", account.get_balance())
# 存款
print(account.deposit(500))
# 取款
print(account.withdraw(200))
print(account.withdraw(1500))
# 查询利率
print("当前利率:", account.get_interest_rate())
# 设置利率
print(account.set_interest_rate(0.03))
print("当前利率:", account.get_interest_rate())
with open("demo.txt", "r") as f:
data = f.read().swapcase()
print(data)
with open('data.txt', 'r') as fp:
data = fp.readlines()
data = [int(line.strip()) for line in data]
data.sort()
data = [str(i) + '\n' for i in data]
with open('data.txt', 'w') as fp:
fp.writelines(data)
import pickle
stu_dict = {"数据结构": 99,
"计算机网络": 90,
"计算机组成原理": 80,
"操作系统": 98}
s = pickle.dumps(stu_dict)
with open("./dict.txt", "wb") as f:
f.write(s)
f.close()
with open("./dict.txt", "rb") as f:
a_dict = f.read()
f.close()
a_dict = pickle.loads(a_dict)
print(a_dict)
import os
catalogue = input("请输入目录:")
filename = input("请输入文件名:")
flag = True
tuple_dirs = os.walk(catalogue)
for root, dirs, files in tuple_dirs:
if filename in files:
print(f"{catalogue} 目录下有文件 {filename}")
flag = False
break
if flag:
print(f"{catalogue} 目录下没有文件 {filename}")
# 定义变量 A 和 B
A = 5
B = 10
# 计算表达式 ((A + B) * (-A / 2)) 并将结果存储在变量 result 中
result = ((A + B) * (-A / 2))
# 打印结果
print(result)
import numpy as np
matrix = np.mod(np.arange(25), 5).reshape(5, 5)
print(matrix)
import numpy as np
print(np.random.random(10))
# 假设给定的4维向量是一个列表
vector = [1, 2, 3, 4]
# 求倒数第一维和倒数第二维的和
last_dim_1 = vector[-1]
last_dim_2 = vector[-2]
sum_last_dims = last_dim_1 + last_dim_2
# 打印结果
print("倒数第一维和倒数第二维的和:", sum_last_dims)
from matplotlib import pyplot as plt
import numpy as np
import math
x = list(np.arange(0, 20, 0.1))
y = []
for i in range(len(x)):
y.append(math.sin(x[i] - 2) ** 2 * math.e ** (0 - x[i] ** 2))
plt.plot(x, y)
plt.xlabel('x-axis', fontsize=14)
plt.ylabel('y-axis', fontsize=14)
plt.title('f(x) = sin²(x-2)e^(-x²)')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-20, 20, 100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('x-axis', fontsize=14)
plt.ylabel('y-axis', fontsize=14)
plt.title('f(x) = sinx')
plt.show()
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# 假设有多年的成本和利润数据,用列表表示
years = [1, 2, 3, 4, 5] # 年份
costs = [1000, 1200, 1500, 1700, 2000] # 成本数据(假设单位是万元)
profits = [2000, 2200, 2300, 2500, 2800] # 利润数据(假设单位是万元)
# 创建一个线性回归模型
model = LinearRegression()
# 将年份作为输入特征,利润作为目标变量进行拟合
years = np.array(years).reshape(-1, 1) # 将年份转换为二维数组
model.fit(years, profits)
# 使用模型预测下一年的利润
next_year = 6 # 假设下一年的年份是6
next_year_profit = model.predict([[next_year]])[0]
print(f"预测下一年的利润为:{next_year_profit:.2f}万元")
# 绘制利润的折线图
years_for_plot = years.flatten()
profits_for_plot = profits
plt.figure(figsize=(8, 6))
plt.plot(years_for_plot, profits_for_plot, marker='o', linestyle='-', color='b')
plt.xlabel('年份')
plt.ylabel('利润(万元)')
plt.title('利润变化趋势')
plt.grid(True)
# 在图上标记预测值
plt.annotate(f'预测值:{next_year_profit:.2f}万元', xy=(next_year, next_year_profit), xytext=(next_year - 1, next_year_profit + 100),
arrowprops=dict(facecolor='red', arrowstyle='->'))
plt.show()