2

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')
fusion_97
  • 31
  • 2
  • 2
    It seems your second function is _printing_ `True`, while the first function is _returning_ it as a value. If you want both to do the same thing, make the second return True instead of printing it. EDIT : Also your first function doesn't even use its input... – Mateo Vial Feb 23 '22 at 17:03
  • On both functions, you can replace the `if` by just returning the value of your statement: `return something == reversed(something)` – 0stone0 Feb 23 '22 at 17:05
  • `reversed` is a type, so `something == reversed(something)` will never be true when `something` is a `str` value. – chepner Feb 23 '22 at 17:06
  • 3
    Maybe because `solution` ignores its input parameter? – Scott Hunter Feb 23 '22 at 17:06

2 Answers2

0

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
Raed Ali
  • 549
  • 1
  • 6
  • 22
0

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.

0stone0
  • 34,288
  • 4
  • 39
  • 64