Farah
Farah

Reputation: 51

permutation using recursion and three arguments

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

Upvotes: 0

Views: 164

Answers (1)

k_ssb
k_ssb

Reputation: 6282

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.

Upvotes: 3

Related Questions