+ 4
Learning Python One-Line of code vs Many
Today I worked on the Code Coach "Fruit Bowl" challenge and solved it for Python. I'm still learning Python and am a beginner. However, I've seen in the course comments, other people who are more skilled at coding than myself often code in one line, what takes me dozens of lines to accomplish. Wonder how to go from the "dozen" or more lines, but the code works, learning stage to the "one line" works?
16 Respostas
+ 7
EO4Wellness
list comrehensions are the way to go if you want to be good at creating oneliners. Apart from that, learn about lambdas and practise functions like map(), reduce() (from the functools module) and filter().
Apart from that, practise functions that return altered copies/iterators of a strucure, like sorted() and reversed() and so on. So instead of
```
lst = [3, 2, 1, 5, 4]
lst.sort()
print(lst)
```
you can simply do
print(list(sorted([3, 2, 1, 5, 4])))
Others can add more points.
Also, you said,
"print(int((fruit/2)/3))"
but that's a syntax error...."
No, it is not a syntax error. The syntax is completely fine.
+ 3
I did a search here on SoloLearn and found @Trigger comment about using the "list comprehension" in this post helpful:
https://www.sololearn.com/Discuss/1938414/how-to-write-one-line-codes
because then I knew what terms to read more. Most of the answers I've previously read here on this just give the correct answers, and not method, used to take yourself from one state of learning to the next.
From it I was able to look up and source a number of useful articles to learn more about this topic/method and to see examples.
When to use (and not) article/examples:
https://realpython.com/list-comprehension-JUMP_LINK__&&__python__&&__JUMP_LINK/
W3 Schools instruction and code examples
https://www.w3schools.com/python/python_lists_comprehension.asp
A video and some coding examples including the LAMBDA method.
https://www.programiz.com/python-programming/list-comprehension
A Python technical documentation on DataStructures including 5.1.3 specific to List Comprehension
https://docs.python.org/3/tutorial/datastructures.html
General Article on WIKI with links to other resources
https://en.wikipedia.org/wiki/List_comprehension
+ 3
@PieterEdwards Yes, this is exactly what I'm wanting to learn how to do. My current approach is to write the code what ever way occurs to me, logically speaking, to go about solving the challenge. Then looking at it for ways to combine. With the fruit bowl challenge, for example, I was thinking of the problem as I need to know the total number of apples. I can find the number of apples by dividing the number of fruit (given in the "Fruit Bowl" problem) in half to arrive at the total number of apples:
print (fruit/2)
then there are two obvious issues with this: division produces floats and we need to print the number of pies it can make so we need a whole number, no remainder. Also it takes 3 apples to make a pie. so more modifications
print (int((fruit/2)/3))
but that's a syntax error and wouldn't run.
Eventually, I saw others posting the answer as print(int(fruit/6))
and lots of discussion(s) about how to arrive at 6, not understanding why/how others decided to arrive at six. So it is this part of the process my question is about. How to go from beginner basic to thinking in such a manner as to see how and why six works instead of something like (puedo code now) total fruits divided by two is the number of apples. the number of apples divided by 3 equals the number of pies. print the number of pies.
Thanks.
+ 3
* Try to reduce the python code lines by practicing new multifarious types of codes.
* Learn data structures.
* Know Python List comprehensions
________________________
Visit the given link:
http://jagt.github.io/python-single-line-convert/
http://www.onelinerizer.com/
https://stackoverflow.com/questions/19626474/can-python-code-be-compressed-like-javascript
Hope this helps.
Note: Don't ask open ended questions here.
+ 3
▀▄🄰🅁🄾🄱🄾▀▄
I think this question is fine. It does not have a specific answer which makes it open-ended, yes. But it's also related to programming. It's a question asking for tips, and getting such answers from real people instead of some blog is understandable. Google has all answers. If we started asking people to not ask things that can be found on google, this section would become a hub for "write this code for me" questions (which it kinda already is).
I like to think of it this way:
If the question has a definite answer that cannot be found (or is hard to find) on the internet - 👍.
(For example - a question where the OP cannot spot the error in their code, or asking for improvements to their code.)
If the question has a definite answer that is easily found - 👎
If the question does NOT have a definite answer and it totally opinion based - 👎
(like "what are your thoughts on x" or "is x better or y")
If the question does NOT have a definite answer, but has a few ideal answers(like this) - 👍
+ 2
Coding in one line compared to many doesn't really matter in the grand scheme of things. When I did those projects in one line they were often hard to understand. But if you really want to basically of you have code like this:
a += 1
print(a)
You could simplify it to:
print(a+=1)
So in summary do the expressions in the print statement
+ 2
EO4Wellness Open ended questions denotes whose question's answers can be kenned even just by browsing. Ask here only programming cognate questions. Check the sololearn community guidelines additionally.
Oh !!! So you've never aurally perceived of such a thing. Better ken about that. Visit for kenning that what you've never aurally perceived https://www.google.com/amp/s/www.questionpro.com/blog/what-are-open-ended-questions/amp/
Hope this helps.
+ 1
Thanks everyone for these thoughtful answers. I appreciate it. It seems too, more practice writing code is another valid answer to help remove syntax errors.
+ 1
Just one thing to note:
One line isn't always the best solution. Often using the best method(), is whatever method works best for the issue (haha, see what I did there?)
To use your example:
'print(fruit/2)' can yield a float.
But, using floor division 'print(fruit//2)' solves that particular issue, and in the case of this challenge works great! Then all thats left for that challenge, is just some simple maths.
I chose a conditional loop to derive the answer, but there are many ways to accomplish the task.
The main thing is keep the code clean, and be versatile! It's like vocabulary. The more you have, the more articulate you are when you speak.
There's plenty of opportunities to string together code, and you will, especially if you start getting into numpy and pandas data frames, but also with list comprehension and functions as well.
Add as many tools to your toolbox, be proficient with them, and chose whatever is best for the task at hand.
I hope that helps!
+ 1
I found yet another answer to this question. If I had known about, and used, a walrus operator, my original code attempt at a one line solution would have worked. Found that info today located here:
https://www.sololearn.com/learning/2429/
+ 1
Thanks, Chris Phillips that is very helpful. Originally, i took the python course here because I've used pandas bumpy tensor flow, but didn't have python in my background. It will be interesting to see how it changes my understanding of these other methods.
+ 1
XXX always after typing my code solutions, upon 'run' the outcome is always 'syntax error' and it won't go to the test cases due to syntax. I don't seem to be able to cut and paste code within this app or you would likely see my syntax error immediately. I learned from your reply, my error likely is some other issue with syntax not the part I retyped here. I wish this app allowed me to cut-n-paste. This syntax thing keeps plaguing me.. Today, for example, I tried 'Gotham' Coded everything but it wouldn't run due syntax error. Googled if-esif & discovered its : not ; to resolve the syntax errors
+ 1
EO4Wellness
You can copy the code, by selecting it and copying it just like you would copy any other text (by tapping "Copy" on the small horizontal menu that hovers over the selected text on a phone, and using keyboard shortcuts on a computer)
Anyways, don't worry much about the syntax. Syntax is actually the easiest part about learning a language. Practise enough and you'll be able to write the correct syntax and also spot the problem when an error occurs. If you forget the syntax or the how a specific function or keyword is used, then it's okay to google it. After a certain amount of time, it'll settle in your mind
+ 1
XXX This section is only meant for asking programming related questions only and not to ask anybody's opinion . Please check out sololearn community guidelines.
0
▀▄🄰🅁🄾🄱🄾▀▄ how does one know what is considered "open ended"? I've never heard of such a thing.
0
▀▄🄰🅁🄾🄱🄾▀▄
Did I say that opinion-based questions are okay?
Note the '👎' emoji at the end of the line
"If the question does NOT have a definite answer and is totally opinion based - 👎"
Again, this is what I think is the right way to judge a question. Anyone can feel free to correct me.