I am trying to convert arrays that contain both Inches and Feet into Inches. The feet are denoted with a single quote (') and inches are denoted with double quotes ("). The data comes in the following forms:
[8'x10']
[60\" x 72\"]
[5'x8',5x8,60\"x92\"]
[8'10\"x12']
What I want:
["96x120"]
["60x72"]
["60x96","60x96","60x96","60x92"]
["106x144"]
What I have:
def ft_inch(numbers):
if str(numbers).find("x") > -1:
numbers=numbers.replace('[','').replace('"','').replace('[','').replace(']','')
try:
nom = numbers.split("x")[0]
nom=nom.replace(r'\\|\"|\]|\[','')
nom_one = nom.split("'")[0]
nom_two = nom.split("'")[1]
den = numbers.split("x")[1]
den=den.replace(r'\\|\"|\[|\]','')
den_one = den.split("'")[0]
den_two = den.split("'")[1]
ft=int(nom_one)*12
inch=nom_two.replace(r'\"| |\\','')
try:
inch=int(inch)
except:
print('B')
tmp = int(ft)+int(inch)
fts=int(den_one)*12
inchs=den_two.replace(r'\"| |\\','')
try:
inchs=int(inchs)
except:
print('B')
tmp_two = int(fts)+int(inch)
return f'["{tmp}x{tmp_two}"]'
except:
return numbers
else:
return numbers
x="[5'1x8'1]"
ft_inch(x)
This works for a single array as long as it has both feet and inches but fails if its only feet [8'x8']. If anyone has a simpler solution please let me know
A regex-based approach:
import re
inputs = [["8'1x10'1"], ["60\" x 72\""], ["5'x8'", "5x8", "60\"x92\""], ["8'10\"x12'"]]
for inpt in inputs:
sub_output = []
for measurement in inpt:
m = re.match(r"(\d+['\"]?)(\d+['\"]?)?x(\d+['\"]?)(\d+['\"]?)?",
"".join(measurement.split()))
groups = [m.groups()[:2], m.groups()[2:]]
result_inches = [0, 0]
for i, group in enumerate(groups):
for raw_val in group:
if raw_val == None:
continue
if '"' in raw_val:
result_inches[i] += int(raw_val[:-1])
elif "'" in raw_val:
result_inches[i] += int(raw_val[:-1])*12
else:
result_inches[i] += int(raw_val)*12
sub_output.append(result_inches)
print([f"{x}x{y}" for x, y in sub_output])
Output:
['108x132']
['60x72']
['60x96', '60x96', '60x92']
['106x144']
I saw your edit and included the ["8'1x10'1"] case :)
I rewrote the entire thing, but this seems to work:
input_ = ["8'x10'", "60\" x 72\"", "5'x8'","5x8","60\"x92\"", "8'10\"x12'", "8'1x10'1\""]
inches_only = []
for s in input_:
s.replace(" ", "")
sides = s.split("x")
new_sides = []
for side in sides:
inches = 0
split1 = side.split("'")
if len(split1) > 1 or (len(split1) == 1 and not side.__contains__('"')):
inches = int(split1[0]) * 12
split2 = side.split('"')
if len(split2) > 1:
inches += int(split2[0].split("'")[-1])
elif len(split2) == 1 and len(split1) > 1 and len(split1[1]) > 0:
inches += int(split1[1])
new_sides.append(str(inches) + '"')
inches_only.append("x".join(new_sides))
print(inches_only)
Output:
['96"x120"', '60"x72"', '60"x96"', '60"x96"', '60"x92"', '106"x144"', '97"x121"']
I have the following code:
from scipy.constants import R as Rgi
from numpy import *
import numpy as np
import matplotlib.pyplot as plt
Constants
Tccomp = array([190.56,305.32,369.83,425.12,469.7,507.6,282.34,365.57,511.76,553.58,562.16,591.8,512.64,513.92,536.78,400.1,408.00,508.2,591.95,469.15,132.45,154.58,126.2,405.65,430.75,304.26,647.13,535.5]) #k
Pccomp = array([45.90,48.50,42.10,37.70,33.60,30.40,50.30,46.30,45.00,41.00,48.00,41.30,81.40,61.20,51.20,52.70,65.90,47.10,57.40,72.60,37.90,50.20,33.98,113.00,78.60,73.90,219.40,41.50]) # bar
Vccomp = array([0.099,0.146,0.2,0.255,0.315,0.373,0.132,0.188,0.257,0.308,0.261,0.314,0.117,0.168,0.22,0.171,0.115,0.21,0.179,0.142,0.092,0.074,0.089,0.072,0.123,0.095,0.056,0.267]) # m^3/kmol
Zccomp = array([0.286,0.279,0.273,0.272,0.271,0.269,0.283,0.286,0.272,0.274,0.273,0.262,0.224,0.24,0.252,0.271,0.223,0.234,0.208,0.264,0.318,0.287,0.288,0.241,0.269,0.277,0.228,0.249])
Wcomp = array([0.011,0.098,0.149,0.197,0.251,0.304,0.086,0.137,0.196,0.212,0.209,0.262,0.566,0.643,0.617,0.192,0.282,0.307,0.463,0.201,0.0,0.02,0.037,0.253,0.244,0.244,0.343,0.323])
Nombre = array(['Metano','Etano','Propano','Butano','Pentano','Hexano','Etileno','Propileno','Ciclopentano','Ciclohexano','Benceno','Tolueno','Metanol','Etanol','1-Propanol','Dimetileter','Formaldehido','Acetona','Acido Actico','Oxido de etileno','Aire','Oxigeno','Nitrogeno','Amoniaco','Dioxido de azufre','Dioxido de carbono','Agua','Metiletilcetona'])
Rbar = Rgi*10 # bar*cm^3/K*mol
Rgas = Rgi # Kj / Kmol * K
Program interface
print 'Cálculo de la fugacidad de una mezcla de gases reales utilizando Peng Robinson'
print '-----------------------------------------------------------------------------------'
print ' Metano |(0)| '
print ' Etano |(1)| '
print ' Propano |(2)| '
print ' Butano |(3)| '
print ' Pentano |(4)| '
print ' Hexano |(5)| '
print ' Etileno |(6)| '
print ' Propileno |(7)| '
print ' Ciclopentano |(8)| '
print ' Ciclohexano |(9)| '
print ' Benceno |(10)|'
print ' Tolueno |(11)|'
print ' Metanol |(12)|'
print ' Etanol |(13)|'
print ' 1-propanol |(14)|'
print ' Dimetileter |(15)|'
print ' Formaldehido |(16)|'
print ' Acetona |(17)|'
print ' Ácido acético |(18)|'
print ' Óxido de etileno |(19)|'
print ' Aire |(20)|'
print ' Oxígeno |(21)|'
print ' Nitrógeno |(22)|'
print ' Amoniaco |(23)|'
print ' Dióxido de azufre |(24)|'
print ' Agua |(25)|'
print ' Metiletilcetona |(26)|'
print '-------------------------------------------------------------------------------------'
print ' '
print ' '
ncomp = int(input('numero de componentes del sistema : '))
def PRMix(T,P):
comp = zeros(ncomp)
y = zeros(ncomp)
Wcomp = zeros(ncomp)
Tccomp = zeros(ncomp)
Pccomp = zeros(ncomp)
a = zeros(ncomp)
b = zeros(ncomp)
sumbi = zeros(ncomp)
s = (ncomp,ncomp)
aij = zeros(s)
sumaij = zeros(s)
for i in arange(0,ncomp,1):
comp[i] = int(input('Escoja el componente : '))
y[i] = float(input(' Fraccion : '))
print ' '
for i in arange (0,ncomp,1):
Wcomp[i] = Wcomp[int(comp[i])]
Tccomp[i] = Tccomp[int(comp[i])]
Pccomp[i] = Pccomp[int(comp[i])]
kappa = 0.37464 + 1.54226*Wcomp - 0.26992*Wcomp**2
alpha = (1 + kappa*(1 - sqrt(T/Tccomp)))**2
a = 0.45724*(((Rgi**2) * (Tccomp**2))/(Pccomp))*alpha
b = 0.0788*((Rgi*Tccomp)/Pccomp)
for i in arange(0,ncomp,1):
sumbi[i] = y[i]*b[i]
for j in arange(0,ncomp,1):
aij[i,j] = sqrt(a[i]*a[j])
sumaij[i,j] = y[i]*y[j] * aij[i,j]
amix = sum(sumaij)
bmix = sum(sumbi)
Aij = (aij * P) / ((Rgi*T)**2)
Bi = (b * P) / (Rgi * T)
Amix = (amix * P)/((Rgi*T)**2)
Bmix = (bmix * P)/(Rgi * T)
pol = [1,(Bmix - 1), (Amix - 2 * Bmix - 3 * Bmix**2),(Bmix**2 + Bmix**3 -Amix * Bmix)]
Z = roots(pol)
Z = real(Z)
Zvmix = max(Z)
Zlmix = min(Z)
LnPhiV = (Bi/Bmix)*(Zvmix-1) - log(Zvmix-Bmix)-(Amix/(2*Sqrt(2)*Bmix)) * ((2 *(dot(Aij,y)/Amix) -(Bi/Bmix)) * log((Zvmix + (1 + sqrt(2)) * Bmix) / (Zvmix + (1 - sqrt(2)) * Bmix)))
LnPhiL = (Bi/Bmix)*(Zlmix-1) - log(Zlmix-Bmix)-(Amix/(2*Sqrt(2)*Bmix)) * ((2 *(dot(Aij,y)/Amix) -(Bi/Bmix)) * log((Zlmix + (1 + sqrt(2)) * Bmix) / (Zlmix + (1 - sqrt(2)) * Bmix)))
PhiV = exp(LnPhiV)
PhiL = exp(LnPhiL)
However, when I run it I get this error:
Traceback (most recent call last):
line 82, in PRMix
Wcomp[i] = Wcomp[int(comp[i])]
IndexError: index 5 is out of bounds for axis 0 with size 2
>>> IndexError: index 5 is out of bounds for axis 0 with size 2
I can't figure out what's wrong. I tried reading about the error but didn't find anything that applied to my code.
Hi I have written a code in sageworksheet format, it runs nice and smooth on sagecloud, but I have one problem : I want to make it more interactive so the user can enter the parameters by himself, so I'm willing to convert this into a sage script or a pyhton script, I have installed sage on my ubuntu machine, again the code runs on the notebook but not on the console it gives me some syntax error on " P.x " (the same goes if I try to run it as a python script) All I want is to make it run as a Python script or Sage script so I can use input function to ask users to enter the parameters ! Here is the code :
P.<x> = PolynomialRing(ZZ);
def bezout(f,g):
P.<x> = PolynomialRing(QQ)
f = f+x-x
g = g+x-x
e=xgcd(f,g)
gcd=e[0]
u=e[1]
v=e[2]
return (u,v,gcd)
def polymod(f,q):
P.<x> = PolynomialRing(QQ)
f = f
c = f.coefficients(sparse=False)
N = len(c)
for i in range(N):
c[i] = Rational(c[i]).mod_ui(q);
p = sum(c[i]*(x^(i)) for i in range(N));
return p
def center(f,q):
u = q/2
v = -u
c = f.coefficients(sparse=False)
N = len(c)
for i in range(N):
if c[i]<v:
c[i] = c[i] + q;
elif c[i]>u:
c[i] = c[i] - q;
else:
c[i] = c[i];
p = sum(c[i]*(x^(i)) for i in range(N));
return p
class Ntru:
N = None
p = None
q = None
d = None
f = None
g = None
h = None
fp = None
fq = None
Phi = None
def __init__(self,N,p,q,d):
self.N = N
self.p = p
self.q = q
self.d = d
v = self.N
self.Phi = x^v -1
def test(self):
if not is_prime(self.N):
print "N n est pas premier, pensez a changer ce parametre"
return False
if gcd(self.N,self.p) != 1:
print "N et p ne sont pas premiers entre eux, pensez a changer ces parametres"
return False
if gcd(self.N,self.q) != 1:
print "N et q ne sont pas premiers entre eux, pensez a changer ces parameres"
return False
if self.q <= (6*self.d+1)*self.p :
print "q doit etre superieur a (6d+1)*p "
return False
return True
def genPublicKey(self,f_new,g_new):
self.f = f_new
self.g = g_new
(b_f,b_phi,bz) = bezout(self.f,self.Phi)
self.fp = polymod(b_f,self.p)
self.fq = polymod(b_f,self.q)
self.h = polymod((self.fq*self.g).quo_rem(self.Phi)[1],self.q)
if not self.test():
print "le cryptage ne peut s effectuer avec ces parametres !"
quit()
def encrypt(self,message,rand):
if self.h!=None:
temp=(self.p*rand*self.h + message).quo_rem(self.Phi)[1]
e=polymod(temp,self.q)
return e
else:
print "Impossible de faire le cryptage : la cle n a pas encore ete generee"
print "Veuillez en generer une avec la fonction genPublicKey"
def decrypt(self,encryptedMsg):
a = (self.f*encryptedMsg).quo_rem(self.Phi)[1]
a = polymod(a,self.q)
a = center(a,self.q)
tmp = (self.fp*a).quo_rem(self.Phi)[1]
m=polymod(tmp,self.p)
return m
NTRU=Ntru(167,3,128,3)
f = 1+x-x^2-x^3-x^4+x^5+x^6
g = -1+x^2+x^3+x^4-x^5-x^6
NTRU.f = f
NTRU.g = g
NTRU.genPublicKey(f,g)
print "La cle publique est : ",NTRU.h
msg = 1+x+x^4+x^5+x^6
rand = -1 -x + x^2 + x^3 - x^4 + x^6
enc = NTRU.encrypt(msg,rand)
print "Le Message crypte est : ",enc
dec = NTRU.decrypt(enc)
print "Le Message dechiffre est : ",dec
print "Le Message en clair etait : ",msg
Thank you !
For a python script, you can start by taking your code at the bottom and defining a function as a main entry point like:
def main():
NTRU=Ntru(167,3,128,3)
f = 1+x-x^2-x^3-x^4+x^5+x^6
g = -1+x^2+x^3+x^4-x^5-x^6
NTRU.f = f
NTRU.g = g
NTRU.genPublicKey(f,g)
print "La cle publique est : ",NTRU.h
msg = 1+x+x^4+x^5+x^6
rand = -1 -x + x^2 + x^3 - x^4 + x^6
enc = NTRU.encrypt(msg,rand)
print "Le Message crypte est : ",enc
dec = NTRU.decrypt(enc)
print "Le Message dechiffre est : ",dec
print "Le Message en clair etait : ",msg
Then after this code block, you need to tell python what code you want it to run as if it was a script like so:
if __name__ == "__main__":
main()
If you would like to run it as an executable from the ubuntu command line, I would suggest adding a shebang at the top like:
#!/bin/python //this should be the path to your python executable
If you are interested in adding command line arguments to the script for user input, I suggest looking into the argParse library included with python:
https://docs.python.org/3.3/library/argparse.html for python 3
https://docs.python.org/2/library/argparse.html for python 2.7
Unfortunately I am unfamiliar with Sage; I hope this gets you started in the right direction.