Python, using recursion
Given an list of ints, compute recursively the number of times that the value 11 appears in the list. We'll use the convention of considering only the part of the list that begins at the given index. In this way, a recursive call can pass index+1 to move down the array. The initial call will pass in index as 0.
array11([1, 2, 11], 0) → 1
array11([11, 11], 0) → 2
array11([1, 2, 3, 4], 0) → 0
Given a string, return true if it is a nesting of zero or more pairs of parenthesis, like "(())" or "((()))".
def array11(lst, index): if index < len(lst): count = array11(lst, index + 1) if lst[index] == 11: count += 1 return count else: return 0 print(array11([1, 2, 11], 0)) print(array11([11, 11], 0)) print(array11([1, 2, 3, 4], 0))
def has_nested_parenthesis(s): if len(s) == 0: return True elif len(s) % 2 == 1: return False else: return s[0] == '(' and s[-1] == ')' and has_nested_parenthesis(s[1:-1]) print(has_nested_parenthesis('(())')) print(has_nested_parenthesis('((()))')) print(has_nested_parenthesis('(()))('))
Get Answers For Free
Most questions answered within 1 hours.