Update xkcd_password.py
authorRahul Goswami <redacted>
Wed, 28 Feb 2018 20:14:26 +0000 (20:14 +0000)
committerGitHub <redacted>
Wed, 28 Feb 2018 20:14:26 +0000 (20:14 +0000)
Replaced unnecessary try-except blocks with if-else statements and some other changes.

xkcdpass/xkcd_password.py

index aee83194280a586cc0c0d6e31d69c1263106c5f7..193bf5231558fac6c8401b1649a3c4a3e61772e4 100755 (executable)
@@ -134,7 +134,7 @@ def generate_wordlist(wordfile=None,
             if regexp.match(thisword) is not None:
                 words.add(thisword)
 
-    return list(words)  # deduplicate, just in case
+    return list(words)
 
 
 def wordlist_to_worddict(wordlist):
@@ -147,11 +147,10 @@ def wordlist_to_worddict(wordlist):
 
     # Maybe should be a defaultdict, but this reduces dependencies
     for word in wordlist:
-        try:
-            worddict[word[0]].append(word)
-        except KeyError:
-            worddict[word[0]] = [word, ]
-
+        if word[0] not in worddict:
+            worddict[word[0]] = []
+        worddict[word[0]].append(word)
+        
     return worddict
 
 
@@ -191,9 +190,9 @@ def find_acrostic(acrostic, worddict):
     words = []
 
     for letter in acrostic:
-        try:
+        if letter in worddict:                        #  better than try catch blocks
             words.append(rng().choice(worddict[letter]))
-        except KeyError:
+        else:
             sys.stderr.write("No words found starting with " + letter + "\n")
             sys.exit(1)
     return words
@@ -203,8 +202,12 @@ def choose_words(wordlist, numwords):
     """
     Choose numwords randomly from wordlist
     """
-
-    return [rng().choice(wordlist) for i in xrange(numwords)]
+    assert len(wordlist) > 0
+   
+    if len(wordlist) >= numwords:
+        return rng().sample(wordlist, numwords)  # ensures no duplicates
+    else:
+      return rng().choices(wordlist, numwords)  # allows duplicates if wordlist is small
 
 
 def try_input(prompt, validate):
git clone https://git.99rst.org/PROJECT