Created
July 20, 2018 08:50
-
-
Save pmutua/232b432182be31ffee42874f6e171612 to your computer and use it in GitHub Desktop.
100 Doors Problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ''' | |
| 100 Doors Problem: | |
| There are 100 doors in a row that are all initially closed. | |
| You make 100 passes by the doors. | |
| The first time through, visit every door and toggle the door (if the door is closed, open it; if it is open, close it). | |
| The second time, only visit every 2nd door (door #2, #4, #6, ...), and toggle it. | |
| The third time, visit every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. | |
| Task: | |
| Answer the question: what state are the doors in after the last pass? Which are open, which are closed? | |
| Note: Edited to take input from user for number of doors. | |
| ''' | |
| # Gets number of doors from user | |
| def get_val(): | |
| num_doors = input('Enter an integer greater than 0: ') | |
| try: | |
| if int(num_doors) > 0: | |
| return int(num_doors) | |
| else: | |
| print('I said greater than zero.') | |
| return get_val() | |
| except: | |
| print(num_doors + " is not an integer. Do it right.") | |
| return get_val() | |
| # Creates doors in closed state using number entered by user | |
| def create_doors(num_doors): | |
| doors = [False] * num_doors | |
| return doors | |
| # Uses pass number to flip state of appropriate doors | |
| # enumerate starting at 1 because the only time the first door should be flipped is on pass 1, | |
| # and 0%X=0. | |
| def flip(doors,iter): | |
| for i, elem in enumerate(doors,1): | |
| if i%iter == 0: | |
| if doors[i-1] == True: | |
| doors[i-1] = False | |
| elif doors[i-1] == False: | |
| doors[i-1] = True | |
| print(i, elem) | |
| return doors | |
| # Creates list of open doors and list of closed doors, displays results | |
| def door_lists(doors): | |
| opened = [] | |
| closed = [] | |
| for i, elem in enumerate(doors): | |
| if elem == True: | |
| opened.append(i + 1) | |
| elif elem == False: | |
| closed.append(i + 1) | |
| print('Open Doors:') | |
| print(opened) | |
| print('Closed Doors:') | |
| print(closed) | |
| # Calls functions to get values from user and create doors. Creates iterator, a list of pass numbers | |
| num_doors = get_val() | |
| doors = create_doors(num_doors) | |
| iterator = list(range(1, num_doors + 1)) | |
| #For each pass (iterator value) call flip func to flip appropriate doors | |
| for i in iterator: | |
| doors = flip(doors,i) | |
| #display final results | |
| door_lists(doors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment