python 第二次作业

def isPrime(num):
    if num == 1:
        return False
    if num == 2:
        return True
    else:
        for item in range(2, int(num ** 0.5 + 1)):
            if num % item == 0:
                return False
            else:
                return True


def isPalindrome(num):
    s = str(num)
    s = s[::-1]
    if int(s) == num:
        return True
    else:
        return False


pp_ls = []
count = 2
while len(pp_ls) < 100:
    if isPalindrome(count) and isPrime(count):
        pp_ls.append(count)
    count += 1

for i in range(0, 100, 10):
    print(*pp_ls[i:i + 10], sep="\t")

运行结果:

这题与上体大致一样,将逆序封装成一个函数,修改判断条件即可

def isPrime(num):
    if num == 1:
        return False
    if num == 2:
        return True
    else:
        for item in range(2, int(num ** 0.5 + 1)):
            if num % item == 0:
                return False
            else:
                return True


def isPalindrome(num):

    if reverse(num) == num:
        return True
    else:
        return False

def reverse(num):
    s = str(num)
    s = s[::-1]
    return int(s)
pp_ls = []
count = 2
while len(pp_ls) < 100:
    if not isPalindrome(count) and isPrime(count) and isPrime(reverse(count)):
        pp_ls.append(count)
    count += 1

for i in range(0, 100, 10):
    print(*pp_ls[i:i + 10], sep="\t")

结果

def sumDigits(n):
    i = len(n)
    n = int(n)
    a = [0]
    c = 0
    for x in range(1, i+1):
        b = n % 10
        a.append(b)
        n //= 10
        c += a[x]
    return c


num = input("请输入一个整数")
print(sumDigits(num))

结果

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值