Skip to content

Update chain-words.py #12

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 20 additions & 42 deletions challenges/chain-words.py
Original file line number Diff line number Diff line change
@@ -1,42 +1,20 @@
"""
#246
Dropbox

Given a list of words, determine whether the words can be chained to form a circle.
A word X can be placed in front of another word Y in a circle if the last character of X is same as the first character of Y.

For example, the words ['chair', 'height', 'racket', 'touch', 'tunic'] can form the following circle:
chair --> racket --> touch --> height --> tunic --> chair.

"""

def checkForCycleHelper(usedWords, remainingWords):
if len(remainingWords) == 0:
# print(usedWords, end=" ") # Uncomment to see the chain
return True

lastLetter = usedWords[-1][-1]
for i in range(len(remainingWords)):
nextWord = remainingWords[i]
if nextWord.startswith(lastLetter) and checkForCycleHelper(usedWords+[nextWord], remainingWords[:i]+remainingWords[i+1:]):
return True

return False


def checkForCycle(words):
return checkForCycleHelper([words[0]], words[1:])

def main():
print(checkForCycle(["geek", "king"])) # True ['geek', 'king']
print(checkForCycle(["for", "geek", "rig", "kaf"])) # True ['for', 'rig', 'geek', 'kaf']
print(checkForCycle(["aab", "bac", "aaa", "cda"])) # True ['aab', 'bac', 'cda', 'aaa']
print(checkForCycle(["aaa", "bbb", "baa", "aab"])) # True ['aaa', 'aab', 'bbb', 'baa']
print(checkForCycle(["aaa"])) # True ['aaa']
print(checkForCycle(["aaa", "bbb"])) # False
print(checkForCycle(["abc", "efg", "cde", "ghi", "ija"])) # True ['abc', 'cde', 'efg', 'ghi', 'ija']
print(checkForCycle(["ijk", "kji", "abc", "cba"])) # False


if __name__ == "__main__":
main()
words = eval(input())
length = len(words) # number of words
chain = [words[0]] # appending first word
words = words[1:] # slicing out the first word from words
for i in range(0, length - 1):
for word in words: # each word in the list
break_flag = False # used to check whether to break the loop or not
if word[0] == chain[-1][-1]: # chain forming condition
for temp_word in words: # each word in the list
# checks if the list contains word for further chain formation
if len(words) != 1 and word[-1] == temp_word[0]:
chain.append(word) # appending the word
words.remove(word) # removing the word to avoid repeated check
break_flag = True # if word added then no use of further iterations
break
elif len(words) == 1: chain.append(word) # in case only one word is left
if break_flag: break # if word already added stop further iterations
# checks whether the chain formed is correct or not
if len(chain) == length and chain[0][0] == chain[-1][-1]: print(chain)
else: print("Sorry. The words cannot be chained to form a circle")