recursion in python - appending to a list - splunktool (2023)

  • Last Update :

  • Techknowledgy :

You could use a intermediate list to append to in each recursive call. That avoids these redefinition problems you're encountering currently:

def replicate_recur(times, data, result = None): if result is None: # create a new resultif no intermediate was givenresult = []if times == 1: result.append(data)else: result.append(data)replicate_recur(times - 1, data, result) # also pass in the "result"return result

When called:

>>> replicate_recur(4, 2)[2, 2, 2, 2]

To make your code work, you need to extend the list in the current execution with the output of the next recursive call. Also, the lowest depth of the recursion should be defined by times = 1:

def replicate_recur(times, data): result2 = []if times == 1: result2.append(data)else: result2.append(data)result2.extend(replicate_recur(times - 1, data))return result2

On another note, you can simply replicate your list with:

def replicate(times, data): return [data] * times

You can use xrange for this, there is no point to use recursion unless it is a coding test.

def replicate(times, data): result2 = []for i in xrange(times): result2.append(data)return result2

Same function can be written in a recursive way like this:

def replicate_recur(times, data, listTest = None): # If a list has not been passed as argument create an empty oneif (listTest == None): listTest = []# Return the listif we need to replicate 0 more timesif times == 0: return listTest# If we reach here at least we have to replicate oncelistTest.append(data)# Recursive call to replicate more times,if needed andreturn the resultreplicate_recur(times - 1, data, listTest)return listTest

Also you could consider doing data*times to replicate if data is a list or simply do

(result2.append(data)) * times

In the recursion, each time replicate_recur is called, a fresh result2 in new name space is created.

[data] * times

Suggestion : 2

The “left” child of the tree must contain a value lesser than its parent. ,We can use recursion to find the element with the minimum value in a list, as shown in the code below. ,The “right” child of the tree must contain a value greater than it’s parent. ,Computing the value of a Fibonacci number can be implemented using recursion. Given an input of index N, the recursive function has two base cases – when the index is zero or 1. The recursive function returns the sum of the index minus 1 and the index minus 2.

def myfunction(n): if n == 0: return nelse: return myfunction(n - 1) myfunction(1000) #results in stack overflow error
Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, ...
 5 / \/ \ 3 8 /\ / \2 4 7 9
def flatten(mylist): flatlist = []for element in mylist: if type(element) == list: flatlist += flatten(element)else: flatlist += elementreturn flatlist print(flatten(['a', ['b', ['c', ['d']], 'e'], 'f'])) # returns['a', 'b', 'c', 'd', 'e', 'f']
def fibonacci(n): if n <= 1: return nelse: return fibonacci(n - 1) + fibonacci(n - 2)
def countdown(value): call_stack = []while value > 0: call_stack.append({ "input": value}) print("Call Stack:", call_stack) value -= 1 print("Base Case Reached") while len(call_stack) != 0: print("Popping {} from call stack".format(call_stack.pop())) print("Call Stack:", call_stack) countdown(4)'''Call Stack: [{'input ': 4}] Call Stack: [{'input ': 4}, {'input ': 3}] Call Stack: [{'input ': 4}, {'input ': 3}, {'input ': 2}] Call Stack: [{'input ': 4}, {'input ': 3}, {'input ': 2}, {'input ': 1}] Base Case Reached Popping {'input ': 1} from call stack Call Stack: [{'input ': 4}, {'input ': 3}, {'input ': 2}] Popping {'input ': 2} from call stack Call Stack: [{'input ': 4}, {'input ': 3}] Popping {'input ': 3} from call stack Call Stack: [{'input ': 4}] Popping {'input ': 4} from call stack Call Stack: []'''

Suggestion : 3

I'm trying to create a recursive function that takes a JSON dictionary and stores any value with key names 'rate' into a list. I will then take that list and find the lowest value. My code looks like this right now, but is producing multiple empty lists within the list.,The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.,A call to index searches through the list in order until it finds a match, and stops there. If you expect to need indices of more matches, you should use a list comprehension, or generator expression.,Wrap the index call in a try/except block which catches ValueError (probably faster, at least when the list to search is long, and the item is usually present.)

I'm trying to create a recursive function that takes a JSON dictionary and stores any value with key names 'rate' into a list. I will then take that list and find the lowest value. My code looks like this right now, but is producing multiple empty lists within the list.

