《算法竞赛入门经典》——第2章课后习题 (Python版本)

习题2-1 水仙花数

for i in range(100, 1000):
    a = int(i / 100)
    b = i % 10
    c = int(i / 10) % 10
    if i == a ** 3 + b ** 3 + c ** 3:
        print(i)
    else:
        continue

习题2-2 韩信点兵

count = 0
while True:
    flag = False
    a = int(input())
    b = int(input())
    c = int(input())
    for i in range(10, 101):
        if (i % 3 == a) and (i % 5 == b) and (i % 7 == c):
            flag = True
            count += 1
            print('Case ' + str(count) + ': ' + str(i))
            break
    if flag == False:
        count += 1
        print('Case ' + str(count) + ': No answer')

习题2-3 倒三角形

n = int(input())
for i in range(1, n+1):
    for j in range(1, i):
        print(' ', end='')
    for j in range(1, 2*(n+1-i)):
        print('#', end='')
    print()

习题2-4 子序列的和

count = 0
while True:
    count += 1
    list1 = list(map(int, input().split()))
    if list1[0] == 0 and list1[1] == 0:
        break
    else:
        result = 0.0
        for i in range(list1[0], list1[1]+1):
            result += 1 / (i ** 2)
        print('Case ' + str(count) + ': ' + '%.5f' % result)

习题2-5 分数化小数

count = 0
while True:
    count += 1
    List = list(map(int, input().split()))
    if List[0] == 0 and List[1] == 0 and List[2] == 0:
        break
    else:
        print('Case ' + str(count) + ": " + '%.'+List[2]+'f' % (List[0] / List[1]))

习题2-6 排列

for abc in range(100, 330):
    deF = 2*abc
    ghi = 3*abc

    number_new = []

    number_new.append(int(abc/100))
    number_new.append(abc % 10)
    number_new.append(int(abc/10) % 10)

    number_new.append(int(deF / 100))
    number_new.append(deF % 10)
    number_new.append(int(deF / 10) % 10)

    number_new.append(int(ghi / 100))
    number_new.append(ghi % 10)
    number_new.append(int(ghi / 10) % 10)

    if len(set(number_new)) == 9:
        print(str(abc) + ' ' + str(deF) + ' ' + str(ghi))

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值