Readability aside, performance is a major issue. One should use the built-in Counter instead of set() and .count() for counting hashable objects to save performance. Also, the code uses sorted() when it really didn't have to.
Is it tho? What's this code for? If the purpose was to have something working in a rush (ex: exam) this is good code, if it's a shared project then less so. At any rate considering you are in high school this is not by any means terrible.
Motherfucker crossed the line. Literally tho. IDE clearly shows a white line at I think 120 characters length. The pep8 standard limit is 80 characters but 120 is pretty popular standard nowadays.
Actually the pep8 standard only says to use a standard across your code base. It suggests 80 but 120 can be used in its place and still pass the pep check if you set your standard.
Suggested max length of a line of code. It comes from when monitors had an 80ish max char width. I'm pretty sure I've seen Java variables at work that break that rule though
Keeping lines under a certain amount of characters helps when you do branch merging. Keeps everything in view even if you have a left(yours)|middle(merge)|right(theirs) merge window open.
A lot of people completely ignoring the horrible time complexity going on here. Generating the frequency table is O(n^2), when a good implementation would just be O(n).
Tbf, it is fine for a small script that you use once for a relatively small to medium sized dataset, but yeah, this needs refinement if you want to use that code more often
with open('myfile.txt', 'w') as file:
file.write('test stringer for ultimate python test manycharstring evenmorecharstring equallencharstring')
with open('myfile.txt', 'r') as file:
text = ''.join([i.lower() for i in file.read() if i.isalnum() or i in [' ', '\n']])
text_freq = set([(i, text.split().count(i)) for i in text.split()])
text_freq_dict = dict(sorted(text_freq, key=lambda _: _[0]))
print(f'''histogram: {text_freq_dict}
total number of words: {sum(i[1] for i in text_freq)}
number of unique words: {len(text_freq)}
most common words: {dict([i for i in text_freq if i[1] == max(text_freq, key=lambda _: _[1])[1]])}''')
def find_longest_word(dictionary: dict) -> dict:
return dict([(i, len(i)) for i in dictionary.keys() if len(i) == max([(k, len(k)) for k in dictionary.keys()], key=lambda _: _[1])[1]])
Outside of the variable naming (i for words, using _ in an unusual way) I don't see one bad thing about this code. It's pretty concise for its purpose (without using any external libraries).
Edit: actually find_longest_word is pretty bad lol (and wrong).
I’ll just say, list comprehension is a very pythonic way to write code. You might be doing too much inside of it though that you’re sacrificing legibility.
Ensure your variable names represent the data to the fullest. There’s potential here to rename some of these variables
Context managers are great but make sure you are only wrapping the code that depends on them inside of it.
Dataclasses are a great way to assign data to a model representation. Then you can easily create helper methods inside of the dataclass to perform data transmutations and provide cleaner and more legible Python code
If you make dataclasses use the frozen dataclass decorator parameter as to ensure you follow the immutable pattern to safeguard against unwanted mutations to existing objects.
I’m also not really a fan of writing the data type in the variable name: *_dict for example. It should be obvious by the operation that it’s a dictionary and therefor redundant to have in the variable name. Also you can enforce typing to allow Pylance the ability to identify the types for your variables
Those people are the best. What's even funnier is watching them not get an offer from companies that hire directly out of college because they can't function around other humans.
Looks like Arrogance. Tons of old school Perl folks write scripts like this. Usually the grey beard / unix admin types. Obfuscation in order to create a false sense of knowledge superiority.
i mean you calling this bad code tells me you don’t even write good python code. LC are the pythonic way to do stuff. Just the type hint of dict triggers me as the correct one is Dict.
When using pep8 common sense applies. If you can't fit a line of logic within 80 character it is almost always a sign that this line has to be rewritten.
Anything but the simplest of Python's list comprehensions will often produce lines over 80 chars. You might as well ban them if that's the hill you're willing to die on.
def do_stuff():
# 79 characters with a single level of indentation and semi-descriptive identifiers
named_variable = [named_transform(x) for x in named_list if named_check(x)]
...
You're acting rude to me just because I respectfully responded to your comment with proper citations. I mean it's okay to have a bad day, but that's really not nice of you.
That being said this looks like a uni assignment, literally noone cares if this conforms to standard. It's like posting a code golf solution and saying it doesn't conform to PEP8. Sure, and?
I put great care into my school assignments. Why would you arbitrarily turn off "writing clean, well-organized, concise, well-styled code"? What do you gain? It sounds like your natural mode of operation is to write bad code. For a good programmer, they have to try to write bad code, because their default is good code. It'd be like saying you should try to misspell words, because you're not writing a formal novel right now. Or... maybe people with good skills in English just spell things correctly (ignoring the case of texting where saving letters can be a matter of convenience).
To begin with: this is not bad code. It's not conforming to standard code. That's formatting, it has nothing to do with whether the code is good or bad.
I don't know any programmer I respect that sees style as having no value. A style should be logical first and foremost. A simple example is using indentation to express control flow compared to hiding it with no gain. If the style of this nature, it's hard to argue not following the style leaves the code's goodness intact. Then, there's more arbitrary rules like camelCase versus snake_case. Good code should follow the general style of the language being used, because it helps others understand it by matching their pattern recognition. When it's contentious, a team should choose something for whatever reason and stick to it. Unusual style is definitely a sign of both a bad programmer and bad code.
In this case, the person has made code that is hard to understand, because it has very long lines. This is a logical consideration like indentation. I'm not aware of any style guide that doesn't discuss how to handle various constructs needing to wrap around to the next line.
Well organized? It is. Well styled? Nobody cares. Why? Because a good programmer doesn't waste time writing standard conforming code in terms of formatting. A good programmer runs black, and let's the machine do it for him. And they do so when there is need, because again, why waste time? So when the code might be reused, or maintained or modified.
Everywhere I've worked, style is grounds for a change not to be deployed to production. Automatic formatting can only do so much as well. Like I said about intentionally misspelling words, I've never met a programmer who doesn't write their code in the style they've been using for years or decades as they write it. I'm guessing you're still in college or maybe high school, so you haven't developed your pattern recognition with respect to style yet.
I'm a teacher, a researcher and have commercial experiance. Everyone with any bit of it will tell you that first you write something that works, then you improve it. Why? Because improvement takes time, and a deadline might come or there might be other sudden priorities. It would be lovely if people always write nicely formatted code, but frankly it's so often a waste of time.
That's shocking, because you can't even spell "experience". Teachers are notorious for writing bad code. In fact, many of the samples in this subreddit are code snippets given by a teacher. The reason is they spend decades writing basic algorithms over and over. Worse, sometimes they write it once and use it forever afterward. As a simple example, I know a teacher who uses the C style in C++. His code samples are from before unordered_set existed, so he made his own one in one example. He doesn't even use range-based for loop constructs.
As they say: Those who can do. Those who can't teach. This is mostly a joke as professors at good colleges are doing nontrivial research. However, that research rarely involves proper, long-term software development. The professor I talked about, for example, released some research about using certain instructions to boost the performance of computation of certain mathematical objects. Now, if you are teaching where you don't do research like a community college, it's even truer. It's a comfortable job with lots of vacation and easy work. Plus, some people like teaching others. That doesn't mean you know much about creating software though.
Just the type hint of dict triggers me as the correct one is Dict.
Well, not necessarily. If you don't have to support Python <3.9, then generics in builtins and collections support type hints by themselves already. If you can set your minimum at 3.10, then you can even get rid of Optional and Union.
First of all, the string enclosed by print contains multiple expressions that could have each been better isolated with the help of intermediate variables. Instead, the code has crammed multiple functions' worth of operations into a single formatted string.
Then there's the incoherence and horizontal span of find_longest_word
In the professional world, readability is probably the most important standpoint (after correctness). Even the original author is not going to remember having written this in a few months.
Which is why they should use extensive doc strings and comments that are more confusing than the code.
The ideal is for the code structure to make a need for 0 comments. As a simple example, instead of a comment and a function f, just call f something expressive like UserDao::add_user. Never ever write a comment that just says exactly what the code is doing line by line. For that summary, people can just look at the code. If a comment is warranted, express the intent behind the code rather than something closer to what the code does. Plus, it makes changing code harder since that synopsis needs updating, and the comment can become stale. Something like /* find the location of 'a' */ auto i = std::find(v, 'a'); is awful. Good code should speak for itself ideally.
The higher up you are in the chain of abstractions, the more justified comments are. For example, a comment over a class is usually more justified than a comment over a function which is usually more justified than a comment over a single line of code.
These are generalities with exceptions. It can often be much less noisy and more understandable to have very few comments.
Whenever I code python I have to stop myself from doing that too much. It's so easy to build up these lines and they don't take up much space horizontally. I assume if you read python a lot it gets easier but I get exhausted actually reading them- like a run-on sentence.
23
u/GudSp31ing Mar 19 '22
I'm fairly certain Python has a Counter object built-in that was specifically made for things like this...
2
u/Farpafraf Mar 19 '22
beside the last line being hard to read I don't really see a problem with it if performance is not an issue
214
u/BigNutBoi2137 Mar 19 '22
Motherfucker crossed the line. Literally tho. IDE clearly shows a white line at I think 120 characters length. The pep8 standard limit is 80 characters but 120 is pretty popular standard nowadays.
159
u/TheUnlocked Mar 19 '22
A lot of people completely ignoring the horrible time complexity going on here. Generating the frequency table is O(n^2), when a good implementation would just be O(n).
34
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Mar 19 '22
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!
59
u/gipp Mar 19 '22
The classic "smart kid just learning to code" style -- the fewer lines it takes to do it, the better the code, right?
29
u/ZuriPL Mar 19 '22
The find longest word function does live up to its name lol
10
u/XxClubPenguinGamerxX Mar 19 '22
This isnt thaaat bad. Sure its unreadable and unefficient but if I was doing a small script to get something done quickly I would ve done the same.
81
u/rmadlal Mar 19 '22 edited Mar 19 '22
Outside of the variable naming (
ifor words, using_in an unusual way) I don't see one bad thing about this code. It's pretty concise for its purpose (without using any external libraries).Edit: actually
find_longest_wordis pretty bad lol (and wrong).13
u/Tm1lly Mar 19 '22 edited Mar 19 '22
I’ll just say, list comprehension is a very pythonic way to write code. You might be doing too much inside of it though that you’re sacrificing legibility.
Ensure your variable names represent the data to the fullest. There’s potential here to rename some of these variables
Context managers are great but make sure you are only wrapping the code that depends on them inside of it.
Dataclasses are a great way to assign data to a model representation. Then you can easily create helper methods inside of the dataclass to perform data transmutations and provide cleaner and more legible Python code
If you make dataclasses use the frozen dataclass decorator parameter as to ensure you follow the immutable pattern to safeguard against unwanted mutations to existing objects.
I’m also not really a fan of writing the data type in the variable name: *_dict for example. It should be obvious by the operation that it’s a dictionary and therefor redundant to have in the variable name. Also you can enforce typing to allow Pylance the ability to identify the types for your variables
2
u/jarrydn Mar 19 '22
Don't you have to close a file before it can be opened for reading?
4
u/zero-360 Mar 19 '22
Code golf gone way too far. It’s all fun and games until you have to debug these kind of methods
3
u/eerklogge Mar 19 '22
This is too much of a mindfuck for me this early.
2
u/[deleted] Mar 19 '22
What in the ACTUAL HELL am I looking at?
2
u/yetzederixx Mar 19 '22
Those people are the best. What's even funnier is watching them not get an offer from companies that hire directly out of college because they can't function around other humans.
2
u/trutheality Mar 20 '22
Python had dict comprehensions for 10 years now. Maybe use them.
4
u/rgnkn Mar 19 '22
Not too bad.
Okay, readability. But one run of
blackwould help here quite allot.It's not perfect but it's coming from a "school" - whatever this means.
So, from my point of view: absolutely fine.
... as long as it doesn't get into industry code.
1
u/[deleted] Mar 19 '22
1
u/Voltra_Neo Mar 19 '22
Please tell me they call themselves a pyxpert (pronounced
pi expert)1
u/Infamous-Gain2231 Mar 20 '22
Looks like Arrogance. Tons of old school Perl folks write scripts like this. Usually the grey beard / unix admin types. Obfuscation in order to create a false sense of knowledge superiority.
1
u/Tvde1 Mar 19 '22
Why is this bad? Looks like something easily out together, not for ant production system
-17
u/nikhil_shady Mar 19 '22
i mean you calling this bad code tells me you don’t even write good python code. LC are the pythonic way to do stuff. Just the type hint of dict triggers me as the correct one is Dict.
0
u/[deleted] Mar 19 '22
[deleted] — view deleted comment