def recurse_keys(df): rates = []for key, value in df.items(): if key == 'rate': rates.append(value)if isinstance(df[key], dict): recurse_keys(df[key])

You need to combine the results from the recursion, and return it:

def recurse_keys(df): rates = []for key, value in df.items(): if key == 'rate': rates.append(value)if isinstance(df[key], dict): rates += recurse_keys(df[key])return rates
if not a: print("List is empty")

1._

>>> ["foo", "bar", "baz"].index("bar")1

2._

list.index(x[, start[, end]])

An index call checks every element of the list in order, until it finds a match. If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. In that case, you should consider a different data structure. Note that if you know roughly where to find the match, you can give index a hint. For instance, in this snippet, l.index(999_999, 999_990, 1_000_000) is roughly five orders of magnitude faster than straight l.index(999_999), because the former only has to search 10 entries, while the latter searches a million:

>>>import timeit >>> timeit.timeit('l.index(999_999)', setup = 'l = list(range(0, 1_000_000))', number = 1000)9.356267921015387 >>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup = 'l = list(range(0, 1_000_000))', number = 1000)0.0004404920036904514

A call to index results in a ValueError if the item's not present.

>>> [1, 1].index(2)Traceback (most recent call last):File "<stdin>", line 1, in <module> ValueError: 2 is not in list
list.index(x[, start[, end]])

Suggestion : 4

Python Program to Count the Occurrences of Elements in a Linked List using Recursion ,This is a Python Program to find the sum of elements in a list recursively.,Here is source code of the Python Program to find the sum of elements in a list recursively. The program output is also shown below.,Python Program to Count the Occurrences of Elements in a Linked List without Recursion

def sum_arr(arr, size): if (size == 0): return 0else: return arr[size - 1] + sum_arr(arr, size - 1)n = int(input("Enter the number of elements for list:"))a = []for i in range(0, n): element = int(input("Enter element:"))a.append(element)print("The list is:")print(a)print("Sum of items in list:")b = sum_arr(a, n)print(b)
Case 1: Enter the number of elementsfor list: 3Enter element: 3Enter element: 56Enter element: 7The list is: [3, 56, 7]Sum of items in list: 66Case 2: Enter the number of elementsfor list: 5Enter element: 23Enter element: 45Enter element: 62Enter element: 10Enter element: 56The list is: [23, 45, 62, 10, 56]Sum of items in list: 196

Suggestion : 5

In the last Chapter, we discussed Python Lists, how theStream object is similar to a List, and howwe can put Note objects into a Stream, lookat their offsets, and .show() the Stream in MusicXML or as text.We ended by putting one Stream inside another Stream, whichseemed like a neat trick until we discovered that we couldn’t get at theelements inside the inner Stream.,In this chapter we will work on how to exploit the power of nestedStreams. We’ll begin with a discussion of recursive lists (sinceStreams work a lot like lists). Those with some programming willprobably want to skip to the following section.,Oh, and since each of these is the last elements of their respectivelists, we could instead write:,In this chapter we looked at how we can look inside lists of lists,which will be important when we consider how to work with Streams ofStreams in music21, to look at Measures within Parts withina Score. We also learned how to define a function and writerecursive functions to do powerful work in just a few lines of code. Inthe next chapter we apply all this to music withStreams of Streams.

listA = [10, 20, 30]listB = [1, 2, 3, listA]
listB
 [1, 2, 3, [10, 20, 30]]
len(listB)
 4
listB[3]


Trending Technology

  • android × 15970
  • angular × 18982
  • api × 5999
  • css × 155656
  • html × 23420
  • java × 29699
  • javascript × 58592
  • json × 19745
  • php × 23600
  • python × 454736
  • reactjs × 27451
  • sql × 2974
  • typescript × 8420
  • xml × 3800


Most popular in

python

  • 1.) python 2.x: how to mock subprocess.popen if stdin=pipe
  • 2.) extracting text from scanned pdf without saving the scan as a new file image
  • 3.) explode nested struct in spark dataframe
  • 4.) how can i get data with order in python dictionary?
  • 5.) element-wise multiplication between all the elements of a vector
  • 6.) how to find descriptive statistics using groupby in pandas dataframe
  • 7.) plot data for many days in bar chart without date information
  • 8.) how to drop multiple columns based on their correlation with another column in the data frame?


Top Articles
Latest Posts
Article information

Author: Patricia Veum II

Last Updated: 04/07/2023

Views: 6328

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.