0

Python non-fruitful recursive function. Implement such a function print_01_strings(k,s,n) that, given a string s of length k, prints all the possible 0/1 strings that are completions of s to length n in the alphanumeric order. Naturally, when print_01_strings(0,'',n) is called, all the 0/1 strings of length n will be printed.

Use the following pattern to implement your solutions and feel free to use the schema for implementing the function:

def print_01_strings(k, s, n):
 #if k equal to n the function only needs to print s which is unique completion
 #otherwise, we'll print all the completions of the string s+'0' of length k+1
 #and all the completions of the string s+'1' of length k+1

print_01_strings(0,'',5)

I have this question in compsci class and for the life of me I cannot get my head around it. I cannot understand how this should work. the output should be something like;

thank you guys in advance, I know I should show an attempt of code but I truly do not know where to start.

--

00000
00001
00010
00011
00100
00101
00110
00111
01000
01001
01010
01011
01100
01101
01110
01111
10000
10001
10010
10011
10100
10101
10110
10111
11000
11001
11010
11011
11100
11101
11110
11111
2
  • 1
    Do you understand recursion? If not, please see your course materials that cover recursion. Commented Oct 22, 2018 at 8:52
  • yes, It involves breaking down a big problem to smaller problem then extrapolating. Commented Oct 22, 2018 at 8:59

1 Answer 1

3

This is an exercise in recursion. I won't do the assignment entirely for you, but I can point out hints to help you get started.

For reference, here is the function you're supposed to implement:

def print_01_strings(k, s, n):
  # if k equal to n the function only needs to print s which is unique completion
  # otherwise, we'll print all the completions of the string s+'0' of length k+1
  # and all the completions of the string s+'1' of length k+1

The comments tell you what to do:

  • In the base case ("k equal to n"), you should just "print s".
  • For the recursive cases ("otherwise, ..."), you'll need to call print_01_strings twice with appropriate arguments.
    1. The first call handles "completions of the string s+'0' of length k+1".
    2. The second call handles "completions of the string s+'1' of length k+1".

Try to figure out what arguments should be passed to the recursive calls to print_01_strings in each of these cases.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the explanation - it makes much more sense to me now!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.