ould be the elements 42, 13 and 5. Before starting to write code for this function, you should consult the parable of "Shlemiel the painter" and think how this seemingly silly tale from a simpler time relates to today's computational problems performed on lists, strings and other sequences. This problem will be the fi
Count dominators
def count_dominators(items):An element of items is said to be a dominator if every element to its right (not just the one element that is immediately to its right) is strictly smaller than it. By this definition, the last item of the list is automatically a dominator. This function should count how many elements in items are dominators, and return that count. For example, dominators of [42, 7, 12, 9, 13, 5] would be the elements 42, 13 and 5.
Before starting to write code for this function, you should consult the parable of "Shlemiel the painter" and think how this seemingly silly tale from a simpler time relates to today's computational problems performed on lists, strings and other sequences. This problem will be the first of many that you will encounter during and after this course to illustrate the important principle of using only one loop to achieve in a tiny fraction of time the same end result that Shlemiel achieves with two nested loops. Your workload therefore increases only linearly with respect to the number of items, whereas the total time of Shlemiel’s back-and-forth grows quadratically, that is, as a function of the square of the number of items.
items |
Expected result |
[42, 7, 12, 9, 2, 5]
|
4 |
[] |
0 |
[99] |
1 |
[42, 42, 42, 42]
|
1 |
range(10**7)
|
1 |
range(10**7, 0, -1)
|
10000000 |
Trying to hide the inner loop of some Shlemiel
Step by step
Solved in 2 steps with 1 images