Class 5 - Recursion quiz II

Pataasin ang iyong marka sa homework at exams ngayon gamit ang Quizwiz!

A programmer is asked to make a function that returns the sum of the first n natural numbers. This recursive function is what they come up with: def bar(n): if n == 1: return n return n + bar(n) We test it on the natural number 6: print(bar(6)) How will it behave? a )It will return the sum of the first n (6) natural numbers b) It will recur endlessly and never return c) It will return the sum of the first n-1 (5) natural numbers d) It will return 1

b) It will recur endlessly and never return

Same code as previous question!A programmer is asked to make a function that returns the sum of the first n natural numbers. This recursive function is what they come up with: def bar(n): if n == 1: return n return n + bar(n) What change is needed for it to work? a) If the condition, n == 1, is true it should return 0 instead of n b) No change, it works correctly already c) In the if condition, we should check if n == 0 instead of n == 1 d) Correct! In the recursive call we need to call bar(n-1) instead of bar(n)

d) Correct! In the recursive call we need to call bar(n-1) instead of bar(n)

A programmer is asked to make a function that calculates n to the power of m. This recursive function is what they come up with: def bar(n, m): return n * bar(n, m-1) We test it on the positive integers 2 and 3: print(bar(2, 3)) How will it behave? a) It will return 8 b) You Answered It will return 6 c) It will return 2 d) It will recur endlessly and never return

d) It will recur endlessly and never return

Look at this recursive program: def foo(a_str, n): if n == 0: return 0 n -= 1 if a_str[n] == 'a': return 1 + foo(a_str, n) return foo(a_str, n) What does it do? a) Returns 1 if 'a' occurs in the first n letters of a_str, otherwise 0 b) Returns the length of the string a_str if 'a' occurs in it, otherwise 0 c) Recurs endlessly and never returns d) Returns the number of times 'a' occurs in the first n letters of a_str

d) Returns the number of times 'a' occurs in the first n letters of a_str

Same code as previous question!A programmer is asked to make a function that calculates n to the power of m. This recursive function is what they come up with: def bar(n, m): return n * bar(n, m-1) What change is needed for it to work? a) No change, it works correctly already b) In the recursive call we need to call bar(n-1, m) instead of bar(n, m-1) c) In the recursive call we need to call bar(n, m+1) instead of bar(n, m-1) d) We need to add a condition: if m == 0: return 1

d) We need to add a condition: if m == 0: return 1


Kaugnay na mga set ng pag-aaral

Analyze an Implementation Plan Instruction/Assignment

View Set

Personal Protective Equipment Career Exploration opportunities

View Set

LAS MENINAS - UNA PINTURA ENIGMÁTICA

View Set

Characteristics of financial goals

View Set