The question is as follows: " Create a password by combining 4 words from the 3 lists above. Print the password" In this question combining means concatenating the words together. My code is printed below but I'm curious as to how it may be optimized. I'm sure I don't need to make the password a list. Feel free to include any other optimizations I could make. Thanks!
import itertools
import random
nouns =[A large list of strings]
verbs = [A large list of strings]
adjs = [A large list of strings]
# Make a four word password by combining words from the list of nouns, verbs and adjs
options = list(itertools.chain(nouns, verbs, adjs))
password = []
for _ in range (4):
password.append(options[random.randint(0,len(options)-1)])
password = "".join(password)
print(password)
There seems to be nothing in your specs that discriminates between the parts of speech. Therefore, you have only one word list for password purposes.
word_list = nouns + verbs + adjs
Now you simply need to grab four random items from the list. You should review the random
documentation again. sample
and shuffle
are useful here. Either can grab 4 items for you.
pass_words = random.sample(word_list, 4)
or
random.shuffle(word_list)
pass_words = word_list[:4]
Finally, simply concatenate the chosen words:
password = ''.join(pass_words)
You can use simple addition to combine the lists:
options = nouns + verbs + adjs
And you can use random.choice()
to select random items from the list:
for _ in range (4):
password.append(random.choice(options))
Few one liners.
Option -1 :
print("".join(random.choice(nouns + verbs + adjs) for _ in range(4)))
Option -2 :
print("".join(random.sample(nouns + verbs + adjs, 4)))
Option-3 (if you want at least one entry from verb, noun and adj) :
print("".join(random.sample([random.choice(nouns),random.choice(verbs),random.choice(adjs),random.choice(nouns + verbs + adjs)], 4)))
There are many such one liners with bit difference in performance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.