class MaxDigit: def __init__(self, n): self.n = n def execute(self): return int(''.join(sorted(str(self.n), reverse=True)))
- class MaxDigit:
- def __init__(self, n):
- self.n = n
- def execute(self):
return int(''.join((sorted([n for n in str(self.n)], reverse=True))))- return int(''.join(sorted(str(self.n), reverse=True)))
Refactored the code to only pass through the password once while keeping track of the raised flags. In addition, short-circuiting when all flags are raised to skip checking the rest of the password.
Improvments:
- named the flags as "upper", "digit" and "special" for clarity.
- converted PUNCTUATION to a set for O(1) contains checks.
- single pass through the password as opposed to 4.
- converted "all" function call to a simple boolean expression.
- short-circuiting if password is shorter than 8 characters - no need to check it in that case.
- short-circuiting once all conditions are met - no need to keep checking once they do.
import string PUNCTUATION = set(string.punctuation) def test_password(password): # password must be no less than 8 characters long if len(password) < 8: return False upper, digit, special = False, False, False for c in password: # password must have at least 1 capital letter if c.isupper(): upper = True # password must have at least 1 number elif c.isdigit(): digit = True # password must have at least 1 special character elif c in PUNCTUATION: special = True if upper and digit and special: return True return False
- import string
PUNCTUATION = string.punctuation- PUNCTUATION = set(string.punctuation)
- def test_password(password):
- # password must be no less than 8 characters long
c1 = len(password) >= 8# password must have at least 1 capital letterc2 = len([1 for t in password if t == t.upper()]) >= 1# password must have at least 1 numberc3 = len([1 for t in password if t.isdigit()]) >= 1# password must have at least 1 special characterc4 = len([1 for t in password if t in PUNCTUATION]) >= 1- if len(password) < 8:
- return False
- upper, digit, special = False, False, False
- for c in password:
- # password must have at least 1 capital letter
- if c.isupper():
- upper = True
- # password must have at least 1 number
- elif c.isdigit():
- digit = True
- # password must have at least 1 special character
- elif c in PUNCTUATION:
- special = True
- if upper and digit and special:
- return True
# Return True if all conditions are Truereturn all([c1,c2,c3,c4])- return False