Python - Create List from Recursive Loop - python

I'm trying to create a list from my recursive loop. I know it is able to produce the results I need since I've already checked that by printing the results.
Here's my recursive loop:
def move_forward_occurences(occurrences, firstListDt):
listingResults = []
for x in range(0, occurrences):
firstListDt = firstListDt + relativedelta(bdays=+2)
listingResults.extend(firstListDt)
return listingResults
Alternatively, the problem could be that I'm not checking it correctly:
if occurrences != 0:
listingResult = move_forward_occurences(occurrences, firstListDt)
for result in listingResult:
print(result)
An explanation of parameters if needed (they're pretty self explanatory already):
occurrences = number of times to produce result
firstListDt = start date
Thanks in advance!

Your return is overly indented. You want to defer the return until after the for loop has finished:
def move_forward_occurences(occurrences, firstListDt):
listingResults = []
for x in range(0, occurrences):
firstListDt = firstListDt + relativedelta(bdays=+2)
listingResults.extend(firstListDt)
return listingResults

Related

Sometimes I want a generator

The following code took me by surprise. I was hoping that I could write a function that might or might not act as a generator.
def mayGen(limit=5, asGenerator=False):
result = []
for i in range(1, limit + 1):
n = i * i
if asGenerator:
yield n
else:
result.append(n)
return result
print(mayGen(5, False))
for x in mayGen(5, True):
print(x)
But no, the output of this program is
<generator object mayGen at 0x7fa57b6ea7b0>
1
4
9
16
25
Calling mayGen with asGenerator=False is simply useless. It seems that the mere existence of a yield statement, regardless of whether it is executed, radically changes the behavior of the containing function.
So what if mayGen was actually big and complicated and I wish I could ask it to either function as a generator, or write its computed output to a file? Is there a well-traveled path here? How are people handling this sort of thing?
Just write a generator. You can always take its output and do whatever you want with it: put it in a list, write it to a file, etc. Although, if that's what you're going to be using it for a lot, you might want to write a wrapper function to do it for you, for example:
def willGen(limit=5):
for i in range(1, limit+1):
n = i * i
yield n
def willReturnList(*args, **kwargs):
return list(willGen(*args, **kwargs))
Edit: For a number of reasons mentioned in comments, this is probably not a great idea. In any event, you can write this:
def mayGen(limit=5, asGenerator=False):
def _generate(limit):
for i in range(1, limit + 1):
n = i * i
yield n
def _return(limit):
result = []
for i in range(1, limit + 1):
n = i * i
result.append(n)
return result
if asGenerator:
return _generate(limit)
return _return(limit)
Edit:
to simiplify even further, you should probably just return list(_generate(limit)) in the final line.

How assign a function which returns muliple values to a variable (python)

NORMAL CODE:
s = list(range(1))
for i in s:
print(i)
RESULT: (Vertical Display)
0
1
2
3
4
I want the same result using a function which i can assign to a variable and use inside a string literal.
def results():
for i in s:
print(i)
numbers = results()
report = f"Here is the list on numbers: {numbers}"
RESULT: None
When i use 'return' inside function, i get just one value.
Any better way to do this???
The function needs to collect all the results into a list instead of printing them. You can use a list comprehension for this.
def results():
return [i for i in s]
When you return within a function in python in a for loop, it will return the singular value and cease function execution. In this particular case, this should work if your desire is only string formatting:
def results():
ret = "\n"
for i in s:
ret += str(i) + "\n"
return ret
s = [1,2,3,4]
numbers = results()
print(f"Here you go: {numbers}")
def results():
s = list(range(10))
for i in s:
print(i)
return s
numbers = results()
report = f"Here is the list on numbers: {numbers}"

Python loop practice

I'm practicing loops. I've been trying to figure out how to get each character printed 4 times and place aside the others, eg: aaaaccccddddcccc. Right now the returned res is only showing me the last character printed 4 times (cccc). I tried nested for loops but that wasn't working for me either. How do I concatenate the returns? (or is there another way)
def quad_char(letter):
res = ''
for i in letter:
res = i * 4
return res
print(quad_char('acdc'))
You were almost there! :-)
On every loop, you are re-assigning to res, instead of appending to it (you overwrite res on every iteration, basically).
Try:
def quad_char(letter):
res = ''
for i in letter:
res = res + (i * 4)
return res
print(quad_char('acdc'))
Which can be shortened to:
def quad_char(letter):
res = ''
for i in letter:
res += i * 4
return res
print(quad_char('acdc'))
More on string concatenation here.
Also worth looking into the performance of various ways to concatenate strings here.
change res = i * 4 to res += i * 4
Could also do:
def quad_char(letter):
for i in letter:
print ("".join(i*4), end="")
forget the explicit for loop and use a list comprehension with a join
def quad_char(letters):
return ''.join(l*4 for l in letters)

How to write a recursive function that returns a list made up of squares of the elements of lst?

Im not sure how to get my recursion to work properly or keep from infinitely repeating.
This is what i have so far:
def listSquareR(lst):
if len(lst)== 1:
return lst[0]**2
else:
return lst[0]**2+[listSquareR(lst[1:])]
last return line is obviously wrong
Another possibility:
def listSquare(L):
if L: return [L[0]**2] + listSquare(L[1:])
else: return []
An even shorter version (as Cristian Ciupitu mentions below) is:
def listSquare(L):
return [L[0]**2] + listSquare(L[1:]) if L else []
You have it almost right, but the key is to mind your types. In your code:
def listSquareR(lst):
if len(lst)== 1:
return lst[0]**2 # Returning a number
else:
return lst[0]**2+[listSquareR(lst[1:])] # Returning a number plus a list of a list
We just need two small fixes:
def listSquareR(lst):
if len(lst)== 1:
return [lst[0]**2] # Returning a list
else:
return [lst[0]**2] + listSquareR(lst[1:]) # Returning a list plus a list
def SquareArea(width):
if width == 0:
return 0
else:
return SquareArea(width-1) + (2*width-1)
This is a recursive function I've recently used to find the area of a square.
And since the area of a square is Side*Side, one can use it to find the square of any function.
Now all that is required of you is to make a loop, eg:
for i in range (list):
and implement this function on i
Or maybe use while loop.
newList=[]
length = len(list)
while i != length:
newList.append(SquareArea(i))
And then return the newList

How to return each value from a for loop

(Using python 3.3.2) Hi, I'm trying to make a crawling function for a text cloud, which would go into a list of links and ideally return a list of the function's output for each element in that list. However, I'm stuck using a print function, print(b), instead of actually returning what I want. In my for loop, how would I return everything I would get from my print(b) statement. It can all be in one list or compiled some way or another. Thank you :)
tl;dr: how do I return all the stuff I get from a for loop
def crawl():
linkList = inputFunction()[1:][0] #makes a list of a bunch of URL's
for i in range(len(linkList)):
print(i)
t = getHTML(linkList[i]) #getHTML returns tuple of text in the input URL
alreadyCrawl = alreadyCrawl + list(linkList[i]) #ignore this
t = list(t)
b = counting(t) #makes dictionary of word counts
print(b)
return
Either you put them in a list and return the list at the end, or you "yield" them (hence creating a generator).
First way:
def f():
acc = []
for x in range(10):
acc.append(someFunctionOfX(x))
return acc
Second way:
def g():
for x in range(10):
yield someFunctionOfX(x)
Maybe the most important difference is the following: If any call to someFunctionOfX causes an exception in example 1, the function won't return anything. In example 2 if let's say the 5th value cannot be yielded for some reason, the previous four have already been yielded and probably used in the caller's context.
Here you can see the difference:
def f():
acc = []
for x in range(-3, 4):
acc.append (2 / x)
return acc
def g():
for x in range(-3, 4):
yield 2 / x
def testF():
for x in f(): print(x)
def testG():
for x in g(): print(x)
Calling testF simply fails (ZeroDivisionError: division by zero) and doesn't print anything. Calling testG prints
-0.6666666666666666
-1.0
-2.0
and fails then (ZeroDivisionError: division by zero).
My (very personal) criterion for either returning a list or yielding values is the following: If I need the data stored somewhere, I return a list. If I just need to process each member, I yield them.
You can return list of values that you want.
def crawl():
list_ret = [] #create empty list to store values
for i in range(len(linkList)):
# do some stuff
b = counting(t) #makes dictionary of word counts
list_ret.append(b) #append value to list
print(b)
return list_ret #return list of values
def crawl():
linkList = inputFunction()[1:][0] #makes a list of a bunch of URL's
return_list = []
for i in range(len(linkList)):
print(i)
t = getHTML(linkList[i]) #getHTML returns tuple of text in the input URL
alreadyCrawl = alreadyCrawl + list(linkList[i]) #ignore this
t = list(t)
b = counting(t) #makes dictionary of word counts
return_list.append(b)
return return_list

Categories

Resources