0

New to python and working on and on daily studying a word generator. I'm testing restrictions IE set word length, making sure it has at least 1 upper, lowercase and digit in it etc.

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)

I'd like to add a further restriction -- making sure consecutive chars aren't the same. Now I've studied string manipulation but simply can't find out how I can apply it. Let me show you something I've studied about string comparison

if stringx == stringy:
    print 'they are the same'
else
    print 'they are different'

I get the actual comparison part but I don't get how I can make the statements run again to generate another character again, disregarding the one it's just made. Any suggestions would be appreciated

4
  • 3
    stringx == stringx That's always going to be true. You're comparing it to itself. Commented Oct 23, 2015 at 17:43
  • 2
    Try to give step-by-step instructions for a human, then translate it to Python. Commented Oct 23, 2015 at 17:46
  • docs.python.org/2/tutorial/controlflow.html#for-statements Commented Oct 23, 2015 at 17:48
  • @MorganThrapp edited! whoops. meant X and Y. Commented Oct 23, 2015 at 17:52

1 Answer 1

1

To continue with your usage of any() structure you need to introduce a pairwise iterable like given in the itertools recipe section, and then you could do something like:

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.