24级数应二班课堂作业2

height = 10.0
count = 0
threshold = 0.01
while True:
    height *= 0.50
    count += 1
    if height < threshold:
        break
print(f"小球在低于{threshold}米前总共反弹了{count}次")

 

2024090106陈嘉怡 求一百以内的素数
for num in range(2, 101):
    is_prime = True
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            is_prime = False
            break
    if is_prime:
        print(num, end=' ')

 

 

import cmath

# 输入系数
a = float(input("请输入a的值: "))
b = float(input("请输入b的值: "))
c = float(input("请输入c的值: "))
m = float(input("请输入m的值: "))
n = float(input("请输入n的值: "))

# 整理方程为标准形式
if a == 0:
    # 退化为一次方程 (b - m)x + (c - n) = 0
    coefficient = b - m
    constant = c - n
    
    if coefficient == 0:
        if constant == 0:
            print("方程有无穷多解")
        else:
            print("方程无解")
    else:
        x = (-constant) / coefficient
        print(f"方程的解为: x = {x}")
else:
    # 二次方程形式
    new_b = b - m
    new_c = c - n
    
    discriminant = new_b ** 2 - 4 * a * new_c
    
    if discriminant >= 0:
        # 实数解
        sqrt_disc = cmath.sqrt(discriminant)
        x1 = (-new_b + sqrt_disc.real) / (2 * a)
        x2 = (-new_b - sqrt_disc.real) / (2 * a)
        print(f"方程的实数解为: x1 = {x1}, x2 = {x2}")
    else:
        # 复数解
        x1 = (-new_b + cmath.sqrt(discriminant)) / (2 * a)
        x2 = (-new_b - cmath.sqrt(discriminant)) / (2 * a)
        print(f"方程的复数解为: x1 = {x1}, x2 = {x2}")

  

 

2024030259储妙 一段文字有几句话
text = "你好!今天天气不错,你打算去哪里玩呢?要不要和我去散步?"
count = text.count('。') + text.count('?') + text.count('!')
print(count)

 

2024010078马思莹筛选姓名
names = ["李白", "王小明", "张白宇", "赵红", "陈白露"]  # 这里是示例人名列表,你可以替换成实际的人名列表
count = 0
for name in names:
    if "白" in name:
        count += 1
print(count)

 

 

2024010056 李竞薇
 1 # 初始化一个空列表,用于存储所有点数组合
 2 all_combinations = []
 3 
 4 # 初始化一个计数器,用于统计组合的总数
 5 total_combinations = 0
 6 
 7 # 使用三重循环生成所有可能的点数组合
 8 for dice1 in range(1, 7):  # 第一个骰子
 9     for dice2 in range(1, 7):  # 第二个骰子
10         for dice3 in range(1, 7):  # 第三个骰子
11             # 将当前组合添加到列表中
12             all_combinations.append((dice1, dice2, dice3))
13             # 计数器加 1
14             total_combinations += 1
15 
16 # 输出总组合数
17 print(f"总组合数: {total_combinations}")
18 
19 # 输出所有点数组合
20 print("所有点数组合:")
21 for i in range(total_combinations):
22     print(f"组合 {i + 1}: {all_combinations[i]}")

 

 2024010049 巨佳瑜 用0237组成的偶数个数
count = 0
 # 一位数的情况
for num in [0, 2]:
     count += 1
 # 两位数的情况
for tens in [2, 3, 7]:
     for units in [0, 2]:
         if tens != units:
             count += 1
 # 三位数的情况
for hundreds in [2, 3, 7]:
     for tens in [0, 2, 3, 7]:
         for units in [0, 2]:
             if hundreds != tens and hundreds != units and tens != units:
                 count += 1
 # 四位数的情况
for thousands in [2, 3, 7]:
     for hundreds in [0, 2, 3, 7]:
         for tens in [0, 2, 3, 7]:
             for units in [0, 2]:
                 if thousands != hundreds and thousands != tens and thousands != units and \
                         hundreds != tens and hundreds != units and tens != units:
                     count += 1
print(count)              

  

 

 
 
2024010052 雷升官
def count_characters(s):
    digit_count = 0
    letter_count = 0
    space_count = 0
    other_count = 0

    for char in s:
        if char.isdigit():
            digit_count += 1
        elif char.isalpha():
            letter_count += 1
        elif char.isspace():
            space_count += 1
        else:
            other_count += 1

    return digit_count, letter_count, space_count, other_count


# 示例字符串
input_string = "Something Just Like This ! ./@1233211234567#$"
digit_count, letter_count, space_count, other_count = count_characters(input_string)

print(f"数字个数: {digit_count}")
print(f"字母个数: {letter_count}")
print(f"空格个数: {space_count}")
print(f"其它字符个数: {other_count}")

 

2024010044 侯研 去除绿色通道
from PIL import Image
# 打开图像
image = Image.open('123.jpg')  # 替换为你的图片文件名
width, height = image.size
# 定义绿色范围(这里只是示例,可根据实际情况调整)
lower_green = (0, 128, 0)
upper_green = (128, 255, 128)
# 遍历每个像素点
for y in range(height):
    for x in range(width):
        pixel = image.getpixel((x, y))
        if len(pixel) == 4:  # 处理RGBA图像
            r, g, b, a = pixel
        else:  # 处理RGB图像
            r, g, b = pixel
            a = 255  # 默认不透明
        if lower_green[0] <= r <= upper_green[0] and lower_green[1] <= g <= upper_green[1] and lower_green[2] <= b <= upper_green[2]:
            # 将绿色像素点设置为白色(不透明)
            image.putpixel((x, y), (255, 255, 255, a))
# 保存处理后的图像
image.save('new_image.png')

 

 

2024010048 景勇强
# 预设的正确用户名和密码
correct_username = "admin"
correct_password = "123456"

# 登录尝试次数,初始值为0
attempts = 0

# 循环最多尝试3次
while attempts < 3:
    # 提示用户输入用户名
    username = input("请输入用户名: ")
    # 提示用户输入密码
    password = input("请输入密码: ")

    # 检查输入的用户名和密码是否正确
    if username == correct_username and password == correct_password:
        print("登录成功!")
        # 如果登录成功,跳出循环
        break
    else:
        # 如果登录失败,尝试次数加1
        attempts += 1
        print(f"用户名或密码错误,你还有{3 - attempts}次尝试机会。")

# 如果尝试次数达到3次还未成功,输出提示信息
if attempts == 3:
    print("已达到最大尝试次数,程序退出。")

 

 2024010053 李海洋

import math
x1,y1=map(float,input("请输入第一个点的坐标(x1,y1):").split())
x2,y2=map(float,input("请输入第二个点的坐标(x2,y2):").split())
x3,y3=map(float,input("请输入第三个点的坐标(x3,y3):").split())
a=math.sqrt((x2-x1)**2+(y2-y1)**2)
b=math.sqrt((x3-x2)**2+(y3-y2)**2)
c=math.sqrt((x1-x3)**2+(y1-y3)**2)
s=(a*b*c)/2
triangle_area=math.sqrt(s*(s-a)*(s-b)*(s-c))
r=triangle_area/s
circle_area=math.pi*r**2
print(f"三角形内切圆的面积是:{circle_area}")

 

2024010077 马京兴
# 定义原始字符串
original_string = "Python is fun!"
# --- 正序输出部分 ---
print("正序输出:",end=" ")
for char in original_string:  # 遍历字符串的每个字符
    print(char,end=" ")               # 逐个打印字符(默认换行)
# --- 反序输出部分 ---
print("反序输出:",end=" ")
for char in reversed(original_string):  # 使用 reversed() 函数反转字符串
    print(char,end=" ")                         # 逐个打印反序后的字符

 

 

 

2024010066 刘梦莹 
sales ={"物品a":[100,2000,300],"物品b":[50,100,200],"物品c":[300,100,20]}
#计算每个物品的销售额
total ={item: sum(sales) for item,sales in sales .items()}
#按总销售额排序
sorted =sorted (total .items(),
                      key =lambda x:x[1],reverse = True)
#输出排序结果
for item, total in sorted:
    print(f"{item}: 总销售额为 {total}")

  

sales_count = {1: 100, 2: 150,3: 1000,}
# 对销售个数进行排序,按照销售个数降序排列
sorted =sorted_sales = sorted(sales_count.items(), key=lambda x: x[1], reverse=True)
# 输出排序结果
for month, count in sorted_sales:
    print(f"月份 {month} 的销售个数为 {count}")

  

 

2024010051 雷晨瑞

# 输入字符串
input_str = "abcdef"

# 提取奇数位的字符并反序排列
reversed_odd_chars = []
for i in range(len(input_str) - 1, -1, -1):  # 从后往前遍历
    if i % 2 == 0:  # 判断索引是否为偶数(奇数位)
        reversed_odd_chars.append(input_str[i])

# 将反序后的字符放回原位置
result = list(input_str)
index = 0
for i in range(len(result)):
    if i % 2 == 0:  # 判断索引是否为偶数(奇数位)
        result[i] = reversed_odd_chars[index]
        index += 1

