Question: https://codility.com/demo/take-sample-test/longest_password/
Question Name: Longest-Password or LongestPassword
The solution could be more Pythonic with some additional space.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | def solution(S): longest = -1 num_of_letters = 0 num_of_digits = 0 num_of_others = 0 for letter in S: if letter.isalpha(): num_of_letters += 1 elif letter.isdigit(): num_of_digits += 1 elif letter == " ": # Check whether it's a valid password. if num_of_others == 0 and \ num_of_letters % 2 == 0 and \ num_of_digits % 2 == 1: if longest < num_of_letters + num_of_digits: longest = num_of_letters + num_of_digits # Reset the counters for the next word. num_of_letters = 0 num_of_digits = 0 num_of_others = 0 else: num_of_others += 1 # Check whether the last word is a valid password. if num_of_others == 0 and \ num_of_letters % 2 == 0 and \ num_of_digits % 2 == 1: if longest < num_of_letters + num_of_digits: longest = num_of_letters + num_of_digits return longest |
The extra code on checking the last possible word could be avoided if you don’t mind an infinite loop wrapper ^_^
All in one line? Zen of Python or Evil of Python? 🙂
Also did Scala, take quite some time and didn’t find an one line solution…
My C++ solution.
My c# solution: