aj1000
aj1000

Reputation: 23

Python if statement not recognized though conditions appear to be met

I'm trying to add 1 to the count each time there's a new letter and keep track of the doubled letters, but python isn't going into the if statement, despite line 6 showing the conditions for the if statement are met. What am I missing?

def duplicate_count(text):
    count = 0
    doubled_letters = []
    for i in text:
        print (i)
        print(i in doubled_letters)
        if i in doubled_letters == False:
            count += 1
            doubled_letters.append(i)
    print(count)
    print(doubled_letters)
    return count

duplicate_count("abbcdea")

this returns:

a
False
b
False
b
False
c
False
d
False
e
False
a
False
0
[]

Upvotes: 0

Views: 103

Answers (2)

Jay
Jay

Reputation: 24895

I think your logic is also flawed in addition to the incorrect usage of the operator. Looks like you are trying to get a count of duplicated letters, but I don't think your program will be able to do it.

I guess you are expecting something like this:

def duplicate_count(text):
    count = 0
    letters = []
    for i in text:
        if i not in doubled_letters:
            letters.append(i)
        else:
            count += 1

    print(count)
    return count

duplicate_count("abbcdea")

In the above code, I am trying to add every letter to a list and if they are duplicated, I increase the count. Based on this, you should be getting 2 as a and b are duplicated in the input.

Upvotes: 0

chepner
chepner

Reputation: 531165

in is a comparison operator, so it gets chained with ==. Your expression is equivalent to

(i in doubled_letters) and (double_letters == False)

You could "break the chain", so to speak, using explicit parentheses:

if (i in double_letters) == False:

but direct comparisons to Boolean literals are rarely, if ever, necessary. Just write

if i not in double_letters:

(Note that not in is a single, two-word operator, not an application of not to in. The equivalent with in would be not (i in double_letters).)

Upvotes: 7

Related Questions