# 将列表转换回字符串
output_str = ''.join(result)

# 输出结果
print(output_str)

 

2024010065 刘欢幸 1,2,3,4可以组成多少个无重复,互不相同的三位数

from itertools import permutations

# 定义数字
digits = [1, 2, 3, 4]

# 生成所有三位数的排列
three_digit_numbers = list(permutations(digits, 3))

# 输出所有三位数
print("可以组成的三位数有:")
for number in three_digit_numbers:
    print(''.join(map(str, number)))

# 输出总数
print(f"总共有 {len(three_digit_numbers)} 个无重复的三位数。")

  

 

2024010047 金佳仪 for循环排序

numbers = list(map(int, input("请输入五个数字,用空格分隔:").split()))
for i in range(len(numbers) - 1):
    for j in range(len(numbers) - 1 - i):
        if numbers[j] > numbers[j + 1]:
            numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
print("排序后的列表:", numbers)

 

2024010045 计旭升 排列五位数的组合次数

from itertools import permutations

# 初始化计数器,用于统计满足条件的五位数的个数
count = 0
# 初始化一个空列表,用于存储满足条件的五位数
results = []
# 定义包含数字0到4的列表,这些数字用于生成五位数
nums = [0, 1, 2, 3, 4]
# 使用permutations函数生成由nums中元素组成的所有长度为5的排列
# 这里的排列是指所有可能的五位数组合
for p in permutations(nums, 5):
    # 检查当前排列中数字2出现的次数是否小于2,并且数字3出现的次数是否小于3
    if p.count(2) < 2 and p.count(3) < 3:
        # 将当前排列中的数字转换为字符串,并拼接成一个五位数的字符串形式
        result = ''.join(map(str, p))
        # 将满足条件的五位数字符串添加到结果列表results中
        results.append(result)
        # 满足条件的五位数个数加1
        count += 1

# 遍历结果列表,打印出每一个满足条件的五位数
for r in results:
    print(r)
# 打印满足条件的五位数的总个数
print("满足条件的五位数的个数为:", count)

 

2024010061李升 统计文本人名的次数

# 假设的人名列表
names = ["张三", "李四", "王五"]
name_count = {name: 0 for name in names}

for name in names:
    name_count[name] = text.count(name)

for name, count in name_count.items():
    print(f"{name} 出现的次数是: {count}")

2024010081孟佳茵  鸡兔同笼

heads = int(input("请输入鸡和兔的总头数: "))
feet = int(input("请输入鸡和兔的总脚数: "))

# 计算兔子数量
rabbits = (feet - 2 * heads) // 2
# 计算鸡的数量
chickens = heads - rabbits

print(f"鸡有{chickens}只,兔有{rabbits}只")

  

 

 

2024010055李金俞 统计出勤签到表的次数

# 初始化签到统计字典
attendance = {}
# 模拟10次签到(每次可输入多个名字)
for i in range(10):
    while True:
        # 输入并清洗数据
        input_str = input(f"第{i + 1}次签到(多人用逗号/空格分隔):").strip()
        # 分割姓名并过滤空值
        names = [name.strip().title() for name in input_str.replace(',', ' ').split() if name.strip()]
        # 有效性验证
        if names:
            break
        print("⚠️ 至少需要输入一个有效姓名!")
    # 统计次数
    for name in names:
        attendance[name] = attendance.get(name, 0) + 1
# 按出勤次数排序(从高到低)
sorted_attendance = sorted(attendance.items(),
                           key=lambda x: (-x[1], x[0]))  # 次数相同按姓名排序
# 打印结果
print("\n出勤统计(从高到低):")
for index, (name, count) in enumerate(sorted_attendance, 1):
    print(f"{index}. {name}:{count}次")

2024010057 李楠 冒泡排序

# 定义冒泡排序函数,接收要排列的列表
def bubble_sort(arr):
    # 获取输入列表的长度
    n = len(arr)
    # 记录内层循环执行的次数,设置循环次数的初始值为0
    count = 0
    # 外层循环,控制排序的轮数,一共需要n - 1轮排序
    for i in range(n - 1):
        # 内层循环,用于比较相邻元素并交换位置
        # n - i - 1表示每一轮内层循环需要比较的次数,随着外层循环i的增加,未排序部分减少,比较次数也减少
        for j in range(0, n - i - 1):
            # 每次内层循环执行一次,count就加1,记录循环次数
            count += 1
            # 比较相邻的两个元素,如果前面的元素大于后面的元素
            if arr[j] > arr[j + 1]:
                # 交换这两个元素的位置,使用元组解包的方式实现交换
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    # 当所有轮次的排序完成后,返回排序后的列表和循环次数
    return arr, count

