← Back to Backtracking

Generate All Sequences

3 of 6

Exercise 2: Generate All Sequences πŸ”’

Your Task

Write a function all_sequences(n, k) that returns all sequences of length k where each element is chosen from 1 to n. Elements can repeat.

Return the sequences in any order.


Examples

print(all_sequences(2, 1)) # Output: [[1], [2]] print(all_sequences(2, 2)) # Output: [[1, 1], [1, 2], [2, 1], [2, 2]] print(all_sequences(3, 2)) # Output: [[1,1], [1,2], [1,3], [2,1], [2,2], [2,3], [3,1], [3,2], [3,3]]

The Pattern

At each position you loop through all n choices and pick one:

            []
          / | \
        [1] [2] [3]        ← pick first element
        /|\  /|\  /|\
    [1,1][1,2][1,3] ...    ← pick second element

When the sequence reaches length k, add it to the result.


Starter Code

def all_sequences(n, k): # Your code here pass # Test your function: print(all_sequences(2, 1)) # Expected: [[1], [2]] print(all_sequences(2, 2)) # Expected: [[1, 1], [1, 2], [2, 1], [2, 2]] print(all_sequences(3, 2)) # Expected: [[1,1],[1,2],[1,3],[2,1],[2,2],[2,3],[3,1],[3,2],[3,3]] print(all_sequences(2, 3)) # Expected: [[1,1,1],[1,1,2],[1,2,1],[1,2,2],[2,1,1],[2,1,2],[2,2,1],[2,2,2]]

Hints

Try it yourself

Code: Generate All Sequences

Loading Python runtime…
Python …
Loading...
bash
$ Click "Run" to execute your code...