Created
February 21, 2019 21:06
-
-
Save pepasflo/1ad8ef5c173db64d43e13e07fd4fccfd to your computer and use it in GitHub Desktop.
Is any permutation of a string a palindrome?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
def is_odd(x): | |
return x % 2 == 1 | |
# is any permutation of a string a palindrome? | |
def anypalin(string): | |
charcounts = {} | |
for ch in string: | |
if ch in charcounts: | |
charcounts[ch] += 1 | |
else: | |
charcounts[ch] = 1 | |
odds = 0 | |
for (k,v) in charcounts.iteritems(): | |
if is_odd(v): | |
odds += 1 | |
if odds > 1: | |
return False | |
return odds < 2 | |
def test(): | |
cases = { | |
"civic": True, | |
"cciiv": True, | |
"civil": False, | |
"ciivl": False | |
} | |
for (k,v) in cases.iteritems(): | |
if anypalin(k) != v: | |
print "Failed: expected %s to be %s" % (k,v) | |
sys.exit(1) | |
print "all tests passed" | |
if __name__ == "__main__": | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment