简体   繁体   中英

Please help me in debugging this python code

This is a program that finds anagrams for words greater than 15 letters.There's no syntax error but the output is not as expected.I will be extremely grateful if u could point out the logical error in the program. I downloaded the word list from http://thinkpython.com/code/words.txt PS-I am new to Python.If there's a better approach please tell me....

def anagrams():
    fin1=open('words.txt')
    val=-1
    fin2=open('dic.txt')
    for i in range(100000):
        fin2.seek(0)              
        word1=fin1.readline()
        if len(word1)>18:               
            for j in range(100000):
                word2=fin2.readline()
                flag=1
                if len(word2)==len(word1)and word1!=word2:

                    for k in range(len(word1)-1):
                        if word1.find(word2[k])==-1:
                            flag=1
                            break
                        else:
                            flag=0
                if flag==0:
                    print word2,'is anagram of ',word1,'\n'

Not related to the code you've posted, but you can do this using simple Counter objects, which will maintain the Count of all the characters for you.

>>> from collections import Counter
>>> def is_anagram(string1, string2):
...     return Counter(string1) == Counter(string2)
... 
>>> is_anagram("anagram anagram", "gramana anagram")
True

One problem I see is that if both words have the same letters but in different amounts, you will claim they are anagrams when they are not.

Some improvements:

  • To see if two words are anagrams, sort the letters in each & compare (they should be the same) (or use Counter as suggested elsewhere)
  • Your code will test each pair of words twice: (word1,word2) and later (word2,word1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM