Pass a variable between multiple several functions | Python 3 - python

thanks for reading this post. I want to make an advanced TicTacToe game with AI and other stuff. I need to pass the spots(s1-s9) variable between different functions. I have been researching for quite a bit now, and I would like to meet an answer. Here is part of the code I need to execute:
def set_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return s1,s2,s3,s4,s5,s6,s7,s8,s9
def print_spots():
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
set_spots(1,2,3,4,5,6,7,8,9)
print_spots()
game_loop()
I want to be able to set the spots in any function like if I had a turnX function. Like if I had:
def turnx(): #This isnt in this code though
#if stuff == other stuff (just example):
set_spots('X','O',3,4,5,6,7,8,9)
But the output is:
NameError: name 's1' is not defined
So basically, I need the program to ask the user where their x or o would be placed on the board (which you don't have to worry about) then have that value stored to be printed out. Like if I change 1 to X in the game, it needs to be stored so it can be printed out.

i believe you should try using the variables from set spots, on print spots:
def print_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return s1,s2,s3,s4,s5,s6,s7,s8,s9):
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
print_spots(1,2,3,4,5,6,7,8,9)
print_spots()
game_loop()
if that doesen't work then i'm not sure

You can do this without the need of the unnecessary set_spots() function.
All you need is an array:
def turnx(s):
if 1 == 1: # (a condition):
s = ['X','O',3,4,5,6,7,8,9]
return s
def print_spots(s):
print('\n')
print(str(s[0]) + ' | ' + str(s[1]) + ' | ' + str(s[2]))
print('--+---+--')
print(str(s[3]) + ' | ' + str(s[4]) + ' | ' + str(s[5]))
print('--+---+--')
print(str(s[6]) + ' | ' + str(s[7]) + ' | ' + str(s[8]))
def game_loop():
spots = [1,2,3,4,5,6,7,8,9] # Use an array
print_spots(spots)
spots = turnx(spots)
print_spots(spots)
game_loop()
This outputs:
1 | 2 | 3
--+---+--
4 | 5 | 6
--+---+--
7 | 8 | 9
X | O | 3
--+---+--
4 | 5 | 6
--+---+--
7 | 8 | 9

do yourself a favor and represent the spots as a list. Then store that list in a variable when you call set spots and pass it on to print:
def set_spots(s1, s2, s3, s4, s5, s6, s7, s8, s9):
return [s1,s2,s3,s4,s5,s6,s7,s8,s9]
def print_spots( spots ):
s1,s2,s3,s4,s5,s6,s7,s8,s9 = spots
print('\n')
print(str(s1) + ' | ' + str(s2) + ' | ' + str(s3))
print('--+---+--')
print(str(s4) + ' | ' + str(s5) + ' | ' + str(s6))
print('--+---+--')
print(str(s7) + ' | ' + str(s8) + ' | ' + str(s9))
def game_loop():
spots = set_spots(1,2,3,4,5,6,7,8,9)
print_spots(spots )
game_loop()

Related

(pyparsing) delimitedList does not work as expected

I have a stringized array that I am receiving from an external system. It is stripped of quotes and separated by a comma and a space.
I'm trying to use pyparsing, but I'm only getting the first element of the array. How do I specify that a word must end in alphanumeric ?
value = '[AaAa=Aaa_xx_12,Bxfm=djfn_13, ldfjk=ddd,ttt=ddfs_ddfj_99]'
LBR, RBR = map(pp.Suppress, "[]")
qs = pp.Word(pp.alphas, pp.alphanums + pp.srange("[_=,]"))
qsList = LBR + pp.delimitedList(qs, delim=', ') + RBR
print(value)
print(qsList.parseString(value).asList())
[AaAa=Aaa_xx_12,Bxfm=djfn_13, ldfjk=ddd,ttt=ddfs_ddfj_99]
# pyparsing.exceptions.ParseException: Expected ']', found 'ldfjk' (at char 30), (line:1, col:31)
BR
Thanks for the mental support :D
LBR, RBR = map(pp.Suppress, "[]")
element = pp.Word(pp.alphanums) + pp.Literal('=') + pp.Word(pp.alphanums + pp.srange("[_]"))
qs = pp.Combine(element + pp.OneOrMore(pp.Optional(pp.Literal(',')) + element))
qsList = LBR + pp.delimitedList(qs, delim= ', ') + RBR
print(value)
print(qsList.parseString(value).asList())
#[AaAa=Aaa_xx_12,Bxfm=djfn_13, ldfjk=ddd,ttt=ddfs_ddfj_99]
#['AaAa=Aaa_xx_12,Bxfm=djfn_13', 'ldfjk=ddd,ttt=ddfs_ddfj_99']

Issues with printing values from multiple arrays in python in the console

So I am trying to make a program that take in input for a flight, and stores it in arrays based on each type of input. Here are the arrays that I use to do this:
airline = []
flightNumbers = []
destination = []
gate = []
status = []
Here is the issue that I am having. After the user goes through and adds 1 flight, I want the program to print a flight status board in the console. For example if I enter:
"Delta", "Dl1480", "Atlanta", "E11", "Ontime"
"American", "AA367", "New York City", "H10", "Delayed"
"United", "UA3411", "Louisville, KY", "F25", "Cancelled"
this is what I want to see output by the program:
airline: | flight number: | destination: | gate: | status:
--------------------------------------------------------------------
Delta | DL1480 | Atlanta | E11 | Ontime
American | AA367 | New York City | H10 | Delayed
United | UA3417 | Louisville,KY | F25 | Cancelled
Here is what I tried to use to get this to print:
def showAll(self):
print("Airline | Flight Number | Destination | Gate | Status")
x = 0
while x < len(a.airline):
print(a.airline + [" | "] + a.flightNumbers + [" | "] + a.destination + [" | "] + a.gate + [" | "]+ a.status + ["\n"])
x += 1
but I get this as output if I enter 2 random entries:
Airline | Flight Number | Destination | Gate | Status
['delta', 'delta', ' | ', '001', '002', ' | ', 'Los angeles, ca', 'atlanta', ' | ', 'a1', 'a3', ' | ', 'ontime', 'ontime', '\n']
['delta', 'delta', ' | ', '001', '002', ' | ', 'Los angeles, ca', 'atlanta', ' | ', 'a1', 'a3', ' | ', 'ontime', 'ontime', '\n']
Can some suggest a way I can fix this, or a better way of going about this entirely? Here is the code for the entire program:
class FSB:
# arrays to store flight information
airline = []
flightNumbers = []
destination = []
gate = []
status = []
input = ""
def addFlight(self):
while input != "bye":
# get inputs
air = input("Enter an airline name >> ")
fn = input("Enter a flight number >> ")
dest = input("Enter a destination >> ")
g = input("Enter a gate number >> ")
stat = input("Enter a flight status >> ")
self.air = air
self.fn = fn
self.dest = dest
self.g = g
self.stat = stat
# add inputs to appropiate arrays
a.airline.append(self.air)
a.flightNumbers.append(self.fn)
a.destination.append(self.dest)
a.gate.append(self.g)
a.status.append(self.stat)
print("Data stored sucessfully.\n")
a.showAll()
def showAll(self):
print("Airline | Flight Number | Destination | Gate | Status")
x = 0
while x < len(a.airline):
print(a.airline + [" | "] + a.flightNumbers + [" | "] + a.destination + [" | "] + a.gate + [" | "]+ a.status + ["\n"])
x += 1
go = input("To add a new entry, enter 1.\nTo reprint list, enter 2.\nTo exit, enter 3.\n")
if go == "1":
a.addFlight()
elif go == "2":
for x in range(1,26):
print(" ")
a.showAll()
elif go == "3":
exit()
if __name__ == "__main__":
a = FSB()
a.addFlight()
You're trying to concatenate a string "|" to your list. Please try doing ["|"]instead.
I ended up iterating through each array manually, and this is what I got:
def showAll(self):
print("Airline\t\t\t" +"| Flight Number\t\t" +"| Destination\t\t" +"| Gate \t\t" +"| Status")
for x in range(len(a.airline)):
print("-------------------------------------------------------------------------------------------------------------------")
print(str(a.airline[x] + "\t\t") + str(a.flightNumbers[x] + "\t\t") + str(a.destination[x] + "\t\t\t\t") + str(a.gate[x] + "\t\t") + str(a.status[x]))
Thank you to everyone who suggested an answer, I appreciate it!

With pyparsing how do you ignore nested structures?

I am having trouble finding a way to ignore a structure if it is nested in another type of structure. In the example below I have a structure_a that I am trying to parse for, but in my results I am also getting matches for structure_a that are nested in another structure. I don't want pyparsing to match those unless I match the outer structure first. How would I go about doing that?
self.LBRACE, self.RBRACE, self.LBRACK, self.RBRACK, self.SEMI, self.COMMA, self.DOUBLEQUOTE = map(pp.Suppress, '{}[];,"')
def parse(self, data):
template = CaselessKeyword("structure_a")
words = Word(alphanums + "_" + "." + "[" + "]")
recursive_grammar = Forward()
recursive_grammar <<= (
Group(words("type") + words("name") + self.LBRACE +
ZeroOrMore(recursive_grammar) + self.RBRACE |
words("name") + self.LBRACE +
ZeroOrMore(recursive_grammar) + self.RBRACE |
self.LBRACE + ZeroOrMore(recursive_grammar) + self.RBRACE |
self.LBRACE + ZeroOrMore(words("type")) + self.RBRACE) |
Group(words("name") + self.EQUAL + recursive_grammar |
ZeroOrMore(words("type")) + words("name") + self.EQUAL +
words("value") + Optional(self.COMMA) |
words("name") + self.EQUAL + words("value") +
Optional(self.COMMA))
)
grammar = (template("category") + words("type") + words("name") +
self.LBRACE + ZeroOrMore(recursive_grammar)("members") +
self.RBRACE + Optional(cStyleComment)("short_description"))
result = grammar.searchString(data)
return result
# I want to match this structure
structure_a type name {
variable = 1
}
structure_b name {
# I only want to match a nested structure_a if I create a new
# grammar to match structure_b that have structure_a nested in it.
# Otherwise I want to ignore nested structure_a
structure_a type name {
variable = 2
}
}
Currently my grammar matches stuff that are in structure_b as well top level elements. I don't want pyparsing to match stuff in structure_b unless I explicitly match structure_b first.
After writing the question out and posting it and taking time away from the problem, I think I have come up with a solution. I think the reason it was matching the nested stucture_a was because it wasn't able to find match for the outer structure_b so the parser just moves to the next line of text and the parser doesn't know that the nested structure_a is nested. So I rewrote my code to this and it seems to work.
self.LBRACE, self.RBRACE, self.LBRACK, self.RBRACK, self.SEMI, self.COMMA, self.DOUBLEQUOTE = map(pp.Suppress, '{}[];,"')
def parse(self, data):
template1 = CaselessKeyword("structure_a")
template2 = CaselessKeyword("structure_b")
words = Word(alphanums + "_" + "." + "[" + "]")
recursive_grammar = Forward()
recursive_grammar <<= (
Group(words("type") + words("name") + self.LBRACE +
ZeroOrMore(recursive_grammar) + self.RBRACE |
words("name") + self.LBRACE + ZeroOrMore(recursive_grammar) +
self.RBRACE |
self.LBRACE + ZeroOrMore(recursive_grammar) + self.RBRACE |
self.LBRACE + ZeroOrMore(words("type")) + self.RBRACE |
# added the nested structure to my recursive grammar
template1("category") + words("type") + words("name") +
self.LBRACE + ZeroOrMore(recursive_grammar)("members") +
self.RBRACE + Optional(cStyleComment)("short_description")) |
Group(words("name") + self.EQUAL + recursive_grammar |
ZeroOrMore(words("type")) + words("name") + self.EQUAL +
words("value") + Optional(self.COMMA) |
words("name") + self.EQUAL + words("value") + Optional(self.COMMA))
)
grammar = (template1("category") + words("type") + words("name") +
self.LBRACE + ZeroOrMore(recursive_grammar)("members") +
self.RBRACE + Optional(cStyleComment)("short_description") |
# Match stucture_b
template2("category") + words("name") + self.LBRACE +
ZeroOrMore(recursive_grammar)("members") + self.RBRACE +
Optional(cStyleComment)("short_description")
)
result = grammar.searchString(data)
return result
# Same example from question...
structure_a type name {
variable = 1
}
structure_b name {
structure_a type name {
variable = 2
}
}
# Results...
Name: name
Category: structure_a
Type: type
['variable', '=', '1']
Name: name
Category: structure_b
Type:
['structure_a', 'type', 'name', ['variable', '=', '2']]

IndexError: Peng Robinson equation code for multiple components

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.

Change from Combine(Literal('#') + 'spec') to Keyword('#spec') removes whitespace

Why does using Combine(...) preserve the whitespace, whereas Keyword(...) removes thes whitespace?
I need to preserve the whitespace after the matched token.
The test is as follows:
from pyparsing import *
def parse(string, refpattern):
print refpattern.searchString(string)
pattern = StringStart() \
+ SkipTo(refpattern)('previous') \
+ refpattern('ref') \
+ SkipTo(StringEnd())('rest')
print pattern.parseString(string)
string = "With #ref to_something"
identifier = Combine(Word(alphas + '_', alphanums + '_') + Optional('.' + Word(alphas)))
pattern_without_space = (CaselessKeyword('#ref') | CaselessKeyword(r'\ref')).setParseAction(lambda s, l, t: ['ref']) \
+ White().suppress() + identifier
pattern_with_space = Combine((Literal('#') | Literal('\\')).suppress() + 'ref') + White().suppress() + identifier
parse(string, pattern_without_space)
parse(string, pattern_with_space)
will output:
[['ref', 'to_something']]
['With', 'ref', 'to_something', '']
[['ref', 'to_something']]
['With ', 'ref', 'to_something', '']
# ^ space i need is preserved here
The problem happens when using alternation (the | operator) with CaselessKeyword. See these examples:
from pyparsing import *
theString = 'This is #Foo Bar'
identifier = Combine(Word(alphas + '_', alphanums + '_') + Optional('.' + Word(alphas)))
def testParser(p):
q = StringStart() + SkipTo(p)("previous") + p("body") + SkipTo(StringEnd())("rest")
return q.parseString(theString)
def test7():
p0 = (CaselessKeyword('#Foo') | Literal('#qwe')) + White().suppress() + identifier
p1 = (CaselessKeyword('#Foo') | CaselessKeyword('#qwe')) + White().suppress() + identifier
p2 = (Literal('#qwe') | CaselessKeyword('#Foo')) + White().suppress() + identifier
p3 = (CaselessKeyword('#Foo')) + White().suppress() + identifier
p4 = Combine((Literal('#') | Literal('\\')).suppress() + 'Foo') + White().suppress() + identifier
print "p0:", testParser(p0)
print "p1:", testParser(p1)
print "p2:", testParser(p2)
print "p3:", testParser(p3)
print "p4:", testParser(p4)
test7()
The output is:
p0: ['This is', '#Foo', 'Bar', '']
p1: ['This is', '#Foo', 'Bar', '']
p2: ['This is', '#Foo', 'Bar', '']
p3: ['This is ', '#Foo', 'Bar', '']
p4: ['This is ', 'Foo', 'Bar', '']
Perhaps this is a bug?
Update: This is how you could define your own parser to match either #Foo or \Foo as a keyword:
from pyparsing import *
import string
class FooKeyWord(Token):
alphas = string.ascii_lowercase + string.ascii_uppercase
nums = "0123456789"
alphanums = alphas + nums
def __init__(self):
super(FooKeyWord,self).__init__()
self.identChars = alphanums+"_$"
self.name = "#Foo"
def parseImpl(self, instring, loc, doActions = True):
if (instring[loc] in ['#', '\\'] and
instring.startswith('Foo', loc+1) and
(loc+4 >= len(instring) or instring[loc+4] not in self.identChars) and
(loc == 0 or instring[loc-1].upper() not in self.identChars)):
return loc+4, instring[loc] + 'Foo'
raise ParseException(instring, loc, self.errmsg, self)
def test8():
p = FooKeyWord() + White().suppress() + identifier
q = StringStart() + SkipTo(p)("previous") + p("body") + SkipTo(StringEnd())("rest")
print "with #Foo:", q.parseString("This is #Foo Bar")
print "with \\Foo:", q.parseString("This is \\Foo Bar")
And the output:
with #Foo: ['This is ', '#Foo', 'Bar', '']
with \Foo: ['This is ', '\\Foo', 'Bar', '']

Categories