[Python] Is there a difference in the order of conditions in a python if statement?

Discussão em 'Python' iniciado por Stack, Janeiro 18, 2025.

  1. Stack

    Stack Membro Participativo

    Let's take the Leetcode problem, "first letter to appear twice" (https://leetcode.com/problems/first-letter-to-appear-twice/). The general solution that I came up with was to iterate over the string, store the values in a "seen" list, and if the next value is already in the "seen" list, then return that value.

    So if I have some code that goes like this:

    class Solution:
    def repeatedCharacter(self, s: str) -> str:
    seen = []
    for i in s:
    if i in seen:
    return i
    else:
    seen.append(i)



    Is it any different (in terms of time or memory) to this:

    class Solution:
    def repeatedCharacter(self, s: str) -> str:
    seen = []
    for i in s:
    if i not in seen:
    seen.append(i)
    else:
    return i



    Is one way actually better/more efficient than the other, or is this just a preference of typing?

    Continue reading...

Compartilhe esta Página