Question 31
MediumWhat is the output of this code?
def power(x, n):
n == :
half = power(x, n // )
half * half n % == half * half * x
(power(, ))
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Data Structures and Algorithms
What is the output of this code?
def power(x, n):
n == :
half = power(x, n // )
half * half n % == half * half * x
(power(, ))
100
1024
20
512
Sign up free to see the answer and a step-by-step explanation.
What is tail recursion?
Recursion with two calls
Recursion without a base case
Recursion that starts at the tail of a list
The recursive call is the last operation in the function, so it can be turned into a loop
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def rev(s):
return s if len(s) <= 1 else rev(s[1:]) + s[0]
print(rev("abcd"))
d
abcd
Sign up free to see the answer and a step-by-step explanation.
How does memoisation speed up a recursive function?
It uses more threads
It converts recursion to iteration automatically
It removes the base case
It stores results of subproblems so each is computed only once
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def f(n):
if n == 0:
return 0
return n % 10 + f(n // 10)
print(f(98765))
35
30
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def p(n):
if n == 0:
return
p(n - 1)
print(n, end=" ")
p(n - 1)
p(3)
1 2 1 3 1 2 1
1 1 2 1 1 2 3
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def subsets(a):
if not a:
return [[]]
rest = subsets(a[1:])
return rest + [[a[0]] + s for s in rest]
r = subsets([1, 2, 3])
print(len(r), [2, 3] in r)
8 True
7 True
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def perms(s):
if len(s) <= 1:
return [s]
out = []
for i, c in enumerate(s):
for p in perms(s[:i] + s[i+1:]):
out.append(c + p)
return out
r = perms("abc")
print(len(r), r[3])
6 bac
3 bca
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def count(n, k):
if k == 0 or k == n:
return 1
return count(n - 1, k - 1) + count(n - 1, k)
print(count(6, 2))
6
15
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
def solve(n):
cols, d1, d2, cnt = set(), set(), set(), 0
def place(r):
nonlocal cnt
if r == n:
cnt += 1
return
for c in range(n):
if c in cols or r - c in d1 or r + c in d2:
continue
cols.add(c); d1.add(r - c); d2.add(r + c)
place(r + 1)
cols.remove(c); d1.remove(r - c); d2.remove(r + c)
place(0)
return cnt
print(solve(6))
2
4
Sign up free to see the answer and a step-by-step explanation.
a
dcba
5
98765
1 2 3
3 2 1 1 2 1 1
8 False
6 True
6 bca
9 cab
30
12
10
6