r/learnpython • u/Biuku Coding since April 2020 • Dec 24 '20
Just turned 5 lines of simple code into 1 unnecessarily convoluted one. FANG, please IM me your offers.
Been at this coding thing since April. Felt things really click more since tackling algo/data structures the past 2 months.
But today I became a man. For the first time in my life, I turned 5 lines of clean, readable code into a single spaghetti expression that I'll have to stare at one day to ever understand where I was going with it.
I think I've earned a Bud Lite shandy.
5 lines
minVal = m.inf
for k, v in self.weight.items():
if k in self.unvisited and v < minVal:
minVal = v
u = kNever slipped a dict comprehension in my lambda before -- but I liked it
u = min({k: self.weight[k] for k in self.unvisited}.items(), key = lambda item: item[1])[0]368
u/socal_nerdtastic Dec 24 '20
Isn't this just
u = min(self.unvisited, key=self.weight.get)12
u/sweettuse Dec 25 '20
in python 3, no. if the key isn't in
weightyou'll end up with a float/None comparison which is aTypeErrorto fix, you could do:
min(set(self.unvisited) & set(self.weight), key=self.weight.get)5
u/socal_nerdtastic Dec 25 '20
Are you trying to fix or replicate OP? Becasue in OP's oneline version they would have a KeyError instead.
1
u/Biuku Coding since April 2020 Dec 25 '20
No, it ran.
7
u/socal_nerdtastic Dec 25 '20
I know, we are discussing hypothetically what would happen if the key isn't in self.weight.
1
u/sweettuse Dec 26 '20
good point. this is only dealing with missing keys, which OP's data might not have.
129
u/mojo_jojo_reigns Dec 24 '20
Google wants to know your location.
110
76
u/drsxr Dec 24 '20
Keep in a gist so you can cut and paste into future code not knowing what it does or why it works, but just gloriously working.
58
Dec 24 '20
Leave it uncommented as well. That'll help future maintainers a lot!
51
u/xelf Elf Dec 24 '20
No, no, comment it with something cryptic and unhelpful
# This works because of p17 and what griffin said4
4
6
40
u/DragonTreeBass Dec 24 '20
I love doing this an exercise in thinking and creativity but god do I HATE people who seriously code like this. It’s cool but completely unreadable.
18
u/thenonovirus Dec 25 '20
The answers on codewars are cancerous. Everyone tries to compete in creating the most "efficient" code which are unreadable.
6
u/haugao Dec 25 '20
I started using codewars to practice python and this is pretty much how I feel whenever I hit submit. Imagine a beginner spending 20-30 mins on some problem and loading into the answers to see a one liner.
I just accepted that I should focus on actually being able to get the answer in the first place for now and be happy with actually understanding the answer.
5
u/Four_Dim_Samosa Dec 25 '20
I think that could be because we need to have a consistent definition of "efficient". Remember that CS is mathematical in nature, so even though you don't use all the math necessarily in the real world every waking moment, it's important to know that the stuff that makes computers work are really based in math. The mathematical aspect of CS is what allows us to precisely define what we mean by "efficient" or "NP complete" for sake of example. Also, we need to balance efficiency with readability. Remember we aren't robots and part of CS is communication. If you communicate with garbled one liners to other coders, you'd probably not get an "impressive reaction"
Fun fact: Hamming code is pretty cool. Grant Sanderson made a great 3 blue 1 brown video on this and I highly recommend his channel.
1
u/Kevinw778 Dec 25 '20
I'm high school we used a website called Javabat and tried creating the most disgusting-looking recursive 1-liners. It was awful and amazing all wrapped into one clusterfuck.
48
u/TSM- Never slipped a dict comprehension in my lambda before, but Dec 24 '20
Never slipped a dict comprehension in my lambda before -- but I liked it
Please mods let us write our own user flares. I've found mine
29
2
0
5
u/Subsequential_User Dec 24 '20
Nice, it's always a good feeling!
What about trading ".items()" for ".values()" (therefore not needing a key parameter with lambda function)
6
u/Biuku Coding since April 2020 Dec 24 '20
I think I needed both to return the key while sorting on the value.
On mobile so not sure now... will take a second look later.
53
u/teerre Dec 24 '20
Hopefully you do realize that regardless of the inefficiency of this algorithm, the first one is the one you should write in any remotely seriously software. The second one is unreadable.
2
u/carugatti Dec 25 '20
when people writes code like this where i was working i just call then regex.
0
25
Dec 24 '20
[removed] — view removed comment
14
Dec 24 '20
yeah the first person you will fool is yourself, there have been many times when, after reading my own codes a week later, I've asked myself wtf was I thinking trying to be more clever than the situation required.
10
Dec 24 '20
Forget other people. I can't count the number of times I went back to my own code and went "why the fuck did I write that?" Be kind to your future self. Write verbose code and comment like mad.
3
u/Four_Dim_Samosa Dec 25 '20
commenting really does help make debugging easy. It's satisfying to be able to save hours of stress just from writing good comments. Most people forget that CS is also an art and part of its emphasis is on communication of your thoughts. The code isn't everything. You need to be able to communicate to the non-technical people. If you can't do that, no one will respect you
11
u/maiyokiprono Github username Dec 24 '20
Can someone please tell me why we need to do list comprehension?
19
u/mumpie Dec 24 '20
List comprehensions have been considered "cooler" for a long time by Pythonistas, so people would wedge them in just because.
However, a few years ago, the Python core developers improved the performance of list comprehensions versus for loops.
Take a look at this link for speed measurements for sample code of a for loop versus a list comprehension: https://switowski.com/blog/for-loop-vs-list-comprehension
Ultimately, whether you use a for loop or a list comprehension it's really a matter of readability and whether you really need the speed.
My advice is to write the code however you prefer and then *measure* the speed of the code. Once you know what bits are slow or fast, you can then decide whether it's worth it to spend time and effort making that bit faster. You'll want to look into using a profiler to determine what parts of your code are run most often and could be improved to speed up your program. Take a look at this for more info on profiling: https://docs.python.org/3/library/profile.html
9
u/xelf Elf Dec 24 '20
performance
functional style of programming
they're one of the core features python offers over similar languages, take advantage of them
readability / encapsulation
Because once you get used to them they are faster to parse while reading code than breaking down multiple lines of a for loop. BUT (and this is critical) like any line of code, if you make it unreadable you've lost the advantage gained.
A readable list comprehension is better than a similar for loop. A readable for loop is better than anything unreadable.
At a glance it's clear what you're doing, it's essentially encapsulated functionality.
When you're scanning through code and you see a line that looks like:
counts = { some nested comprehension }You don't need to know how the comprehension works if you just accept that it's getting the counts. Whereas 6-7 lines broken down as nested for loops, you have to read through them to figure out what's going on.
If you need to debug the comprehension, now you need to look at it, and you are no worse off than you would have been if you had to debug the 6-7 lines of nested for loops.
Let's take a look at these 3 lines: (day 24 AOC spoilers ahead)
>! flips = floor | { x for k in floor for x in neighbors(k) } counts = { k:sum(x in floor for x in neighbors(k)) for k in flips } floor = { k for k,s in counts.items() if s==2 or (k in floor and s==1) }
I saw solutions posted that were 50+ lines that did the same thing.
3
u/JennaSys Dec 24 '20
This is a great explanation. I sometimes find it difficult to explain to others about the readability issue, and reducing the cognitive burden of understanding a block of code. It's the difference between just being able to look a block of code and immediately understand the end result of what it's doing versus having to study it to figure it out its purpose.
12
u/johnnymo1 Dec 24 '20
Often faster than other ways of building lists, and as long as it's not too complicated, it makes common manipulations very readable. For instance, if you have a list of data and you have some transformation described by a function
fthat you want to do to each element, it's just:transformed_list = [f(item) for item in data_list]Plus you can include ifs to filter only data that meets some condition, etc.
3
1
Dec 25 '20
Why is this faster than a for loop? [f(item) for item in data_list] has a for loop in it.
1
u/johnnymo1 Dec 25 '20
I don't know a lot of the details, but the for loop in a comprehension doesn't compile down to the same bytecode as a bare for loop, and the version in a comprehension is better optimized.
4
u/POGtastic itertools evangelist Dec 24 '20
It often looks cleaner than standard higher-order functions, and you can combine
mapandfilterinto a single operation.2
u/Decency Dec 25 '20
map, filter, and collect!
3
u/POGtastic itertools evangelist Dec 25 '20
This is true for some things, (specifically, when you're collecting it as a data structure like a list, set, dictionary, or generator) but in other cases, you still have to use
functools.reduceor some function initertools. In contrast, anything that you do withmapandfilter, you can also do with a comprehension.4
Dec 24 '20
If they're used properly they make your code much better. The hate on them usually comes from people using them improperly. That said they're a poor replacement for fluent map, filter, reduce syntax.
4
u/hughjward Dec 24 '20
I did a double comprehension at work last week. Dict comprehension with list comprehension within. Felt like a genius! (But left the multi line version in as comments cus I wouldn't wish anyone to have to decipher a double comprehension!)
1
u/kaddkaka Dec 25 '20 edited Dec 25 '20
And what happens when someone modify the comprehension and the comment gets outdated?
1
u/hughjward Dec 25 '20
Well then they better add good comments/documentation or the deserve to burn in hell...
3
u/flyingwizard1 Dec 24 '20
If you want a challenge, try implementing quick sort in one line!
4
u/xelf Elf Dec 24 '20 edited Dec 24 '20
It's not a very short line, but here you go:
>! qsort=lambda a:a if len(a)<=1 else qsort([x for x in a[1:]if x<a[0]])+[a[0]]+qsort([x for x in a[1:]if x>=a[0]])
(note, not as performant as .sort()) =)
1
u/Decency Dec 25 '20
.sort() uses Timsort!
2
u/wikipedia_text_bot Dec 25 '20
Timsort is a hybrid stable sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data. It was implemented by Tim Peters in 2002 for use in the Python programming language. The algorithm finds subsequences of the data that are already ordered (runs) and uses them to sort the remainder more efficiently. This is done by merging runs until certain criteria are fulfilled.
About Me - Opt out - OP can reply !delete to delete - Article of the day
This bot will soon be transitioning to an opt-in system. Click here to learn more and opt in.
2
u/xelf Elf Dec 25 '20
Hey Tim, what should we call your new sort?
I don't care.
timsort it is!
No, wait, I'll be stuck with it forever.
Too late, it's timsort, and committed.1
3
u/4sent4 Dec 24 '20
I've been playing with one liners lately.. I just take some basic programming problems and trying to solve them in one line..
I like how many features are there in python, even though I rarely use them in code I write for the purpouse.
I've got to make recursive lambda functions, used this := thingy (twice in the same line) and all that stuff.. Never got to the dictionary comprehension, though..
3
u/aelism Dec 24 '20
this
:=
thingy
"i am the walrus!"
4
1
u/4sent4 Dec 25 '20
Oh, thank you. I was trying to find or remember it's name, but all I got is 'Assingment expression' which was too long to type :)
1
2
u/ermagawsh Dec 24 '20
ok but have u seen the guy who did Pac-Man in one line lmao (iirc it was Pac-Man but it could’ve been another game )
2
u/jreebel Dec 25 '20
Having coded professionally for over 30 years, this is the kind of stuff that drives me nuts. If you are the only one who ever looks at this, fine, enjoy. But if you are coding for a living and others have to work with you, or look at your code later, complexity like this is anathema and a real hit on productivity.
2
u/simonsanchezart Dec 24 '20
I find myself doing that often, this is from yesterday (although not in python)
int** C = new int*[3]{new int[4]{1, 2, 3, 4}, new int[4]{5, 6, 7, 8}, new int[4]{9, 10, 11, 12}};1
1
u/scienceNotAuthority Dec 25 '20
Glad you left Apple off the list. You are granted entry to the nerd club.
1
u/doulos05 Dec 25 '20
That's what git commits are for. Every time you look at it and can't remember, you can git blame the file, find the git commit, see the old code and new code side by side, and read a narrative description of what the heck was going through your mind.
15
u/Peanutbutter_Warrior Dec 24 '20
You're ready to play code golf