Skip to content

Instantly share code, notes, and snippets.

@pepasflo
Created February 21, 2019 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pepasflo/1ad8ef5c173db64d43e13e07fd4fccfd to your computer and use it in GitHub Desktop.
Save pepasflo/1ad8ef5c173db64d43e13e07fd4fccfd to your computer and use it in GitHub Desktop.
Is any permutation of a string a palindrome?
#!/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