Created
December 11, 2018 14:26
-
-
Save priyankvex/b9bdd16d175b33989e093660cb1f91f2 to your computer and use it in GitHub Desktop.
Scamming the Coding Interview: Problem #1: Generate Power Set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Scamming the Coding Interview | |
""" | |
def generate_super_sets(power_set, elements, running_set, start_index): | |
if start_index > len(elements): | |
return | |
for i, num in enumerate(elements): | |
if i < start_index: | |
continue | |
temp_running_set = running_set[:] | |
temp_running_set.append(num) | |
power_set.append(temp_running_set) | |
generate_super_sets(power_set, elements, temp_running_set, i+1) | |
if __name__ == '__main__': | |
power_set = [] | |
elements = [1, 2, 3] | |
power_set.append([]) | |
generate_super_sets( | |
power_set=power_set, elements=elements, running_set=[], start_index=0 | |
) | |
print(power_set) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Just big no to recursion - you do not need it.
given the size of your set is n you know size of power set is m=2**n. You can generate each subset based on binary encoding:
so if your set is {1,3,'k'} - you will have 2**3 subsets
If it's
magic
for you the mask generator is changin number to it's binary representation:having that mask you can zip it with the orginal set and filter by it value to generate final subset