-
-
Save drewhutchison/1f4e5e35dcb06977cda0 to your computer and use it in GitHub Desktop.
This file contains 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
#!/usr/bin/python | |
#--------------------------------------------------------------------------- | |
# | |
# Pirates | |
# | |
# We need to find the number of pirates to talk to before we loop. | |
# Each pirate will refer us to another pirate, eventually we will find a | |
# pirate that directs us back to the original pirate, and we can exit. | |
# | |
#--------------------------------------------------------------------------- | |
def answer(numbers): | |
## Our pirates | |
pirates = [] | |
## Ask the first pirate who to talk to | |
pirates.append(numbers[numbers[0]]) | |
## Start looping the numbers | |
for i in numbers: | |
last_pirate = pirates[-1] | |
## Our last pirate said to talk to numbers[X] Have we talked to them yet? | |
## If yes then quit and you found the loop | |
if numbers[last_pirate] in pirates: | |
print "pirates: " + str(len(pirates)) | |
return | |
## We haven't talked to this pirate yet so lets add them to our pirates | |
else: | |
pirates.append(numbers[last_pirate]) | |
answer([1, 0]) # 2 | |
answer([1, 2, 1]) # 2 | |
answer([1, 3, 0, 1]) # 2 | |
answer([2, 1, 3, 2]) # 2 | |
answer([2, 2, 4, 4, 0]) # 3 | |
answer([2, 3, 1, 4, 5, 0]) # 6 | |
answer([1, 7, 1, 4, 5, 0, 7, 6]) # 2 | |
answer([19, 3, 1, 21, 22, 11, 13, 12, 8, 20, 32, 27, 2, 4, 23, 9, 36, 25, 39, 0, 15, 16, 38, 26, 37, 33, 7, 17, 29, 10, 34, 6, 35, 31, 24, 18, 30, 4, 14, 3]) # 2 | |
answer([5, 9, 5, 1, 6, 3, 6, 7, 2, 3, 0, 1]) # 3 | |
answer([12, 47, 7, 58, 53, 28, 9, 10, 5, 21, 27, 1, 13, 30, 38, 19, 18, 35, 57, 26, 36, 20, 33, 32, 6, 2, 24, 29, 8, 52, 54, 0, 44, 39, 23, 37, 4, 51, 40, 45, 55, 22, 34, 59, 43, 46, 49, 3, 14, 41, 42, 25, 56, 11, 15, 16, 50, 17, 48, 31]) #50 | |
answer([22, 19, 65, 76, 60, 3, 15, 27, 53, 1, 23, 45, 38, 72, 54, 73, 29, 78, 47, 21, 0, 42, 63, 39, 13, 7, 59, 28, 51, 36, 11, 18, 74, 6, 50, 8, 17, 33, 64, 4, 12, 9, 79, 24, 62, 56, 14, 70, 41, 69, 67, 5, 48, 16, 71, 52, 58, 34, 68, 49, 40, 43, 26, 30, 32, 66, 35, 10, 20, 2, 61, 31, 77, 55, 37, 25, 46, 75, 57, 44]) # 10 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment