Home > Software design >  Trying to code a solution to a kids puzzle - some calculations seem out of place
Trying to code a solution to a kids puzzle - some calculations seem out of place

Time:04-07

I have been trying to learn python for the last month through some online courses, with no prior knowledge of coding whatsoever. Having finished with some of the basics I wanted to do some projects to expand my knowledge and skills. So, I came across a children's math [Puzzle game][1], whose idea is to turn the wooden cubes around in such a way that every face of the puzzle is solved at the same time. Each other cube is a sequence of 1,2,3, and 4 - while the operations (cubes 2 and 4) are - * /. The sixth cube is always a "=" sign. This devil's thing is much harder than it looks! So, as an exercise, I thought it would be fun to try and code my way to a solution. I have been doing my very best for the past couple of days but now I think I am hitting a brick wall because of some inexplicable (to my eyes) problems my code is facing.

My idea was to "flatten out the cubes" and try out all possible combos, see if there are any that manage to 'solve' the puzzle in all sides at the same time. Here is what I have coded so far:

import numpy as np
import pandas as pd
import operator
import random

# defining the sequences of each cube - l1 to l3 the first 3 numeric cubes, s1 the last cube, f1 and f2 the function cubes
l1 = [3, 2, 1, 4]
l2 = [2, 1, 3, 4]
l3 = [2, 4, 1, 3]
s1 = [3, 1, 4, 2]
f1 = ['*', '-', ' ', '/']
f2 = ['-', '/', ' ', '*']

# Getting all possible and put them in a dataframe
shuf1 = pd.DataFrame([l1[len(l1)-i:]   l1[0:len(l1)-i] for i in range(len(l1))])
shuf_f1 = pd.DataFrame([f1[len(f1)-i:]   f1[0:len(f1)-i] for i in range(len(f1))])
shuf2 = pd.DataFrame([l2[len(l2)-i:]   l2[0:len(l2)-i] for i in range(len(l2))])
shuf_f2 = pd.DataFrame([f2[len(f2)-i:]   f2[0:len(f2)-i] for i in range(len(f2))])
shuf3 = pd.DataFrame([l3[len(l3)-i:]   l3[0:len(l3)-i] for i in range(len(l3))])
shuf4 = pd.DataFrame([s1[len(s1)-i:]   l1[0:len(s1)-i] for i in range(len(s1))])

#define operators you want to use
allowed_operators={
    " ": operator.add,
    "-": operator.sub,
    "*": operator.mul,
    "/": operator.truediv}

# these lists are for iteration purposes later on
v1 = [0,1,2,3]
v2 = [0,1,2,3]
v3 = [0,1,2,3]
v4 = [0,1,2,3]
v5 = [0,1,2,3]
v6 = [0,1,2,3]
v7 = [0,1,2,3]

# opening some empty "boxes" for later use
test_results = []
temp_list = np.array([0, 0])

for v in v6:
    for w in v5:
        for z in v4:
            for u in v3:
                for y in v2:
                    for x in v1:
                        for r in v7:
                            for i in range(len(l1)):
                                
                                # Setting the face of each cube
                                a=shuf1.iloc[i,r]
                                b=shuf2.iloc[i,x]
                                c=shuf3.iloc[i,y]
                                d=shuf4.iloc[i,u]
                                string_operator=shuf_f1.iloc[i,z]
                                string_operator2=shuf_f2.iloc[i,w]
                                
                                # Doing the calculations
                                result=allowed_operators[string_operator](a,b)
                                result2=allowed_operators[string_operator2](result,c)
                                logic_test = result2 == shuf4.iloc[i,v]
                                test_results.append(result2 == logic_test)
                                
                                # feed results to list
                                newrow = []
                                second_box = str(a)   str(string_operator)   str(b)   str(string_operator2)   str(c)   "="   str(d)
                                newrow.append(second_box)
                                newrow.append(logic_test)
                                temp_list = np.vstack([temp_list, newrow])
# Append to dataframe
solution_list = pd.DataFrame(temp_list, columns = ['Operation','Result'])

# Print out outcomes
print(solution_list.head(10))
print(solution_list.info())
preview = solution_list[solution_list['Result'] == 'True']
print(preview.head(20))

# Locate the index of the sequence of 4 consequtive positive solutions
quadruple_sequence = np.where((solution_list['Result'] == 'True') & (solution_list['Result'].shift() == 'True') & (solution_list['Result'].shift(periods=2) == 'True') & (solution_list['Result'].shift(periods=3) == 'True'))[0]
print(quadruple_sequence.size)
print(quadruple_sequence)

# Print out the 4 sequence
solution_list.iloc[quadruple_sequence]

Now my problem is that I am receiving a weird output. Here I am pasting some of the output that I receive when I filter the dataframe of the possible combos for those that have a positive solution to the puzzle (result = True). In the beginning as you can see there is a true relationship between the operation result and the "result": for instance, 1 2 1 indeed equals 4, hence the "True" statement is indeed true. But looking at some other lines of the dataframe, it seems that python is recognizing as "True" some very untrue combinations. I am absolutely clueless of why this might be happening. Any ideas?

Example of output in the head of the dataframe:

  Operation Result
0         0      0
1   3*2-2=3  False
2   4/4*3=2  False
3   1 3 1=4  False
4   2-1/4=1  False

the sequence of True results from the same dataframe:

    Operation   Result
2164    2/2/1=1 True
2420    2/2/1=4 True
2676    2/2/1=2 True
2932    2/2/1=3 True

I am wondering how is this possible and where did I go wrong. I am sure that you could think of better ways of structuring the problem and any ideas are welcome! Just keep in mind that I am really beginner level with my understanding and trying to learn! Thanks! =) [1]: https://i.stack.imgur.com/MToqG.jpg

CodePudding user response:

You are iterating twice over the last cube in

d=shuf4.iloc[i,u]

and

logic_test = result2 == shuf4.iloc[i,v]

changing that last line to

logic_test = result2 == d

and removing the loop over v will result in the desired result. Btw. pandas is maybe not the best framework for this exercise, you should look into list operators.

  • Related