Python can't implement timeit module [closed] - python

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
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.
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.
Improve this question
This is a basic exercise. I just don't know hot to implement the timeit module correctly. I keep recieving syntax errors
import timeit
import random
def bubblesort(LAux):
for i in range(len(LAux)):
exchange = False
for j in range(len(LAux)-1):
if LAux[j] > LAux[j+1]:
tmp = LAux[j+1]
LAux[j+1] = LAux[j]
LAux[j] = tmp
exchange = True
if not exchange:
break
return(LAux)
a=int(input("Size of list: "))
lst = [0]*a
for i in range(a):
lst[i] = random.randint(1,100)
print(bubblesort(lst))
print(timeit.timeit()

You seem to have misinterpreted the function of timeit.timeit - the idea is that you tell it what to actually time, and it then times it. Normally, it does the thing you're timing many, many times, so you can get a meaningful average. This means it also needs to provide a 'setup' argument, as the list should presumably be different for each test. Refer to the examples in the documentation if you need - I normally find that they're easy enough to suit to your purpose. I've implemented timeit below:
a=int(input("Size of list: "))
n = 100000
setup = "lst = [random.randrange(100) for _ in range(a)]"
time = timeit.timeit("bubblesort(lst)", setup=setup, globals=globals(), number=n)
print("{} sorts took {}s".format(n, time))
Of course, if you're using IPython you can do something like this:
In [1]: from bubble import bubblesort
In [2]: from random import randrange
In [3]: %timeit bubblesort([randrange(100) for _ in range(50)])
10000 loops, best of 3: 175 µs per loop
Maybe you were expecting timeit() to tell you just how much time has passed. If so, this could be done using the time module, quite simply.
import time
start_time = time.time()
bubblesort(lst)
time_taken = time.time() - start_time
print("One sort took {}s".format(time_taken))
On another note, I'd recommend using a different name for the argument "Laux". As you can see, SO's syntax highlighting thinks it's a class, as normally anything starting with a capital letter is a class. Laux also doesn't particularly tell me as an outsider what it is, although I can infer from the name bubblesort.

Related

How would I be able to have certain lines of code be executed randomly? [duplicate]

This question already has answers here:
Percentage chance to make action
(4 answers)
Closed 10 months ago.
I feel this should be an obvious answer, however, I am having issues coding a personal project of mine. How would I be able to have certain lines of code be executed randomly?
Not from the project itself but the principles are still, say for example I would want the following code to be executed every 1/1000 times or so.
print("Lucky!")
How would I exactly be able to do that?
Set a trace function that will have a 1/1000 chance to print:
import random, sys
def trace(frame, event, arg):
if random.random() < 1/1000:
print("Lucky!")
return trace
sys.settrace(trace)
You're welcome to test it with a 1/2 chance.
Generate a random integer in the range [0,1000). Pick any single value in the range, and check for equality to see if you should print.
import random
def lucky():
if random.randrange(1000) == 42:
print("Lucky!")

Beginner python3 question about elif statement syntax and the use of print_function [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 2 years ago.
Improve this question
Trying to build a simple script for returning disk, cpu usage and network connectivity checks. I keep getting errors in my elif statement syntax. I've tried revising this for 3 days and finally am not getting errors in the str format line 36 but now i get an invalid syntax error on line 37 (line containing only "else:". I read that in earlier python versions you had to import print_function, which is why it is listed, though I believe you shouldn't need to do this in Python3. Any suggestions or insight into why this error is occurring would be very much appreciated.
#!/usr/bin/env python3
import shutil
import psutil
import print_function
from network import *
def dsk_free(disk):
df = shutil.disk_usage(disk)
fre = df.free / df.total * 100
dsk_out = 'Disk usage = {}%'.format(fre)
return (dsk_out)
def cpu_ok():
cpuse = psutil.cpu_percent(1)
cpu_out = 'Cpu usage = {}%'.format(cpuse)
return (cpu_out)
def check_disk_usage(disk):
du = shutil.disk_usage(disk)
free = du.free / du.total * 100
return free > 20
def check_cpu_usage():
usage = psutil.cpu_percent(1)
return usage < 75
x = dsk_free
y = cpu_ok
if not check_disk_usage("/") or not check_cpu_usage():
print("ERROR! Shut down immediately!")
elif check_connectivity() and check_localhost():
print("Everything is awesome! Disk Usage is {}% and Cpu usage is {}%".format(dsk_free(),cpu_ok())
else:
print("Network connection failure!")
if not check_disk_usage("/") or not check_cpu_usage():
print("ERROR! Shut down immediately!")
elif check_connectivity() and check_localhost():
print("Everything is awesome! Disk Usage is {}% and Cpu usage is {}%".format(dsk_free(),cpu_ok())
else:
print("Network connection failure!")
in your second elif statement, where you have your print statement, you are missing the finishing ), add one more ) at the end and you should be good to go

function start to run in the first second of the minute [closed]

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 5 years ago.
Improve this question
I want a function start to run in the first second of the minute but i can't do it
this is my code
import datetime
now = datetime.datetime.now()
while not (now.second == "01"):now = datetime.datetime.now()
Your code doesn't work because you're comparing a number (now.second) to a string "01". In Python numbers and their string representations are not equal (unlike some other programming languages), so this will never work.
Try comparing with 1 (or maybe 0 if you really want the top of the minute). And maybe instead of busy-looping (which will use all of one core of your CPU while waiting), you should perhaps instead use time.sleep to wait until the start of the next minute.
import datetime
import time
now = datetime.datetime.now()
sec = now.second
if sec != 0:
time.sleep(60-sec)
# it should be (close to) the top of the minute here!
There's always some unpredictability when dealing with time on a computer, since your program might be delayed from running by the OS at any moment (more likely if your CPU is very busy). I'd not worry about it too much though, likely it's good enough to be very close to the right time.
import time
while True:
if time.strftime("%S") == "01":
#Run Your Code
time.sleep(59)
That would pound your system like crazy, give it a little room to breathe:
import time
while True:
current_seconds = time.gmtime().tm_sec
if current_seconds == 1:
print("The first second of a minute...")
time.sleep(0.9) # wait at least 900ms before checking again
You can further streamline it by calculating how much time to wait before you start checking again - if you're interested only in the first second you can safely sleep until the end of the minute.

class and functions in python [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 8 years ago.
Improve this question
I'm new to Python and I'm trying classes and objects, I have this script:
#!/usr/bin/env python
class test:
def __init__(self, username):
self.username = username
def name_again(self):
for i in range(0-4):
print ("username is %s" %self.username)
ahmed = test('ahmbor')
ahmed.name_again()
I'm expecting this script to print "username is ahmbor" 5 times
When I run this script, I have nothing
Please help find what's wrong with this
You are telling range() to loop over 0-4 (subtract four from zero), which is -4. Because the default is to start at 0 and count up, that is an empty range:
>>> range(0-4)
range(0, -4)
>>> len(range(0-4))
0
Use a comma instead, and use 5 to loop 5 times, not 4. The endpoint is not included:
>>> len(range(0, 4))
4
>>> len(range(0, 5))
5

Best Python way to harvest user entropy from keystrokes a la PGP? [closed]

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
Does anyone recall PGP prompting a user to "generate some entropy" by striking random keys?
PGP would measure the entropy as it was being collected, indicating to the user with a cool little progress bar, and internally would time the key strokes, do some processing and use this as a seed for something or other.
I want to make a quick routine (console app) that does a similar "entropy collection" step in python, but I'm at a loss regarding a number of issues :
Best method of timing
Best method of collecting individual keystrokes
Best method to display cool progress bar back to user
Ideas about processing step, or actual details of the PGP step.
Best in the above means :
Tightest cleanest code
Most accurate (as in timing to picosecond or something)
Most pythonic/functional and using the standard library
So yeah :
def gen_user_random():
from Fourganizical import pack8
import time,sys
print 'Hey there user, start a-bashing that keyboard to make some randomness.'
keystimes = []
lasttime = None
while len(keystimes) < 20:
key = getch()
timenow = (time.time() + time.clock())
if lasttime:
timesince = timenow-lasttime
keystimes.append(int(timesince*100000000000000000))
lasttime = timenow
print 'Check out this *nasty* random number you made!'
rnum = int(''.join([str(x) for x in keystimes]))
print rnum
print 'And OMG here is that *nasty* set of bytes it made!'
rbytes = pack8(rnum)
print
sys.stdout.write(''.join(rbytes))
print
print
return keystimes
This creates some really nasty randomness.
pack8 just takes an integer of any length and outputs it in radix 256 as a sequence of bytes.

Categories