I'm a beginner and I am doing some exercises from codewars. This is the description of the exercise:
- Assume we take a number x and perform any one of the following operations:
a) Divide x by 3 (if it is divisible by 3), or
b) Multiply x by 2
- After each operation, we write down the result. If we start with 9, we can get a sequence such as:
[9, 3, 6, 12, 4, 8] -- 9 / 3 = 3 --> 3 * 2 = 6 --> 6 * 2 = 12 --> 12 / 3 = 4 --> 4 * 2 = 8
You will be given a shuffled sequence of integers and your task is to reorder them so that they conform to the above sequence. There will always be an answer.
For the above example:
solve([12, 3, 9, 4, 6, 8])=[9, 3, 6, 12, 4, 8]
My code passed the first Tests. Then when i tried ATTEMPT (which is the second step and includes many more tests and more complicated tests) my code took to long. There is a time limit of 12000 ms.
I am looking for hints about how to speed up my code. (or, which maybe is necessary, how to change the approach to get a faster code)
This is my code:
from itertools import permutations
def solve(arr):
# First i construct a list of lists of all possible sequences, using permutations.
perm = [i for i in permutations(arr, len(arr))]
perm = [list(j) for j in perm]
# Then i start walking this list until i find a sequence that works.
for p in perm:
# for index and elements in the sequence
for ind, el in enumerate(p[:-1]):
# I calculate n1, n2: the two possible next numbers in the sequence
n1 = el/3
if n1.is_integer():
n1 = int(n1)
n2 = el * 2
# If n1 or n2 isnt the next number in the sequence i break and look
# at the next sequence p.
if (n1 != p[ind+1]) and (n2 != p[ind+1]):
break
# otherwise i am able to walk the entire sequence
# and this means i have found the right one and i can return it
else:
return p