How do I put these variables in place correctly? - python

u = 'stringandstring'
b = "network:"
e = "yeser;"
def haystack(b,e,u):
i = re.search('%s(.*)%s', u)
r = i.group(1)
return r
or
.....
def haystack(b,e,u):
i = re.search('b(.*)e', u)
.....
how do i get those variables inside that function correctly?

I guess you can try concatenation (str1+str2)
def haystack(b,e,u):
i = re.search(b+'(.*)'+e, u)
if i: #check if there is any result
return i.group(1) #return match
#now try to call it
print haystack("this","str","this is str") #this should output ' is '
print haystack("no","no", "this is str") #this should not print anything
this is working perfectly for me so far

Related

How can I write the code in such a way that multiple functions get created but I don't have to write the same code again and again?

I have all these functions doing a similar task. How can I write the code in such a way that all these functions get created but I don't have to write the same code again and again?
def get_civilservice_result(user_skill_string):
civilservice_keyword = firestore.client().collection('keyword').document('civilservice').get().to_dict()['key']
civilservice_keyword_string = ' '.join(str(e) for e in civilservice_keyword)
result = get_result(user_skill_string, civilservice_keyword_string)
return result
def get_education_result(user_skill_string):
education_keyword = firestore.client().collection('keyword').document('education').get().to_dict()['key']
education_keyword_string = ' '.join(str(e) for e in education_keyword)
result = get_result(user_skill_string, education_keyword_string)
return result
def get_engineering_result(user_skill_string):
engineering_keyword = firestore.client().collection('keyword').document('engineering').get().to_dict()['key']
engineering_keyword_string = ' '.join(str(e) for e in engineering_keyword)
result = get_result(user_skill_string, engineering_keyword_string)
return result
You can use more input variables to change what the function does based on its inputs. Like this:
def get_result_(user_skill_string, document_type: str):
engineering_keyword = firestore.client().collection('keyword').document(document_type).get().to_dict()['key']
engineering_keyword_string = ' '.join(str(e) for e in engineering_keyword)
result = get_result(user_skill_string, engineering_keyword_string)
return result
I would do a loop for the list of keywords you are using:
def get_skill_result(user_skill_string, skill_field):
for skill in skill_field:
skill_keyword = firestore.client().collection('keyword').document(skill).get().to_dict()['key']
skill_keyword_string = ' '.join(str(e) for e in skill_keyword)
result.append(get_result(user_skill_string, skill_keyword_string))
return result
fields = ["civilservice","education","engineering"]
data = get_skill_result(user_skill_string, fields)
I would go ahead and say that you don't even need the 3 functions at all.
You are performing 2 basic operations:
creating a keyword_string for a specific document name;
getting the final result, for both the user_skill_string and the above keyword_string.
Well, It seems you already have the second function get_result coded somewhere. You just need one for get_keyword_string.
def get_keyword_string(document_name):
keyword = firestore.client().collection('keyword').document(document_name).get().to_dict()['key']
return ' '.join(str(e) for e in engineering_keyword)
That is it!
Now, in the call site, where you wanted to invoke get_civilservice_result, you just need to do this instead:
get_result(user_skill_string, get_keyword_string('civilservice'))

Returning values from function in python 3.5

I am aware that this question was asked before and I have checked the answers, tried the solutions but so far I couldn't achieve what I want.
Essentially I defined 2 different functions which print values from different sources. What I am trying to do is grab those values and compare them with each other.
coins_list_text_file= open("coins.text","r").read().split("\n")
coins_list_text_file = list(filter(None, coins_list_text_file))
def wazi():
symbol = list(map(lambda x: "{}{}".format(x, "inr").lower(), coins_list_text_file))
response = requests.get('https://api.wazirx.com/sapi/v1/tickers/24hr')
wazirx_list = json.loads(response.content)
filtered_list = [d for d in wazirx_list if d["symbol"] in symbol]
for values in filtered_list:
w_symbol = str(values["symbol"])
w_bid_price = float(values["bidPrice"])
w_ask_price = float(values["askPrice"])
def binance(): #check prices on binance exchange
symbol = list(map(lambda x: "{}{}".format(x, "USDT"), coins_list_text_file))
response = requests.get('https://api.binance.com/api/v3/ticker/24hr')
binance_list = json.loads(response.content)
filtered_list = [d for d in binance_list if d["symbol"] in symbol] #filter binance list
for values in filtered_list:
binance_symbol = str(values["symbol"])
binance_bid_price = float(values["bidPrice"])
binance_ask_price = float(values["askPrice"])
def compare(): #this part is not working
if binance_symbol == w_symbol
if binance_ask_price < w_ask_price:
print("buy" + binance_symbol + "on Binance")
else:
print("buy" + binance_symbol + "on Wazirx")
compare()
I think you are looking for something like this, try this it will work:
import requests
import json
def compare():
wazi_symbol = list(map(lambda x: "{}{}".format(x, "USDT").lower(), coins_list_text_file))
response_wazi = requests.get('https://api.wazirx.com/sapi/v1/tickers/24hr')
wazirx_list = json.loads(response_wazi.content)
wazi_filtered_list = [d for d in wazirx_list if d["symbol"] in wazi_symbol]
binance_symbol = list(map(lambda x: "{}{}".format(x, "USDT"), coins_list_text_file))
binance_response = requests.get('https://api.binance.com/api/v3/ticker/24hr')
binance_list = json.loads(binance_response.content)
binance_filtered_list = [d for d in binance_list if d["symbol"] in binance_symbol]
for wazir_value in wazi_filtered_list:
for binance_value in binance_filtered_list:
#print(str(wazir_value["symbol"]).lower()," ",str(binance_value["symbol"]).lower())
if str(wazir_value["symbol"]).lower() == str(binance_value["symbol"]).lower():
if float(wazir_value["bidPrice"]) < float(binance_value["bidPrice"]):
print("buy {} on Binance".format(str(binance_value["symbol"])))
else:
print("buy {} on wazir".format(str(binance_value["symbol"])))
compare()
The reason why your code is not working is that the variables you are trying to compare
if binance_symbol == w_symbol
if binance_ask_price < w_ask_price:
print("buy" + binance_symbol + "on Binance")
else:
print("buy" + binance_symbol + "on Wazirx")
which are binance_symbol and w_symbol
are not defined in the scope of the function.
When defining a function, all variables defined inside the function are only available in that context. If you would like to access those variables outside the function you would either have to define them as global variables, which is not as good a solution, or return them and get them outside of that function.
You are doing neither.
You should add return statements at the end of the functions manipulating the variables you are interested in (in your case those will be wazi and binance) and, get the results and use those when doing the Comparison.

