How to complete this if statement - if-statement

If user_tickets is less than 5, assign 1 to num_tickets. Else, assign user_tickets to num_tickets.
Sample output with input: 3
Value of num_tickets: 1
user_tickets = int(input())
if user_tickets < 5:
num_tickets = 1
else:
user_tickets = num_tickets
print('Value of num_tickets:', num_tickets)

Here what you need to do:
user_tickets = int(input())
num_tickets = 0 #define num_tickets
if user_tickets < 5:
num_tickets = 1
else:
num_tickets = user_tickets #assining user_tickets to num_tickets
print('Value of num_tickets:', num_tickets)

Related

GLPK output formats

I am new to GLPK, so my apologies in advance if I'm missing something simple!
I have a largeish LP that I am feeding through GLPK to model an energy market. I'm running the following command line to GLPK to process this:
winglpk-4.65\glpk-4.65\w64\glpsol --lp problem.lp --data ExampleDataFile.dat --output results2.txt
When I open the resulting text file I can see the outputs, which all look sensible. I have one big problem: each record is split over two rows, making it very difficult to clean the file. See an extract below:
No. Row name St Activity Lower bound Upper bound Marginal
------ ------------ -- ------------- ------------- ------------- -------------
1 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1990)_
NS 0 0 = < eps
2 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1991)_
NS 0 0 = < eps
3 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1992)_
NS 0 0 = < eps
4 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1993)_
NS 0 0 = < eps
5 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1994)_
NS 0 0 = < eps
6 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1995)_
NS 0 0 = < eps
7 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1996)_
NS 0 0 = < eps
8 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1997)_
NS 0 0 = < eps
9 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1998)_
NS 0 0 = < eps
10 c_e_SpecifiedDemand(UTOPIA_CSV_ID_1999)_
NS 0 0 = < eps
11 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2000)_
NS 0 0 = < eps
12 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2001)_
NS 0 0 = < eps
13 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2002)_
NS 0 0 = < eps
14 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2003)_
NS 0 0 = < eps
15 c_e_SpecifiedDemand(UTOPIA_CSV_ID_2004)_
NS 0 0 = < eps
I would be very grateful of any suggestions for either:
How I can get each record in the output text file onto a single row, or
Ideas on how to clean / post-process the existing text file output.
I'm sure I'm missing something simple here, but the output is in a very unhelpful format at the moment!
Thanks!
I wrote a Python parser for the GLPK output file. It is not beautiful and not save (try-catch) but it is working (for pure simplex problems).
You can call it on output file:
outp = GLPKOutput('myoutputfile')
print(outp)
val1 = outp.getCol('mycolvar','Activity')
val2 = outp.getRow('myrowname','Upper_bound') # row names should be defined
The class is as follows:
class GLPKOutput:
def __init__(self,filename):
self.rows = {}
self.columns = {}
self.nRows = 0
self.nCols = 0
self.nNonZeros = 0
self.Status = ""
self.Objective = ""
self.rowHeaders = []
self.rowIdx = {}
self.rowWidth = []
self.Rows = []
self.hRows = {}
self.colHeaders = []
self.colIdx = {}
self.colWidth = []
self.Cols = []
self.hCols = {}
self.wcols = ['Activity','Lower_bound','Upper bound','Marginal']
self.readFile(filename)
# split columns with weird line break
def smartSplit(self,line,type,job):
ret = []
line = line.rstrip()
if type == 'ROWS':
cols = len(self.rowHeaders)
idx = self.rowWidth
else:
cols = len(self.colHeaders)
idx = self.colWidth
if job == 'full':
start = 0
for i in range(cols):
stop = start+idx[i]+1
ret.append(line[start:stop].strip())
start = stop
elif job == 'part1':
entries = line.split()
ret = entries[0:2]
elif job == 'part2':
start = 0
for i in range(cols):
stop = start+idx[i]+1
ret.append(line[start:stop].strip())
start = stop
ret = ret[2:]
# print()
# print("SMART:",job,line.strip())
# print(" TO:",ret)
return ret
def readFile(self,filename):
fp = open(filename,"r")
lines = fp.readlines()
fp.close
i = 0
pos = "HEAD"
while pos == 'HEAD' and i<len(lines):
entries = lines[i].split()
if len(entries)>0:
if entries[0] == 'Rows:':
self.nRows = int(entries[1])
elif entries[0] == 'Columns:':
self.nCols = int(entries[1])
elif entries[0] == 'Non-zeros:':
self.nNonZeros = int(entries[1])
elif entries[0] == 'Status:':
self.Status = entries[1]
elif entries[0] == 'Objective:':
self.Objective = float(entries[3]) #' '.join(entries[1:])
elif re.search('Row name',lines[i]):
lines[i] = lines[i].replace('Row name','Row_name')
lines[i] = lines[i].replace('Lower bound','Lower_bound')
lines[i] = lines[i].replace('Upper bound','Upper_bound')
entries = lines[i].split()
pos = 'ROWS'
self.rowHeaders = entries
else:
pass
i+= 1
# formatting of row width
self.rowWidth = lines[i].split()
for k in range(len(self.rowWidth)): self.rowWidth[k] = len(self.rowWidth[k])
# print("Row Widths:",self.rowWidth)
i+= 1
READY = False
FOUND = False
while pos == 'ROWS' and i<len(lines):
if re.match('^\s*[0-9]+',lines[i]): # new line
if len(lines[i].split())>2: # no linebrak
entries = self.smartSplit(lines[i],pos,'full')
READY = True
else: # line break
entries = self.smartSplit(lines[i],pos,'part1')
READY = False
FOUND = True
else:
if FOUND and not READY: # second part of line
entries += self.smartSplit(lines[i],pos,'part2')
READY = True
FOUND = False
if READY:
READY = False
FOUND = False
# print("ROW:",entries)
if re.match('[0-9]+',entries[0]): # valid line with solution data
self.Rows.append(entries)
self.hRows[entries[1]] = len(self.Rows)-1
else:
print("wrong line format ...")
print(entries)
sys.exit()
elif re.search('Column name',lines[i]):
lines[i] = lines[i].replace('Column name','Column_name')
lines[i] = lines[i].replace('Lower bound','Lower_bound')
lines[i] = lines[i].replace('Upper bound','Upper_bound')
entries = lines[i].split()
pos = 'COLS'
self.colHeaders = entries
else:
pass #print("NOTHING: ",lines[i])
i+= 1
# formatting of row width
self.colWidth = lines[i].split()
for k in range(len(self.colWidth)): self.colWidth[k] = len(self.colWidth[k])
# print("Col Widths:",self.colWidth)
i+= 1
READY = False
FOUND = False
while pos == 'COLS' and i<len(lines):
if re.match('^\s*[0-9]+',lines[i]): # new line
if len(lines[i].split())>2: # no linebreak
entries = self.smartSplit(lines[i],pos,'full')
READY = True
else: # linebreak
entries = self.smartSplit(lines[i],pos,'part1')
READY = False
FOUND = True
else:
if FOUND and not READY: # second part of line
entries += self.smartSplit(lines[i],pos,'part2')
READY = True
FOUND = False
if READY:
READY = False
FOUND = False
# print("COL:",entries)
if re.match('[0-9]+',entries[0]): # valid line with solution data
self.Cols.append(entries)
self.hCols[entries[1]] = len(self.Cols)-1
else:
print("wrong line format ...")
print(entries)
sys.exit()
elif re.search('Karush-Kuhn-Tucker',lines[i]):
pos = 'TAIL'
else:
pass #print("NOTHING: ",lines[i])
i+= 1
for i,e in enumerate(self.rowHeaders): self.rowIdx[e] = i
for i,e in enumerate(self.colHeaders): self.colIdx[e] = i
def getRow(self,name,attr):
if name in self.hRows:
if attr in self.rowIdx:
try:
val = float(self.Rows[self.hRows[name]][self.rowIdx[attr]])
except:
val = self.Rows[self.hRows[name]][self.rowIdx[attr]]
return val
else:
return -1
def getCol(self,name,attr):
if name in self.hCols:
if attr in self.colIdx:
try:
val = float(self.Cols[self.hCols[name]][self.colIdx[attr]])
except:
val = self.Cols[self.hCols[name]][self.colIdx[attr]]
return val
else:
print("key error:",name,"not known ...")
return -1
def __str__(self):
retString = '\n'+"="*80+'\nSOLUTION\n'
retString += "nRows: "+str(self.nRows)+'/'+str(len(self.Rows))+'\n'
retString += "nCols: "+str(self.nCols)+'/'+str(len(self.Cols))+'\n'
retString += "nNonZeros: "+str(self.nNonZeros)+'\n'
retString += "Status: "+str(self.Status)+'\n'
retString += "Objective: "+str(self.Objective)+'\n\n'
retString += ' '.join(self.rowHeaders)+'\n'
for r in self.Rows: retString += ' # '.join(r)+' #\n'
retString += '\n'
retString += ' '.join(self.colHeaders)+'\n'
for c in self.Cols: retString += ' # '.join(r)+' #\n'
return retString

