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.
Related
I am making a little math game, similar to zeta mac. Everything seems to be working well. Ideally I would like this console output to erase incorrect answers entered by the user, without reprinting the math problem again for them to solve. Is something like this possible?
For example, I may prompt the user to answer "57 + 37 = " in the console, then if they type 24 (console would look like this "57 + 37 = 24", I would like the 24 to be erased, and for the "57 + 37 = " to remain, allowing the user to guess again, without the same equation having to be printed again on a line below.
Here is the source code (sorry if its messy, I just started learning python):
import random
import time
def play(seconds):
start_time = time.time()
score = 0
while True:
current_time = time.time()
elapsed_time = current_time - start_time
a = random.randint(2, 100)
b = random.randint(2, 100)
d = random.randint(2, 12)
asmd = random.choice([1, 2, 3, 4])
if (asmd == 1):
solve = a + b
answer = input("%d + %d = " % (a, b))
elif (asmd == 2):
if (a > b):
solve = a - b
answer = input("%d - %d = " % (a, b))
else:
solve = b - a
answer = input("%d - %d = " % (b, a))
elif (asmd == 3):
solve = a * d
answer = input("%d * %d = " % (a, d))
else:
solve = d
c = a * d
answer = input("%d / %d = " % (c, a))
while (solve != int(answer)):
answer = input("= ")
score += 1
if elapsed_time > seconds:
print("Time\'s up! Your score was %d." % (score))
break
play(10)
Just use add these two lines after answer = input("= "):
sys.stdout.write("\033[F") #back to previous line
sys.stdout.write("\033[K") #clear line
import random
import time
import sys
def play(seconds):
start_time = time.time()
score = 0
while True:
current_time = time.time()
elapsed_time = current_time - start_time
a = random.randint(2, 100)
b = random.randint(2, 100)
d = random.randint(2, 12)
asmd = random.choice([1, 2, 3, 4])
if (asmd == 1):
solve = a + b
answer = input("%d + %d = " % (a, b))
elif (asmd == 2):
if (a > b):
solve = a - b
answer = input("%d - %d = " % (a, b))
else:
solve = b - a
answer = input("%d - %d = " % (b, a))
elif (asmd == 3):
solve = a * d
answer = input("%d * %d = " % (a, d))
else:
solve = d
c = a * d
answer = input("%d / %d = " % (c, a))
while (solve != int(answer)):
answer = input("= ")
if solve != int(answer):
sys.stdout.write("\033[F") #back to previous line
sys.stdout.write("\033[K") #clear line
score += 1
if elapsed_time > seconds:
print("Time\'s up! Your score was %d." % (score))
break
play(10)
Removing characters from the end of the input is probably not the best approach as you aren't quite sure how many characters there will be (depends on the number).
The answer from #QualidSai does clear the terminal but it doesn't show your formula string again. To solve this I'd store the formula string that you print as part of your input as a string variable, then you can use that when looping. For example:
import random
import time
import sys
def play(seconds):
start_time = time.time()
score = 0
while True:
current_time = time.time()
elapsed_time = current_time - start_time
a = random.randint(2, 100)
b = random.randint(2, 100)
d = random.randint(2, 12)
asmd = random.choice([1, 2, 3, 4])
if (asmd == 1):
solve = a + b
question = "%d + %d = " % (a, b)
elif (asmd == 2):
if (a > b):
solve = a - b
question = "%d - %d = " % (a, b)
else:
solve = b - a
question = "%d - %d = " % (b, a)
elif (asmd == 3):
solve = a * d
question = "%d * %d = " % (a, d)
else:
solve = d
c = a * d
question = "%d / %d = " % (c, a)
answer = False
while (solve != int(answer)):
answer = input(question)
sys.stdout.write("\033[F")
sys.stdout.write("\033[K")
score += 1
if elapsed_time > seconds:
print("Time\'s up! Your score was %d." % (score))
break
play(10)
def main():
a,b=numbers(5,1,100)
print("Number of Odd values = " + str(a))
print("Number of Even values = " + str(b))
def numbers(N,A,B):
even_count,odd_count=0,0
for i in range(N):
n=random.randint(A,B)
if n%2==0:
even_count+=1
else:
odd_count+=1
return odd_count, even_count
main()
Need fix this code.i don't know when the number can't go through.
print("Number of Odd values = " + str(a))
NameError: name 'a' is not defined
Try this:
import random
def numbers(N,A,B):
even_count,odd_count=0,0
for i in range(N):
n=random.randint(A,B)
if n%2==0:
even_count+=1
else:
odd_count+=1
return odd_count, even_count
a,b=numbers(5,1,100)
print("Number of Odd values = " + str(a))
print("Number of Even values = " + str(b))
you need to make sure the print statements are coming inside the scope of function main()
and import module random at the top of the script. below is the formatted version.
def main():
a,b=numbers(5,1,100)
print("Number of Odd values = " + str(a))
print("Number of Even values = " + str(b))
def numbers(N,A,B):
even_count,odd_count=0,0
for i in range(N):
n=random.randint(A,B)
if n%2==0:
even_count+=1
else:
odd_count+=1
return odd_count, even_count
main()
I guess you need you to reorder the code,try this:
import random
def numbers(N,A,B):
even_count, odd_count = 0, 0
for i in range(N):
n = random.randint(A, B)
if n % 2 == 0:
even_count += 1
else:
odd_count += 1
return odd_count, even_count
def main():
a, b = numbers(5, 1, 100)
print("Number of Odd values = " + str(a))
print("Number of Even values = " + str(b))
main()
def get_positive_int():
while True:
n = int(input("Height: "))
if n > 0 and n < 9:
return n
def print(n):
for i in range(n):
print(" " * (n - i) + "#" * i + " " + "#" * i)
def main():
n = get_positive_int()
print(n)
if __name__ == "__main__":
main()
and here is my error message:
TypeError: 'str' object cannot be interpreted as an integer
Since int(input()) has already translate n into an int I an curious why would n recieve an string?
The issue is that you have defined a custom function named print() and you call print() again in the loop. So, in the next recursion call, you call the custom defined print() with str object in print(" " * (n - i) + "#" * i + " " + "#" * i) and range() then throws the error since it expects an integer but it got an str object.
Change the name of the print() method to something else:
def get_positive_int():
while True:
n = int(input("Height: ").strip())
if n > 0 and n < 9:
return n
def print_0(n):
for i in range(n):
print(" " * (n - i) + "#" * i + " " + "#" * i)
def main():
n = get_positive_int()
print_0(n)
if __name__ == "__main__":
main()
Whilst attempting CS50's PSET6, I was trying to create a double-half pyramid of a size specified by the user.
The pyramid is fine but there's a random new line after the user input and before the pyramid starts. How can I fix it? Any help is appreciated :D
The code is as follows
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
def main():
hashHeight = height()
create(hashHeight)
# get height
def height():
h = int(input("Height: "))
if h >= 1 and h <= 8:
return h
else:
height()
#print hash
def create(x):
for i in range(1, x + 1):
print(" " * (x - i) + "#" * i + " " + "#" * i)
main()
I have a program that is supposed to ask how many primes to calculate then write them all to a text file. However, it creates the file then dosen't run.
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
while(True):
constantcall()
Your problem is the code:
while len(primes) < int(ask):
k = 2
at this point len(primes) is less than int(ask), and there is nothing that add items to primes, so infinite loop.
Your code must be (in order to avoid infinite loop):
def constantcall():
j = 2
chk = 1
f = open("primes.txt", "w")
primes = []
notprimes = []
ask = input("how many primes? ")
while len(primes) < int(ask):
k = 2
while not(k==j) and not(j%k==0):
k = k + 1
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close
return(" ")
if __name__ == '__main__':
constantcall()
Using Sieve of Eratosthenes algorithm
You could use the algorithm Sieve of Eratosthenes:
def primes(count):
"""
Returns a list with the first `count` prime numbers.
An advice: If you will be using this functiona a lot it's better
for performance if you precalculate cribe.
"""
# Calculate primes up to 50, you can change this to your preference.
MAX = 50
sieve = [1] * MAX
for i in range(2, int(MAX ** 0.5) + 2 ):
for j in range(i + i, MAX, i):
sieve[j] = 0
# Finally primes are indexes in the list that still has 0.
result = []
for index, elem in enumerate(sieve):
if elem == 1: result.append(index)
return result[1:count + 1]
Your code can then be rewrited as:
def constantcall():
f = open("primes.txt", "w")
ask = int(input("how many primes? "))
prime_numbers = primes(ask)
f.writelines(map(lambda x: "{0}\n".format(x), prime_numbers))
if __name__ == '__main__':
constantcall()
Your code does nothing.
while len(primes) < int(ask):
k = 2
Is useless.
while not(k==j) and not(j%k==0):
k = k + 1
Is useless as j is always 2.
if k == j:
primes.append(j)
f.write(str(j)+"\n")
else:
notprimes.append(j)
Here you append 2 to primes once.
if len(primes) >= 1000*chk:
chk = chk + 1
print("There have been " + str(len(primes)) + " primes counted so far")
j = j + 1
print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
f.close()
return
So len(primes) is always 1.
Here is a solution. Sorry for C language, but you could easily pythonize it.
#include <stdio.h>
typedef unsigned long long ull;
int main(){
ull numb=10000,stop=20000;
ull i,c;
int cnt;
printf("Here are the primes between %lld and %lld :\n\n",numb,stop);
while(numb<=stop){
for(i=1;i<=numb;++i){
if(!(numb%i)) ++cnt;
}
if ((cnt==2) || (i==1)) printf("%lld; ",numb);
cnt=0;
++numb;
}
printf("\n\nThat's all\n");
}