Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
94 views
in Technique[技术] by (71.8m points)

python - Question about if statement if not thing is specified after it?

I wanted to ask three things. Firstly, for the 10th line, is this an 'else' statement? It doesn't seem to be the case- if it not, what purpose does it serve?

Secondly, for the 8th line, are we saying that if 'val' is in the list char_set, then return False? And generally speaking is this how we would write this?

Lastly, for line 5, what does [False for _ in range(128)] do? Thanks!

 def unique(string):
    if len(string) > 128:
        return False

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

    return True
question from:https://stackoverflow.com/questions/65643877/question-about-if-statement-if-not-thing-is-specified-after-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Let's answer this in chronological order (of code execution):

  • Line 5, [False for _ in range(128)] creates a list of 128 False values. This is list comprehension, which can be rewritten as follows:
char_set = []
for _ in range(128):
    char_set.append(False)

The _ means read the value from the iterator (range object), and discard it.

  • Line 8: val is the ord of a character, meaning a number. char_set[val] gives us the element at index val, which is initialized as False. During your code (line 10, specifically), this might be overwritten to be a True. The if statement here checks if the value in that index is True.
  • Line 10: it's not an else statement, albeit in this case it works the same. In this code, if the condition in line 8 does not meet, then the code execution flow skips like 9 and "falls through" to line 10, and life goes on. If the condition in line 8 meets (i.e. char_set[val] is True), then the line 9 gets executed, and the return statement ends the function call abruptly while returning False as its result.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...