Skip to content

Instantly share code, notes, and snippets.

@pogorelov-ss
Last active August 29, 2015 14:24
Show Gist options
  • Save pogorelov-ss/9b25007149f9ca0d82d7 to your computer and use it in GitHub Desktop.
Save pogorelov-ss/9b25007149f9ca0d82d7 to your computer and use it in GitHub Desktop.
rearrange the letters so that they become palindromes
words = ['ivcci', 'oyotta', 'cecaaarar', 'bbb', 'babbb']
def compute_palindromes(words):
def is_palindrom(word):
return word == ''.join(reversed(word))
def try_be_palindrom(word):
char_dict = {}
for char in word:
if char_dict.has_key(char):
char_dict[char] += 1
else:
char_dict[char] = 1
odd_count = 0
odd_char = ''
palindrom = ''
for char in char_dict:
if odd_count>1:
return -1
if char_dict[char]%2 != 0:
if char_dict[char]>1:
return -1
odd_count += 1
odd_char = char
else:
while char_dict[char]>0:
palindrom +=char
char_dict[char] -=2
palindrom += odd_char + palindrom[::-1]
return palindrom
for word in words:
if is_palindrom(word):
print word
else:
print try_be_palindrom(word)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment