有关回文序列的Python代码

时间:2019-06-13 08:17:32

标签: python-3.x

有一个回文序列。现在,恰好一对随机选择的字母相互交换。如果可能的话,编写一个python程序来确定字母的原始回文序列。 def get_original_palindrome(edited_sequence):

1 个答案:

答案 0 :(得分:-1)

def get_misplaced_indexes(w):
    misplaced_indexes = []
    for i in range(len(w)//2):
        if w[i] != w[len(w)-1-i]:
            misplaced_indexes.append(i)
    if len(misplaced_indexes) == 1:
        misplaced_indexes.append(len(w)//2)
    return misplaced_indexes

def get_one_of_original_palindrome(misplaced_indexes, w):
    ans = ""
    index1, index2 = misplaced_indexes
    for i in range(len(w)):
        if i == index1:
            ans += w[index2]
        elif i == index2:
            ans += w[index1]
        else:
            ans += w[i]
    return ans

def get_original_palindrome(w):
    if w == w[::-1]:
        return(w)
    else:
        misplaced_indexes = get_misplaced_indexes(w)
        return get_one_of_original_palindrome(misplaced_indexes, w)


print(get_original_palindrome("radar"))
print(get_original_palindrome("ardar"))
print(get_original_palindrome("rdaar"))
print(get_original_palindrome("helelh"))