Quantcast
Viewing all articles
Browse latest Browse all 8

Answer by MarianD for Simplifying a Scrabble Word Finder - Python

Your function definition

def calc_score(word):
    """Calculate the score of a given word."""
    word_score = 0
    for x in word:
        word_score += scores[x]
    return word_score

may be as simple as

def calc_score(word):
    """Calculate the score of a given word."""
    return sum([scores[x] for x in word])

[scores[x] for x in word] is so called list comprehension - it creates the list of scores[x] for every x in word - and then the function sum() will add its items together.


Similarly, your function definition

def look_up():
    """Create the variable containing the master list of words."""
    read_dict = open("sowpods.txt", "r")
    master = read_dict.read()
    read_dict.close()
    master = master.split("\n")
    return master

may be as simple as

def look_up():
    """Create the variable containing the master list of words."""
    with open("sowpods.txt", "r") as sowpods:
        master = list(sowpods)
    return [m.rstrip('\n') for m in master]

Using the context manager (with) is preferred for files, as it properly closes a file for you, even after the occurrence of an exception, and moreover gives you individual lines in the sowpods variable.


Viewing all articles
Browse latest Browse all 8

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>