Promila Ghosh
Promila Ghosh

Reputation: 389

How to determine unique characters in a string

I have a solution in python to find the string having unique characters.

def is_unique_with_ascii(string):
    if len(string) > 128:
        return False
    char_set = [False] * 128

    for char in string:
        val = ord(char)
        if char_set[val]:
            print(char_set[val])
            return False
        char_set[val] = True
    return True

In this code, the char_set has been initialized with false values. But in if statement when the same character that has already in string caught the statement become true means the char_set[val] got true value.My question is in python how to if char_set[val]: statement works to get the same value. Please help me out.

Upvotes: 1

Views: 183

Answers (1)

Abhinav Mathur
Abhinav Mathur

Reputation: 8101

Looking at the documentation for if, it evaluates the condition, which is char_set[val] in this case. Since it already returns a Bool, the if statement evaluates it right away, to give the impression that "if char_set[val] statement works to get the same value"

Upvotes: 2

Related Questions