Result as new argument - python

I wish to repeat this function (say 200times), each time taking the output as a new argument:
def coop(url):
num_body = re.search('\d+', urllib.urlopen(url).read()).group(0)
num_head = re.search('\d+', url).group(0)
new = url.replace(num_head, num_body)
return new

You could do this with a simple loop:
for _ in range(0,200):
url = coop(url)
This works with the function you have written ands stores the result in url to feed into the next call.

Related

Get returned value of function in function which called it

I am newbie in python, and I build two functions in which, I am calling second function with 1 parameters in first function and I am trying to access second function's returned data in first function.
def second_function(first_param):
final = first_param + 50
return final
def first_function():
second_function(50)
# trying to access second_function's returned data HERE
print(second_function)
But it is not showing any returned data.
Any help would be much Appreciated. Thank You in Advance.
The problem here is that you are using print(second_function), so that will simply output the name of the function. Now, if you want to output the result of the function, you should do:
def second_function(first_param):
final = first_param + 50
return final
def first_function():
output = second_function(50)
print(output)
you could first put the returned value in a variable like this
def second_function(first_param):
final = first_param + 50
return final
def first_function():
value = second_function(60)
print(value )
or print the returned value with out using any variable
def second_function(first_param):
final = first_param + 50
return final
def first_function():
print(second_function(50))
That's because second_function is an object in its own right. Try either of the following:
def first_function():
out = second_function(50)
# trying to access second_function's returned data HERE
print(out)
def first_function_alternate():
print(second_function(50))
What's happening when you do print(second_function) is that the computer is trying to print the value of the function itself, not what it returns. We can store this value to a variable (my first answer) or simply generate it on-the-fly (my second answer).
In Python, the returned data from a function will be assigned to a variable. So you would use:
my_value = second_function(60)
and the returned value would be stored in the variable my_value

How can I share a function variable within a nested function?

UPDATED:
How can I use a function variable within nested function? I've simplified my problem in the following example:
def build():
n = 1 # code to parse rpm package minor version from file
f = min_ver(n) # update minor version
return
def min_ver(n):
n = 2 # this is defined by another process, not set intentionally
s = 1 + n # still need the original value from build()
return s
The actual use case is that I'm grabbing a parsed rpm package minor version value in ex1() from disk called 'n'. When ex2() is executed from ex1(), it deletes the old package, builds a new rpm package with a new minor version. So when it calls for ex1()'s value within the nested function, it's not changed to the new version.
How can I maintain the original 'n' value within the nested function, before passing onto a new value of 'n' post nested function?
A simple way to do this would be to pass the variable as an argument to ex2.
def build():
n = int(1)
f = ex2(n) # pass the value to the next function
n = int(5)
return
def min_ver(n_old):
n = 2
s = 1 + n_old # use the n that was passed in
return s
If you make ex2() actually nested then you can access the outer variables.
def ex1():
n = int(1)
def ex2():
s = 1 + n
return(s)
f = ex2()
n = int(5) # done with nested value, rewrite new value
return()
Also, you probably want to return f or n instead of an empty tuple, I would imagine.
And you don't need to say int(1) you can just say 1. Everything, including integers and strings, is implicitly an object in python.

Using result of a function as search conditional

I would like to insert the 1st result of the function def elliptic() into the 2nd function entity_noun(). In the 2nd function, it finds the node which has the attribute with a specific value. I want this value (which is a string in quotes "??????") to be retrieved from the returned value of the 1st function.
from bs4 import BeautifulSoup
def elliptic():
last_a_tag = soup.find_all("sn", elliptic="yes")
for item in last_a_tag:
entity = item.get('entity')
return(entity)
def entity_noun():
ent = soup.find(entity="??????")
noun = ent.find('n')
return(noun)
Do you have any suggestion how to do this?
You can pass the result of calling the function right in the parameters.
So in this case you would do:
ent = soup.find(entity=elliptic())
You have here two functions. function should be called to return a result.
if you do something like this :
from bs4 import BeautifulSoup
def elliptic():
last_a_tag = soup.find_all("sn", elliptic="yes")
for item in last_a_tag:
entity = item.get('entity')
return(entity)
def entity_noun():
ent = soup.find(entity=elliptic())
noun = ent.find('n')
return(noun)
entity_noun()
you will call entity_noun() which will call elliptic()
an other option is to use argument :
from bs4 import BeautifulSoup
def elliptic():
last_a_tag = soup.find_all("sn", elliptic="yes")
for item in last_a_tag:
entity = item.get('entity')
return(entity)
def entity_noun(X):
ent = soup.find(entity=X)
noun = ent.find('n')
return(noun)
A=elliptic()
entity_noun(A)
in this case you will call the first function elliptic() keep the result in A and then pass A to entity_noun(). with this second method each function will stay independent one from an other and so be used independently in different context.

Getting Bound method error when calling function from another class

So i have a class called read that is full of Def, im trying to call one of them and i get a 'Bound method' error, what do you think.
from ExcelRead import Read
t = Read()
L = t.other
print L
def Other():
User = []
Excel = []
lst = OpenExcel()
User = OpenFile("whatever.txt")
for item in lst:
Excel.append(str(item.value))
Excel = [line.strip() for line in Excel]
Differ = comp(User, Excel)
print Differ
This is calling other functions
Where other is the name of the function i want to call, this function does return a value. thanks for your help
You aren't getting any error at all here. You're simply printing the function, which is indeed bound.
As with any other function in Python, if you want to call it, you need to use parentheses:
L = t.other()
print L

multiple call to a function to return a list of accumulated result

try to loop in the main function, call to another function, at the end of the loop get a list of accumulative values:
code like this:
def stock_stats(i):
tmp=[]
tmp.append(i+10)
yield tmp
def main():
for stockid in total_nos_of_stock:
stockinfo=readstock(stockid)
result=stock_stats(stockinfo)
print(list(result))
expected result should be [stats for stock1,stats for stock2,...,stats for stockN]
try generator and closure, but didn't get it work.
i know i could append the values in the main loop or pass an empty list to called function, but i prefer most of the calculation in the called function and keep simple assignment in the main loop.
tkyou!
You mixed up couple of concepts to the point that is hard to say what is wrong. Idea behind generators is that they produce series of values. It is pointless to just have a list at try to yield it. This is how you should really do it:
def called_function(source):
for i in source:
yield i + 10
def main():
print(list(called_function(range(5))))
After reading your comment I guess that is what you really wanted:
def stock_stats(i):
return i + 10
def main():
result = []
for stockid in total_nos_of_stock:
stockinfo=readstock(stockid)
result.append(stock_stats(stockinfo))
print(result)
class Statistician(list):
KEYS = {'RSI':0, 'MACD':1, 'CAPRATIO':2, 'OTHER':3}
def __init__(self):
list.__init__(self)
def read_stocks(self, stocks):
for stock in stocks:
self.read_stock(stock)
def read_stock(self, stock):
self.append(stock)
def stock_stats(self, stock_info):
if stock_info not in Statistician.KEYS.keys() :
raise Exception('Unknow stock_info category. Please use one of the following value : {0}'.format(str(list(Statistician.KEYS.keys()))))
return list(map(lambda x: x[Statistician.KEYS[stock_info]],self))
if __name__ == "__main__":
stocks = [('rsi1', 'macd1','capratio1','other1'),
('rsi2','macd2','capratio2','other2'),
('rsi3', 'macd3','capratio3','other3')]
statistician = Statistician()
for stock in stocks :
statistician.read_stock(stock)
print(statistician.stock_stats('RSI'))
print(statistician.stock_stats('MACD'))
Execution :
python3 sof-script.py
['rsi1', 'rsi2', 'rsi3']
['macd1', 'macd2', 'macd3']
Do this match your need ?
==================================================================================
EDIT : The same code using a closure form, as requested in comments.
Assuming that stocks are constant you could do that. This is the only way to use closure that make sense using this implementation. Other that use a given Statistician and read the blocks data inside the collect function require to use a set instead of a list in order to avoid side effect and data duplication.
stocks = [('rsi1', 'macd1','capratio1','other1'),
('rsi2','macd2','capratio2','other2'),
('rsi3', 'macd3','capratio3','other3')]
S = Statistician()
S.read_stocks(stocks)
#define a closure function
def statisticCollector(statistician, key):
def collect():
return statistician.stock_stats(key)
return collect
#instanciate the closed function
collectRSI = statisticCollector(S, 'RSI')
collectMACD= statisticCollector(S, 'MACD')
if __name__ == "__main__":
print(collectRSI())
print(collectMACD())
instead of sending each i send total range to the called_function . so that you can yield total list at a time
def called_function(n):
yield list(range(10, 10+n))
def main():
result=called_function(5)
print(list(result))
main()

Categories

Resources