Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I learnt about DRY code and
Flat is better than nested
I also know that excessively DRY code is bad and I am not "religiously" DRY or anything. But which of these would be better? (I can't make out as the creator what might be less readable)
"""
Basically the variable "answer" is overwritten to equal "number" "+" or "-"
or "*" or "/" or "**" the existing value of answer. Here, operation is a
dictionary; and a value (such as to add, subtract etc.) is accessed based on
symbol the user has inputted (such as "+", "-" etc.)
"""
#Type 1:
number = float(input("Enter number: "))
answer = operation[symbol](answer, number)
#Type 2:
answer = operation[symbol](answer, (float(input("Enter number: "))))
Its greate that you think about software quality right from the start. The best answer is not always very clear, and especially if you consider a decision on a very low level of a single instruction call, as you do now.
I would vote for Type1, but Type2 is also entirely OK. This is dependent on person's habits that develop over time.
I think you can go with any of them for now, but still consider best practices and design patterns when thinking about the overall shape of your program. The goal is for software to be easily maintainable and (in case you create a library) easy to use by other programmers.
This example is not so complicated, so type 2 would be Okay (but meh) for me, but overall I would go for type 1 because I think it is more readable. Not just for me, but also for everyone else who will be working with my code later. I don't like the multiple actions in one line, I think it makes things unnecessarily complicated when you (or someone else) come back to it later
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I'm writing a z3 python program that is running a bit slow. The reason why it is running slow is because there is one part of the program where I am adding many harder constraints in nested for loops. My instructor told us that adding equality constraints would make the program run faster in terms of limiting the possibilities the program goes through when the line Solver().check() is reached.
I'm wondering whether I should be adding the equality constraints before the "harder" constraints to make it go faster, or whether the equality constraints should go after the "harder" constraints?
I would want the equality constraints to be checked first to limit possibilities of the harder constraints, so I would assume s.add(x == y), or something should be added first so that it is checked first?
These sorts of questions come often; and the honest answer is that the performance of the solver on any given question relies on many factors. Changing the order of constraints should in general have no effect, but in practice it usually does. (See https://github.com/Z3Prover/z3/issues/5559 as an example.) Even renaming variables (something you'd think that'd have no effect) can change performance. (See here, for instance: https://github.com/Z3Prover/z3/issues/5147)
If you're having performance problems, it's best to address it as a modeling issue: i.e., how can you formulate your problem so it's "easier" to solve; instead of thinking about how to "reorder" the constraints, which is a never-ending guessing game. I suggest you actually post your actual encoding and ask about specific advice regarding that problem. Your question is unanswerable in the sense that there's no single strategy that will work well in all cases.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
this is my very first stackoverflow question.
I'm not a native speaker, but I study mainly in english, and I've tried to search this around the internet with different approaches to my text but I couldn't find anything.
And i'm having trouble to find some directions to write a simple code that follows something like this:
example:
We have a set of values, for example, characters from a game, or flags from a country, etc.
Suposing we have three flags: Japan, Usa and Israel.
We inform to the user these values, so then he knows what are the possible picks, and choose one.
Then, the algorithm make questions like: "Is the blue color present in this flag? yes or no?"
(if the answer is yes, than the algorithm eliminates Japan, for example)
Then the algorithm make some more pertinent questions until just one flag is left.
"You chose the flag of United States."
I know stackoverflow maybe it's not intended for such simple and beginner questions, but if I could have any clue on how to develop this simple algorithm maybe it would help me on how to apply if statements and things like that into my codes and my current ideas. I'm learning Python and Math by myself currently, and every small step is very enlightening.
If someone could fill me in with some Python structure for this or, or pseudocode, or even what phrase should I google, it would mean a lot to me.
Sorry for my bad english!
I think you have to prepare a list of questions first, then with each question, you will have a list of remaining answers. After asking a bunch of questions, you will get the final answer as you wish.
For example, I will have a dictionary storing questions for the flag examples above:
list_options = [{'q': 'does the blue present in the flag?', 'y':['israel'], 'n': ['japan', 'usa']}, {'q': 'is the circle in the flag?', 'y': ['japan'], 'n': ['usa']}]
So at each step, you throw a question to the user and eliminate some answers until you get the last one.
Hope this could help
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
As mentioned in PEP 484:
Using type hints for performance optimizations is left as an exercise for the reader.
Assuming one would be interested in doing this exercise, how hard would it be to undertake, even partially? Is there prior art for using type-hinting in an interpreted language to improve execution speed or is this only possible by going with a JIT compiler?
I should note that I also understand that this is a non-goal and that:
Python will remain a dynamically typed language, and the authors have no desire to ever make type hints mandatory, even by convention.
Consequently, I understand that efforts moving to improve speed would go against this by encouraging type hints by convention. However, I'm still curious about the difficulty of this task.
Update: Although this question is too broad for this site, it is partially answered in the PyPy FAQ:
... the speed benefits would be extremely minor.
There are several reasons for why.
One of them is that annotations are
at the wrong level (e.g. a PEP 484 “int” corresponds to Python 3’s int
type, which does not necessarily fits inside one machine word; even
worse, an “int” annotation allows arbitrary int subclasses).
Another
is that a lot more information is needed to produce good code (e.g.
“this f() called here really means this function there, and will never
be monkey-patched” – same with len() or list(), btw). The third
reason is that some “guards” in PyPy’s JIT traces don’t really have an
obvious corresponding type (e.g. “this dict is so far using keys which
don’t override __hash__ so a more efficient implementation was
used”). Many guards don’t even have any correspondence with types at
all (“this class attribute was not modified”; “the loop counter did
not reach zero so we don’t need to release the GIL”; and so on).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
On many websites I often see comments that code isn't Pythonic, or that there is a more Pythonic way to achieve the same goal.
What does Pythonic mean in this context? For example, why is
while i < someValue:
do_something(list[i])
i += 1
not Pythonic while
for x in list:
doSomething(x)
is Pythonic?
Exploiting the features of the Python language to produce code that is clear, concise and maintainable.
Pythonic means code that doesn't just get the syntax right, but that follows the conventions of the Python community and uses the language in the way it is intended to be used.
This is maybe easiest to explain by negative example, as in the linked article from the other answers. Examples of un-Pythonic code often come from users of other languages, who instead of learning a Python programming patterns such as list comprehensions or generator expressions, attempt to crowbar in patterns more commonly used in C or Java. Loops are particularly common examples of this.
For example, in Java I might use
for (int index = 0; index < items.length; index++) {
items[index].performAction();
}
In Python we can try and replicate this using while loops, but it would be cleaner to use:
for item in items:
item.perform_action()
Or, even a generator expression
(item.some_attribute for item in items)
So essentially when someone says something is un-Pythonic, they are saying that the code could be rewritten in a way that is a better fit for Python's coding style.
Typing import this at the command line gives a summary of Python principles. Less well known is that the source code for import this is decidedly, and by design, un-Pythonic! Take a look at it for an example of what not to do.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Perhaps this is not the correct place to ask this question, and part of me thinks that there is no real answer to it, but I'm interested to see what experienced Python users have to say on the subject:
For maximum readability, concision, and utility, what is a range for an optimal length of a Python function? (Assuming that this function will be used in combination with other functions to do something useful.)
I recognize that this is incredibly dependent on the task at hand, but as a Sophomore Comp. Sci. major, one of the most consistent instructions from professors is to write programs that are comprised of short functions so as to break them up into "simple", discrete tasks.
I've done a big of digging, including through the Python style guide, but I haven't come up with a good answer. If there are any experienced Python users that would like to weigh in on this subject, I would appreciate the insight. Thanks.
I'm sure a lot of people have strong opinions about this, but for new programmers a good rule of thumb is to try and keep it below 10-20 lines. A better rule of thumb is that a function should do one thing and do that one thing well. If it becomes really long, it is likely doing more than one thing and can be broken down into several functions.