A
A
Alexey Nevazhny2019-10-27 12:00:02
Python
Alexey Nevazhny, 2019-10-27 12:00:02

How to fix a bug in the "game of cities"?

It is necessary to solve the problem of "playing cities", i.e. the input data is the words in Latin, for example, "aab", "aac", "baas", respectively, the answer will be "aab", "baas", "aac". It works fine on a small number of words, but with an input of ~ 900 words, it loops endlessly in the part:

for j in range(0,N-U):
    if (s[j][0] == words[i][-1]):
       searchNextWord(s,j,U)

I can not understand what the problem is .. I would like to get advice.
Whole code:
def searchNextWord(words,i,U):
        global Result
        s = [None]*N
        if (Result==True):
            return
        res[U] = words[i]
        U += 1
        if (U == N):
            Result = res[U - 1] == words[i]
        if (Result==True):
            return

        for j in range(0,N-U):
            if (j<i):
                s[j]=words[j]
            else:
                s[j]=words[j+1]

        for j in range(0,N-U):
            if (s[j][0] == words[i][-1]):
                searchNextWord(s,j,U)


    words=[]
    N=int(input())
    if (N<1 or N>1000):
        exit()
    for i in range(N):
        new_element = str(input())
        words.append(new_element)

    res = [None]*N
    for i in words:
        if (len(i)>10):
            exit()

    Result = False
    for i in range(0,N):
        if (Result==False):
            searchNextWord(words, i, 0)

    if (Result==True):
        for i in range(0,N):
            print(res[i])
    else:
        print("NO")

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
longclaps, 2019-10-27
@longclaps

Sorry, my friend, but the logic of your code is impossible to understand without your comments.
The only thing that is obvious is that words do not go anywhere from the words list as the game progresses - so why not the program get stuck if there is a looped set of words in words.

X
xmoonlight, 2019-10-29
@xmoonlight

Try to imagine a set of words as a "deck of cards" and exclude the found words from this "deck" as you find the correct chain.
Initially, make sure that all the words in this "deck" are unique.
This will avoid circular cycles.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question