Jump to content
Fórum Script Brasil
  • 0

Busca de palavras


Question

Estou fazendo um programa que busca palavras inversas (pedro e ordep, por exemplo) em um arquivo cuja cada linha é uma palavra (link:https://drive.google.com/open?id=15aj-5coD_dBKIunMHuGZTAT3cgkrSuyD). Tentei usar um algoritmo de for para buscar cada inverso na lista, mas o programa para na primeira iteração do loop. abaixo o código completo:

def seek_word(lista, word): //procura a palavra na lista de maneira otimizada
    length = len(lista)
    if len(lista) == 0:
        return False
    middle_word = lista[int(length / 2)]
    if word == middle_word:
        lista = [lista[int(length / 2)]]
        return True
    elif word > middle_word:
        del lista[:int(length / 2) + 1]
        return seek_word(lista, word)
    elif word < middle_word:
        del lista[int(length / 2):]
        return seek_word(lista, word)


def create_list(fin): //cria uma lista com as palavras do arquivo
    lista = []
    for line in fin:
        lista.append(line.strip())
    return lista


with open('files/words.txt') as fin:
    lista = create_list(fin)
    for word in lista:
        if seek_word(lista, word[::-1].strip()):
            print('{} is inverse of {}'.format(word[::-1], word))
Link to post
Share on other sites

1 answer to this question

Recommended Posts

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



  • Forum Statistics

    • Total Topics
      148692
    • Total Posts
      644525
×
×
  • Create New...