[Python] Testing almost a palindrome

Discussão em 'Python' iniciado por Stack, Março 13, 2025.

  1. Stack

    Stack Membro Participativo

    I'm studying Python at the university and our task was to check if a current string is almost a palindrome.


    A string that almost a palindrome is a string that if you delete one char from it, no matter which and only one char,you can read the string in the same way from left to right or right to left; for example: abba, aa and aba.
    ​

    When I submit my code, there is an automatic system that checks your algorithm and the system tells that there are some problems with my algorithm and I can't find where the problems are.

    This is the code of my function:

    def question3(str):#define function with input string
    i=0#define counter which will run through the whole string from the begining
    j=0#define counter which will run through the whole string without the char we deleted from the begining of the string
    k=0#define counter which will run through the string without the deleted char from the end of the string
    answer=False #define answer

    while i<len(str):#run a loop through the string
    k=len(str)-1
    while j<len(str):# run a loop through the string without the deleted char
    if i==j:# if j is in the place of the deleted chart,j skip to the next char
    j=j+1
    continue
    if k==i:# if k is in the place of the deleted chart,k skip to the next char
    k=k-1
    continue

    if str[j]==str[k]:#check if the chart in the j's place equal to the char in the k's place
    answer=True

    else:
    answer=False#if the answer is false,we don't need to check the rest of the string because it's already not almost a polyndrom
    break#exit the inner loop

    j=j+1#j moves to the next chart
    k=k-1# k moves to the next chart
    if answer==True:# if we found that the string is almost a polyndrom without a specific char,
    #we don't need to check the rest of the string without the rest of the chars and we can exit the outer loop
    break# exit the loop
    i=i+1# move to the next chart
    j=0#nullify the counter that runs through the whole string from the beginning without a specific char

    print(answer)
    return;

    Continue reading...

Compartilhe esta Página