Skip to content

Instantly share code, notes, and snippets.

@pfirpfel
Created April 19, 2021 14:16
Show Gist options
  • Save pfirpfel/0818c1d728c5825153eafecdf9070e60 to your computer and use it in GitHub Desktop.
Save pfirpfel/0818c1d728c5825153eafecdf9070e60 to your computer and use it in GitHub Desktop.
"""
Goal is to fill the empty spots in the initial tuple with positive integers
in a way that always four consecutive number have a product of 120.
"""
import numpy
initial = (None, None, 2, None, None, 4, None, None, None, None, None, 3, None, None) # tuple is immutable
possible_factors = [2, 3, 4, 5, 6, 10, 15] # all possible factors of 120 if there are 4 factors
# test if every 4 consecutive numbers have a product of 120
def test(iteration):
current_pos = 0
while current_pos <= len(iteration) - 4:
current_list = iteration[slice(current_pos, current_pos + 4)]
if None in current_list:
return
if numpy.prod(current_list) != 120:
return False
current_pos += 1
return True
def rec_step(iteration, next_pos):
# test if end is reached
if len(iteration) <= next_pos:
if test(iteration): # print valid solution
print(iteration)
return
# test intermediate result to abort early
if next_pos >=4:
if not test(iteration[slice(0, next_pos)]):
return
# try every possible value for empty slots
if iteration[next_pos] is None:
list_iteration = list(iteration)
for factor in possible_factors:
list_iteration[next_pos] = factor
rec_step(tuple(list_iteration), next_pos + 1)
else: # skip already filled values
rec_step(iteration, next_pos + 1)
rec_step(initial, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment