I have a piece of code where I am trying to export the output. I tried this, but the only problem was where and what ~str~ had to be.
with open("piStorage.txt", "w") as fp:
fp.write(~str~)
Here is my code to find ~str~
import csv
import time
start_time = time.time()
def calcPi(limit):
q, r, t, k, n, l = 1, 0, 1, 1, 3, 3
decimal = limit
counter = 0
while counter != decimal + 1:
if 4 * q + r - t < n * t:
yield n
if counter == 0:
yield '.'
if decimal == counter:
print('')
break
counter += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
def main():
pi_digits = calcPi(int(input(
"Enter the number of decimals to calculate to: ")))
i = 0
for d in pi_digits:
print(d, end='')
i += 1
if i == 200:
print("")
i = 0
if __name__ == '__main__':
main()
print("--- %s seconds ---" % (time.time() - start_time))
with open("piStorage.txt", "w") as fp:
fp.write(main)
I tried using this, but it doesn't work. It came up as:
"
Traceback (most recent call last):
File "c:\Users\William\Desktop\pi.py", line 48, in <module>
fp.write(main)
TypeError: write() argument must be str, not function
"
with open("piStorage.txt", "w") as fp:
fp.write(main)
You can use contextlib.redirect_stdout.
def main():
pi_digits = calcPi(int(input(
"Enter the number of decimals to calculate to: ")))
i = 0
from contextlib import redirect_stdout
with open("piStorage.txt", "w") as fp:
with redirect_stdout(fp):
for d in pi_digits:
print(d, end='')
i += 1
if i == 200:
print("")
i = 0
fp.write(main)
Since you're using a function name without parentheses (), this refers to the function object itself.
I think you meant to call the function by using parentheses:
fp.write(main())
This will call main() and write its returned value to the file.
However in this case that still won't work, because the way you've written main(), it doesn't actually return anything.
You need to change main() so that it writes to the file directly, instead of calling print().
import threading
# The number to add.
# Change this for your experiment
n = 1000000
# Result variable
result = 0
def thread1(count):
global result
x = 0
for i in range(1, count + 1):
x = x + i
result = x
def thread2():
global result
result = result * 3
th1 = threading.Thread(target = thread1, args=[n, ])
th2 = threading.Thread(target = thread2)
th1.start()
th2.start()
correct = n * (n + 1) / 2 * 3
print("Correct result is %d." % correct)
print("Final result is %d." % result)
if result == correct:
print("CORRECT!")
else:
print("WRONG!")
When running the code with n = 10, we will get correct result. But when running the code with n= 1000000, we would get incorrect results. May I know what's wrong with n= 1000000 that leads to incorrect execution?
im rather new to python and found someones lottery simulation in github. After playing around with it for a while i wanted to add a counter, that counts the number of matches of your Number out of the total draws.
I don't know if it is because i did not write the code myself, but i can't seem to make it happen. I've tried some of pythons counter modules bu that did'nt seem to be the right thing.
Heres my code:
import random
import time
### TODO - Refactor GetDrawNumbers (add timers)
### TODO - Refactor CheckNumbers
def GetDrawNumbers():
drawNumbers = []
for i in range(6):
x = None
while (x == None or x in drawNumbers):
x = random.randint(1, 49)
drawNumbers.append(x)
return drawNumbers
def CheckNumbers(myTicket, actualNumbers):
numbersMatched = 0
for number in myTicket:
if number in actualNumbers:
numbersMatched += 1
return numbersMatched
### Script starts here
startTime = time.perf_counter()
myNumbers = [4, 8, 15, 16, 23, 42]
for draw in range(2000):
drawNumber = draw + 1
thisWeeksDraw = GetDrawNumbers()
numbersMatched = CheckNumbers(myNumbers, thisWeeksDraw)
##print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
if numbersMatched == 4:
print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
count = numbersMatched
print("Total matches: " + str(count))
endTime = time.perf_counter()
elapsedTime = endTime - startTime
print("Completed in " + str(elapsedTime) + " seconds!")
If anyone knows a way to implement a counter, that counts the number of times this the program gets 3,4,5 or 6 correct matches i would be super relieved! It's not that this project would be super important but solving the problem would be a milestone for me and my learning process!
Thanks in advance and best wishes!
How about this where I have added a check of the numbersMatched value and increment a counter whenever it is 3 or more
import random
import time
### TODO - Refactor GetDrawNumbers (add timers)
### TODO - Refactor CheckNumbers
def GetDrawNumbers():
drawNumbers = []
for i in range(6):
x = None
while (x == None or x in drawNumbers):
x = random.randint(1, 49)
drawNumbers.append(x)
return drawNumbers
def CheckNumbers(myTicket, actualNumbers):
numbersMatched = 0
for number in myTicket:
if number in actualNumbers:
numbersMatched += 1
return numbersMatched
### Script starts here
startTime = time.perf_counter()
myNumbers = [4, 8, 15, 16, 23, 42]
countOfThreeOrMoreMatched = 0
for draw in range(2000):
drawNumber = draw + 1
thisWeeksDraw = GetDrawNumbers()
numbersMatched = CheckNumbers(myNumbers, thisWeeksDraw)
##print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
if numbersMatched >= 3:
countOfThreeOrMoreMatched += 1
if numbersMatched == 4:
print("Week " + str(drawNumber) + " numbers : " + str(thisWeeksDraw) + " (" + str(numbersMatched) + " matched)")
print(f"Count with 3 or more matches {countOfThreeOrMoreMatched}")
count = numbersMatched
print("Total matches: " + str(count))
endTime = time.perf_counter()
elapsedTime = endTime - startTime
print("Completed in " + str(elapsedTime) + " seconds!")
Hello wonderful people of the internet.
I am having difficulty writing to two files at once. The code I am using looks like this. I would be grateful for any help.
with open("solutionnoiseoneonemode.txt", "w+") as solution, open("projectionononemode.txt", "w+") as projection:
solution.write("%s " % 0)
for j in np.arange(Nx):
if j % 10:
solution.write("%e " % x[j])
solution.write("\n")
projection.write("%s " % 0)
initialp = np.matmul(projectionmatrix,q0)
print("initial p")
print(initialp)
projection.write("%e " % initialp)
projection.write("\n")
solution.write("%s " % 0)
for j in np.arange(Nx):
if j % 10:
solution.write("%e " % q[j])
solution.write("\n")
for i in range(np.int(T)):
print(i)
tstep = i*timestep
print(tstep)
#print(q)
qnew = np.matmul(inverted, (q - timestep * (q ** 3) + beta(x)))
qproj = np.matmul(projectionmatrix, qnew)
print(qproj)
if i % 10 == 0:
solution.write("%s " % tstep)
for j in np.arange(Nx):
if j % 10 == 0:
solution.write("%e " % q[j])
solution.write("\n")
q = qnew
Nothing comes out in the projection file!! This is super annoying.
This was a take home test question (which I mailed 20 minutes ago if Prof. Gruhn is ruthlessly scouring stackoverflow). First computer science course, Intro using Python. Using the book "Starting Out With Python 2nd Ed." The test was basically on creating our own module libraries, reading and writing to a file, and try/except logic.
The first part asked to create a lottery mumber simulator. One that generated nonunique numbers, the other unique, non repeating numbers. Every answer I saw on here utilized lists, which is sadly the next chapter, and we were expressly forbidden from using them.
My code for this section:
import random
def ballPickerOne():
a = random.randint(1, 59)
b = random.randint(1, 59)
c = random.randint(1, 59)
d = random.randint(1, 59)
e = random.randint(1, 59)
f = random.randint(1, 35)
showNumbers(a,b,c,d,e,f)
def ballPickerTwo():
a = random.randrange(1,59,2)
b = random.randrange(1,59,3)
c = random.randrange(1,59,5)
d = random.randrange(1,59,7)
e = random.randrange(1,59,11)
f = random.randint(1,35)
showNumbers(a,b,c,d,e,f)
def showNumbers(a,b,c,d,e,f):
print("Your Numbers ...")
print()
print("Ball 1: ", a)
print("Ball 2: ", b)
print("Ball 3: ", c)
print("Ball 4: ", d)
print("Ball 5: ", e)
print("Red Ball: ", f)
print()
print("Good Luck")
We were required to use the showNumbers function to display the results, and in the format that would result from it. ballPickerTwo is the "unique" one, which I used prime number intervals in a failed attempt at uniqueness. I toyed with using a loop, but couldn't figure out how to display the numbers generated using showNumbers.
This is a really tedious way of doing it, but it doesn't use lists. It will pick random and unique values.
def ballPickerTwo():
a = random.randint(1, 59)
b = a
while b == a:
b = random.randint(1, 59)
c = b
while c == b or c == a:
c = random.randint(1, 59)
d = c
while d == c or d == b or d == a:
d = random.randint(1, 59)
...
Just return the values you have generated - use return in your functions. E.g.:
def ballPickerOne():
a = random.randint(1, 59)
b = random.randint(1, 59)
c = random.randint(1, 59)
d = random.randint(1, 59)
e = random.randint(1, 59)
f = random.randint(1, 35)
return a,b,c,d,e,f
showNumbers(a,b,c,d,e,f)
What if:
from random import sample, randint
def ballPickerOne():
a,b,c,d,e = sample(range(1,59), 5)
f = randint(1,35)
while f!=a and f!=b and f!=c and f!=d and f!=e:
f = randint(1,35)
return a,b,c,d,e,f
How about use an integer as the bitmap to check unique?
import random
def showNumbers(a,b,c,d,e,f):
print("Your Numbers ...")
print()
print("Ball 1: ", a)
print("Ball 2: ", b)
print("Ball 3: ", c)
print("Ball 4: ", d)
print("Ball 5: ", e)
print("Red Ball: ", f)
print()
print("Good Luck")
def ballPickerTwo():
while True:
a = random.randint(1, 59)
b = random.randint(1, 59)
c = random.randint(1, 59)
d = random.randint(1, 59)
e = random.randint(1, 59)
f = random.randint(1, 35)
m = 2**a + 2**b + 2**c + 2**d + 2**e + 2**f
if bin(m).count("1") == 6:
break
showNumbers(a,b,c,d,e,f)
This is similar to HYRY's answer in that it is using the bits in a number to remember which numbers have been selected already. This works because Python can handle arbitrarily large numbers.
import random
def showNumbers(a, b, c, d, e, f):
print("Your Numbers ...")
print()
print("Ball 1: ", a)
print("Ball 2: ", b)
print("Ball 3: ", c)
print("Ball 4: ", d)
print("Ball 5: ", e)
print("Red Ball: ", f)
print()
print("Good Luck")
def pick(cur_val):
while True:
v = random.randint(1, 59)
m = 2**v
if (cur_val & m) == 0: # bit not set, v never picked before
return (cur_val | m), v # return updated cur_val and bit number now set in it
def ballPickerTwo():
cur_val = 0
cur_val, a = pick(cur_val)
cur_val, b = pick(cur_val)
cur_val, c = pick(cur_val)
cur_val, d = pick(cur_val)
cur_val, e = pick(cur_val)
cur_val, f = pick(cur_val)
showNumbers(a, b, c, d, e, f)