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().
Related
Code implements the dynamic programming solution for global pairwise alignment of two sequences. Trying to perform a semi-global alignment between the SARS-CoV-2 reference genome and the first read in the Nanopore sample. The length of the reference genome is 29903 base pairs and the length of the first Nanopore read is 1246 base pairs. When I run the following code, I get this message in my terminal:
import sys
import numpy as np
GAP = -2
MATCH = 5
MISMATCH = -3
MAXLENGTH_A = 29904
MAXLENGTH_B = 1247
# insert sequence files
A = open("SARS-CoV-2 reference genome.txt", "r")
B = open("Nanopore.txt", "r")
def max(A, B, C):
if (A >= B and A >= C):
return A
elif (B >= A and B >= C):
return B
else:
return C
def Tmax(A, B, C):
if (A > B and A > C):
return 'D'
elif (B > A and B > C):
return 'L'
else:
return 'U'
def m(p, q):
if (p == q):
return MATCH
else:
return MISMATCH
def append(st, c):
return c + "".join(i for i in st)
if __name__ == "__main__":
if (len(sys.argv) != 2):
print("Usage: align <input file>")
sys.exit()
if (not os.path.isfile(sys.argv[1])):
print("input file not found.")
sys.exit()
S = np.empty([MAXLENGTH_A, MAXLENGTH_B], dtype = int)
T = np.empty([MAXLENGTH_A, MAXLENGTH_B], dtype = str)
with open(sys.argv[1], "r") as file:
A = str(A.readline())[:-1]
B = str(B.readline())[:-1]
print("Sequence A:",A)
print("Sequence B:",B)
N = len(A)
M = len(B)
S[0][0] = 0
T[0][0] = 'D'
for i in range(0, N + 1):
S[i][0] = GAP * i
T[i][0] = 'U'
for i in range(0, M + 1):
S[0][i] = GAP * i
T[0][i] = 'L'
for i in range(1, N + 1):
for j in range(1, M + 1):
S[i][j] = max(S[i-1][j-1]+m(A[i-1],B[j-1]),S[i][j-1]+GAP,S[i-1][j]+GAP)
T[i][j] = Tmax(S[i-1][j-1]+m(A[i-1],B[j-1]),S[i][j-1]+GAP,S[i-1][j]+GAP)
print("The score of the alignment is :",S[N][M])
i, j = N, M
RA = RB = RM = ""
while (i != 0 or j != 0):
if (T[i][j]=='D'):
RA = append(RA,A[i-1])
RB = append(RB,B[j-1])
if (A[i-1] == B[j-1]):
RM = append(RM,'|')
else:
RM = append(RM,'*')
i -= 1
j -= 1
elif (T[i][j]=='L'):
RA = append(RA,'-')
RB = append(RB,B[j-1])
RM = append(RM,' ')
j -= 1
elif (T[i][j]=='U'):
RA = append(RA,A[i-1])
RB = append(RB,'-')
RM = append(RM,' ')
i -= 1
print(RA)
print(RM)
print(RB)
This has nothing to do with python. The error message comes this line:
if (len(sys.argv) != 2):
print("Usage: align <input file>")
The code expects to be called with exactly one argument, the input file:
align path/to/input/file
You provided a different number of arguments, probably zero.
I am making a python script that lets you entire an imei number then checks if it is valid, I keep getting an error
Traceback (most recent call last):
File "program.py", line 28, in
if isValidEMEI(n):
File "program.py", line 19, in isValidEMEI
d = (int)(n % 10)
TypeError: not all arguments converted during string formatting
the code is
def sumDig( n ):
a = 0
while n > 0:
a = a + n % 10
n = int(n / 10)
return a
def isValidEMEI(n):
s = str(n)
l = len(s)
if l != 15:
return False
d = 0
sum = 0
for i in range(15, 0, -1):
d = (int)(n % 10)
if i % 2 == 0:
d = 2 * d
sum = sum + sumDig(d)
n = n / 10
return (sum % 10 == 0)
n = input("Enter number")
if isValidEMEI(n):
print("Valid IMEI Code")
else:
print("Invalid IMEI Code")
I have not really being sure what to try and do but I have looked up the error and nothing helpful/stuff I know to to interpret is showing up.
I am new to learning python so this will probalbly have a very simple sulution
I will update this with a "shortest replication of this error"
Thank you so much all help is welcome, this is for a challange I set myself so I am very determind to finish it
I have fixed it, replace n = input("enter number") with n = int(input("Enter number"))
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()
I am creating a basic RSA encryption program without using an RSA library that takes a secret message, converts each character in the string to its ASCII value, encrypts with a public key and concatenates the values, and then decrypts it using a private key and returns it to a string.
All with the principle of cipher = pow(plain,e,n) and plain = pow(cipher,d,n). My issue is that when the numbers get very large as I need d and n to be 16 digits minimum, the pow() function seems to result in an error in calculation that yields an ASCII value that is out of range to convert to a character. I've been struggling to figure out where I'm going wrong for days now. Any help is appreciated. Code below:
from random import randrange, getrandbits
def is_prime(n, k=128):
# Test if n is not even.
# But care, 2 is prime !
if n == 2 or n == 3:
return True
if n <= 1 or n % 2 == 0:
return False
# find r and s
s = 0
r = n - 1
while r & 1 == 0:
s += 1
r //= 2
# do k tests
for q in range(k):
a = randrange(2, n - 1)
x = pow(a, r, n)
if x != 1 and x != n - 1:
j = 1
while j < s and x != n - 1:
x = pow(x, 2, n)
if x == 1:
return False
j += 1
if x != n - 1:
return False
return True
def generate_prime_candidate(length):
# generate random bits
p = getrandbits(length)
#p = randrange(10**7,9*(10**7))
# apply a mask to set MSB and LSB to 1
p |= (1 << length - 1) | 1
return p
def generate_prime_number(length=64):
p = 4
# keep generating while the primality test fail
while not is_prime(p, 128):
p = generate_prime_candidate(length)
return p
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def generate_keypair(p, q):
n = p * q
#Phi is the totient of n
phi = (p-1) * (q-1)
#Choose an integer e such that e and phi(n) are coprime
e = randrange(1,65537)
g = gcd(e, phi)
while g != 1:
e = randrange(1,65537)
g = gcd(e, phi)
d = multiplicative_inverse(e, phi)
return ((e, n), (d, n))
def multiplicative_inverse(e, phi):
d = 0
k = 1
while True:
d = (1+(k*phi))/e
if((round(d,5)%1) == 0):
return int(d)
else:
k+=1
def encrypt(m,public):
key, n = public
encrypted = ''
print("Your original message is: ", m)
result = [(ord(m[i])) for i in range(0,len(m))]
encryption = [pow(result[i],key,n) for i in range(0,len(result))]
for i in range(0,len(encryption)):
encrypted = encrypted + str(encryption[i])
#encrypted = pow(int(encrypted),key,n)
print("Your encrypted message is: ", encrypted)
#return result,encrypted
return encrypted, encryption
def decrypt(e,c,private):
key, n = private
print("Your encrypted message is: ", c)
print(e)
decryption = [pow(e[i],key,n) for i in range(0,len(e))]
print(decryption)
result = [chr(decryption[i])for i in range(0,len(decryption)) ]
decrypted = ''.join(result)
print("Your decrypted message is: ",decrypted)
return result,decrypted
def fastpow(x,y,p):
res = 1
x = x%p
while(y>0):
if((y&1) == 1):
res = (res*x)%p
y = y>>1
x = (x*x)%p
return res
message = input("Enter your secret message: ")
p1 = generate_prime_number()
p2 = generate_prime_number()
public, private = generate_keypair(p1,p2)
print("Your public key is ", public)
print("Your private key is ", private)
encrypted,cipher = encrypt(message,public)
decrypt(cipher,encrypted,private)
Traceback:
File "<ipython-input-281-bce7c44b930c>", line 1, in <module>
runfile('C:/Users/Mervin/Downloads/group2.py', wdir='C:/Users/Mervin/Downloads')
File "C:\Users\Mervin\Anaconda3\lib\site-packages\spyder\util\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\Mervin\Anaconda3\lib\site-packages\spyder\util\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/Mervin/Downloads/group2.py", line 125, in <module>
decrypt(cipher,encrypted,private)
File "C:/Users/Mervin/Downloads/group2.py", line 100, in decrypt
result = [chr(decryption[i])for i in range(0,len(decryption)) ]
File "C:/Users/Mervin/Downloads/group2.py", line 100, in <listcomp>
result = [chr(decryption[i])for i in range(0,len(decryption)) ]
OverflowError: Python int too large to convert to C long
Your method multiplicative_inverse is not correct. I'm not certain what you are doing in that method with the round method and floating point division, but even if you got that part correct it would be too slow anyway, requiring O(φ) steps. The usual method for computing modular multiplicative inverses is an adaptation of the extended Euclidean algorithm, which runs in O(log(φ)2) steps. Here is a straightforward mapping from the psuedocode in the Wikipedia article to python 3 code:
def multiplicative_inverse(a, n):
t, newt = 0, 1
r, newr = n, a
while newr:
quotient = r // newr
t, newt = newt, t - quotient * newt
r, newr = newr, r - quotient * newr
if r > 1:
raise ZeroDivisionError("{} is not invertible".format(a))
if t < 0:
t = t + n
return t
I am trying to build an Action potential simulation (a graph of voltage relative to time, where the voltage values are obtained through numerically solving a couple of differential equiations). I have used the code from an online simulation of this in javaScript and am trying to translate it into python. However, due to the different ways in which python and java handle floats, I get an Overflowerror: math range error. Does anyone know how I can circumvent this in this specific situation? I am posting everything i've written and my error output:
import numpy as np
import math
import matplotlib.pyplot as plt
import random
class HH():
def __init__(self):
self.dt = 0.025
self.Capacitance = 1
self.GKMax = 36
self.GNaMax = 120
self.Gm = 0.3
self.EK = 12
self.ENa = 115
self.VRest = 10.613
self.V = 0
self.n = 0.32
self.m = 0.05
self.h = 0.60
self.INa = 0
self.IK = 0
self.Im = 0
self.Iinj = 0
self.tStop = 200
self.tInjStart = 25
self.tInjStop = 175
self.IDC = 0
self.IRand = 35
self.Itau = 1
#classmethod
def alphaN(cls,V):
if(V == 10):
return alphaN(V+0.001)
else:
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
print("alphaN: ", a)
return a
#classmethod
def betaN(cls,V):
a = 0.125*math.exp(-V/80)
print("betaN: ", a)
return a
#classmethod
def alphaM(cls, V):
if (V == 25):
return alphaM(V+0.0001)
else:
a = (25 - V)/10 * (math.exp( (25-V)/10) - 1)
print("alphaM", a)
return (a)
#classmethod
def betaM(cls, V):
return 4 * math.exp(-V/18)
#classmethod
def alphaH(cls, V):
return 0.07 * math.exp(-V/20)
#classmethod
def betaH(cls, V):
return 1/(math.exp((30-V/10)+1))
def iteration(self):
aN = self.alphaN(self.V)
bN = self.betaN(self.V)
aM = self.alphaM(self.V)
bM = self.betaM(self.V)
aH = self.alphaH(self.V)
bH = self.betaH(self.V)
tauN = 1/(aN + bN)
print("tauN: ", tauN)
tauM = 1/(aM + bM)
print("tauM", tauM)
tauH = 1/(aH + bH)
print("tauH: ", tauH)
nInf = aN * tauN
print("nInf: ", nInf)
mInf = aM * tauM
print("mInf: ", mInf)
hInf = aH * tauH
print("hInf: ", hInf)
self.n += self.dt/ tauN * (nInf - self.n)
print("n: ", self.n)
self.m += self.dt/tauM * (mInf - self.m)
print("m: ", self.m)
self.h += self.dt/tauH * (hInf - self.h)
print("h: ", self.h)
self.IK = self.GKMax * self.n * self.n * self.n * self.n * (self.VRest - self.EK)
print("IK: ", self.IK)
self.INa = self.GNaMax * self.m * self.m * self.m * self.h * (self.VRest - self.ENa)
print("INa: ", self.INa)
self.Im = self.Gm * (self.VRest * self.V)
print("Im: ", self.Im)
self.V += self.dt/self.Capacitance * (self.INa + self.IK + self.Im + self.Iinj)
print("V: ", self.V)
print("nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn")
return self.V
if __name__ == '__main__':
hodgkinHuxley = HH()
V_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt)) #v_vector
Iinj_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt)) #stim_vector
n_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
m_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
h_vector = np.zeros(math.floor(hodgkinHuxley.tStop/hodgkinHuxley.dt))
plotSampleRate = math.ceil(hodgkinHuxley.tStop/2000/hodgkinHuxley.dt) #t_vector
print("plotsamplerate: ", plotSampleRate)
i = 0
t_vector = []
for t in range(0, hodgkinHuxley.tStop+1):
t= t+hodgkinHuxley.dt
if(math.floor(t)>hodgkinHuxley.tInjStart & math.ceil(t)<hodgkinHuxley.tInjStop):
rawInj = hodgkinHuxley.IDC + hodgkinHuxley.IRand * 2 * (random.random()-0.5)
else:
rawInj = 0
hodgkinHuxley.Iinj += hodgkinHuxley.dt/hodgkinHuxley.Itau * (rawInj - hodgkinHuxley.Iinj)
hodgkinHuxley.iteration()
counter = 0
if(i == plotSampleRate):
V_vector[counter] = hodgkinHuxley.V
Iinj_vector[counter] = hodgkinHuxley.Iinj
n_vector[counter] = hodgkinHuxley.n
m_vector[counter] = hodgkinHuxley.m
h_vector[counter] = hodgkinHuxley.h
i=0;
counter+=1
i+=1
Error:
plotsamplerate: 4
alphaN: 0.05819767068693265
betaN: 0.125
alphaM 27.956234901758684
tauN: 5.458584687514421
tauM 0.03129279788667988
tauH: 14.285714285707257
nInf: 0.3176769140606974
mInf: 0.8748288084532805
hInf: 0.9999999999995081
n: 0.31998936040167786
m: 0.7089605789167688
h: 0.6006999999999995
IK: -0.5235053389507994
INa: -2681.337959108097
Im: 0.0
V: -67.0465366111762
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
alphaN: 0.00034742442109860416
betaN: 0.2889909708647963
alphaM 91515.37543280824
tauN: 3.456160731837547
tauM 1.0907358211913938e-05
tauH: 0.5000401950825147
nInf: 0.0012007546414823879
mInf: 0.9981909817434281
hInf: 1.0
n: 0.31768341581102577
m: 663.6339264765652
h: 0.6206633951393696
IK: -0.5085774931025618
INa: -2272320232559.0464
Im: -213.46946791632385
V: -56808005886.37157
nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn
Traceback (most recent call last):
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 131, in <module>
hodgkinHuxley.iteration()
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 71, in iteration
aN = self.alphaN(self.V)
File "C:\Users\Huinqk 2.0\Documents\projects\python\tariq_neural networks\plotting function.py", line 38, in alphaN
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
OverflowError: math range error
[Finished in 0.8s]
You can write an altered version of math.exp which will behave more like the javascript function.
def safe_exp(n):
try:
return math.exp(n)
except OverflowError:
return float('inf')
OverflowError: math range error mean that's math.exp((10-V)/10) slightly outside of the range of a double, so it causes an overflow...
You may expect that this number is infinite with:
try:
a = (10-V)/(100 * (math.exp((10-V)/10) -1))
except OverflowError:
a = (10-V)/(float('inf'))