Congratulations, you managed to write the simplest possible programming problem in a manner that is completely indecipherable by 98% of professional programmers. That's a feat!
It's so weird you lowkey popped off at this guy just because he provided a solution in a different language.
Like, the only reason the python solution at the top of this thread isn't "indecipherable" by more programmers is because Python and numpy are so widely used. Knowing that using the modulo and equality operators on a numpy array returns an array with those operators individually applied to each element and then also knowing that summing trues and falses gives you a count of trues isn't exactly super obvious.
If more people used APL, this guy's solution would be better known it isn't inherently that much less obvious.
I think the snark seeped in because the fact that their comment looked like an advertisement rubbed me the wrong way. You might be right though, that wasn't necessarily fair.
I do think there is a big difference between the python version and the APL snippet above. The operators used in the python version are at least universal, even in pseudo-code. Brackets are indexing. What are we indexing with? The truth value of a modulo two. Doesn't take any real familiarly with numpy to understand what's going on there. Conversely, if I wouldn't have been told the APL line does the same thing, my best guess would have probably been "divide the value in the result from the previous line by the inverse of 2 (bitwise inverse, I guess?) and store that in a variable called data". Or something. It's quite a bit more arcane.
I think the snark seeped in because the fact that their comment looked like an advertisement rubbed me the wrong way.
I mean, it seems really unlikely that this guy is actively advertising a 50 year old programming language, right? I get that not everyone knows of every language but at least take two seconds to check what APL is before assuming it's this guy pushing his own pet project.
The operators used in the python version are at least universal, even in pseudo-code. Brackets are indexing. What are we indexing with? The truth value of a modulo two. Doesn't take any real familiarly with numpy to understand what's going on there
Have you forgotten what the python version is?
(data % 2 == 0).sum()
Brackets aren't used for indexing? They're for changing the order of operations or calling functions/methods. Square brackets are for indexing. I'm not sure that "indexing with a truth value of modulo two" makes as much sense as you think it does because it's complete nonsense. Implicitly understanding that you can call operators on an array and have them be applied to the elements individually and then implicitly understanding that using "sum" on boolean values returns the count of "truths" both require a bit of previous knowledge on the functioning of numpy and duck typing.
And that's my point. You understand the python version because you're used to it. It doesn't make the APL version necessarily worse.
I thought you were talking about the one at the actual top of the thread, which is the square bracket version.
That said, hard disagree on the statement that things like summing booleans resulting in an integer containing the number of truth values is only understandable to people who are used to python or similar languages. That's literally how we teach toddlers to count. Not all previous knowledge is created equal.
Actually, "summing booleans" is exactly what the APL code is doing, it just has a different syntax.
Explanation of the APL Code -->
data -> modulo 2 the whole array -> "flip" the remainder (boolean not : 1->0, 0->1) -> sum the values ("sum the booleans", as you said)
As for the syntax, why don't you prove your claim that Python's syntax is "natural"? Show me a reputable study in which laymen (with no programming knowledge) are able to understand even a page of Python code. If you can do that, then I'll accept your claim.
I'm not sure that "indexing with a truth value of modulo two" makes as much sense as you think it does because it's complete nonsense
You're right there. I don't use python a lot and have never used numpy and wouldn't know what data[data % 2 == 0] does without the comment above the function.
No, but I think linking to a commercial product in the middle of a discussion looks like an advertisement, because so often it is. Had the person above you finished their comment with "You can download a nice proprietary implementation of R here! [link]", I would have probably had the same gut reaction. Again, I'm not actually accusing you of shilling, you probably have nothing to do with Dyalog the company, but I was explaining why my comment came out a tad more snarky than might have been merited.
First, I mentioned APL only, not Dyalog APL. APL has many branches - Dyalog APL is proprietary, but there are other branches such as GNU APL (which is Free & Open Source).
As for the link - it was simply in case someone wanted to run the APL code I wrote. Try APL has an online REPL for APL, so there is no need to download any software.
Again, I hardly think there is anything sinister about providing a Try it Online link - plenty of people do it.
As someone who knows nothing about this language, does this map each element in data into an array of boolean, then .sum() will implicitly cast each boolean into 1 or 0 before adding them together?
More or less, yep. But keep in mind this is quite specific to the numpy library that the question is based on, the built-in lists and other collections won't function this way.
To be fair, while I know some of the basics, the reason I can't test out of this particular class is because it's about specific applications to statistics.
Huh, maybe they should make a basic python class a prereq before moving onto the statistics stuff. That class should cover list and array comprehensions.
Also I don't consider list comprehensions basic lol. The only stuff more complicated is the actual software engineer stuff, like refactoring, DNRY, etc
I mainly did it like that because it's a homework assignment, usually I'm a lot less verbose. At most I would have just one comment that says "find the evens".
People who spend too much of their time in python dealing with partially integrated C++ libraries. If half of your code calls methods from libraries like SimpleITK with brilliant names like sitk.GetArrayFromImage(), at some point you just give up on trying to keep your own stuff in proper style.
An arithmetic operation on a numpy array object will return a new numpy array object with each item of its internal collection operated on by that operation.
It's like half of the `.__foo__`s become a silent `.map(foo)` . Madness!
In numpy you can pass a selector array of booleans as an index if it has the same length as the array being indexed. This has the effect of returning a new array constructed from only the values of the old array where the selector had "true"
⍝ set index origin to zero
⎕IO←0
⍝ first 10 integers
⍳10
0 1 2 3 4 5 6 7 8 9
⍝ modulo 2 of first 10 integers
2|⍳10
0 1 0 1 0 1 0 1 0 1
⍝ sum up even values of first 10 integers
+/2|⍳10
5
A few years back I would have agreed with you, but after being exposed to math more often I see that it's just a mathematical language. You write programs as math expressions, more or less. It's really powerful and just some abstraction leves higher than most other languages
There is a special APL keyboard, I believe. You can also opt for the J programming language, which is very similar but uses normal ASCII characters. You can say something for both languages, so it really just boils down to personal preference
So data%2==0 returns an array of bools. Let's call this array bool_array. How come that data[bool_array] returns an array? Shouldn't it throw an error since an array of bools is not a valid index?
If they're trying to teach you for loops, just use a native python list. Why involve numpy at all if they specifically want you to avoid the functionality it brings to the table?
# 5) Define a function called Even_Values.
# This function will take a numpy array as an argument, then using a for loop,
# calculate how many values in the array are even, and print the number of even values:
# ok, first let me just say that it would be way better to just use len(data[data%2==0])
# in fact let's just do a terrible version of that
def Even_Values(data):
evens = 0
for i in range(len(data[data%2==0])):
evens += 1
print(evens)
# perfect
Unfortunately we only get feedback from our classmates and the TAs so I'll probably never know. I'm hoping for a cocktail of amusement and mild rage though.
The worst part is the naming convention though, not the code.
I've never seen Title_Case_With_Underscore as a convention, as most definitely never in Python. It looks like a case of "its done this way in my preferred language, so it is the only valid way".
It makes me wonder, where this particular convention is coming from. I know that C# seems to have a HeadUpCamelCase style for both methods and classes (though I'm not sure). Java usually has HeadUpCamelCase for classes and drinkingCamelCase for fields and methods usually. For Python the style guide says lowercase or lower_case_with_underscores_if_it_is_more_readable for functions/methods and HeadUpCamelCase for classes, but even the builtin modules are not consistent in this. Constants are usually CAPITALIZED_WITH_UNDERSCORES across many languages.
But I've never before seen Title_Case_With_Underscores. Though our code base uses TitleCase_WithUnderScoreAfterModulePrefix. But that's mostly because Fortran doesn't really have a well-established style.
Curiously, weird naming conventions seem to be common in programming classes, especially "programming for engineers/scientists" classes.
The reason they want you to use a for loop for that is because that's how you would do it with a regular (non numpy) array. That's probably to make sure the fundamentals are solid for people with not that much programming experience before introducing expressive numpy features. Of course then the argument shouldn't be necessarily a numpy array, but I guess they want you to ignore other types of collections in a stats class.
Yeah, give them a numpy array and tell them to loop through it. That will teach them how to code.
"it's just an exercise, bro"
It teaches an anti-pattern coming from a college professor. Big red flag. I'd change schools. How do you know they won't teach anything as stupid down the road but you won't know?
To be fair it's the second week of a half-semester course and one of the focuses of the assignment is for loops. Is this a terrible thing to use a for loop for? Yeah, but I don't expect them to make me do something like this again. Not with a loop anyway.
That said I don't think I'll take another course from this professor because his quiz questions are all really silly things that it's obvious weren't even run past a TA, but hey who cares as long as I get an A?
Dunno. You can go to an unranked noname college and get an A in every subject without doing much. Or you could go to MIT and barely manage to graduate with a 3.0 GPA. Now you tell me why would everyone want to hire the second guy.
I up to this day don't know where to use recursion and why. Cuz all the use cases they showed me had better solutions to them. Fibbonachi, for example, through dynamic programming. Long story short, I never use recursion.
I'm not really here to teach, but alright: recursion is the least sloppy way to descend down a tree, like you said, a JSON tree or HTML. Any context-free grammar by definition does not need to know anything about its parent to be understood. Therefore, the best way to parse a context-free grammar is to take the parent token, then recursively call the parse function on all its children. Almost all compilers use recursion. This keeps the compiler from gathering bugs due to state, and allows you to describe each grammar rule independently of each other rule.
State is the largest source of bugs in production code. But with recursion, mistakes don't stick around as much. Each layer of a process is separated and broken down into discrete parts. In the codebase I work on, recursive code without state is so much cleaner than stateful object-oriented mess.
That's too bad because sometimes recursion is the right tool for the job. Traversing a tree-like structure for example, is way easier to read when it's done recursively as opposed to iteratively. And please don't say "recursion bad because performance and stackoverflow". That's absolutely a non-argument in 95% of the cases
Calm down man, it's probably just an introductory class that wants to teach basic control structures. Teaching new students the best way to do something from the start is a bad way of teaching. You have to let the students discover for themselves what could be better and why. Otherwise they will do it the right way because they are told it's the best way, but don't actually understand why that is and what the alternatives are
Because that's a simple thing to do, ya know, assuming the OP is American. If its pre-university, they'd likely have to get enrolled in a private school because public schools are all done by zip code and kids have about as much rights as animals. If its college or university...yeah, that's gonna end up, at best, with a lot of wasted time, a mountain of wasted money that's likely in the form of student loans, and that's not even getting into the rigamarole of having to apply to a completely different school.
I wouldn't have gotten past my first Java class in university, if I'd have done something that alarmingly moronic, and I'd be many thousands of dollars more in debt. Oh, and probably have the government on my ass because I basically pissed away my Pell grant money for literally nothing.
I suspect a lot of the parts you hate about numpy are things that got carried over by people used to R. The array indexing in particular I'm pretty sure would actually work exactly as intended if you copied it into RStudio (as long us you had a vector with the name data, of course).
None of that impacts what you're saying of course. Just saying it makes perfect sense to a specific set of people.
Probably not R. MATLAB is a more likely inspiration. Anyway, this notation is common in scientific computing, where you think in terms of operating on entire arrays rather than element-by-element.
Numpy arrays just have operator overloading to allow you to do mass operations on their contents. Once you know that the code becomes pretty clear. It's not a super steep learning curve exactly.
The statement is pretty easy when we apply the above.
data % 2 creates an array based on data, but each value is modulo its source.
== 0 then filters by each value being equal to zero. Produces an array of booleans.
data[someNewArray] is just filtering based on the boolean array.
It's just operator overloading, which is a pretty standard feature in python. It's okay as long as it does pretty much what it says on the tin.
Yeah idk. I get what you’re saying but there is something to be said for readable syntax. I’d rather a method than an overloaded operator that’s not self explanatory.
I agree with you that self-explanatory things are preferable, but you don't want to limit yourself to that. Take for example conventions. We need them but they are not self-explanatory per se.
i somewhat agree. i dislike how many people think "learning python" == "learning numpy" and are surprised when theres a python dev without in depth python knowledge.
i dont agree with the general dislike of numpy tho, its decent at its job and that job imo is bringing R like syntax and efficient arrays to python.
It's just a few overloaded operators. You could make an array class in almost any language that lets you overload these operators that would act the same, no lambdas necessary. (Conversely, if you want your head to explode look into modern R code.)
And the intent in the numpy code is very clear here. You're indexing data with []. At what index (es)? data%2 == 0. You can break those down further, realizing that data % 2 is an array of ints and comparing that to 0 gives an array of bools. If anything is confusing here it's because it's a one-liner. You could unfold it into 4 lines of code to make the steps more explicit.
The slicing operator is central to numpy (and pandas) notation. If you don't understand index slicing, you straight up don't fundamentally understand numpy. You are just using maths over arrays at that point.
go read a piece of Rust
laughs in borrow checker
It's like saying "I hate rust, what's with mut everywhere, what's 'a everywhere, why are types in angle brackets when it's not being used for less/greater than?"
Seriously who actually groks rust but can't handle numpy?
Normally I'd use this as a teaching moment, but you hold up Rust as the exemplar of intuitive notation, ffs. I love rust but it is hardly a simple, easy to pick up, syntax set.
"And that's my problem with numpie. The intent is not clear until you learn the entire ruleset"
The last part if my original comment was regarding this sentence. It's basically stating that you won't understand something if you don't take the time to learn how it works. Granted, there are certain concepts you can understand just by looking at it, but it's stupid to want this to always be the case. It's extremely limiting and will lead to worse results in the long run.
Clarity and intent are immediately obvious if you know how index masking works. It's like saying it's unclear how <'a> works in rust because you aren't familiar with lifetimes.
298
u/gipp Oct 14 '21
(data % 2 == 0).sum()arguably better still29
u/G4METIME Oct 14 '21
You could have skipped the creation of the range:
4
u/Beli_Mawrr Oct 14 '21
You know it's good to hear they're finally teaching python, but you clearly should be able to test out of it.
3
u/polyworfism Oct 14 '21
I've inherited projects with millions of lines code, and fewer comments/less documentation
79
u/The_Northern_Light Oct 14 '21
If they want you to write C, they should just have you write C.
61
u/halfanothersdozen Oct 14 '21
Who uses upper snake case for method defs in python?
104
u/nosam56 Oct 14 '21
Had to learn about numpy to understand why this works. Nice
61
u/[deleted] Oct 14 '21
How does that
data[data%2==0]works?18
u/kryptogalaxy Oct 14 '21
If they're trying to teach you for loops, just use a native python list. Why involve numpy at all if they specifically want you to avoid the functionality it brings to the table?
10
u/josh2751 Oct 14 '21
oh damn. LOL.
Well, it does solve the problem, using a for loop.
15
u/Ravi5ingh Oct 14 '21 edited Oct 16 '21
7
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Oct 14 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
1
u/Jackiboi307 Oct 15 '21
Teacher getting owned, glorious. What was their reaction?
2
u/ExaminationBig6909 Oct 15 '21
Am I missing something? Where does it say the array is a set of consecutive ascending (or descending) integers? Wouldn't [2, 2, 2] be a valid array?
2
u/R3D3-1 Oct 15 '21
The worst part is the naming convention though, not the code.
I've never seen
Title_Case_With_Underscoreas a convention, as most definitely never in Python. It looks like a case of "its done this way in my preferred language, so it is the only valid way".It makes me wonder, where this particular convention is coming from. I know that C# seems to have a
HeadUpCamelCasestyle for both methods and classes (though I'm not sure). Java usually hasHeadUpCamelCasefor classes anddrinkingCamelCasefor fields and methods usually. For Python the style guide sayslowercaseorlower_case_with_underscores_if_it_is_more_readablefor functions/methods andHeadUpCamelCasefor classes, but even the builtin modules are not consistent in this. Constants are usuallyCAPITALIZED_WITH_UNDERSCORESacross many languages.But I've never before seen
Title_Case_With_Underscores. Though our code base usesTitleCase_WithUnderScoreAfterModulePrefix. But that's mostly because Fortran doesn't really have a well-established style.Curiously, weird naming conventions seem to be common in programming classes, especially "programming for engineers/scientists" classes.
2
u/omg_drd4_bbq Oct 15 '21
Folks in the comments be like
Hahaha numpy go BRRRRRR
1
u/murtaza64 Oct 15 '21
The reason they want you to use a for loop for that is because that's how you would do it with a regular (non numpy) array. That's probably to make sure the fundamentals are solid for people with not that much programming experience before introducing expressive numpy features. Of course then the argument shouldn't be necessarily a numpy array, but I guess they want you to ignore other types of collections in a stats class.
0
u/incoralium Oct 15 '21 edited Oct 15 '21
Expected answer :
Edit : fuck reddit retarded formating
-8
u/RedditAcc-92975 Oct 14 '21
Yeah, give them a numpy array and tell them to loop through it. That will teach them how to code.
"it's just an exercise, bro"
It teaches an anti-pattern coming from a college professor. Big red flag. I'd change schools. How do you know they won't teach anything as stupid down the road but you won't know?
0
u/[deleted] Oct 14 '21
[deleted] — view deleted comment