Skip to content

Instantly share code, notes, and snippets.

@haircommander
Created April 29, 2020 16:08
Show Gist options
  • Save haircommander/332289b4013835a12c6c55227e041c0d to your computer and use it in GitHub Desktop.
Save haircommander/332289b4013835a12c6c55227e041c0d to your computer and use it in GitHub Desktop.
mdame's impossible problem
#!/usr/bin/python3
import itertools
operations = []
# thanks to https://www.geeksforgeeks.org/print-all-combinations-of-given-length/
# for reminding (telling) me how to permute every possible string of length k that can be formed from a set of n characters
# The method that prints all
# possible strings of length k.
# It is mainly a wrapper over
# recursive function printAllKLengthRec()
def printAllKLength(set, k):
n = len(set)
printAllKLengthRec(set, [], n, k)
# The main recursive method
# to print all possible
# strings of length k
def printAllKLengthRec(set, prefix, n, k):
# Base case: k is 0,
# print prefix
if (k == 0) :
operations.append(prefix)
return
# One by one add all characters
# from set and recursively
# call for k equals to k-1
for i in range(n):
# Next character of input added
newPrefix = prefix.copy()
newPrefix.append(set[i])
# k is decreased, because
# we have added a new character
printAllKLengthRec(set, newPrefix, n, k - 1)
# Driver Code
if __name__ == "__main__":
ops = ['+', '*', '-', '/']
k = 3
printAllKLength(ops, k)
for num_perm in itertools.permutations(['2', '8', '3', '12']):
for op in operations:
equation = ""
for i in range(0,3):
equation += num_perm[i] + op[i]
equation += num_perm[3]
res = eval(equation)
if res == 33:
print(equation, "=", res)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment