函数与递归、第五章习题

字符串反转:

1. 可用切片实现 s[: : -1]

2. 递归链条

def rvs(s):
    if s == "":
        return s
    else:
        return rvs(s[1:]) + s[0]

关于汉诺塔

https://www.zhihu.com/question/24385418?utm_source=wechat_session&utm_medium=social&utm_oi=33645293207552

=====================

第五章编程题

import random

def genpwd(length):
    return random.randint(10**(length-1), 10**length-1)

length = eval(input())
random.seed(17)
for i in range(3):
    print(genpwd(length))

import math
def prime(m):
    count = 0
    for i in range(n, 1000000):    # 由于不知道怎么才能不定义i,下补
        if count < 5:
            for m in range(2, i):
                if i % m == 0:
                    break
            else:
                count += 1
                if count < 5:
                    print(i, end=",")
                else:
                    print(i)

n = math.ceil(eval(input()))

prime(n)

修正版:

import math


def prime(i):
    count = 0
    while count < 5:
        for m in range(2, i):
            if i % m == 0:
                break
        else:
            count += 1

            if count < 5:
                print(i, end=",")
            else:
                print(i)
        i += 1
n = math.ceil(eval(input()))

prime(n)

提供的答案:

def prime(m):
    for i in range(2,m):
        if m % i == 0:
            return False
    return True

n = eval(input())
n_ = int(n)
n_ = n_+1 if n_ < n else n_
count = 5

while count > 0:
    if prime(n_):
        if count > 1:
            print(n_, end=",")
        else:
            print(n_, end="")
        count -= 1 
    n_ += 1
原文地址:https://www.cnblogs.com/p36606jp/p/15113933.html