Skip to content

Instantly share code, notes, and snippets.

@flavienbwk
Last active January 24, 2019 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flavienbwk/24fd2d29533fd787b9b4cc438f56fd63 to your computer and use it in GitHub Desktop.
Save flavienbwk/24fd2d29533fd787b9b4cc438f56fd63 to your computer and use it in GitHub Desktop.
Coding interview problem : prints all the subsets of a list of numbers (integers).
# This is the kind of software engineering interview algorithm you may have to do at Facebook.
# You must print all the subsets of a given set.
#
# If the input is [1, 2, 3], you will have to print :
#
# 1, 2, 3,
# 1, 2,
# 1, 3,
# 1,
# 2, 3,
# 2,
# 3,
#
# In any order you want.
import sys
def printSubsets(set):
# Here, we use a formula to determine the number of
# subsets from the length of the given set.
#
# We use binary addition and convert this binary value
# to a list. The '1's of the binary list behaves
# like a "trigger-key" of the actual set.
# It will start with : [0, 0, 0]
# And then : [0, 0, 1] // Prints '3' if the input is [1, 2, 3]
# And then : [0, 1, 0] // Prints '2' if the input is [1, 2, 3]
# ...
max_int = 2 ** len(set)
for i in reversed(range(0, max_int)):
bin_list = list("{0:b}".format(i)) # Converts decimal to binary string
for a in range(0, len(set) - len(bin_list)):
bin_list.insert(0, '0') # We have to add trailing '0's
for n in range(0, len(bin_list)):
if bin_list[n] == "1":
sys.stdout.write(str(set[n]) + ", ") # Avoids carriage return
sys.stdout.write("\n")
printSubsets([1,2,3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment