[Tutor] function with multiple checks
Brian Jones
bkjones at gmail.com
Mon Sep 27 17:43:10 CEST 2010
On Mon, Sep 27, 2010 at 11:09 AM, Tim Miller <tim at 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
>
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 at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100927/f45894dc/attachment-0001.html>
More information about the Tutor
mailing list