Pyomo - NameError: name 'm' is not defined

I will be grateful for help with the above-stated error message from running my pyomo script file - "pyomo solve Katrina_Model5.py Katrina_paper.dat --solver=gurobi --summary --stream-solver --report-timing" at the command prompt. I am still new to the software. I have included full code and data file to aid with your help.
Below is the entire syntax of my problem below:
from pyomo.environ import *
#--define the mode:
model = AbstractModel()
#--declaring parameters:
model.n = Param(within=PositiveIntegers, doc='total no. of depots & afected areas')
model.L = Param(within=PositiveIntegers, doc='Max. no. of nodes a salesman may visit')
model.K = Param(initialize=2, within=PositiveIntegers, doc='Min. no. of nodes a salesman may visit')
#model.m = Param(within=PositiveIntegers, doc='no. of initial salesmen positioned at depot i &j')
#--declare model sets names:
model.I = RangeSet(model.n, name='Set of Origin/intermediary nodes')
model.J = RangeSet(model.n, name='Set of affected areas/destination nodes')
model.A = model.I*model.J
model.D = RangeSet(2, name='Set of depots comprises first d nodes of Set V')
model.U = RangeSet(3,5, name='Set of impacted areas/or customers')
model.V = model.D | model.U
#-- define additional parameters with indexed sets:
model.d = Param(model.I, model.J, doc='Represents cost/travel time matrix.')
#--define model Variables:
model.x = Var(model.I, model.J, within=Binary, name="Var of a salesman traveling.")
model.u = Var(within=RangeSet(2,5), name="no. of nodes visited on traveler's path from origin up to node i")
model.m =Var(model.D, name='no. of initial salesmen positioned at depot i &j')
"""#model's objective function defined.#"""
def objective_rule(model):
return sum(model.d[i,j]*model.x[i,j] for (i,j) in model.A)
model.objective = Objective(rule=objective_rule, sense=minimize, name="Total distance traveled")
"""--Below we define and declare the constraints of the model --"""
#.....constraint # 2
def constrTWO_rule(model, i):
return sum(model.x[i,j] for j in model.U) == m[i]
model.ConsOutTrvler = Constraint(model.D, rule=constrTWO_rule)
#.....constraint # 3
def constrTHREE_rule(model, j):
return sum(model.x[i,j] for i in model.U) == m[j]
model.ConsInTrvler = Constraint(model.D, rule=constrTHREE_rule)
#.....constraint # 4
def constrFOUR_rule(model, j):
return sum(model.x[i,j] for i in model.V) == 1
model.ConsTrvlerInn = Constraint(model.U, rule=constrFOUR_rule)
#.....constraint # 5
def constrFIVE_rule(model, i):
return sum(model.x[i,j] for j in model.V) == 1
model.ConsTrvlerOut = Constraint(model.U, rule=constrFIVE_rule)
#......constraint # 6
def constrSIX_rule(model, i):
return u[i] + (L-2)*sum(model.x[k,i]-model.x[i,k] for k in model.D)-L + 1 <= 0
model.consLowBounds = Constraint(model.U, rule=constrSIX_rule)
#.....constraint # 7
def constrSEVEN_rule(model, i):
return u[i] + sum(model.x[k,i] + (2-K)*model.x[i,k] for k in model.D) >= 2
model.consUpBounds = Constraint(model.U, rule=constrSEVEN_rule)
#.....constraint # 8 ---DOUBLE-CHECK FORMULATION
def constrEIGHT_rule(model, k, i):
return model.x[k,i] + model.x[i,k] <= 1
model.consNotOneAffArea = Constraint(model.D, model.U, rule=constrEIGHT_rule)
#.....constraint # 9 ---DOUBLE-CHECK FORMULATION
def constrNINE_rule(model, i, j):
return ( u[i] - u[j] + L*x[i,j] + (L-2)*x[i,j] ) <= L-1
model.consSubTourElim = Constraint(model.U, rule=constrNINE_rule)
And, here are the '.dat' data file used:
param n := 5 ;
param L := 5 ;
param K := 2 ;
param d: 1 2 3 4 5 :=
1 0 8 4 9 9
2 8 0 6 7 10
3 4 6 0 5 6
4 9 7 5 0 4
5 9 10 6 4 0 ;

Simple function dosen't return what i want

I want this function to give me around 10 values split in 2 list, but it only gives me 1 value. Why?
import random
def chance():
count = 0
while count < 10:
list11 = []
list22 = []
num = random.randint(1,11)
if num > 6:
list11.append(num)
elif num < 6:
list22.append(num)
count += 1
print list11
print list22
chance()

python function to split a list by indexes

I am trying to build an efficient function for splitting a list of any size by any given number of indices. This method works and it took me a few hours to get it right (I hate how easy it is to get things wrong when using indexes)
Am I over-thinking this?
Code:
def lindexsplit(List,*lindex):
index = list(lindex)
index.sort()
templist1 = []
templist2 = []
templist3 = []
breakcounter = 0
itemcounter = 0
finalcounter = 0
numberofbreaks = len(index)
totalitems = len(List)
lastindexval = index[(len(index)-1)]
finalcounttrigger = (totalitems-(lastindexval+1))
for item in List:
itemcounter += 1
indexofitem = itemcounter - 1
nextbreakindex = index[breakcounter]
#Less than the last cut
if breakcounter <= numberofbreaks:
if indexofitem < nextbreakindex:
templist1.append(item)
elif breakcounter < (numberofbreaks - 1):
templist1.append(item)
templist2.append(templist1)
templist1 = []
breakcounter +=1
else:
if indexofitem <= lastindexval and indexofitem <= totalitems:
templist1.append(item)
templist2.append(templist1)
templist1 = []
else:
if indexofitem >= lastindexval and indexofitem < totalitems + 1:
finalcounter += 1
templist3.append(item)
if finalcounter == finalcounttrigger:
templist2.append(templist3)
return templist2

