On Mon, Sep 27, 2010 at 11:43 AM, Brian Jones <bkjo...@gmail.com> wrote:
> > > On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller <t...@lashni.net> wrote: > >> I've got a small function that I'm using to check whether a password is of >> a certain length and contains mixed case, numbers and punctuation. >> >> Originally I was using multiple "if re.search" for the patterns but it >> looked terrible so I've read up on list comprehensions and it's slightly >> improved. I just can't escape the feeling that there's a more elegant way to >> do this that I'm missing. >> >> I've been looking through all the python stuff that I thought might be >> relevant (lambda, map, filter, set, frozenset, etc) but nothing has come >> together. Just wondering if anyone has suggested reading material for >> alternate ways they'd handle this code. >> >> CODE: >> >> from string import ascii_lowercase, ascii_uppercase, digits, punctuation >> >> >> def complex_password(password): >> """Checks password for sufficient complexity.""" >> if len(password) < 12: >> return False >> if len([c for c in password if c in punctuation]) == 0: >> return False >> if len([c for c in password if c in digits]) == 0: >> return False >> if len([c for c in password if c in ascii_uppercase]) == 0: >> return False >> if len([c for c in password if c in ascii_lowercase]) == 0: >> return False >> return True >> > How about this: d = [digits, punctuation, ascii_uppercase, ascii_lowercase] s = 'asdf1234A' for c in d: if not [x for x in s if x in c]: print x, ' not in ', c Just a quick hack, but you get the idea. It breaks when you want different numbers of characters from the different lists in the password. > > > You can probably make other optimizations, but just to start, you can get > rid of 'len' and '== 0': > > if not [c for c in password if c in ascii_lowercase]: > return False > > will return False if there are no lowercase characters. An empty list > evaluates to False. With that in mind, you could just 'return [c for c in > password if c in ascii_lowercase]' if the calling code is written to handle > it. > > > > >> _______________________________________________ >> Tutor maillist - Tutor@python.org >> To unsubscribe or change subscription options: >> http://mail.python.org/mailman/listinfo/tutor >> > > > > -- > Brian K. Jones > My Blog http://www.protocolostomy.com > Follow me http://twitter.com/bkjones > -- Brian K. Jones My Blog http://www.protocolostomy.com Follow me http://twitter.com/bkjones
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor