How to collect the result values using while? - python

I have a question of while in python.
How to collect the result values using while?
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
Blank_text = ""
Blank_text = Blank_text + ColumnCount_text
ColumnCount_int = ColumnCount_int - 1
print(Blank_text)
result shows as below
<colspec colnum="3" colname="3">
<colspec colnum="2" colname="2">
<colspec colnum="1" colname="1">
but i want to collect all result like as below
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">
Would you tell me which part wrong is ?

You can fix the code by following where Blank_text = "" is moved before while loop and print(Blank_text) is called after the loop.
(Note: since Blank_text accumulates, variable name changed to accumulated_text as suggested in the comment):
ColumnCount_int = 3
accumulated_text = "" # variable name changed, used instead of Blank_text
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
accumulated_text = accumulated_text + ColumnCount_text
ColumnCount_int = ColumnCount_int - 1
print(accumulated_text)
Result:
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">
Update:
However, same result can be from following in little compact way with .join:
result = ''.join('<colspec colnum="{0}" colname="{1}">'.format(i,i) for i in range(3,0,-1))
print(result)

Try appending it to the new list i created l, then do ''.join(l) to output it in one line :
l = []
ColumnCount_int = 3
while ColumnCount_int > 0 :
ColumnCount_text = str('<colspec colnum="'+ str(ColumnCount_int) +'"' ' ' 'colname="'+ str(ColumnCount_int) + '">')
Blank_text = ColumnCount_text
ColumnCount_int = ColumnCount_int - 1
l.append(Blank_text)
print(''.join(l))
Output:
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">
Shorter Way
Also try this:
l = []
ColumnCount_int = 3
while ColumnCount_int > 0 :
l.append(str('<colspec colnum="'+str(ColumnCount_int)+'"'' ''colname="'+str(ColumnCount_int)+'">'))
ColumnCount_int-=1
print(''.join(l))
Output:
<colspec colnum="3" colname="3"><colspec colnum="2" colname="2"><colspec colnum="1" colname="1">

Related

Why does my python loop return Key Error : 0 when I change the input dataframe?

I'm trying to do iterative calculation that will store the result of each iteration by append into a dataframe
however when I try to change the input dataframe into something else, I got the key error : 0
here are my complete code
d = []
df_it = df_ofr
i = 0
last_col = len(df_it.iloc[:,3:].columns) - 1
print("User Group : " + df_it[['user_type'][0]][0] + " " + df_it[['user_status'][0]][0])
for column in df_it.iloc[:,3:]:
if i > 0 :
if i < last_col: # 1 step conversion
convert_baseline = df_it[[column][0]][0]
convert_variant_a = df_it[[column][0]][1]
elif i == last_col: # end to end conversion
convert_baseline = df_it[[column][0]][0]
convert_variant_a = df_it[[column][0]][1]
lead_baseline = step_1_baseline
lead_variant_a = step_1_variant_a
#perform proportion z test
test_stat, p_value = proportions_ztest([convert_baseline,convert_variant_a], [lead_baseline,lead_variant_a], alternative='smaller')
#perform bayesian ab test
#initialize a test
test = BinaryDataTest()
#add variant using aggregated data
test.add_variant_data_agg("Baseline", totals=lead_baseline, positives=convert_baseline)
test.add_variant_data_agg("Variant A", totals=lead_variant_a, positives=convert_variant_a)
bay_result = test.evaluate(seed=99)
#append result
d.append(
{
'Convert into': column,
'# Users Baseline': lead_baseline,
'# Users Variant A': lead_variant_a,
'% CVR Baseline' : convert_baseline / lead_baseline,
'% CVR Variant A' : convert_variant_a / lead_variant_a,
'Z Test Stat' : test_stat,
'P-Value' : p_value,
'Prob Baseline being the Best' : bay_result[0]['prob_being_best'],
'Prob Variant A being the Best' : bay_result[1]['prob_being_best']
}
)
elif i == 0:
step_1_baseline = df_it[[column][0]][0]
step_1_variant_a = df_it[[column][0]][1]
i = i+1
lead_baseline = df_it[[column][0]][0]
lead_variant_a = df_it[[column][0]][1]
pd.DataFrame(d)
the one that I'm trying to change is this part
df_it = df_ofr
thanks for your help, really appreciate it
I'm trying to do iterative calculation that will store the result of each iteration by append into a dataframe

Replacing each character/string in a list one at a time with python

I have a string "MQADKVMEPT" and the desired output I want is:
.QADKVMEPT
M.ADKVMEPT
MQ.DKVMEPT
MQA.KVMEPT
MQAD.VMEPT
MQADK.MEPT
MQADKV.EPT
MQADKVM.PT
MQADKVME.T
MQADKVMEP.
Using this code:
motif = 'MQADKVMEPT'
motiflist = list(motif)
pos = 0
for aa in motiflist:
motiflist[pos] = '.'
pos += 1
str = ''
for a in motiflist:
str += a
print(str)
My output is:
.QADKVMEPT
..ADKVMEPT
...DKVMEPT
....KVMEPT
.....VMEPT
......MEPT
.......EPT
........PT
.........T
..........
How do I reinitialize the original motiflist so that it doesn't give me this output?
"Quick" fix would be copy the original list. Using your code:
motif = "MQADKVMEPT"
motiflist = list(motif)
pos = 0
for aa in motiflist:
motiflist_copy = motiflist.copy() # <--- copy the original list
motiflist_copy[pos] = "."
pos += 1
s = ""
for a in motiflist_copy:
s += a
print(s)
Prints:
.QADKVMEPT
M.ADKVMEPT
MQ.DKVMEPT
MQA.KVMEPT
MQAD.VMEPT
MQADK.MEPT
MQADKV.EPT
MQADKVM.PT
MQADKVME.T
MQADKVMEP.
Shorter solution:
motif = "MQADKVMEPT"
for i in range(len(motif)):
s = motif[:i] + "." + motif[i + 1 :]
print(s)

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!

Print a list of lists of dicts in Python

I have the following list of lists of dicts:
l = [[{'close': 'TRUE'}], [{'error': 'FALSE'}], [{'close': 'TRUE', 'error': 'TRUE'}, {'close': 'TRUE', 'error': 'FALSE'}]]
and I would like to print it this way:
(close = TRUE) & (error = FALSE) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
For the moment, I have the following function which nearly do the job:
def pretty_string(l):
print ' & '.join('({0})'
.format(' | '
.join('({0})'
.format(' & '
.join('{0} = {1}'
.format(key, value)
for key, value
in disjuncts.items()))
for disjuncts
in conjuncts))
for conjuncts
in l)
But it gives me:
((close = TRUE)) & ((error = FALSE)) & ((close = TRUE & error = TRUE) | (close = TRUE & error = FALSE))
Notice the extra parentheses around "(close = TRUE)" and "(error = FALSE)".
How can these be removed?
Just use if statement to change format string (('({0})' if len(disjuncts) > 1 else '{0}')) depending on the length of your internal list. Like this:
def pretty_string(l):
print ' & '.join(
'({0})'.format(
' | '.join(
('({0})' if len(disjuncts) > 1 else '{0}').format(
' & '.join(
'{0} = {1}'.format(key, value) for key, value in disjuncts.items()
)
) for disjuncts in conjuncts
)
) for conjuncts in l
)
def conv(item):
if(isinstance(item, dict)):
yield '(' + ' & '.join("{} = {}".format(*i) for i in item.items()) + ')'
elif(isinstance(item, list)):
for i in item:
for s in conv(i):
yield s
def pretty_string(l):
return ' | '.join(conv(l))

PyParsing: Parsing Cisco's "show ip bgp"

I am trying to parse a string as below using PyParsing.
R1# show ip bgp
BGP table version is 2, local router ID is 1.1.1.1
Status codes: s suppressed, d damped, h history, * valid, > best, i - internal,
r RIB-failure, S Stale
Origin codes: i - IGP, e - EGP, ? - incomplete
Network Next Hop Metric LocPrf Weight Path
> 10.1.1.0/24 192.168.1.2 0 0 200 i
Note that LocPrf value is empty but it can be a number.
ipField = Word(nums, max=3)
ipAddr = Combine(ipField + "." + ipField + "." + ipField + "." + ipField)
status_code = Combine(Optional(oneOf("s d h * r")) + ">" + Optional(Literal("i"))
prefix = Combine(ipAddr + Optional(Literal("/") + Word(nums,max=2)))
next_hop = ipAddr
med = Word(nums)
local_pref = Word(nums) | White()
path = Group(OneOrMore(Word(nums)))
origin = oneOf("i e ?")
This is the grammar.
g = status_code + prefix + next_hop + med + local_pref + Suppress(Word(nums)) + Optional(path) + origin
I just need to parse the Bold line. But this is not parsing it properly. It assigns Weight value to LocPrf.
Please look over the following code example (which I will include in the next pyparsing release). You should be able to adapt it to your application:
from pyparsing import col,Word,Optional,alphas,nums,ParseException
table = """\
12345678901234567890
COLOR S M L
RED 10 2 2
BLUE 5 10
GREEN 3 5
PURPLE 8"""
# function to create column-specific parse actions
def mustMatchCols(startloc,endloc):
def pa(s,l,t):
if not startloc <= col(l,s) <= endloc:
raise ParseException(s,l,"text not in expected columns")
return pa
# helper to define values in a space-delimited table
def tableValue(expr, colstart, colend):
return Optional(expr.copy().addParseAction(mustMatchCols(colstart,colend)))
# define the grammar for this simple table
colorname = Word(alphas)
integer = Word(nums).setParseAction(lambda t: int(t[0])).setName("integer")
row = (colorname("name") +
tableValue(integer, 11, 12)("S") +
tableValue(integer, 15, 16)("M") +
tableValue(integer, 19, 20)("L"))
# parse the sample text - skip over the header and counter lines
for line in table.splitlines()[2:]:
print
print line
print row.parseString(line).dump()

Categories