Advertisement
GoodiesHQ

TypeSpeed

Feb 1st, 2016
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.33 KB | None | 0 0
  1. from time import time
  2. from random import SystemRandom
  3. from decimal import Decimal, getcontext
  4.  
  5. getcontext().prec = 3
  6. minimumWordLength = 5
  7. numberOfWords = 25
  8.  
  9.  
  10. class typingspeed:
  11.     def __init__(self, wordfile):
  12.         self.rdev = SystemRandom()
  13.         try:
  14.             possibleWords = set(open(wordfile, "r").read().splitlines())
  15.             possibleWords = filter(lambda _: len(_) >= minimumWordLength, possibleWords)
  16.             possibleWords = [word.strip() for word in possibleWords]
  17.             assert(len(possibleWords) >= numberOfWords)
  18.             # List comprehension form:
  19.             # possibleWords=[word.strip() for word in filter(lambda _: len(_)>=5, set(open(wordfile, "r").readlines()))]
  20.         except IOError:
  21.             print("File '{}' does not exist.".format(wordfile))
  22.             return
  23.         # (word, [0, 0]) = word, [time taken for word, string attempt (for later comparison), errors]
  24.         self.words = dict((word, None) for word in self.rdev.sample(possibleWords, numberOfWords))
  25.  
  26.     def begin(self):
  27.         while raw_input("Type 'ready' to begin: ").lower() != "ready":
  28.             pass
  29.         for word in self.words:
  30.             print(word)
  31.             t1 = time()
  32.             attempt = raw_input("")
  33.             t2 = time()
  34.             self.words[word] = [t2 - t1, attempt == word]
  35.  
  36.     def __str__(self):
  37.         if not hasattr(self, "words"):
  38.             return ""
  39.         successfulWords = {
  40.             word: [timetaken, correct]
  41.             for (word, [timetaken, correct]) in self.words.items()
  42.             if correct == True
  43.         }
  44.         if len(successfulWords) < 1:
  45.             return "All words were errors. You are a fucking terrible typer."
  46.         fastestWord = min(
  47.             successfulWords.items(),
  48.             key=lambda word: word[1][0] / len(word[0])
  49.         )
  50.         slowestWord = max(
  51.             successfulWords.items(),
  52.             key=lambda word: word[1][0] / len(word[0])
  53.         )
  54.         return '\n'.join([
  55.             "Fastest Word: {} {}s/letter",
  56.             "Slowest Word: {} {}s/letter"
  57.         ]).format(
  58.             fastestWord[0],
  59.             Decimal(fastestWord[1][0])/len(fastestWord[0]),
  60.             slowestWord[0],
  61.             Decimal(slowestWord[1][0])/len(fastestWord[0])
  62.         )
  63.  
  64. ts = typingspeed("words.txt")
  65. ts.begin()
  66. print(ts)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement