![]() ![]() This can cause cognitive friction, and there is more than one way to address the issue. My approach is to simply have an unused value at the start of the list, and to have 101 items in total rather than 100. Next up we need to iterate over the doors list. for i in range(1, 101): # 101 because of how range worksĭoors = not doors # Using `not` to invert the Boolean value Since we know the number of iterations needed in advance, we use a for loop. Notice how we toggled the state of each door in the above code. We accessed the doors list using i as the index, and used the logical not operator to invert the values. OK so we have done one pass of the doors, but that’s just the start. ![]() We need to make 100 passes, with the skipping behaviour described in the problem definition. There are two key components needed to achieve this. One is the use of nested for loops, which you can learn more about from the link.Ī basic example of a nested for loop would be: for x in range(1, 6):īefore running this code you should think carefully about what the output will be. The other component is the use of a step value in our for loops.įor example, the following code for i in range(1, 11, 2): Then go ahead and run it and see if you were right. It is the third argument to range which determines the step. Notice that 11 is not displayed because the upper bound for range is not inclusive. Now we have the ingredients to solve the problem, there is just one final trick you will need to put them all together. This is to use the outer loop counter ( i in this case) as a parameter in the range of the inner loop. I have put a comment explaining how this works in my solution below. Solution for the 100 Doors Python Coding Challenge. ![]() # for the second pass, x = 2, so we start at door 2, for the 3rd pass we start at door 3 etc.ĭoors = not doors # using `not` to invert the Boolean value doors = * 101 # so we can start at door 1. # Print out just the positions of the open doors ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |