Home > Blockchain >  n FOR loops in python with changable iterable, need help understanding
n FOR loops in python with changable iterable, need help understanding

Time:08-01

I am doing a project which calculates how many combinations there are of a old-fashioned android lock screen. So the lock screen is a 3x3 shown on image where the first row is respectively A, B, C, second one: D, E, F and the third one G, H, I

I include my starting point and the length (dots/points "clicked/checked") on the lock screen as my function arguments, so for example function("A", 2) would return a list containing AB, AD, AE, AH, AF and a couple for funcion("A", 3) would be: ABC, ABF, ABE and AEI -> (here, A can't go straight to I because E is inbetween and needs to be "clicked" first) I have made a function valid_moves() which takes 2 arguments: startingpoint and board. So If I call this function: valid_moves("A", my_board) it returns ['B', 'D', 'E', 'F', 'H'] if the board is "fresh" and "A" is my first point/dot.

My nested list board contains 3 row lists ([[a1, b1, c1], [d1, e1, f1], [...]], the number after the letter can be 1 or 2 (1 - not clicked and 2 - clicked).

My idea is to iterate through every possibility and add it to the list. So if my func() would have the length of 2, i would simply do 2 for loops to iterate over all of the possibilities while changing the "clicked" dot's number from 1 to 2. But the length is also my N amount of FOR LOOPS and my board will change with every iteration. How do I do this? I found out about itertools.product 5 minutes about but I don't really understand it and have to idea how to implement the logic of clicked dot, Any suggestions? Thanks in advance!!

CodePudding user response:

The way you describe the problem is that you have the same problem in every iteration and possibly the same "solution" independently of the sub-paths. You want to search through all paths which counts the possible combinations.

This sounds like it's made for recursion as you can solve the same problem in each function call and return the count for each recursion.

CodePudding user response:

You could use tuples to identify the buttons:

(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)

Then you can find all the lock sequences of length N with recursion: you build a tree with depth N and recursively find all the sequences, i.e.

Start: (0,0), length: 4

For any adjacent button, add the button to the sequence, increase the current length. You can find the adjacent buttons if the euclidean distance is either 1 or square root of 2.

  • Related