Function Basic Practice Question8

Screen Link:
https://app.dataquest.io/m/1012/python-fundamentals-practice-problems/8/palindrome

My Code:

def is_palindrome(dna):
    n = len(dna)
    for i in range(n):
        if dna[i] != dna[:: -1]:
            return False
    return True

print(is_palindrome(input_1))
print(is_palindrome(input_2))
print(is_palindrome(input_3))

What I expected to happen:
I am expecting the input_1 to be True. But it is false.

What actually happened:

"Your function returned an incorrect answer. Input: ['ATTA'] Your answer: False Expected answer: True"

I am confused about this part of the answer, is there anyone can explain why the range is (n//2)?
what does “dna[n -i -1]” means? why i can not use “dna[::-1]” to pick the last one in the list?


for i in range(n // 2):
if dna[i] != dna[n - i - 1]:

Thanks!

dna[:: -1] #this reverse the string
dna[n - i - 1] #this subtract the length(n) by integer(i) minus 1
if dna[i] != dna[n - i - 1]: #this compare this 2 statements execute if is different (dna[i] slice the string)

1 Like

Hello @jinyushan1990

Here is a bug, you are checking if letter in index i is not equal to dna[::-11]

POINT TO NOTE: dna[::-1] is the reverse of the intire parameter dna.


The approach that is used is to check if the entire dna is equal to the dna reversed dna[::-1', check my function below.

def is_palindrome(dna):
    return dna == dna[::-1]

If you want to pick the last element in a list/string use dna[-1]

Thanks for explaining it! @andreycarvalho.
I just want to follow up with one missing question. Dataquest offered below code as the standard answer:

def is_palindrome(dna):
n = len(dna)
for i in range(n//2):
if dna[i] != dna[n -i -1]:
return False
return True

print(is_palindrome(input_1))
print(is_palindrome(input_2))
print(is_palindrome(input_3))

Why the range is n//2 instead of n?

1 Like

sorry @info.victoromondi
I definitely get you confused about my question, what I am trying to understand is the following part in the standard answer offered by Dataquest:

for I in range(n//2):
if dna[i] = dna[n -i -1]:

Can you give me a more detailed explanation about why the range is (n//2) instead of n?
why we are using dna[n -i -1] instead of dna[-1]?

Thanks

1 Like

I stuck on this problem too. Now I get it by actually breaking down the logic on a piece of paper.
Why using dna[n -i -1] instead of dna[-1]? Because dna[-1] gets you only the last element while dna[n -i -1] picks for you any of the last elements…

Why the range is (n//2) instead of n? Well, it would still work with range(n). You get the result faster with fewer steps doing it halfway using range(n // 2).

2 Likes

Can anyone help, what i am doing wrong here, as i am trying to solve the exercise with the below logic but don`t know where i failed

def is_palindrome(dna):
    for i in range(len(dna)):
        if dna[i] == dna[-i-1]:
            return True
   
    return False

Meanwhile when i used the below code, it worked

def is_palindrome(dna):
    for i in range(len(dna)):
        if dna[i] != dna[-i-1]:
            return False

    return True

Hi @karimyousrymohamedom,

def is_palindrome(dna):
    for i in range(len(dna)):
        if dna[i] == dna[-i-1]:
            return True
   
    return False

In the above case, the function returns True if the first and last character is the same. It won’t wait till the for loop checks all characters. Because of that, it will return True for all the inputs.

def is_palindrome(dna):
    for i in range(len(dna)):
        if dna[i] != dna[-i-1]:
            return False

    return True

On the other hand, the above code will only return False if the characters in comparison are not equal. If they are equal, it will patiently wait until all characters are checked and then return True.

Best,
Sahil

4 Likes

Hi,

Still nobody answer the question why double slash font in " for i in range(n // 2): " in dataquest answer… :frowning:

Below full code:

def is_palindrome(dna):
    n = len(dna)
    for i in range(n // 2):  **#what's that? those slashes ?** 
        if dna[i] != dna[n - i - 1]:
            return False
    return True

“//” is used in python to get only the quotient part without the fraction or remainder from a division operation, I hope you’ve got it now.
As in, 7 // 2 will give you the result = 3.
@ drill_n_bass Drill N Bass

2 Likes

Hi @andreycarvalho ,
in the second line, you said subtract the length (n) by integer(i), how come this i is an integer? it isn’t a string??
Thanks

Hi @samantha, it looks like it’s been a while since Andrey has been around so I thought I’d try to help you out with your question.

If we look at where i is instantiated/defined, it comes from this block of code:

for i in range(n):

which means i will be an integer for each pass in the loop, increasing by 1 each time.

Does that make sense?

Hi @Sahil, why is this the case?

Why does the first program not “patiently wait until all characters are checked and then return True”? I thought “for loops” are used for the very purpose of going through each iteration before providing a result.

Furthermore, why does the second program “patiently wait until all characters are checked and then return True”. I’m not understanding the difference and the reasoning.

The focus is on the phrase before that -

The second program has an if condition which is checking if the characters don’t match.

So, if they are equal, then the loop will keep iterating till they are not the same.

For example, take a random word lool.

In the first iteration, the if condition checks if l is not equal to l. Are they not equal? No. So, the loop continues.

In the second iteration, the if condition checks if o is not equal to o. Are they not equal? No. So, the loop continues.

Consider the example word lawl (I am literally making words up just to explain this, so ignore the randomness :sweat_smile:)

The first program will check if the first and last characters are equal on the first iteration. That is it will check if l and l are equal. They are. The if condition is True and the code returns a True. Even though we can see that a and w are not the same, the function still says the word is a palindrome.

The second program ensures that we if the word is actually a palindrome, we iterate through all the characters to confirm that. The first one stops as soon as any two characters will match and that is not desirable.

Thanks @the_doctor . It’s still confusing to me, but I think it’s one of those things where I will just move on and hopefully it will show up in another situation and turn a light bulb on in my head. I appreciate the explanation!