Python small topic 7

(1) Use the recursive function call method to display the input 5 characters in reverse order.
(2) There are 5 people sitting together, ask the 5th person how old he is, he says he is 2 years older than the 4th person. Ask the age of the fourth person, he said that he is 2 years older than the third person. Ask the age of the third person, he said that he is 2 years older than the second person. Ask the age of the second person, he said 2 years older than the first person. Finally, I asked the first person, and he said he was 10 years old. How old is the fifth person?
(3) Given a positive integer with no more than 5 digits, it is required to: a) find out how many digits it is, b) display the digits in reverse order.
(4) For a 5-digit number, determine whether it is a palindrome. For example, 12321 is a palindrome number, the ones is the same as the tens of thousands, and the tens is the same as the thousands.

first question,

#利用递归函数调用方式,将所输入的5个字符,以相反顺序显示出来。
def dayin(num,*five):
    if num == 0:
        print(*five[num])
    else:
        print(*five[num])
        dayin(num - 1,*five)
dayin(4,'a','b','c','d','e')    #这个方法局限性太大了

#这种方法更好
str = input("请输入五个字符:")
def dayin2(num1):
    if num1 == -1:
        return ''
    else:
        return str[num1] + dayin2(num1 - 1)
print(dayin2(len(str) - 1))

Second question:

#有5个人坐在一起,问第5个人多少岁,他说比第4个人大2岁。问第4个人的岁数,
#他说比第3个人大2岁。问第3个人的岁数,他说比第2人大2岁。问第2个人的岁数,
#他说比第1个人大2岁。最后问第1个人,他说是10岁。请问第5个人多大岁数?

#这个方法也有局限性,没有下面那个递归方法好,因为这个要自己去设定值
#而递归不用设置值
sum = 10
for i in range(1,5):
    sum += 2
print(sum)

#递归
def suishu(num):
    if num == 1:
        return 10
    else:
        return suishu(num - 1) + 2
print(suishu(5))

The third question:

#给一个不多于5位的正整数,要求:a)求它是几位数,b)逆序显示各位数字。
#这个题目就比较简单了,一点点代码就解决了
num1 = input("请输入一个不多于五位的正整数:")
print(num1,'是',len(num1),'位数')
print('逆序显示为:',num1[::-1])     #切片方法

Fourth question:

#对于一个5位数,判断它是不是回文数。如12321是回文数,个位与万位相同,十位与千位相同。
#之前有一篇文章专门提到了回文数,有兴趣可以去看看
num2 = input("请输入一个五位数:")
if len(num2) == 5 and num2 == num2[::-1]:
    print(num2,'是回文数')
elif len(num2) != 5:
    print('您输入的不是一个五位数!!!')
else:
    print(num2,'不是回文数')

insert image description here

Guess you like

Origin blog.csdn.net/weixin_43635067/article/details/128971814