Example code
This example generates all combinations of characters from a string:How it works
The combinations function uses a prefix-based approach:- Base case: When the string
sis empty, return (all characters have been processed) - Recursive cases: For the first character in
s:- Include: Add
s[0]to the prefix and recurse with the remaining string - Exclude: Keep the prefix unchanged and recurse with the remaining string
- Include: Add
- Each valid combination (when including a character) is added to the result list
st
For a string of length n, this generates 2^n - 1 non-empty combinations. The recursion tree structure mirrors the subset problem but operates on string characters.
Decorator configuration
The@vs decorator is configured with:
show_argument_name=False: Shows only values without parameter namesnode_properties_kwargs: Custom styling for visual appealshape="record": Record-based node shapecolor="#f57542": Orange border colorstyle="filled": Filled nodesfillcolor="grey": Grey fill color
Output
Running this code withs='abc' generates:
- Console output: List of combinations including
['a', 'ab', 'abc', 'ac', 'b', 'bc', 'c'] - Animation file:
combinations.gifshowing the recursion tree with a 3-second delay between frames
Recursion pattern
The algorithm explores combinations by:- Building up prefixes character by character
- At each step, deciding whether to include or exclude the current character
- Creating a binary tree where paths represent different character selections
Visualization insights
In the recursion tree:- Each node shows the current
prefixand remaining strings - Left branches typically represent including the first character
- Right branches represent excluding it
- The tree depth equals the length of the input string