+ 1
Attitude Towards Output and Results
Let’s say we have the following code: def Order(ID): # makes your meal based on ID return meal Q = int(input()) order_list = [input() for i in range(Q)] Now, you want to output the meal for each test case. Which approach do you prefer?: A. for i in order_list: print(Order(i)) B. meal_list = [] for i in order_list: meal_list.append(Order(i)) for i in meal_list: print(i) Clearly, one is faster and uses less memory, but I just wanted to know if people store their results first.
3 Respuestas
+ 1
Generally, if possible and still readable, I'd prefer to not create an extra value, if I don't need it again - I'd just print/use it.
When you have to access an object from some storage at least twice or thrice, it might make sense to store it in an extra value, especially if the item is annoying to write.
Let's say I have to write something like...
my_object.attribute[i][j].value
... over and over, probably (either my code has become too messy and I should tidy it up or) I'll store it under a temporary name...
v = my_object.attribute[i][j].value
... and henceforth only use that.
+ 1
I realized this really is more of a question of readability vs maintainability vs performance. I sometimes tend to optimize my code based on maintainability or “how much less I have to modify my code if I had to add something” (e.g. Using Python dictionaries or C switch cases instead of several if/elif/else if statements).
This is why I tend to store my results first even when the problems only ask me to output them.
+ 1
You can decide on a case-by-case basis.
When you think, readability doesn't suffer much, don't store the value.
So not:
x = (y+z)*42
return x
Instead (because, well, come on, right? We can understand this!):
return (y+z)*42
But if code becomes hard to look at, depending how bad it gets, paying a performance price for a good look may be worth it.
And if you think about it:
This is thoroughly 'Pythonic', because Python is all about the ease vs. performance in the first place (x times slower than C for example).