Home > database >  similar code logic, two different answers
similar code logic, two different answers

Time:02-24

why does the output of these two functions give different outputs when the logic or idea is the same and they are working with the same string?

def solution(inputString):
    a = ""
    b = a[::-1]
    if a == b:
        return True
    else:
        return False



print(solution("az"))

def ans(something):
    if something == reversed(something):
        print(True)
    else:
        print(False)
ans('az')

CodePudding user response:

This is I think because you are not using your inputString parameter in the function solution(). This may be closer to what you want:

def solution(inputString):
    a = inputString
    b = a[::-1]
    if a == b:
        return True
    else:
        return False

CodePudding user response:

when the logic or idea is the same

No, the solution and ans functions have different logic.


solution uses the common way of reversing a string, thats fine


However, the second function uses reversed() function, which does:

reversed(seq)

Return a reverse iterator. seq must be an object which has a __reversed__() method or supports the sequence protocol ...

It does not return the reversed string as you'd probably expected.

To put that in perspective, the following code returns False:

print("oof" == reversed("foo"))

Because the return value of reversed("foo") is an <reversed object> and not the reversed String.

  • Related