# 定义一个示例数据列表
data = [64, 90, 25, 78,22, 11,56]
sorted_data, loop_count = bubble_sort(data)
print("排序后的结果:", sorted_data)
print("循环次数:", loop_count)

 2024010059 李若楠 排序循环次数

nums = [8, 1, 5, 3, 2]
n = len(nums)
outer_count = 0  # 外层循环计数器
inner_count = 0  # 内层循环计数器

for i in range(n - 1):
    outer_count += 1
    for j in range(0, n - i - 1):
        inner_count += 1
        if nums[j] > nums[j + 1]:
            nums[j], nums[j + 1] = nums[j + 1], nums[j]

print(f"外层循环次数:{outer_count}")  # 输出:4
print(f"内层循环次数:{inner_count}")  # 输出:10
print(f"总循环次数:{outer_count + inner_count}")  # 输出:14

 

 

 

 

 

 

 

 

2024010062 廖佳怡 删除下划线前面的文字

text = "这是一些前置12内容_34需要保留的部分"
result = text.split('_', 1)[-1]
print(result)

 


 

2024010064 刘纯怡 输出国际象棋棋盘,,找出白色方形棋和黑色方形棋

def print_chessboard():
    chessboard = []
    for i in range(8):
        row = []
        for j in range(8):
            if (i + j) % 2 == 0:
                row.append('□')  # White square
            else:
                row.append('■')  # Black square
        chessboard.append(row)
    return chessboard

def find_squares(chessboard, color):
    squares = []
    for i in range(8):
        for j in range(8):
            if chessboard[i][j] == color:
                squares.append((i, j))
    return squares

# Print the chessboard and find white and black squares
chessboard = print_chessboard()
for row in chessboard:
    print(' '.join(row))

white_squares = find_squares(chessboard, '□')
black_squares = find_squares(chessboard, '■')

print("\nWhite squares:")
for square in white_squares:
    print(square)

print("\nBlack squares:")
for square in black_squares:
    print(square)

 

2024010068 刘晓津 几年几月多少天

year = int(input("请输入年份: "))
month = int(input("请输入月份: "))

if month in [1, 3, 5, 7, 8, 10, 12]:
    days = 31
elif month in [4, 6, 9, 11]:
    days = 30
elif month == 2:
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        days = 29
    else:
        days = 28
else:
    print("输入的月份不合法")
    days = None

if days is not None:
    print(f"{year}年{month}月有{days}天")

 2024010076 马凤凤 标准差

import math
input_str = input("请输入一些数字,用空格分隔:")
nums = [float(x) for x in input_str.split()]

n = len(nums)
mean_value = sum(nums) / n
variance = sum((x - mean_value) ** 2 for x in nums) / n
standard_deviation = math.sqrt(variance)
print(f"这些数字的标准差是:{standard_deviation}")

 

2024010072刘芝池几年几月几天

year = int(input("请输入年份: "))
month = int(input("请输入月份: "))
day = int(input("请输入日期: "))

# 每个月的天数(不考虑闰年)
days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

# 判断是否为闰年
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    days_in_month[1] = 29

# 计算当前日期是当年的第几天
total_days = sum(days_in_month[:month - 1]) + day

print(f"{year}年{month}月{day}日是{year}年的第{total_days}天。")

2024010075鲁美宏求内切圆圆心坐标及半径

import math

# 三角形顶点坐标
x1, y1 = 0, 0
x2, y2 = 3, 0
x3, y3 = 0, 4

# 计算三角形三边的长度
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)

# 计算半周长
s = (a + b + c) / 2

# 计算内切圆半径
radius = math.sqrt((s - a) * (s - b) * (s - c) / s)

# 计算内切圆的圆心坐标
cx = (a * x1 + b * x2 + c * x3) / (a + b + c)
cy = (a * y1 + b * y2 + c * y3) / (a + b + c)

print(f"内切圆的圆心坐标为: ({cx}, {cy})")
print(f"内切圆的半径为: {radius}")

 2024010084 师罗琦 统计文本中大于十三个字的句子

def count_long_sentences(text):
    
    sentences = text.replace('。', '.').replace('?', '?').replace('!', '!').split('.')
    sentences = [s.strip() for s in sentences if s.strip()]  # 去除空白字符和空句子

    
    count = 0
    for sentence in sentences:
        if len(sentence) > 13:
            count += 1

    return count

text = "友情也是人生中不可或缺的一部分。真正的朋友,是在你最困难的时候伸出援手的人,是在你迷茫的时候为你指点迷津的人。"


