i forgot to mention that this section of the course was supposed to introduce while as an alternative to for for iterating. so the use of while isn't really what makes it bad. but this tiny piece of code has plenty of problematic things regardless. including (but probably not limited to):
mutating the list (though i'm not sure about this since i don't know if sort(list) is the same as list.sort())
sorting the list in the first place
the potential IndexError
using tot as the index as well as the total (the logic checks out, but it makes it less readable)
instead of being able to focus on learning how while works, my friend was stuck trying to figure out the reasoning behind the stuff in the example (was confused by tot being used as an index, the list being sorted, and stuff about functions). in the end, i just gave an example of my own (exactly the same as the one in the comment by cant-find-username)
If this is the most egregious thing you or your friend or whoever encounter in the real world, count your blessings. This is trivial to the things "rockstar" devs were doing 25 years ago.
In what world is sorting the array and then iterating over it just to find the count of elements whose value is < 20 is fine? If it was a binary search kinda thing, makes sense. But not for this at all.
Just a simple while loop will do it faster and is more understandable.
count = 0
while i < len(arr):
if arr[i] < 20:
count += 1
return count
Don’t materialize to a list just to get the Count – this will cause unnecessary allocations. Use the Count() method instead. Which also has an overload taking a predicate. So your code could be simplified to: return numbers.Count(x => x < 20);
Python has generator expressions (and list comprehensions, set comprehensions, and dictionary comprehensions - but those are just fancy ways of turning a generator expression into a collection). Generators in Python are lazy, much like the intermediate IEnumerables in LINQ code. The equivalent Python code to your LINQ example would be
return len([x for x in numbers if x < 20])
But I might write it as
return sum(1 for x in numbers if x < 20)
to avoid the memory overhead of building a new list. That would be like taking the .ToList() out of your LINQ code and calling .Count() on the IEnumerable directly.
TypeError: object of type 'generator' has no len()
Since they're evaluated lazily, you must consume the entire generator to know how long it is. It could even be infinite, in which case that sum call would never return. Python could make len(generator) consume the entire generator, but that would be expensive and probably confusing. For everything else, len is constant time and non-destructive (well, you can implement your own __len__ magic method that does whatever you'd like, but that's outside the scope of the design of the standard library).
def count_below_20(some_list):
return len(list(filter(lambda x: x < 20, some_list)))
Calling filter returns a generator, so we have to pour its contents back into a list in order to get the length. Of course, while this looks really slick, we wouldn't have to produce a generator or a new list object to do this if we just used a simple loop and conditional:
def count_below_20(some_list):
count = 0
for x in some_list:
if x < 20:
count += 1
return count
You can't call len(...) on a generator, I just tried it.
>>> a=[1,34,12,124,30,2,11]
>>> len(x for x in a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>TypeError:
object of type 'generator' has no len()
>>> sum(1 for x in a if x < 20)
4
>>> len([x for x in a if x < 20])
4
If the goal is introducing certain learning concepts, then it would be fine.
We have no context. We don’t know what the clues or instructions are. We only see this piece of code. It’s always best to not jump to conclusions, and to assume the best in others until proven otherwise.
This is true in just about every aspect of life, and is worth practicing to reduce stress.
Question about the sort() call: does this language pass by value or by reference? Which is to say, does this method mutate that array? If so, then this code has gone from just "not good" to "actively harmful".
list.sort() modifies the list, but since this sort() is a function call and not a method call, there'd have to be some function sort defined elsewhere.
You could bind sort = list.sort, but that method doesn't just modify the list in place—it returns None, which means this code wouldn't work.
technically, it could be an in-place modification that return selfs at the end, but that would be probably more redundant than even the authors of this code would prefer.
The default list type won't do that. You could subclass it and override its sort method to return self, but I seriously doubt anyone writing code this bad has the computer science chops to write a fluent API.
Technically, a member function like sort in Python is just a function that takes the object as its first parameter (i.e. the parameter that's usually labeled self in the function implementation). So I believe that sort(x) is actually the exact same thing as x.sort() if x is a list. But yeah, it would still return None.
Did you even try that in an interpreter before you posted this? That's not how it works.
If you have a list named x, then x.sort() is equivalent to list.sort(x) because it needs to know what class (either via the class itself or an object instantiated thereof) the method belongs to, otherwise it's just going to search the local or global scope for a function called sort.
There is no passing by value or by reference in python. It always uses a different kind of argument passing that you can call "by label", which is based on a concept of immutable (mostly scalars, also strings) and mutable (most other variables, including containers) types.
You can sort of say (there are probably corner cases that I'm not thinking about right now) that immutable ones are being passed by value, and mutable by pointer.
Forgive my dated terminology. The mutability is the issue here. There's no good reason to mutate that parameter when the function can do what it's supposed to without doing so. Tbh I might be being a bit zealous with my functional paradigm but I feel like there's rarely if ever a reason to mutate your parameters rather than returning a different object.
The reason so many sorting implementations mutate is because destructive sort can be implemented way faster than non-destructive sort can be. Python does also offer a way to sort non-destructively with the sorted() function though.
No. sort(iterable) doesn't exist, and sorted doesn't mutate its input list whereas list.sort does
>>> l = [3, 1, 2]
>>> sorted(l)
[1, 2, 3]
>>> sort(l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'sort' is not defined. Did you mean: 'sorted'?
>>> l
[3, 1, 2]
>>> l.sort()
>>> l
[1, 2, 3]
>>>
It doesn't pass by reference or value, because python is weird. No, it won't mutate the list. I don't know how to explain it but what python does is very close to passing by value
If there is one number in the list, and that number is 1. It would look at the first number 1 and then try to do the next number but find there isn't one and throw an out of bounds.
Even if you're not writing with performance in mind, this shouldn't be the output of a competent programmer. What's the point of sorting it? As i said in my other comment, even my friend who isn't a programmer was questioning the sorting step.
Even from a teaching perspective, this example is atrocious. If you only want to teach one simple thing, you don't unnecessarily make your example difficult for beginners to understand (see my other comment about tot). You also don't throw in a bunch of unrelated things in the example, and if you do, you sure as shit better make sure what you throw in there isn't garbage
It wouldn't work without the sort. The whole point of that loop is that the array is sorted, so that the loop will exit the first time it finds a number over twenty.
I think it's pretty obvious that i and pretty much everyone else here understands how the function works. What i meant was why do this in a way that requires the sort at all?
edit: because apparently, people don't get it. according to waldo667, the sorting is there because without it, the logic in the loop won't work as intended. and that's the point. the loop logic shouldn't be that way when a more straightforward alternative that doesn't require sorting (and is easier for beginners to understand) can be written instead. so again, why sort?
Because it’s a teaching code? If you don’t do it right you learn the pitfalls of a while loop.
and? this example was to demonstrate how to use a while loop, not how it can go wrong. if it was for the latter, then it would have been intentionally bad and i wouldn't have posted it here.
and even if it was to show the gotchas of while loops, that still doesn't explain/justify the convoluted sort-before-counting process (nor the other issues i mentioned in one of my other comments).
Also, we only have the code and not the context.
since you already know the example was for while loops, i'm assuming you already read my other comment giving the context. what additional context do you think would make this not a bad example?
i realize that this example isn't the worst piece of code out there, but i did not expect this many people attempt to defend code that seems to me is clearly bad inside and outside of the context of teaching.
Because in the best case your function takes no time.
If you get a sorted list and there are no numbers below 20, it returns almost instantly. With a naive solution, you still spend time checking each index even if you know the array is sorted and contains no numbers less than 20.
It’s just one way to solve the problem. Honestly, you’re just doing yourself a disservice but spending so much time and frustration on such a trivial thing.
I think the example is missing the context it was used in. It is such a strange example when just taken on its own that there must have been stuff surrounding it that made it make sense.
Bro has no Ideer about didactic(the way to teach), teaching code is not supposed to be the most compact and fastest running code! Someone who never coded before will learn here that python has a sort Funktion and you can use it inside of Funktions, also they will learn that you can use a while loop to run over an array. You could easily enumerate, but there would be no learning done, can you all stop shitting about teaching code!
teaching code is not supposed to be the most compact and fastest running code!
You realize what makes this code bad isn't only that it isn't compact/fast, right?
will learn here that python has a sort Funktion and you can use it inside of Funktions
Because they can't have a separate lesson on functions? They have to learn about it in passing in the lesson for while loops. Gotcha. You do realize it would be very simple to come up with an example that show functions along with while loops that doesn't include bad code as well, right?
also they will learn that you can use a while loop to run over an array
Yeah, they'll learn how to write a while loop that causes errors. They'll also learn that attempting to write clever code (that isn't really even clever, but in fact worse) is more important than readability.
The final scan is linear, so it's about the sorting, which depending on the algorithm is nlogn as the worst case (and for all good algorithms nlogn in the average case), unless I'm missing something?
70
u/tills1993 Feb 26 '23
Honestly depending on how basic the course is at this stage this might be fine.
Maybe they haven't gone over for or list comprehensions yet.
389
u/Plumeh Feb 26 '23
who needs linear time anyways
163
u/reverendsteveii Feb 26 '23
Question about the sort() call: does this language pass by value or by reference? Which is to say, does this method mutate that array? If so, then this code has gone from just "not good" to "actively harmful".
56
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Feb 26 '23
Image Transcription: Code
I'm a human volunteer content transcriber and you could be too! If you'd like more information on what we do and why we do it, click here!
6
u/dankwormhole Feb 26 '23
R is vectorized
5
u/TallBoyPirateSqaud Feb 27 '23
Don’t use this language but wouldn’t this code infinitely loop in the scenario all numbers in the array where under 20?
4
u/CaitaXD Feb 26 '23
I challenge you to make a nn log n version of this
3
u/[deleted] Feb 27 '23
Huh? Why sort the numbers?
2
u/sainishwanth Feb 27 '23
Idk seems like a normal program to teach the usage of a while loop?
It's likely beginner course so makes sense to write verbose code.
2
u/JudgeFed Feb 27 '23
Sexy
4
u/new_pribor Feb 26 '23 edited Feb 27 '23
Here's how I would do it:
1
u/MkMyBnkAcctGrtAgn Feb 27 '23
Tots dude
1
u/Cybasura Feb 27 '23
Here's the thing, give me a second
I can kinda see what they are doing, since this is python, len() exists
However, im guessing they want to create a size function from scratch which technically works, not the most optimal but it works for beginners
Edit: I just realised they added a hard limiter "<20", WHY THE FUCK
I take back my comment, this is just weird
1
u/Lagger625 Feb 27 '23
When you find out the "if" statement is evil for performance since it trashes the CPU branch predictor
1
u/vtrkukfxxxmfkplnxt Feb 27 '23
; is missing. Am I mistaken?
0
u/[deleted] Feb 26 '23
Just wondering, would dynamic programming be the most efficient solution to this problem?
0
u/[deleted] Feb 26 '23
[deleted] — view deleted comment
0
u/[deleted] Feb 26 '23
[deleted] — view deleted comment
0
u/[deleted] Feb 26 '23
[deleted] — view deleted comment