Python的新手,每天都在研究一个单词生成器。我正在测试IE设置字长的限制,确保它至少有1个大写,小写和数字等。
import random
from string import ascii_uppercase, ascii_lowercase, ascii_letters, digits
pool = ascii_letters + digits
wordLen=random.randint(7,14)
answer = random.sample(pool, wordLen)
while True:
if not any(char.isupper() for char in answer):
answer[random.randrange(len(answer))] = random.choice(ascii_uppercase)
continue
if not any(char.islower() for char in answer):
answer[random.randrange(len(answer))] = random.choice(ascii_lowercase)
continue
if not any(char.isdigit() for char in answer):
answer[random.randrange(len(answer))] = random.choice(digits)
continue
break
answer = ''.join(answer)
我想添加一个进一步的限制 - 确保连续的字符不一样。现在我研究了字符串操作,但根本无法找到我如何应用它。让我向您展示我研究过的字符串比较
if stringx == stringy:
print 'they are the same'
else
print 'they are different'
我得到了实际的比较部分,但我不知道如何再次运行语句再生成另一个字符,忽略它刚才制作的那个字符。任何建议将不胜感激
答案 0 :(得分:1)
要继续使用any()
结构,您需要引入itertools recipe section中给出的成对迭代,然后您可以执行以下操作:
import itertools
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return itertools.izip(a, b)
answer = "abcdeffghik"
if any( first_char == second_char for first_char, second_char in pairwise(answer)):
print "Duplicates exists"