We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
That is a significant improvement for most cases. But you can do better by having a list of checks to perform and removing checks from the list as soon they ever pass. That way you are only ever worrying about checks that still need to be done and not endlessly testing whether some checks have or have not passed yet.
And you're still checking isdigit() for a character even if isalpha() returned true for that character, and so on.
names=['isalnum','isalpha','isdigit','islower','isupper']# The only tests we actually need to applytests={'isdigit':str.isdigit,'islower':str.islower,'isupper':str.isupper}results={k:Falseforkinnames}s=input()forcins:#Iteratejustonceoverthestringforname,testinlist(tests.items()):iftest(c):results[name]=Truedeltests[name]#Noneedtoapplyasuccessfultesteveragaincontinue#Jumptonextcharacter-testsaremutuallyexclusiveifnottests:#Allthetestssucceeded,noneedtocontinuebreak# Two tests can be determined from the result of other testsresults['isalpha']=results['islower']orresults['isupper']results['isalnum']=results['isdigit']orresults['isalpha']# Now print the results in the order asked forfornameinnames:print(results[name])
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
String Validators
You are viewing a single comment's thread. Return to all comments →
That is a significant improvement for most cases. But you can do better by having a list of checks to perform and removing checks from the list as soon they ever pass. That way you are only ever worrying about checks that still need to be done and not endlessly testing whether some checks have or have not passed yet.
And you're still checking isdigit() for a character even if isalpha() returned true for that character, and so on.