Recursion Practice

1. The following recursive function  nd_min returns the minimum of a list. Fill in the base case:
def find_min(lst):
	#base case
	return min(lst[0], find_min(lst[1:]))
For example:
>>> find_min([5, 7, 8 , -5, 10])
> -5

solution:
"non-recursion"
def find_min(lst):
	a = lst[0]
    for item in lst:
        if item < a:
            a = item
    return a
"recursion"    
def find_min(lst):
    if len(lst) == 1:
        return lst[0]
    return min(lst[0], find_min(lst[1:]))
print(find_min([5, 7, 8, -5, 10]))

2. The following recursive function  rst_upper returns the  rst upper case letter of a string. It returns an empty string if it cannot  nd any. Fill in the base case
def first_upper(string): 
	#base case
	else:
		return first_upper(string[1:])
For example:
>>> first_upper('abc Xyz') 
> X

solution:
"non-recursion"
def first_upper(string):
    a = 0
    for item in string:
        if item == item.upper():
            a = item
            return a
    if a == 0:
        return " "
print(first_upper('abcds'))
"recursion"
def first_upper(string):
    if string == '':
        return ''
    elif string[0] != '' and string[0] == string[0].upper():
        return string[0]
    else:
        return first_upper(string[1:])
print(first_upper('avDds'))

3. The following recursive function count_repeat counts how many times a target element appears in a list. Fill in the recursive case.
def count_repeat(lst,target): 
	if len(lst) == 0:
		return 0 
		#recursive case
For example:
>>> count_repeat([15, 1, 10, 9, 10], 10) 
> 2
> 
def count_repeat(lst,target): 
	if len(lst) == 0:
		return 0 
	if lst[0] == target:
		return 1 + count_repeat(lst[1:],target)
	else:
		return count_repeat(lst[1:],target)

4. Write a function which returns factorial of a given number n. 
For example:
>>> factorial (5) 
> 120

solution:
"non-recursion"
def factorial(n):
    if n == 0:
        return 1
    if n < 0:
        return None
    if n > 0:
        num = 1
        while n > 0:
            num *= n
            n -= 1
        return num
print(factorial(5))
"recursion"
def factorial(n):
	if n == 1 or n == 0:
		return 1
	else:
		return n * factorial(n-1) 

Practice
1. Write a recursive function digit_sum that sums the digits of an integer number, without converting the number to string. For example:
>>> digit_sum(523) 
> 10(5+2+3)

solution
"non-recursion"
def degit_sum(n):
    remainder = 0
    a = 0
    while n > 0:
        a = n % 10
        remainder += a
        n = n // 10
    return remainder
print(degit_sum(523))
"recursion"
def degit_sum(n):
    if n == 0:
        return 0
    else:
        return n % 10 + degit_sum(n // 10)
print(degit_sum(523))

2. Write a recursive function remove_neg to remove all negative numbers from a list. 
For example:
>>> remove_neg([2, -5, 3, -7, 10])
> [2, 3, 10]	

solution:
"non-recursion"
def remove_neg(lst):
    new_lst = []
    for item in lst:
        if item > 0:
            new_lst.append(item)
    return new_lst
print(remove_neg([2, -5, 3, -7, 10]))
"recursion"
def remove_neg(lst):
    if len(lst) == 0:
        return []
    if lst[0] >= 0:
        return [lst[0]] + remove_neg(lst[1:])
    else: 
        return remove_neg(lst[1:])
print(remove_neg([2, -5, 3, -7, 10]))

3. Write a recursive function which returns the value of the Fibonacci series for the nth element. 
For example:
>>> fib (6) 
> 8
>>> fib (10)
> 55

"recursion":
def fib(n):
	if n == 0:
		return 0 
	if n == 1:
		return 1
	else:
		return fib(n-1) + fib(n-2)

Challenge
1. Write a recursive function replace_between(string, deli, ch) to replace all characters bounded by a delimiter deli (special word) in a string with a character ch. Note that the string contains zero or at most one special word. 
For example:
>>> replace_between('zzz$1234$xx', '$', '0')
> 'zzz$0000$xx'
>>> replace_between('aaa$bbb', '$', '0')
> 'aaa$bbb'
Hints:
  1. try to reduce string by one or two characters (if possible) in each recursion.
  2. think about the smallest string you might have and what should be returned with such string.you might have more than one base case and recursive case.

solution:
def replace_between(string, ch1, ch2): 
    if len(string) <= 2:
        return string
    if string[0] == string[-1] == ch1:
        return ch1 + ch2*(len(string)-2) + ch1 
    if string[0] == ch1:
        return replace_between(string[:-1], ch1, ch2) + string[-1] 
    if string[-1] == ch1:
        return string[0] + replace_between(string[1:], ch1, ch2)
    return string[0] + replace_between(string[1:-1], ch1, ch2) + string[-1]
print(replace_between('zzz$1234$xx', '$', '0'))

2. Write a function that returns all the permutations of a given string. 
For example:
>>> permute('abc')
['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
Hints:
  1.the permutations of a single character is itself  2. the permutations of 'abc' is given by
permute('abc') == ['a' + permute('bc'), 'b' + permute('ac'), 'c' + permute('ab')]

solution:(***)
def permute(s):
    newlst = []
    if len(s) == 1:
        return s 
    else:
        for i,j in enumerate(s):
            for perm in permute(s[:i] + s[i+1:]):
                newlst += [j + perm] 
    return newlst
print(permute('abc'))











  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值