unitval.replace statements overwriting other part of code? - python

I am trying to convert units within an excel file. The code below was working until I added the unitval.replace statements, after which the unit conversion doesn't occur. These are to replace , to . in the data and " " to no space. Is it possible to write something like this and still get the unit conversion code below it to work? Thanks!
def unitConversion(ssheet,scollist,units,c):
if (units != None):
unitval = str(ssheet.cell_value(units,c))
factor = 1
if "," in unitval:
unitval = unitval.replace(",",".")
if " " in unitval:
unitval = unitval.replace(" ", "")
try:
factor = REF.conversions[unitval]
for i in range(0,len(scollist),1):
try:
scollist[i] = float(scollist[i]) * factor
except:
if (scollist[i] == ""):
scollist[i] = ""
elif ((scollist[i][0] == "<") or (scollist[i][0] == ">")):
temp = float(scollist[i][1:])
scollist[i] = "-" + str(temp/1000)

Related

How to correctly check through an array

Here is my code
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return str(code)
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + code)
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
So I basically want to generate a random string from the letters I have provided and then check if the user guesses a correct entry in that string (I'm trying to make mastermind). The issue I have is checking to see if the user's guess is in the code which is generated.
This is what my code outputs:
Why is my convCode variable printing ['E' and not EAFB?
If the code is returned as a list instead of a string, you can access the individual letters of the code in the manner you want to.
import random
codeLength=4
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + str(code))
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
In your gen_code function you convert the list to a string before you return it:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
# This converts it to a string, rather than leaving it as a list
# which is presumably what you want.
return str(code)
So later in your code:
convCode = code[0] + code[1] + code[2] + code[3]
Gives you the first four characters of that string which are exactly ['E'
Try changing gen_code to this:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
code is a list use slicing to get the required result which will give you flexibility as you need not write hardcoded list indices each time.
import random
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(5)
print("The code is " + str(code))
convCode =code[:4]
print(convCode)

Python formatting print

I'm having some formatting issues with my call to print function. For lack of knowledge of better ways to format, i've ended up with an issue. here is what it should look like
However the actual result of my print returns this.
def tupleMaker(inputString):
s1 = inputString.split()
# Adding the surname at the end of the string
s2 = [s1[len(s1) - 1]]
# Number of other names(no surname)
global noOfNames
noOfNames = len(s1) - 4
# Adding all the other names
for i in range(noOfNames):
s2.append((s1[i + 3]))
# Adding the Reg number
s2.append(s1[0])
# Adding the Degree scheme
s2.append(s1[2])
# Adding the year
s2.append("Year " + s1[1])
# Making it a tuple
t = ()
for i in range(len(s2)):
t = t + (s2[i],)
return t
def formatting(t):
s1 = ""
for i in range(len(t)):
s1 += t[i]
if (i == 0):
s1 += ", "
elif (i == len(t) - 4):
s1 += " "
else:
s1 += " "
#print(t[0] + ", ", end="")
#for i in range(noOfNames):
#print (t[i+1], end= " ")
#print(format(t[1+noOfNames], "<32s"))
#print(format(thenames, "<32d") + format(regNo, "<7d") + format(degScheme, ">6s") + format(year, ">1s")
print("")
print(s1)
I would recommend looking at using pythons built in string.format() function a small tutorial is located here: https://pyformat.info/

Dynamically create a Python function with positional or key-word args, not from a string

Over at this question there are some neat tricks for generating functions on the fly in Python.
In my use case, however, I need to make sure the generated function has a particular name and particularly-named arguments as well. I'll give an example.
Suppose I want to parse a Yaml file that has a format like this:
Root:
my_idea:
type: conditional
conditionals:
- foo
- bar
query: >
SELECT * FROM some_table
This needs to be interpreted as: create a function for me called "my_idea" which has arguments named "foo" and "bar" (in that order).
When the function is called, use some existing tool to connect to a database and prepare the query element from the Yaml file. Then add a WHERE clause based on the conditional names matching the values passed in to the function for that argument.
So, after this happens, a user should be able to call:
my_idea(10, 20)
and it would be equivalent to executing the query
SELECT * FROM some_table WHERE foo = 10 AND bar = 20
If I used def to make the function, it might be something like this:
def my_idea(arg1, arg2):
query = (query_retrieved_from_file +
" WHERE {}={} AND {}={}".format(arg1_name_from_file,
arg1,
arg2_name_from_file,
arg2))
connection = ExistingLibraryConnectionMaker()
return connection.execute(query).fetchall()
This is a really simplified example -- I'm not endorsing the specifics of this little function, just trying to illustrate the idea.
The question is: how to create this on-the-fly, where the name of the function and the name of the positional arguments are extracted from a text file?
In the other question, there is some example code:
import types
def create_function(name, args):
def y(): pass
y_code = types.CodeType(args,
y.func_code.co_nlocals,
y.func_code.co_stacksize,
y.func_code.co_flags,
y.func_code.co_code,
y.func_code.co_consts,
y.func_code.co_names,
y.func_code.co_varnames,
y.func_code.co_filename,
name,
y.func_code.co_firstlineno,
y.func_code.co_lnotab)
return types.FunctionType(y_code, y.func_globals, name)
but it's not clear how to have the positional args reflect what I want them to semantically reflect.
The other solution I found was like this:
import types
import sys,imp
code = """def f(a,b,c):
print a+b+c, "really WoW"
"""
module = imp.new_module('myfunctions')
exec code in module.__dict__
module.f('W', 'o', 'W')
Output:
WoW really WoW
This is much closer, but requires all of the code to be embedded in a string format. I'm looking to build up a function programmatically, and across a reasonably large set of options, so handling them all deep in strings is not doable.
LL Parser example, made for fun.
Generates
Generated Code:
def my_idea(arg0,arg1,atasdasd):
query = "SELECT * FROM some_table WHERE foo==arg0 AND bar>arg1"
connection = ExistingLibraryConnectionMaker()
return connection.execute(query).fetchall()
def lool(hihi,ahah):
query = "SELECT * FROM some_table WHERE foo<=hihi AND bar<ahah"
connection = ExistingLibraryConnectionMaker()
return connection.execute(query).fetchall()
###end
from
Root:
my_idea:
args :
-arg0
-arg1
-atasdasd
type: conditional
conditional:
-foo == arg0
-bar > arg1
query:
SELECT * FROM some_table
lool:
args :
-hihi
-ahah
type: conditional
conditional:
- foo <= hihi
- bar < ahah
query:
SELECT * FROM some_table
Can handle any number of functions.
Code:
from __future__ import print_function
import re
import traceback
import sys
glIndex = 0
code = ""
class Token(object):
def __init__(self, pattern, name, value=None, transform=None):
self.pattern = pattern
self.name = name
self.value = value
tokens = {
Token(r"(\()","lpar"),
Token(r"(\))","rpar"),
Token(r"(\d(?:\.\d*)?)","number"),
Token(r"(\+)", "plus"),
Token(r"(?!\-\-)(\-)","minus"),
Token(r"(?!\=\=)(\=)","egal"),
Token(r"(;)","colon"),
Token(r"([a-zA-Z][a-zA-Z0-9_]*)(?=[\s\:])","unique"),
Token(r"(\=)\=","=="),
Token(r"(\>\=)",">="),
Token(r"(\<\=)","<="),
Token(r"(?!\>\=)(\>)",">"),
Token(r"(?!\<\=)(\<)","<"),
Token(r"\:",":"),
Token(r"\*","*")}
def peekComp(l):
symbol = None
if peekMatch(l,">=") :
symbol = ">="
elif peekMatch(l,"<=") :
symbol = "<="
elif peekMatch(l,">") :
symbol = ">"
elif peekMatch(l,"<") :
symbol = "<"
elif peekMatch(l,"==") :
symbol = "=="
return symbol
def parseListItem(l):
match(l,"minus")
u = match(l,"unique")
return u
def parseTitle(l):
val = match(l,"unique")
match(l,":")
return val
def parseComp(l):
match(l,"minus")
lvar = match(l,"unique")
symbol = peekComp(l)
if symbol == None:
print("Homemaid SyntaxError: needed a comp symbol")
exit(1)
symbolS = match(l,symbol)
rvar = match(l,"unique")
return (lvar,symbolS,rvar)
def tokenize(s):
l=[]
i=0
while i < s.__len__():
if re.match(r"\s",s[i]):
i+=1
continue
foundAMatch = False
for t in tokens:
pat = "^(" + t.pattern + ").*"
#print("trying with pat :'"+pat+"';")
res = re.match(pat,s[i:])
if res != None:
print("Match: -what : '" + res.group(1) + "' -to-token-named :'" + t.name + "'; \t\tTotal text : '" + res.group(0) + "';" )
i += res.group(1).__len__()
foundAMatch = True
l.append(Token(t.pattern,t.name,res.group(1)))
break
if not foundAMatch:
print("Homemaid SyntaxError: No match for '" + s[i:] + "';")
quit()
return l
def syntaxError(l,fname):
global glIndex
print("Homemaid SyntaxError: '"+l[glIndex].name+"'")
print(fname)
quit()
def match(tokens, wanted):
global glIndex
if tokens[glIndex].name == wanted:
glIndex+=1
print("Matched '" + tokens[glIndex-1].value + "' as '" + wanted + "';")
return tokens[glIndex-1].value
else:
print("Homemaid Syntax Error : Match failed on token '" + tokens[glIndex].name + "' with wanted token '" + wanted + "' and text '" + tokens[glIndex].value + "';")
exit(1)
def peekMatch(token, wanted):
global glIndex
if glIndex < token.__len__() and token[glIndex].name == wanted:
print("Matched "+wanted)
return True
else:
return False
def parse(l):
#root
localCode = ""
rootName = parseTitle(l)
print("Root : " + rootName)
#parse funcitons
while peekMatch(l,"unique"):
localCode += parseFunction(l)
print("Done with the parsing.")
return localCode
def parseFunction(l):
print("CAME IN PARSE FUNCITON")
#function name
localCode = "\n\ndef " + parseTitle(l) +"(";
#args
args = set()
title = parseTitle(l)
if title!="args":
print("Homemaid Syntax Error : title should be 'args', was instead '" + title + "';")
exit(1)
while(peekMatch(l,"minus")):
lastArg = parseListItem(l)
args.add(lastArg)
localCode += lastArg
if peekMatch(l,"minus") :
localCode += ","
localCode += "):\n"
#type
if parseTitle(l)!="type":
print("Homemaid Syntax Error : title should be 'type'")
exit(1)
#query
##query name
queryTypeName = match(l, "unique")
##query args
queryTypeArgs = []
if parseTitle(l)!=queryTypeName:
print("Homemaid Syntax Error : title should be the same as the name of the query.")
exit(1)
while(peekMatch(l,"minus")):
queryTypeArgs.append(parseComp(l))
##query sql code
if parseTitle(l) != "query":
print("Homemaid Syntax Error : title should be 'query'.")
exit(1)
initialQuery = parseBasicSqlQuery(l)
if queryTypeName == "conditional" and queryTypeArgs.__len__() <= 0 :
print("Homemaid Syntax error : Conditional query needs at least one arg.")
exit(1)
##query codegen
localCode += "\tquery = \"" + initialQuery + " WHERE "
first = True
if queryTypeName == "conditional":
for lArg, cmpSign, rArg in queryTypeArgs:
if not first:
localCode += " AND "
if rArg in args:
first = False
localCode += lArg + cmpSign + rArg
else:
print("queryTypeArgs : " + str(queryTypeArgs))
print("Homemaid Logic Error: Query arg '" + rArg + "' is not in the funciton args " + str(args) + ".")
quit(1)
localCode += "\"\n\tconnection = ExistingLibraryConnectionMaker()\n\treturn connection.execute(query).fetchall()"
return localCode
def parseBasicSqlQuery(l):
selectS = match(l,"unique")
whatS = match(l,"*")
fromS = match(l,"unique")
tableNameS = match(l,"unique")
if selectS.upper() != "SELECT" or fromS.upper() != "FROM":
print("Homemaid Syntax error: bad basic sql.")
exit(0)
return selectS + " " + whatS + " " + fromS + " " + tableNameS
def parseVal(l):
if match(l, "lpar"):
parseVal(l)
match(l, "rpar")
elif peekMatch(l, "number") and (peekMatch(l, "plus") or peekMatch(l, "minus") or peekMatch(l, "equal")):
glIndex+=1
print("peekMatched!")
parseOp(l)
parseVal(l)
elif match(l, "number"):
pass
else:
syntaxError(l, "parseVal")
print("** Parsed val.")
def parseOp(l):
if match(l, "plus"):
pass
elif match(l, "minus"):
pass
elif match(l, "egal"):
pass
else:
syntaxError(l, "parseVal")
print("** Parsed op.")
if __name__ == "__main__":
with open("sqlGenTest.SQLGEN", "rw") as file:
print("File:\n'")
text = file.read()
print(text + "'\n")
tokens = tokenize(text)
names = map(lambda x: str("'" + x.name + "'" + " : " + "'" + x.value + "'"), tokens)
map(print,names)
code = parse(tokens)
print("")
print("###Generated Code:\n" + code)
print("###end")
print()

NameError: name 'countrychoice' is not defined

I'm having some trouble with the current program I'm writing.
I'm letting the user type in a country, and then a city city in that country, and then see a weather forecast for the choosen city using API.
I'm using a class, like this:
class requestChoice:
def __init__(self):
self.countrychoice = None
self.citychoice = None
def countryChoice(self):
self.countrychoice = input("Enter which country your city is in(in english): ")
def cityChoice(self):
self.citychoice = input("Enter the name of the city: ")
And my main program looks like this:
from requestchoice import requestChoice
import requests
if __name__ == '__main__':
"""Introducion"""
print ("\nThis program lets you see a weather forecast for your choosen city.")
rc = requestChoice()
while True:
print("\nWhen you have typed in country and city, press 3 in the menu to see the weather forecast for your choice.\n")
menu = input("\nPress 1 for contry\nPress 2 for city\nPress 3 to see forecast\nPress 4 to exit\n")
if menu == "1":
rc.countryChoice()
elif menu == "2":
rc.cityChoice()
elif menu == "3":
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
data = r.json()
try:
for day in data['forecast']['simpleforecast']['forecastday']:
print (day['date']['weekday'] + ":")
print ("Conditions: ", day['conditions'])
print ("High: ", day['high']['celsius'] + "C", '\n' "Low: ", day['low']['celsius'] + "C", '\n')
except Exception as e:
print ("\nHave you typed in the correct country and city?\nBecause we got a" ,e, "error")
else:
print ("\nGoodbye")
break
When I run my program I get the error NameError: name 'countrychoice' is not defined. It is going to be the same error with the citychoice. I've tried creating a list in my class and append the countrychoice to the list but without any luck. How am I supposed to make it work as wished?
You are getting a NameError on here:
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
because you have no names countrychoice and citychoice defined. Perhaps you meant to use rc.countrychoice and rc.citychoice instead?
You have to access them with the corresponding object name. In this case
rc.countrychoice
rc.citychoice
So, this line
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + countrychoice + "/" + citychoice + ".json")
becomes
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")
You need to use rc.countrychoice and rc.citychoice here
r = requests.get("http://api.wunderground.com/api/0def10027afaebb7/forecast/q/" + rc.countrychoice + "/" + rc.citychoice + ".json")

New Hangman Python

I am working on a Hangman game, but I am having trouble replacing the dashes with the guessed letter. The new string just adds on new dashes instead of replacing the dashes with the guessed letter.
I would really appreciate it if anyone could help.
import random
import math
import os
game = 0
points = 4
original = ["++12345","+*2222","*+33333","**444"]
plusortimes = ["+","*"]
numbers = ["1","2","3"]
#FUNCTIONS
def firstPart():
print "Welcome to the Numeric-Hangman game!"
def example():
result = ""
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
return ori
# def actualGame(length):
#TOP LEVEL
firstPart()
play = raw_input("Do you want to play ? Y - yes, N - no: ")
while (play == "Y" and (points >= 2)):
game = game + 1
points = points
print "Playing game #: ",game
print "Your points so far are: ",points
limit = input("Maximum wrong guesses you want to have allowed? ")
length = input("Maximum length you want for the formulas (including symbols) (must be >= 5)? ")
result = "" #TRACE
ori = random.choice(original)
for i in range(2,len(ori)):
if i % 2 == 0:
result = result + ori[i] + ori[0]
else:
result = result + ori[i] + ori[1]
test = eval(result[:-1])
v = random.choice(plusortimes) #start of randomly generated formula
va = random.choice(plusortimes)
formula = ""
while (len(formula) <= (length - 3)):
formula = formula + random.choice(numbers)
formula2 = str(v + va + formula)
kind = ""
for i in range(2,len(formula2)):
if i % 2 == 0:
kind = kind + formula2[i] + formula2[0]
else:
kind = kind + formula2[i] + formula2[1]
formula3 = eval(kind[:-1])
partial_fmla = "------"
print " (JUST TO TRACE, the program invented the formula: )" ,ori
print " (JUST TO TRACE, the program evaluated the formula: )",test
print "The formula you will have to guess has",length,"symbols: ",partial_fmla
print "You can use digits 1 to 3 and symbols + *"
guess = raw_input("Please enter an operation symbol or digit: ")
a = 0
new = ""
while a<limit:
for i in range(len(formula2)):
if (formula2[i] == partial_fmla[i]):
new = new + partial_fmla[i]
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
a = a+1
print new
guess = raw_input("Please enter an operation symbol or digit: ")
play = raw_input("Do you want to play ? Y - yes, N - no: ")
The following block seems problematic:
elif (formula2[i] == guess):
new[i] = guess
else:
new[i] =new + "-"
Python does not allow modification of characters within strings, as they are immutable (cannot be changed). Try appending the desired character to your new string instead. For example:
elif formula2[i] == guess:
new += guess
else:
new += '-'
Finally, you should put the definition of new inside the loop directly under, as you want to regenerate it after each guess.

Categories