Use of recursion for repetitive algorithms

--Originally published at Quirino´s Projects


Repetitive algorithms are useful when you want to do something with some values, then with the results of that, do the same until we reach to our desired result

#Ignore newList() its a function i created for creating a completely new list so the original won’t be affected

1 def chain(word,elements,wordChain):
2      elements = newList(elements)
3      wordChain.append(word)
4     elements.remove(word)
5     for nextWord in elements:
6          if word[-1] == nextWord[0]:
7               chain(nextWord,elements,wordChain)
8               return wordChain
9       newWordChain = newList(wordChain)
10       wordChain = []
11       return newWordChain

 

The function above at first its a bit hard to understand, so ill do my best, and explain step by step

The function creates the biggest chain possible with the following rule:

We have a word, the first character in the next word of the chain must be the same as the last one of the last of the word

In the first Function run the word is a word (doesn’t matter which one right now) in the elements list, elements is a list that contain a set of words, and wordChain will be the chain to be returned

(3) First, the word its appended, since it will be the first word

(4) We remove the word from the elements list so we can’t repeat words

(5-7)We search for every word in elements that meets our condition if it gets evaluated to true, then we call the function with the values we have right now

For the second run we do the same but now the function parameters are the ones from the first run, when the condition

not met, we simply return the wordChain