Last active
May 2, 2018 21:31
-
-
Save Dmitrii-I/1475569b5e6e1a8e29201763c35fb23e to your computer and use it in GitHub Desktop.
Power set of an arbitrary set, not allowed to use set functions
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
def power_set(any_set): | |
any_set = list(any_set) | |
subsets = [] | |
s = tuple(range(1, len(any_set)+1)) | |
buffer = [[el] for el in s] | |
while buffer: | |
new_buffer = [] | |
for buff_el in buffer: | |
i = max(buff_el) | |
if i < len(s): | |
for j in range(i, len(s)): | |
new_buffer.append(buff_el + [s[j]]) | |
subsets += new_buffer | |
buffer = [el for el in new_buffer] | |
power_set = [[]] + any_set | |
for subset in subsets: | |
subset_elements = [] | |
for element_index in subset: | |
subset_elements.append(any_set[element_index-1]) | |
power_set.append(subset_elements) | |
return power_set | |
if __name__ == "__main__": | |
print(power_set({1, 2, 3, 4})) | |
print(len(power_set({1, 2, 3, 4}))) | |
print(power_set({'a', 'b', 'c', 'd', 'e'})) | |
print(len(power_set({'a', 'b', 'c', 'd', 'e'}))) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a daily coding challenge:
Good morning. Here's your coding interview problem for today.This problem was asked by Google.The power set of a set is the set of all its subsets. Write a function that, given a set, generates its power set.For example, given the set {1, 2, 3}, it should return {{}, {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}}.You may also use a list or array to represent a set.Upgrade to premium and get in-depth solutions to every problem.If you liked this problem, feel free to forward it along! As always, shoot us an email if there's anything we can help with!