Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- def valuesFromFile(file):
- values = {}
- for line in open(file):
- keyVal = [i.strip() for i in line.split(":")] # whitespace should not matter
- if len(keyVal) != 2: continue # invalid line, was not in the form <key>:<value>
- letter, val = keyVal # now we know there's exactly two values - key, and value
- # all values should be lowercase, so case doesn't matter on lookups
- letter = letter.lower()
- # if we didn't get an integer in the string (or no string at all), just use 1
- try: val = int(val)
- except (TypeError, ValueError): val = 1
- values[letter] = val
- return values
- class Scrabble:
- def __init__(self, valueFile="letterValues.txt"):
- # get a letter-value map - what it says on the tin
- self.letterValues = valuesFromFile(valueFile)
- def getWordValue(self, word):
- # keep running tally
- totalValue = 0
- for i in word: # i being the next character in word
- i = i.lower() # case shouldn't matter
- letterValue = self.letterValues.get(i, 0) # if character not in values, assume default of 0
- totalValue += letterValue
- return totalValue
- def getBestWord(self, words):
- highest = -1
- best = ""
- for word in words:
- # code reuse son
- val = self.getWordValue(word)
- # higher values wins always
- # lower length wins on ties
- if val > highest or (val == highest and len(word) < len(best)):
- highest = val
- best = word
- return best
- def main():
- import sys # we need this for sys.stderr
- import os # we need this for os.path.isfile
- pointFile = input("point-value file? (hit enter for default) ")
- # if we got an actual file, use it
- if os.path.isfile(pointFile):
- pointThingy = Scrabble(pointFile)
- else: # otherwise, just use the default
- # if the user gave a file path, tell him it doesn't exist
- # silence on errors is typically not a good decision
- if len(pointFile) > 0:
- # {} gets replaced with pointFile here
- # we print to sys.stderr because technically, this is an error
- print("file \"{}\" does not exist, using default".format(pointFile), file=sys.stderr)
- pointThingy = Scrabble()
- wordsRaw = input("words? (seperate with comma) ") # this is a string, no newline
- wordList = [i.strip() for i in wordsRaw.split(",")] # every word in wordsRaw, split on commas, with whitespace trimmed
- # self-explanatory
- if len(wordList) == 1:
- word = wordList[0]
- # first {} gets replaced with word, second {} its value
- print("value of \"{}\" is {}".format(word, pointThingy.getWordValue(word)))
- else:
- best = pointThingy.getBestWord(wordList)
- # {} replaced with best
- print("best word in list is \"{}\"".format(best))
- # python trick: this is true if you're running from the command line or whatever,
- # but false if you're importing
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement