老师又布置了一道题,生成随机密码,就是要从一个生成随机密码的模块中获取密码,随机密码是 2,3 或者 4 位的,就是说有时是 length 是 2,有时 3,有时 4,随机。。。
我现在需要随机输入一个数字比如 10,代表 10 位密码,然后从模块中得到这些密码,要求用到 def。 我的思路是,定义一个函数,先获取一个随机密码 i,然后如果我输入的 n 大于这个随机密码长度,那就在原来基础上在获取一个随机密码,直到 i 的长度等于我输入的值的大小, def easy_password(n): int(n)>1 i = get_random_text() while len(i)<int(n): i = i+get_random_text() if len(i) == n: return i
print(easy_password(5))
但是,这样有个很大问题,经常会出现 None。。。比如我想 n=5,如果第一次 i=3,再获取一次 i 的时候,i 有可能等于 6 或者 7,这样就直接 None 了。。。 我也不知道我思路对不对,求大家给点提示或者思路。。。
我想如何能在出现 None 时重新获取密码,直到 len ( i )== n 再 return ? 或者有没有更好的办法?
技术大拿来救救我吧,想了一天了。 原题如下。
Exercise 3. Random passwords are safe but it is hard to remember them. Your task will be to write a function which will generate an easy to remember random 1 password. Such password will consist of short fragments of text which are easy to pronounce. Function to sample such fragments is in file fragments.py (download it from ILIAS) and is called get_random_text. The function can return fragments only of length 2, 3, or 4. An example usage of this function looks like this: from fragments import get_random_text i = 0 while i < 3: print( ' Random text: ' + get_random_text()) i += 1
file, not the fragments.py). The function should accept one integer parameter length (assume that length > 1) and generate a password with exactly length characters. An example usage of this function: • easy_password(10) can return ’getbacuson’ • easy_password(10) can return ’piaftromer’ • easy_password(15) can return ’spresedparmonset’ • easy_password(2) can return ’en’ Remember, that the password has to be built from full fragments given by get_random_text .
fragments.py 如下,
from random import choice
txts = """tive la lo ies li tain to ti ly get de mon fac day tri tro dif eve mo dis el set tem ten ed num sion sen ter es er est sub for ry per re pen ra ble rec ro ri ings be lec ba men ple mer ket ern on of ty ob tle ture op ci co ence pos son cy en cu pr tor pa fer pi po pres gen ward ers car der up cal ber tion my pre ac ad af vi pro it an ap as ar im in tal ic ing ni par min na ny mis out nu mar ness fa ties lar man sy land no so daq""".split()
def get_random_text(): return choice(txts)