I have method called 'encode(string_argument)' which converts string(sentence) to ascii and reverse it. I have to write method which decode the string.
Code:
str1 = 'This is sample text'
def encode(str1):
encoded_str = ''
for i in str1:
encoded_str += str(ord(i))
return encoded_str[::-1]
def decode(encoded_str):
rev_encoded_str = encoded_str[::-1]
# Incomplete
encoded_str = encode(str1)
decode(encoded_str)
Input for encode():
This is sample text
Output from encode():
6110211016112310180121190179511235115012351150140148
Input for decode():
6110211016112310180121190179511235115012351150140148
Output from decode():
This is sample text
Thanks in advance.
Finally got the solution:
def encode(str1):
encoded_str = ''
for i in str1:
encoded_str += str(ord(i))
return encoded_str[::-1]
def decode(encoded_str):
reverse_string = encoded_str[::-1]
temp_array = convert_to_possible_string_ascii(reverse_string)
final_decoded_string = ""
for x in temp_array:
# print(str(chr(int(x)))+": "+x)
final_decoded_string = final_decoded_string + str(chr(int(x)))
print(final_decoded_string)
return final_decoded_string
def convert_to_possible_string_ascii(str_array):
temp_array = []
temp_char = ""
counter = 0
for current_char in range(0, len(str_array), 1):
temp_char = temp_char+str_array[current_char]
counter = counter+1
if counter==1:
temp_var = is_valid_string_ascii(temp_char)
if temp_var:
temp_array.append(temp_char)
counter = 0
temp_char = ""
elif counter==2:
temp_var = is_valid_string_ascii(temp_char)
if temp_var:
temp_array.append(temp_char)
counter = 0
temp_char = ""
elif counter==3:
temp_var = is_valid_string_ascii(temp_char)
if temp_var:
temp_array.append(temp_char)
counter = 0
temp_char = ""
return temp_array
def is_valid_string_ascii(ascii_value):
valid_list = list(range(65, 91)) + list(range(97, 123)) +[32]
boolean_var = False
if int(ascii_value) in valid_list:
boolean_var = True
return boolean_var
str1 = 'This is sample text'
encoded_str = encode(str1)
decode(encoded_str)
Related
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
I'm trying to set one of an objects attributes to be equal to a combination of other attributes.
class poly_Uservar(object):
def __init__(self):
self.long1 = 0
self.long2 = 0
self.long3 = 0
self.long4 = 0
self.x = 0
self.command = ''
self.formats = self.long1,self.long2,self.long3,self.long4
def setUservars(self):
for self.x in range (0,50):
decim1 = float(.07)*float(self.x)
decim2 = float(.07)*float(self.x+1)
self.long1 = float(float(10.00000) + float(decim1))
self.long2 = float(float(10.00000) + decim2)
self.long3 = float(self.long1 +.030000)
self.long4 = float(self.long3 +.020000)
cmd = self.command % self.formats
print cmd
time.sleep(.2)
def main():
type= raw_input('Enter type')
Uservar = poly_Uservar()
if type == '3':
Uservar.command = 'Uservar[%i]: 10.07000 %f 10.01000 %f 9.93000 %f\r'
Uservar.formats = Uservar.x,Uservar.long1,Uservar.long2,Uservar.long1
Uservar.setUservar()
if type == '4':
Uservar.command = 'Uservar[%i]: 10.07000 %f 10.01000 %f 9.93000 %f 9.93000 %f\r'
Uservar.formats = Uservar.x,Uservar.long1,Uservar.long2,Uservar.long2,Uservar.long1
Uservar.setUservar()
The issue that I'm running into is that my formats atrribute doesn't get updated to the other attributes as they get set. And I can't reassign them in the for loop because depending on user input the format changes. So cmd always prints out what the other attributes are initialized too. Is there a way to force my code to update my formats attribute as they change in my method?
Thanks in advace!
Ok I eventually came up with a solution that works. It is not very "pythonic", however, so If someone has a better way of doing it I still would love to see:) Anyways here's what I ended up doing.
class poly_Uservar(object):
def __init__(self):
self.long1 = 0
self.long2 = 0
self.long3 = 0
self.long4 = 0
self.command = ''
self.formats = [1,2,3]
def setUservars(self):
for self.x in range (0,50):
for x in range (0,50):
decim1 = float(.07)*float(x)
decim2 = float(.07)*float(x+1)
self.long1 = float(float(10.00000) + float(decim1))
self.long2 = float(float(10.00000) + decim2)
self.long3= float(self.long1 +.030000)
self.long4= float(self.long3 +.020000)
vals = [self.long1, self.long2, self.long3, self.long4]
cmd_args = [x]
for i in range (0, len(self.formats)):
cmd_args.append(vals[self.formats[i]-1])
cmd = self.command % tuple(cmd_args)
print cmd
def main():
type= raw_input('Enter type')
Uservar = poly_Uservar()
if type == '3':
Uservar.command = ':Uservar[%i] 10.07000 %f 10.01000 %f 9.93000 %f\r'
Uservar.formats = [1,2,1]
Uservar.setUservar()
I am having trouble storing the ID to keys, like a sub (parent-child) kind of thing. I spent hours on it and could not figure a way to accomplish this. What output I am expecting is at the end of this post. Any help would be great.
import sys
import collections
dict = collections.OrderedDict()
dict["A.1"] = {"parent_child":0}
dict["A.1.1"] = {"parent_child":1}
dict["A.1.1.1"] = {"parent_child":2}
dict["A.1.1.2"] = {"parent_child":2}
dict["A.1.1.3"] = {"parent_child":2}
dict["A.1.2"] = {"parent_child":1}
dict["A.1.2.1"] = {"parent_child":2}
dict["A.1.2.2"] = {"parent_child":2}
dict["A.1.2.2.1"] = {"parent_child":3}
dict["A.1.2.2.2"] = {"parent_child":3}
dict["A.1.2.3"] = {"parent_child":2}
dict["A.1.3"] = {"parent_child":1}
dict["A.1.4"] = {"parent_child":1}
print(dict)
new_dict = {}
p = 0 # previous index
i = 0 # current
n = 1 # next index
current_PC = 0 # current parent_child
next_PC = 0 # next parent_child
previous_id = ""
current_id = ""
next_id = ""
change_current = True
change = True
lst = []
while(True):
if change_current:
current_id = dict.keys()[i]
current_PC = dict.values()[i]["parent_child"]
change_current = False
try:
next_id = dict.keys()[n]
next_PC = dict.values()[n]["parent_child"]
except:
pass # it will go out of index
print("KEY {0}".format(current_id))
if next_PC > current_PC:
if next_PC - current_PC == 1:
lst.append(next_PC)
next_PC += 1
print("next_PC: {0}".format(next_PC))
if next_PC == current_PC:
new_dict[current_id] = lst
lst = []
break
print(new_dict)
Trying to make output looks like this (at in similar way), the new_dict should look like:
new_dict["A.1"] = ["A.1.1", "A.1.2", "A.1.3", "A.1.4"]
new_dict["A.1.1"] = ["A.1.1.1", "A.1.1.2", "A.1.1.3"]
new_dict["A.1.1.1"] = []
new_dict["A.1.1.2"] = []
new_dict["A.1.1.3"] = []
new_dict["A.1.2"] = ["A.1.2.1", "A.1.2.2", "A.1.2.3"]
new_dict["A.1.2.1"] = []
new_dict["A.1.2.2"] = ["A.1.2.2.1", "A.1.2.2.2"]
new_dict["A.1.2.2.1"] = []
new_dict["A.1.2.2.2"] = []
new_dict["A.1.2.3"] = []
new_dict["A.1.3"] = []
new_dict["A.1.4"] = []
This gives you the output you are asking for. Since i did not see a {"parent_child":...} in you desired output i did not proceed with anything else.
options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]
new_dict = {}
for i, key in enumerate(options):
new_dict[key] = []
ls = []
for j, opt in enumerate(options):
if (key in opt) and (len(opt)-len(key)==2):
new_dict[key].append(opt)
print(new_dict)
EDIT
Using the comment of #Ranbir Aulakh
options = ["A.1","A.1.1","A.1.1.1","A.1.1.2","A.1.1.3","A.1.2","A.1.2.1","A.1.2.2","A.1.2.2.1","A.1.2.2.2","A.1.2.3","A.1.3","A.1.4"]
new_dict = {}
for i, key in enumerate(options):
new_dict[key] = []
ls = []
for j, opt in enumerate(options):
if (key in opt) and (len(opt.split("."))-len(key.split("."))==1):#(len(opt)-len(key)==2):
new_dict[key].append(opt)
print(new_dict)
I have an empty list, (r) and declared first element as r[0] = a
import time, urllib.request,random
def getDictionary():
word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"
response = urllib.request.urlopen(word_site)
txt = response.read()
return txt.splitlines()
def getWordsList(listOfWords, sample):
word = ""
randWords = []
for i in range(0,sample):
while(len(word) <=2):
word = random.choice(listOfWords).decode('utf-8')
randWords.append(word)
word = ""
return randWords
start = True
noOfWords = 25
words = getDictionary()
wordsList = getWordsList(words, noOfWords)
start = True
print ("\nINSTRUCTIONS\nWhen the coundown gets to zero, type the word in lowercase letters!\n That's the only rule!")
name = input("What is your name? ")
name = name.split(" ")
input("Press enter when ready...")
while start == True:
print("Game will start in: ")
print ("3 seconds")
time.sleep(1)
print ("2 seconds")
time.sleep(1)
print ("1 seconds")
time.sleep(1)
times = []
k = list()
r = list()
for i in range(25):
startTime = time.time()
userWord = input(str(i+1) + ". " + wordsList[i].capitalize() + " " )
k.append(wordsList[i].capitalize())
if (userWord.lower() == wordsList[i].lower()):
endTime = time.time()
times.append(endTime - startTime)
r[i] = str(endTime - startTime)
else:
times.append("Wrong Word")
r[i] = ("Wrong Word")
Above is where I am having a problem.
for i in range(25):
startTime = time.time()
print (str(i+1) + ". " + str(k[i]) + ": " + str(times[i]) )
a = 0
for i in range(25):
a = a+i
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
b = (a/len(r))
c = round(b, 2)
print (c)
start = False
here is my error:
r[i] = "Wrong Word"
IndexError: list assignment index out of range
The pop() method removes an element from the list and returnes it (see an example). What I think is happening is that at some point the condition of the if statment resolves to true. Next, after calling r.pop(i) r is replaced by its i-th element. It's probpably a string so calling its (i+1)-th element later can result in Index out of range error.
In other words, something like this is happening:
r = ["a", "foo", "bar", "baz"]
for i in range(4):
if r[i] == "a": # for i=0 this gives "a" == "a"
r = r.pop(i) # later,this results in r = "a"
next loop iteration with i = 1 will result in "a"[1] which will result in Index out of range.
All in all instead of:
for i in range(25):
if r[i] == "Wrong Word":
r = r.pop(i)
you could just write:
r = [item for item in r if item != "Wrong word"]
which would be also more pythonic solution.
I am using below code snippet to get the red reduced price from amazon but simehow I am always getting the old price and not the reduced red one.
enter code here`def getSignedUrlAmazon(searchvalue):
params = {'ResponseGroup':'Medium',
'AssociateTag':'',
'Operation':'ItemSearch',
'SearchIndex':'All',
'Keywords':searchvalue}
action = 'GET'`enter code here`
server = "webservices.amazon.in"
path = "/onca/xml"
params['Version'] = '2011-08-01'
params['AWSAccessKeyId'] = AWS_ACCESS_KEY_ID
params['Service'] = 'AWSECommerceService'
params['Timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
# Now sort by keys and make the param string
key_values = [(urllib.quote(k), urllib.quote(v)) for k,v in params.items()]
key_values.sort()
# Combine key value pairs into a string.
paramstring = '&'.join(['%s=%s' % (k, v) for k, v in key_values])
urlstring = "http://" + server + path + "?" + \
('&'.join(['%s=%s' % (k, v) for k, v in key_values]))
# Add the method and path (always the same, how RESTy!) and get it ready to sign
hmac.update(action + "\n" + server + "\n" + path + "\n" + paramstring)
# Sign it up and make the url string
urlstring = urlstring + "&Signature="+\
urllib.quote(base64.encodestring(hmac.digest()).strip())
return urlstring
forgot the price grabbing part:
def getDataAmazon(searchvalue,PRICE, lock):
try:
searchvalue = removeStopWord(searchvalue)
url = getSignedUrlAmazon(searchvalue)
data = etree.parse(url)
root = objectify.fromstring(etree.tostring(data, pretty_print=True))
gd=[]
gd1=[]
counter = 0
if hasattr(root, 'Items') and hasattr(root.Items, 'Item'):
for item in root.Items.Item:
cd={}
priceCheckFlag = False
try :
if hasattr(item.ItemAttributes, 'EAN'):
cd['EAN'] = str(item.ItemAttributes.EAN)
elif hasattr(item, 'ASIN'):
cd['ASIN'] = str(item.ASIN)
cd['productName'] = str(item.ItemAttributes.Title)
if hasattr(item, 'SmallImage'):
cd['imgLink'] = str(item.SmallImage.URL)
elif hasattr(item, 'MediumImage'):
cd['imgLink'] = str(item.MediumImage.URL)
cd['numstar'] = "0"
cd['productdiv'] = '1'
cd['sellername'] = 'Amazon'
if hasattr(item, 'DetailPageURL'):
cd['visitstore'] = str(item.DetailPageURL)
if hasattr(item.ItemAttributes, 'ListPrice') and hasattr(item.ItemAttributes.ListPrice, 'Amount'):
cd['price'] = item.ItemAttributes.ListPrice.Amount/100.0
elif hasattr(item, 'OfferSummary') and hasattr(item.OfferSummary, 'LowestNewPrice'):
cd['price'] = item.OfferSummary.LowestNewPrice.Amount/100.0