Print the entire expression object of sympy when changes in internal structure occur

So as the question says i want to print an entire expression object when internal structure of its tree changes, but as the sympy objects are immutable i cannot to do this with the name the object is bound to
Here is an example of Code on how i am changing the Internal Structure
from sympy import *
from sympy.abc import x,y
input = 'x*(x+4)+3*x'
expr = sympify(input,evaluate=False)
def traverse(expr):
if(expr.is_Number):
return 1,True
oldexpr = expr
args = expr.args
sargs = []
hit = False
for arg in args:
arg,arghit = traverse(arg)
hit |= arghit
sargs.append(arg)
if(hit):
expr = expr.func(*sargs)
return expr,True
else:
return oldexpr,False
print(srepr(expr))
expr,hit = traverse(expr)
print(expr)
here i am changing the number to 1 whenever i encounter a number in the expression tree. And i want to print the complete expression when i made the change like this: x*(x+1)+3*x and then x*(x+1)+x
Can anyone suggest me on how to achieve this.
Just a slight mod to what you have might be what you are looking for:
def traverse(expr):
if any(a.is_Number and abs(a) != 1 for a in expr.args):
print(expr,'->',expr.func(*[(a if not a.is_Number else 1) for a in expr.args]))
if expr.is_Number and abs(expr) != 1:
return 1, True
oldexpr = expr
args = expr.args
sargs = []
hit = False
for arg in args:
arg,arghit = traverse(arg)
hit |= arghit
sargs.append(arg)
if(hit):
expr = expr.func(*sargs)
return expr, True
else:
return oldexpr, False
This produces
>>> traverse(2*x+3)
(2*x + 3, '->', 2*x + 1)
(2*x, '->', x)
(x + 1, True)
/c

Invalid syntax. I save my text file on my desktop calling it file.

Create graph:-
def loadGraphFile(file):
graph = []
for line in file:
contents = line.split()
movieName = contents[0]
actorNames = [contents[i]+ " " + contents[i+1] for i in range(1, len(contents), 2)]
movieNode = findNode(graph, movieName)
if movieNode == None:
movieNode = mkNode(movieName)
graph.append(movieNode)
for actorName in actorNames:
actorNode = findNode(graph,actorName)
if actorNode == None:
actorNode = mkNode(actorName)
graph.append(actorNode)
actorNode.neighbor.append(movieNode)
movieNode.neighbor.append(actorNode)
return graph
def loadGraphFileName('file.text'):
return loadGraphFile(Open('file.text'))
You declared your function wrong:
def loadGraphFileName('file.text'): # change this
return loadGraphFile(Open('file.text'))
To this:
def loadGraphFileName(): # You don't use it anyway
return loadGraphFile(Open('file.text'))
Or:
def loadGraphFileName(filename='file.text'): # file.text will be the default. if you give an parameter with it, filename will change to that parameter
return loadGraphFile(Open(filename)) # And use it here
You cannot have literals as function params
You can instead do
def loadGraphFileName(f = 'file.txt'):
return loadGraphFile(Open(f))

Python -- using __init__ with an inherited method for polynomials class

This is a class which will take in as input and then output a polynomial in string form (both ways same format). Some arithmetic is performed in the various methods. I've been trying to inherit this class into another class that will then use the __mod__() special method of the first class (or make it's own special method if necessary but I don't see how you can't just use the original method) to perform the mod on intake. Seems like this goes into __init__() but I've tried 5 different versions of this, even going so far as to change the parent class, and I'm getting nowhere. I'm teaching myself Python so I'm sure that even a junior Python dev can see where I'm going totally wrong.
import re
class GF2Polynomial(object): #classes should generally inherit from object
def __init__(self, string):
'''__init__ is a standard special method used to initialize objects.
Here __init__ will initialize a gf2infix object based on a string.'''
self.string = string #basically the initial string (polynomial)
self.key,self.lst = self.parsePolyVariable(string) # key determines polynomial compatibility
self.bin = self.prepBinary(string) #main value used in operations
def id(self,lst):
"""returns modulus 2 (1,0,0,1,1,....) for input lists"""
return [int(lst[i])%2 for i in range(len(lst))]
def listToInt(self,lst):
"""converts list to integer for later use"""
result = self.id(lst)
return int(''.join(map(str,result)))
def parsePolyToListInput(self,poly):
"""
replaced by parsePolyVariable. still functional but not needed.
performs regex on raw string and converts to list
"""
c = [int(i.group(0)) for i in re.finditer(r'\d+', poly)]
return [1 if x in c else 0 for x in xrange(max(c), -1, -1)]
def parsePolyVariable(self,poly):
"""
performs regex on raw string, converts to list.
also determines key (main variable used) in each polynomial on intake
"""
c = [int(m.group(0)) for m in re.finditer(r'\d+', poly)] #re.finditer returns an iterator
letter = [str(m.group(0)) for m in re.finditer(r'[a-z]', poly)]
m = max(c); varmatch = True; key = letter[0]
for i in range(len(letter)):
if letter[i] != key: varmatch = False
else: varmatch = True
if varmatch == False: return "error: not all variables in %s are the same"%a
d = [1 if x in c else (1 if x==0 else (1 if x=='x' else 0)) for x in xrange(m, -1, -1)]
return key,d
def polyVariableCheck(self,other):
return self.key == other.key
def prepBinary(self,poly):
"""converts to base 2; bina,binb are binary values like 110100101100....."""
x = self.lst; a = self.listToInt(x)
return int(str(a),2)
def __mod__(self,other):
"""
__mod__ is the special method for overriding the % operator
returns remainder formatted as polynomial
"""
if self.polyVariableCheck(other) == False:
return "error: variables of %s and %s do not match"%(self.string,other.string)
if self.bin == other.bin: return 0
return GF2Polynomial(self.outFormat(self.bin%other.bin))
def __str__(self):
return self.string
def outFormat(self,raw):
"""process resulting values into polynomial format"""
raw = "{0:b}".format(raw); raw = str(raw[::-1]); g = [] #reverse binary string for enumeration
g = [i for i,c in enumerate(raw) if c == '1']
processed = "x**"+" + x**".join(map(str, g[::-1]))
proc1 = processed.replace("x**1","x"); proc2 = proc1.replace("x**0","1")
if len(g) == 0: return 0 #return 0 if list empty
return proc2 #returns result in gf(2) polynomial form
The desired result is to be able to call it on a new (child) class with the parent type and while changing the parent class as little as possible (if even at all). Note that class "BinaryField" is the intended child class:
p=GF2Polynomial("x**2+x**1+x**0")
a=BinaryField("x**1+x**0", p)
b=BinaryField("x**1", p)
On intake, the given polynomial should be modulus divided by the 2nd element (here it's 'p'). This is necessary for finite field math.
EDIT:
when running it with --
## "x**1 + x**0" polynomial string style input
poly1 = "x**14 + x**1 + x**0"; poly2 = "x**6 + x**2 + x**1"; poly3 = "y**6 + y**2 + y**1"
a = GF2Polynomial(poly1); b = GF2Polynomial(poly2); c = GF2Polynomial(poly3)
## "x+1" polynomial string style input
poly4 = "x**14 + x + 1"; poly5 = "x**6 + x**2 + x"; poly6 = "y**6 + y**2 + 1"
d = GF2Polynomial(poly4); e = GF2Polynomial(poly5); f = GF2Polynomial(poly6)
bf1 = BinaryField(poly1,b); print bf1
bf2 = BinaryField(poly4,e); print bf2
Both of these styles are possible because of the way I coded it, but they should both return the same answer. However the result on that code is:
>>>
x**5 + x**4 + x**3 + 1
x**5 + x
Also, when using BinaryField(poly4,d), which is just the same string with it's GF2Polynomial() initialization, this errors as:
AttributeError: 'int' object has no attribute 'string'
Does this solves your problem?
class BinaryField(GF2Polynomial):
def __init__(self, string, mod):
modded = GF2Polynomial(string) % mod
super(BinaryField, self).__init__(modded.string)
>>> p = GF2Polynomial("x**2+x**1+x**0")
>>> a = BinaryField("x**1+x**0", p)
>>> print a
x + 1
You can also make the BinaryField class to be just a factory method:
def BinaryField(string, mod):
return GF2Polynomial(string) % mod

Categories