Why doesn't this for loop in Python take ages? [duplicate] - python

This question already has answers here:
How do I do exponentiation in python? [duplicate]
(3 answers)
Closed 6 years ago.
I am running this little loop on a Jupyter notebook
import time
def time_loop(reps):
start = time.clock()
count = 0
for i in range(reps):
count += 1
return time.clock() - start
time_loop(10000^100)
No matter what I enter as an argument, I seem to always get an output around 0.003
0.0031050000000050204
What is going on?
One guess is that python understands that the result of the loop will simply be count = reps, and quits the loop?
But if I run this instead
import time
import numpy as np
def time_loop(reps):
start = time.clock()
count = 0
for i in range(reps):
count += np.sin(reps)
return time.clock() - start
time_loop(10000^100)
It does take longer as I increase the argument, even though the result of the loop is still quite simply count = reps*sin(reps).

^ is xor and not exponentation:
>>> 10000^100
10100
That's a big number but not like with exponentation: **, that returns:
>>> 10000**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
That also takes a "while" to iterate over.
A good reference for the operators and their precedence is avaiable in the python documentation:
^ - Bitwise XOR
** - Exponentiation

Related

What is the concept on Start:Stop:Step [duplicate]

This question already has answers here:
Understanding slicing
(38 answers)
Closed 3 months ago.
I am new to python and I seem to be unable to understand the concept in Start:Stop:Step. For example
word = "Champ"
print (word[0:5:2])
why do I get cap as I result ? if someone could help me with this I would truly appreciated
I tried using different numbers to see what the outcome was but even there I was not able to understand why was I getting that outcome
Let's see this way:
word = "Champ"
print (word[0:5:2])
# you are taking index=0, then index=0+2, then index=0+2+2
# then index=0+2+2+2 (don't have this)
# so you got 0,2, and 4
# Hope, makes sense
print(word[0])
print(word[2])
print(word[4])
Maybe it's best to imagine it as a simple while-loop that creates an output. Take this example:
string = "Champ"
start = 0
stop = 5
step = 2
index = start
output = ""
while index < stop and index < len(string):
output += string[index]
index += step
print(output)
# >>> Cap
Here the current index starts at the start parameter, and then adds the current item to the output, then increments by the value step. If ever the current index is larger than the length of the original string, or larger than the stop value, the while-loop exits. Hope this helps!

Acessing a random array a given number of times without using the random module (Python) [duplicate]

This question already has answers here:
Shuffle an array with python, randomize array item order with python
(11 answers)
How can I randomly select an item from a list?
(17 answers)
Closed 2 years ago.
For instance, let's say I have a random array [5,2,1,3,6,4] and I want to access it at least 6 times (i.e. 6 == len(array)) (the acess order doesn't matter, nor does it matter that I've accessed them all). How can I randomly access the whole array without popping any of the values ?
In other words, I am trying to write a function find_new_index which takes an index i such that:
arr = [5,2,1,3,6,4]
i=0
x = 0
while i < 6:
access = arr[i]
x+=1
i = i + find_new_index(i)
assert(x >= 6)
The idea is that this function works for any random array of size N which has random values from 1 to N.
PS : The easy way to write find_indexis to generate a random number within it. However, I want to know if it's possible to write this function without loops or any function calls.
This differs from other questions, since I don't want to use the Random Module.
You can use the random.choice(my_list) function.
import random
arr = [5,2,1,3,6,4]
i = 0
while i < 6:
access = random.choice(arr)
#do whatever you want
i += 1
For example, print the access adding a print(access) instead of the comment can output something like:
2
2
6
6
4
1
you probably want to use the random module:
import random
arr=[5,2,1,3,6,4]
access =[]
for i in range(len(arr)):
access.append(arr[random.randint(0,len(arr))])
print(access)
>>> [1,2,1,4,4,6]
UPDATE
This differs from other questions, since I don't want to use the Random Module.
the one way i think you can make it is with the time module....
from datetime import datetime
def get_random(mini,maxi):
timestamp = datetime.now().timestamp() * 1000
return timestamp % maxi + mini
# rest of the code ...
for i in range(len(arr)):
access.append(arr[get_random(0,len(arr))])

Why won't less-than operator work between these two strings? [duplicate]

This question already has answers here:
Ordering of string representations of integers [duplicate]
(6 answers)
Closed 2 years ago.
Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing? Here's my code, super new to python. Struggling to understand why if I use < it always thinks is less than even though it will print a higher number. If I use greater than it works just fine. What am I missing?
import time
t=time.localtime()
msttime=time.strftime("%H",t)
if(msttime < '2'):
print(msttime)
else:
print("This calculation believes msttime is greater than 2")
This code will give you the expected result:
import time
t = time.localtime()
msttime = time.strftime("%H", t)
if (int(msttime) < 2):
print(msttime)
else:
print("This calculation believes msttime is greater than 2")
The reason is that "18" < "2" lexographically, but 18 > 2 numerically. This is because the lexographical comparison has no regard for the second digit. Since 1 is before 2, the comparison ends there. In the numerical comparison, all digits are accounted for.

Capped at 32-bit maximum, why is my code not able to pull the solution above this maximum? [duplicate]

This question already has answers here:
Numpy is calculating wrong [duplicate]
(2 answers)
Closed 3 years ago.
I am attempting to solve problem 8 of projecteuler. I am having difficulty understanding exactly why my code is not outputting the correct solution. I am aware that the solution to this problem is above the 32 bit maximum, but I do not know how to allow python to work with numbers above that within my code.
For reference, the original question states : "Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?"
from numpy import prod
f = 7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450
z = list(int(i) for i in str(f))
a1 =[]
start = 0
end = start + 13
while end <= len(z):
a1.append(prod(z[start:end]))
start+=1
end+=1
a = a1.index(max(a1))
print(a1[a]) #prints the product solution
print('---')
dimlen=end-start
newstart = a
newend=a+dimlen
print(z[newstart:newend]) #prints the integers that build the solution
I keep getting the number 2091059712, (the solution is 23514624000)
I think it might be numpy.prod. It might be preserving the input type and wrapping the value. Try using:
def prod(it):
p = 1
for m in it:
p *= m
return p

Python time.sleep method not working properly [duplicate]

This question already has answers here:
How to print one character at a time on one line?
(4 answers)
How to make it look like the computer is typing? [duplicate]
(1 answer)
Closed 5 years ago.
I have written this small code in Python. It should print every character in a string with a small sleeptime between them...
import time, sys
def writeText(string, t):
i = 0
while i < len(string):
sys.stdout.write(string[i])
time.sleep(float(t))
i += 1
writeText("Hello World", 0.5)
but it only prints the whole string after 0.5 seconds... I often have this issue but I haven't found a solution yet.
sys.stdout.flush() might solve your problem.
import time, sys
def writeText(string, t):
i = 0
while i < len(string):
sys.stdout.write(string[i])
time.sleep(float(t))
i += 1
sys.stdout.flush()
writeText("Hello World", 0.5)
You should add
sys.stdout.flush()
after writing, to force the output of the text.

Categories