Megan Wright
Megan Wright

Reputation: 13

Python If == true statement only working on last line of readline

My function only says that the last word in a file of words is an anagram (the first helper function). But every word in the file is an anagram of the word I tested and returns true independently with the helper function outside of the main function. I am not sure if it has something to do with /n being a part of the string, and then it accounting for that, but I tried putting in an if statement saying to delete it if it was in there and that did not work either. I also did test to make sure it is running through each word in the .txt file and it is.

def is_anagram(string1, string2):
    """Returns True if the two strings are anagrams of eachother.

    str, str -> bool"""
    if sorted(string1)==sorted(string2):
        return True
    else:
        return False


def find_anagrams(word):
    final = []
    content = open("small_list.txt")
    content.close
    while True:
        line = content.readline()
        print(line)
        if is_anagram(word, line) == True:
            print("bruh")
            final.append(line)
        elif line == '':
             break
    return final

Upvotes: 1

Views: 765

Answers (1)

cs95
cs95

Reputation: 403120

This is expected, based on the method you use to read a line (file.readline). From the documentation:

f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline.

Your line has a trailing newline, but word certainly does not. So, in the end, all you'd need to change is:

line = content.readline().rstrip()

Well, that's all you'd need to change to get it working. Additionally, I'd also recommend using the with...as context manager to handle file I/O. It's good practice, and you'll thank yourself for it.

with open("small_list.txt") as f:
    for line in f:
        if is_anagram(word, line.rstrip()):
            ... # do something here

It's better to use a for loop to iterate over the lines of a file (rather than a while, it's cleaner). Also, there's no need to explicitly call f.close() when you use a context manager (you're not currently doing it, you're only referencing the method without actually calling it).


Incorporating @Christian Dean's suggestion in this answer, you can simplify your anagram function as well - call sorted and return the result in a single line:

def is_anagram(a, b):
    return sorted(a) == sorted(b)

Upvotes: 2

Related Questions