Last active
August 29, 2015 14:24
-
-
Save pogorelov-ss/9b25007149f9ca0d82d7 to your computer and use it in GitHub Desktop.
rearrange the letters so that they become palindromes
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
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