当前位置:网站首页>Lesson 023 and 024: recursion: these little bunnies, Hanoi Tower after class test questions and answers

Lesson 023 and 024: recursion: these little bunnies, Hanoi Tower after class test questions and answers

2022-06-22 21:35:00 ChaseTimLee

use one's hands :

0. Use recursion to write a function that converts decimal to binary ( Required “ take 2 Remainder ” The way , Results and calls bin() Return the string form as well ).

def Dec2Bin(dec):
    result = ''
    
    if dec:
        result = Dec2Bin(dec//2)
        return result + str(dec%2)
    else:
        return result

print(Dec2Bin(62))

1. Write a function get_digits(n), The parameter n Break down the number of each bit and put it in the list in order . give an example :get_digits(12345) ==> [1, 2, 3, 4, 5]

result = []
def get_digits(n):
        if n > 0:
                result.insert(0, n%10)
                get_digits(n//10)

get_digits(12345)
print(result)

2. Remember the problem of finding palindrome strings ? Now let's use recursion to solve , Can I be proud to say I can ?

def is_palindrome(n, start, end):
        if start > end:
                return 1     
        else:
                return is_palindrome(n, start+1, end-1) if n[start] == n[end] else 0
        
string = input(' Please enter a string :')
length = len(string)-1

if is_palindrome(string, 0, length):
        print('"%s" It's palindrome string !' % string)
else:
        print('"%s" It's not a palindrome string !' % string)

3. Use recursive programming to solve the following problems :

Yes 5 A person sits together , Ask the fifth person how old ? He said bidi 4 Personal big 2 year . Ask No 4 Personal age , He said bidi 3 Personal big 2 year . Ask the third person , And he said bidi 2 People are two years old . Ask No 2 personal , Say two years older than the first one .
Finally, ask the first person , He says it is 10 year . How old is the fifth person ?

def age(n):
    if n == 1:
        return 10
    else:
        return age(n-1) + 2
        
print(' ha-ha , I got it! , The age of the fifth person is  %d  year , Bobo crisp !' % age(5))

原网站

版权声明
本文为[ChaseTimLee]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206222005194361.html