December 2023
Intermediate to advanced
504 pages
11h 43m
English
What follows is another implementation of the has_duplicate_value function that doesn’t rely on nested loops. It’s a bit clever, so let’s first look at how it works and then we’ll see if it’s any more efficient than our first implementation.
| | def has_duplicate_value(array): |
| | existing_numbers = [0] * 11 |
| | |
| | for i in range(len(array)): |
| | if existing_numbers[array[i]] == 1: |
| | return True |
| | else: |
| | existing_numbers[array[i]] = 1 |
| | |
| | return False |
Here’s what this function does. It creates an array called existing_numbers, which starts out as an array containing eleven zeroes. We’re ensuring that our array has at least eleven slots so we can keep track of the eleven possible ratings users can leave (0 to 10).
Then ...
Read now
Unlock full access