result = count_long_sentences(text)
print(f"大于13个字的句子个数为: {result}")

 

  2024010063  林柯妍  求一个整数加一百和加一百六十八后都是完全平方数

import math
def is_perfect_square(n):
    """判断一个数是否是完全平方数"""
    root = math.isqrt(n)
    return root * root == n

def find_special_integer():
    """寻找满足条件的整数"""
    for i in range(1, 1000000):  # 设置一个合理的搜索范围
        if is_perfect_square(i + 100) and is_perfect_square(i + 168):
            return i
    return None  # 如果没有找到,则返回None
# 调用函数并打印结果
result = find_special_integer()
if result is not None:
    print(f"满足条件的整数是: {result}")
    print(f"{result} + 100 = {math.isqrt(result + 100) ** 2}")
    print(f"{result} + 168 = {math.isqrt(result + 168) ** 2}")
else:
    print("在给定的范围内没有找到满足条件的整数。")

  

 2024010060 李若语

movies = [
    {"name": "阿凡达", "country": "美国"},
    {"name": "复仇者联盟4:终局之战", "country": "美国"},
    {"name": "阿凡达:水之道", "country": "美国"},
    {"name": "泰坦尼克号", "country": "美国"},
    {"name": "星球大战:原力觉醒", "country": "美国"},
    {"name": "哪吒之魔童闹海", "country": "中国"},
    {"name": "复仇者联盟3:无限战争", "country": "美国"},
    {"name": "蜘蛛侠:英雄无归", "country": "美国"},
    {"name": "头脑特工队2", "country": "美国"},
    {"name": "侏罗纪世界", "country": "美国"}
]
# 创建一个空字典用于存储国家和对应的电影数量
country_count = {}

# 遍历电影列表,统计每个国家的电影数量
for movie in movies:
    country = movie["country"]
    if country in country_count:
        country_count[country] += 1
    else:
        country_count[country] = 1

# 输出结果
for country, count in country_count.items():
    print(f"{country}: {count}")

 2024010046 焦梦妍

def encrypt_at_fifth_char(text, encrypt_char='*'):
    if len(text) >= 5:
        # 在第五个字符处插入加密字符
        encrypted_text = text[:4] + encrypt_char + text[4:]
        return encrypted_text
    else:
        return text  # 如果字符串长度小于5,返回原字符串

# 示例用法
original_text = "HelloWorld"
encrypted_text = encrypt_at_fifth_char(original_text)
print("原始文本:", original_text)
print("加密后的文本:", encrypted_text)

2024010080 毛蕊婷

n = 5  # 可以调整n的值来改变菱形的大小
# 打印上半部分
for i in range(n):
    print(' '*(n - i - 1) + '* '*(i + 1))
# 打印下半部分
for i in range(n - 2, -1, -1):
    print(' '*(n - i - 1) + '* '*(i + 1))
# 定义学院和专业的对应关系字典
college_majors = {
    "数学科学学院": ["数学与应用数学", "统计学"],
    "物理科学与技术学院": ["物理学", "应用物理学", "材料物理"],
    "化学化工学院": ["化学", "环境", "应用化学", "化学工程与工艺"]
}

# 计算每个学院的专业数量,生成包含学院名和专业数量的元组列表
college_count_list = [(college, len(majors)) for college, majors in college_majors.items()]

# 按照专业数量从多到少对学院进行排序
sorted_college_count_list = sorted(college_count_list, key=lambda x: x[1], reverse=True)

# 输出排序结果
for college, count in sorted_college_count_list:
    print(f"{college}: {count}个专业")

2024010074卢笑悦

 2024010086孙景涵

def is_prime(n):
    if n <= 1:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False
    for i in range(3, int(n**0.5) + 1, 2):
        if n % i == 0:
            return False
    return True
sum_of_primes = sum(n for n in range(2, 100) if is_prime(n))
print(sum_of_primes)

 2024010085 施祺

correct_username="shi"
correct_passward="123456"
username=input("请输入用户名;")
passward=input("请输入密码;")
if username==correct_username and passward==correct_passward:
   print("用户名和密码正确,登陆成功")
else:
   print("用户名或者密码错误,登陆失败")

 

 2024010083彭子晖小球实验

 

height = 10.0
count = 0
threshold = 0.01
while True:
    height *= 0.50
    count += 1
    if height < threshold:
        break
print(f"小球在低于{threshold}米前总共反弹了{count}次")

 

  

 

 

 

posted @ 2025-04-14 12:03  szmtjs10  阅读(26)  评论(0)    收藏  举报