how to make a counter in python

I am trying to make a counter so if I type 'bye' it starts counting how long it has been since I said bye but the problem is that I can't type anything to stop the counter and I don't know how to have it tell you something when you type something to stop it. Here is my code for a counter but I tried to type something and it does not stop:
import time
s = 0
m = 0
h = 0
while s<=60:
print h, 'Hours', m, 'Minutes', s, 'Seconds'
time.sleep(1)
s+=1
if s == 60:
m+=1
s = 0
elif m ==60:
h+=1
m = 0
s = 0
Consider using threading.Thread:
import time
import threading
class MyTimer(threading.Thread):
def __init__(self):
self.h = 0
self.m = 0
self.s = 0
def count(self, t, stop_event):
while self.s <= 60:
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
time.sleep(1)
self.s += 1
if self.s == 60:
self.m += 1
self.s = 0
elif self.m == 60:
self.h += 1
self.m = 0
self.s = 0
elif stop_event.is_set():
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
break
class Asking(threading.Thread):
def asking(self, t, stop_event):
while not stop_event.is_set():
word = raw_input('enter a word:\n')
if word == 'bye':
timer_stop.set()
question_stop.set()
timer = MyTimer()
question = Asking()
question_stop = threading.Event()
timer_stop = threading.Event()
threading.Thread(target=question.asking, args=(1, question_stop)).start()
threading.Thread(target=timer.count, args=(2, timer_stop)).start()
Running it as an example:
$ python stackoverflow.py
enter a word:
0 Hours 0 Minutes 0 Seconds
0 Hours 0 Minutes 1 Seconds
0 Hours 0 Minutes 2 Seconds
0 Hours 0 Minutes 3 Seconds
hi
enter a word:
0 Hours 0 Minutes 4 Seconds
0 Hours 0 Minutes 5 Seconds
0 Hours 0 Minutes 6 Seconds
bye
0 Hours 0 Minutes 7 Seconds
The code could probably be a bit more neater :p. I shocked myself that I was able to produce this :D.
The only way I know is with pygame. It would set up a normal pygame loop, except having it only being 1 by 1, so you can see the background window, and when you enter in a letter it would exit the pygame loop.
maybe better...
.....
.....
while self.s <= 60:
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
time.sleep(1)
self.s += 1
if self.s == 60:
self.m += 1
self.s = 0
if self.m == 60:
self.h += 1
self.m = 0
elif stop_event.is_set():
print self.h, 'Hours', self.m, 'Minutes', self.s, 'Seconds'
break
......
......