PTA每日一题

1.基于泰勒级数展开求余弦函数值

def factorial(n):
    fact = 1
    for i in range(1, n + 1):
        fact *= i
    return fact

def cos_expend(x):
    i = 0
    c = 1
    a = ((-1) ** i) * (x ** (2 * i)) / factorial(2 * i)
    b = a
    while abs(a) >= 1e-5:
        i += 1
        c += 1
        a = ((-1) ** i) * (x ** (2 * i)) / factorial(2 * i)
        b += a
    return b, c

if __name__ == '__main__':
    x = float(input())
    a, c = cos_expend(x)
    print('cos(x)={:.6f}'.format(a))
    print('count={}'.format(c))

错误分析:

1.在定义cos_expend()时把i和c当成一个东西了,i是a定义里的,而c是计算迭代次数。

*2.每次循环更新b,然后赋值给a

def cos_expend(x):
    i = 0
    c = 1
    a = ((-1) ** i) * (x ** (2 * i)) / factorial(2 * i)

    while abs(a) >= 1e-5:
        i += 1
        c += 1
        b = a + ((-1) ** i) * (x ** (2 * i)) / factorial(2 * i)
        a = b
    return a, c

结果报错:OverflowError: int too large to convert to float,改阶乘定义里的初始值1为1.0没用

更改更新方式,直接更新a,累加到b后才运行正确

2.计算1∗2∗3+3∗4∗5+...+99∗100∗101

a,b,c=1,2,3
d = 6
while a < 99:
    a += 2
    b += 2
    c += 2
    d += a*b*c
print('sum={}'.format(d))

*3.查找夫妻数

def get_divisors_sum(num):
    # 计算一个数的所有因数之和
    divisors_sum = 0
    for i in range(2, int(num ** 0.5) + 1):
        if num % i == 0:
            divisors_sum += i
            if i != num // i:
                divisors_sum += num // i
    return divisors_sum

def find_couple_numbers(m, n):
    count = 0
    couples = set()  # 使用set去重存储夫妻数对
    for x in range(m, n + 1):
        y = get_divisors_sum(x)
        if x != y and get_divisors_sum(y) == x and (y, x) not in couples:
            couples.add((x, y))
            count += 1
    if count == 0:
        print("没有找到")
    else:
        for couple in couples:
            print(couple)
        print(f"共找到{count}对夫妻数")

# 输入两个正整数m和n
m, n = map(int, input().split())

find_couple_numbers(m, n)

4.埃拉托色尼筛法

def find_kth_removed_number(n, k):
    primes = []  # 存储素数
    is_prime = [True] * (n+1)  # 初始认为所有数都是素数

    for i in range(2, n+1):
        if is_prime[i]:
            primes.append(i)
            for j in range(i*i, n+1, i):  # 划掉所有i的倍数
                is_prime[j] = False

    removed = []  # 存储被删除的整数
    for i in range(len(primes)):
        p = primes[i]
        for j in range(p, n+1, p):  # 划掉p的所有倍数
            if j not in removed:
                removed.append(j)
                if len(removed) == k:
                    return j

if __name__ == '__main__':
    n, k = map(int, input().split())
    result = find_kth_removed_number(n, k)
    print(result)

错误分析:

def ailatuose(n,k):
    a = []
    nums = [i for i in range(2,n+1)]
    for i in nums:
        for j in range(2,n):
            # 找到素数
            if i % j != 0 or i == 2:
                a.append(i)
                nums.remove(i)
                # 素数的倍数
                for g in range(2, n // 2 + 1):
                    multiple = i * g
                    if multiple in nums:
                        a.append(multiple)
                        nums.remove(multiple)
                        # 第k个被划掉的整数
                        if len(a) == k:
                            return a[-1]
if __name__ == '__main__':
    n, k = map(int, input().split())
    print(ailatuose(n,k))

原先筛选素数的倍数我用素数依次乘以(2,n/2 + 1),看在不在(2,n)里面,改进后,用range(start, stop, step)从起始数字一直加素数。

用remove会导致

ValueError: list.remove(x): x not in list

5.计算a+aa+aaa+...+aa...a(n个a)的值

a, n = map(int, input().split())

# 计算累加和
sum = 0
for i in range(1, n+1):
    term = int(str(a) * i)
    sum += term

# 输出结果
print("sum={}".format(sum))

巧用字符串和整型的转换

*6.sdut-C语言实验-汉诺塔

n = int(input())

def hannuota(n):
    if n == 1:
        print("Move disk 1 from A to C")
    else:
        count = 1
        while n > 1:
            print("Move disk {} from A to B".format(count))
            count += 1
            n -= 1
        print("Move disk {} from A to C".format(count))
        for i in range(count-1,0,-1):
            print("Move disk {} from B to C".format(i))

hannuota(n)

第一个问题就是它莫名报错我多了一个空行

这一点只要在结尾添加end=""就可以解决该报错,在这题把这句代码添加在print("Move disk {} from B to C".format(i))即可。

*7.请用正则表达式实现,多行字符串处理

def find_duplicate_words(lines):
    duplicates = []

    for i, line in enumerate(lines):
        words = line.strip().split()
        seen = set()
        
        for word in words:
            if word in seen:  # 如果单词已经出现过一次,则添加到重复列表中
                duplicates.append((word, line))
            else:
                seen.add(word)  # 将单词添加到已经出现过的集合中

    return duplicates


n = int(input())
lines = []
for _ in range(n):
    lines.append(input())

duplicates = find_duplicate_words(lines)

for i, duplicate in enumerate(duplicates):
    if i != len(duplicates) - 1:
        print(f"{duplicate[0]},{duplicate[1]}")
    else:
        print(f"{duplicate[0]},{duplicate[1]}",end="")

8.幂级数的和函数验证

import math

# 输入x和n
x, n = map(float, input().split())
n = int(n)

# 计算幂级数的前n项和
sum_of_series = 0
for i in range(1, n+1):
    sum_of_series += (((-1)**(i-1))/(i*(2*i-1)))*x**(2*i)

# 计算和函数在x处的值
value_of_function = 2*x*math.atan(x)-math.log(1+x**2)

# 输出结果
print("{:.10f}".format(sum_of_series))
print("{:.10f}".format(value_of_function),end="")

这里要注意一下传入的参数一个是浮点数,一个是整数,运算的时候要确保数据类型一致,小心TypeError: 'float' object cannot be interpreted as an integer这个报错^_^

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值