Timeit module, triple quotes code vs function [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I was using timeit module for measure some the execution of my code, and while checking different scripts I found this big difference on 'the same script' but defined on different ways.
Code.py
import timeit
code = '''
def count():
for i in range(100):
pass
'''
def count():
for i in range(100):
pass
print(timeit.timeit(code))
print(timeit.timeit(count))
Output:
0.17939981000017724
3.7566073690004487
What is really happening under the hood? I mean, in both cases the piece of code is exactly the same, but the time execution difference is huge.

In the string example, you're only defining the function but not actually calling it, so you're essentially timing the function creation rather than its execution.
You'll need to append a count() function call at the end of your code string for it to actually run and include in the profiling.
code = '''
def count():
for i in range(100):
pass
count()
'''
But note that technically you're timing both the function declaration and it's execution in the string example, and just the function call in the second example.
This would be a fairer comparison:
code = '''
def count():
for i in range(100):
pass
'''
def count2():
for i in range(100):
pass
print(timeit.timeit("count()", setup=code))
print(timeit.timeit(count2))

code in only a string not a function definition.
code = '''
def count():
for i in range(100):
pass
'''
It does not executing any calculation or iteration. code:
'\ndef count():\n for i in range(100):\n pass\n'
but count is:
<function __main__.count()>

Related

Python Beginner: Why is this my output? function generate at 0x0000021EE6848700 [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I'm trying to generate random numbers using user input. This is for a homework question and is structured as the professor instructed. I'm returning x amount of this instead of numbers. function generate at 0x0000021EE6848700
I feel like this is a stupid question and I'm missing something obvious. When I try to define main with generate I get an error that I'm missing a positional argument. I have tried using print and return, and neither under generate. Am I not defining something correctly?
import random
def generate():
print(random.randint(-100, 100))
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
print(generate)
main()
You're not calling the generate method - you're literally printing the method itself. I think that you meant print(generate()).
That being said, print(generate()) doesn't make sense either because generate() doesn't return anything - it already prints. If you want to print the result of generate in main, you should return the result instead of printing. If you do that, though, the generate function wouldn't make much sense in the first place because all it would do is return the result of random.randint(-100, 100). In that case, you should just call that method "directly."
So, the corrected versions could be any one of the following:
def generate():
print(random.randint(-100, 100))
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
# Let the generate() function print
generate()
or
def generate():
return random.randint(-100, 100)
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
print(generate())
However, in this second version, the generate function is kind of pointless; it would be better to just do:
def main():
howMany=int(input('How many random numbers do you want: '))
for count in range(howMany):
print(random.randint(-100, 100))

How do I shuffle the print statement of 3 separate functions? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
def a():
print(a)
def b():
print(b)
def c():
print(c)
How do I shuffle a, b and c? I cannot print a,b,c out of the function because there is additional code that I haven't mentioned here in order to simplify the question. I've tried putting all 3 inside random.shuffle() and also tried to associate variables with each function and tried to shuffle the variables (this also doesn't work out because of the code inside each function).
Send help.
The issue you are most likely running into is that you calling the functions inside of your shuffle. Just put the functions themselves without calling them and you can easily do this:
random.shuffle([a,b,c]) # correct
# vs.
random.shuffle([a(),b(),c()]) # incorrect, calls functions before shuffle
Then you can do a for loop and call them or whatever you need:
for f in random.shuffle([a,b,c]):
f()

Difference among Yield vs. Print vs. Return [closed]

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 1 year ago.
Improve this question
Two questions/clarifications:
Most people may ask the difference between yield and return.
def square(n):
for i in range(n):
yield i**2
for i in square(10000000000):
print(i)
I understand this is a way to run the 'function' in a generator way. If we directly run print([i**2 for i in range(10000000000)]) or this way
def square():
return [i**2 for i in range(10000000000)]
Python will run almost infinite time. However, if we run in the generator way, we will save a lot of memories, and Python can keep printing the squared numbers. In the generator, we directly print out the result we got and do not save it anywhere. However, in a function-return way, we will save the results into a list so it will waste a lot of memories and time. Am I correct about this?
My another question is yield vs. print: if we want to save memories and hope to directly print out the results, then why don't we just use print to directly print out the result, like:
def square(n):
for i in range(n):
print(i**2)
square(10000000000)
Python will do the same thing as the yield-generator way, right? So what is the difference between yield and print? Thanks!
Depends on the purpose and the caller.
When you are print-ing, you are calling a console writer in the loop. Thus print sends to a fixed and forced destination.
When you are yielding, you are not calling anything, but simply return-ing your output in gradual way to "any" caller which can take it and do whatever it like.

Bind the output of a method before using or call the method when you need its output? [closed]

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 1 year ago.
Improve this question
In both examples, class.method() returns a list.
Example A:
if class.method():
for i in class.method():
# do stuff
Example B
list = class.method()
if list:
for i in list:
# do stuff
Which is better? It would seem to me that in some languages (but I don't know which), example A would result in class.method() being needlessly evaluated twice, and example B would be best practice. However, perhaps other languages (again not knowing which) might retain the output of a method in memory in case that method is called again, therefore avoiding having to do the same evaluation twice and resulting in little difference between examples A and B. Is this so? If so, can you give examples of a language for each case? And the real reason for the question: which is best practice in Python?
Unless your Python interpreter has JIT capabilities, the method will be evaluated every time you call it.
And even when the JIT compilation is possible, methods have to be proven by the compiler / interpreter that they do not have any side effects, that is they are deterministic.
For example, consider a method that pulls data from a database or a method that contains a call to a random number generator:
import random
def method():
return random.uniform(0.0, 1.0)
Output of such a method cannot be saved in memory because the second time you call it, it may change.
On the other hand, getter methods that accumulate data are a great example of a deterministic method, given that they do not call a non-deterministic method in their body.
from dataclasses import dataclass
#dataclass
class Example:
a : list
b : list
def method(self):
return self.a + self.b
In practice, you are better of to not assume anything from the compiler / interpreter and do these small, easy to do optimizations yourself. You also have to consider that your code can be run on multiple platforms, which further complicates things.
So I would recommend you to call the method only once and save its output in a temporary variable:
result = class.method()
if result :
for i in result:
# do stuff
And given that it's Python, I recommend to ask for forgiveness with the try keyword if most of the time you run the method, its output is not None:
result = class.method()
try:
for i in result:
# do stuff
except TypeError:
pass

python passing dictionary parameter with key [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I want to make a function call with a dictionary like:
valueattime(simulaton_01['Temperature_05'], 20)
but I always get a syntax error with the following function
def valueattime(experiment[key], time):
...
It works with simple parameters. But for autocompletion sake it would be great to pass the parameters in the dictionary-form.
Any ideas?
You don't need to change the function signature to pass parameters directly from the dictionary:
def valueattime(temperature, time):
...
valueattime(simulation_01['temp_05'], 20) # this works just fine
Python will first run simulation_01['temp_05'] to retrieve the value, and pass it as temperature to the function.
You should pass it as a regular argument:
def valueattime(temp, time):
pass
a = {'some_key': 'some_value'}
valueattime(a['some_key], 20)
This works!
To supply dictionary items to a function, you can use dictionary comprehension:
new_dict = {k: valueattime(v) for k, v in a.iteritems()}
Remember it'a all objects...
def valueattime(temp, time)
Defines a method taking two input parameters, two object which are referred to by the names temp and time
simulation_01['temp_05'] return an object, so calling your method like: valueattime( simulation_01['temp_05'], 20 ) should be what you are looking for

Categories

Resources