Search code examples
pythonpython-2.7palindrome

Python Palindrome error


This is my solution to the problem: whether given string can be permuted to form a palindrome or not . I get correct for very few text cases. For the given case it prints YES even though it should print NO

string = "cdefghmnopqrstuvw"

found = False

count = 0
for i in string:
if string.count('i') % 2 == 0:
    found = True
else:
    count += 1

if count > 1:
    found = False

if not found:
    print("NO")
else:
    print("YES")

Solution

  • A string can be permuted to a palindrome, if when it has even length, it has only even number of occurrences for its letters, or if when has odd length, all letters but one has even number of occurrences. So the following will work:

    from collections import Counter
    def can_be_palindrome(s):
        return sum(v % 2 for v in Counter(s).values()) == len(s) % 2
    

    With the sum we count the number of letters with odd number of occurrences. len(s) % 2 will have value 0 if s has even length and 1 if it has odd length.

    Examples:

    >>> can_be_palindrome("aab")
    True
    >>> can_be_palindrome("abbb")
    False
    >>> can_be_palindrome("abcabc")
    True