[Python] How to debug an infinite loop in my Python anagram generator

Discussão em 'Python' iniciado por Stack, Maio 11, 2025.

  1. Stack

    Stack Membro Participativo

    The aim of the program is to generate an anagram given 6 randomly generated alphabets. The syntax seems to be correct but there's some sort of logical error which I am not able to figure out. If I execute the program then it will just go on running and won't stop.

    I don't think it's because of any infinite loop, rather it's due to its inability to find anagram using the 6 generated letters. Have I made a mistake? I have highlighted the portion where I think there is error.

    The file words.txt can be downloaded from http://thinkpython.com/code/words.txt.

    import random

    def game():

    while True:
    ch=[]
    res=[]
    print 'The 6 randomly generated alphabets are :'
    for i in range(6):
    ch.append(chr(random.randrange(97,123)))
    print ch,'\n'
    delimiter=''
    z=delimiter.join(ch) #converted list to a string
    word_list2=dict() #word_list2 is a dictionary containing randomly generated letters as keys
    for c in z:
    if c not in word_list2:
    word_list2[c]=1
    else:
    word_list2[c]=word_list2[c]+1

    fin=open('words.txt')
    for c in range(130000):
    words=fin.readline()
    word=words.strip()
    flag=1
    if len(word)==6:

    word_list1=dict() #word_list1 is a dict containing char present in word as keys

    for c in word:
    if c not in word_list1:
    word_list1[c]=1
    else:
    word_list1[c]=word_list1[c]+1

    ***for c in word_list2:
    if c not in word_list1:
    flag=1
    break
    else:
    if word_list1[c]==word_list2[c]: #comparing if characters in both dict have same no. i.e 'a' should occur 2 times in both etc
    flag==0
    else:
    flag=1
    break***



    if flag==0:
    res.append(word)

    if not res:
    print 'the list is empty'
    print 'Selecting a new set of randomly generated characters\n'

    else :
    print res
    break

    game()

    Continue reading...

Compartilhe esta Página