Code

Recursion in Real Life

Recursion in Real Life

Free Python Course ➞ Mini-course for beginners and experienced coders. 4 cool projects in the portfolio, live communication with the speaker. Click and find out what you can learn in the course.

Learn more

Recursive functions became clear to me in computer science classes. At first, I perceived recursion as an abstract concept, having no relation to real life. However, in school they don’t mention that recursion is present in nature, science, and art. Recursive algorithms find application even in everyday tasks, which makes them much more significant and practical than it seems at first glance.

What is recursion

In programming, a recursive function is a function that calls itself with modified parameter values. This method allows you to solve problems by breaking them down into simpler subproblems. Recursion is widely used in algorithms such as sorting, searching, and data processing. Proper use of recursive functions can significantly simplify code and make it more understandable, but it is important to be aware of potential risks such as stack overflow.

A function can be called by itself, and it can also be called through intermediate functions. For example, function A initiates function B, which then calls function A again. This phenomenon is called recursion and is widely used in programming to solve complex problems where the solution can be represented as repeated subproblems. Recursive functions can significantly simplify code and improve its readability, but it is important to be aware of the possibility of infinite loops and optimize them using mechanisms such as memoization.

A chain of function calls cannot continue indefinitely. It must terminate and produce a result. This requires an edge case in which the function no longer calls itself with new parameters. In such situations, a ready-made answer can be returned immediately, avoiding further recursion. This ensures the efficiency of the algorithm and prevents call stack overflow.

It sounds complicated, but don't worry - everything will become clearer with an example.

A recursive function is a powerful tool in programming, and a classic example of its use is calculating a factorial. The factorial of a number N is denoted as N! and is equal to the product of all natural numbers from 1 to N. This is a simple yet effective application of recursion, allowing you to solve problems related to combinatorics and mathematical analysis. The recursive approach not only simplifies the code, but also makes it more readable, which is especially important when developing complex algorithms.

In this case, when N=0, we are dealing with a special case. The function in this case does not perform any calculations and immediately returns the value of one. This is based on the mathematical definition according to which the factorial of zero is one.

Recursion in a broader sense means a description or representation of an object, phenomenon, or thing within itself. The recursive principle is the self-reproduction and complexity of a system according to the same algorithm. This approach is widely used in various fields, including programming, mathematics, and artificial intelligence. Recursion allows for the creation of efficient solutions to complex problems, simplifying the process of developing and analyzing systems. Understanding recursive methods is key for specialists working with algorithms and data structures.

In this context, it becomes clear that humans can be viewed as recursive structures. Every cell in our body contains the information necessary for the functioning of the entire organism, and DNA molecules contain instructions for the synthesis of DNA itself. This allows us to understand how complex biological systems are organized and develop based on recursive principles that operate at different levels of life.

Recursion is not the same as an infinite loop

Although it is often confused with it, the difference can be easily understood with an example. Imagine that your boss issued an order:

A cyclic order. Image: Ekaterina Stepanova / Skillbox Media

In this situation, we are not faced with recursion, but with an infinite call loop that occurs when the boss makes bad decisions. Such loops can lead to process delays and deteriorate team performance. It's important to recognize such situations and find ways to resolve them to avoid negative consequences for the project and the team.

You can make a small change to achieve recursion. Recursion is the process by which a function calls itself to solve a problem, breaking it down into smaller subproblems. In programming, recursion is often used to handle data structures such as trees and graphs. Proper use of recursion allows for elegant and simple solutions to complex problems. However, it's important to remember the base case to avoid endless function calls. Making changes to the code structure can significantly simplify the understanding and implementation of recursive algorithms.

Recursive order. Image: Ekaterina Stepanova / Skillbox Media

The order became recursive, since in one of its branches it calls itself. This leads to the repetition of certain operations and can be used to solve problems that require iteration or hierarchical data processing. Recursive constructs are often used in programming to optimize algorithms and simplify code.

A moment of humor is a great way to take a break from everyday worries and lift your spirits. Humor has the power to bring people together, ease stressful situations, and brighten up life. Whether you prefer jokes, anecdotes, or funny stories, there's something for everyone. A clear understanding of humor not only helps in communication but also in strengthening social connections. Incorporate a moment of humor into your day, and you'll notice how positive thinking changes your perception of the world around you.

For lunch, we offer the Recursive Salad, which includes fresh tomatoes, crisp cucumbers, and lettuce. This light and healthy salad is ideal for those watching their diet. Tomatoes provide vitamins, cucumbers add freshness, and lettuce adds a crunchy texture. This lunch will be an excellent choice for maintaining health and energy throughout the day.

Recursion Can Be Seen

Recursive images, also known as fractal patterns or fractals, are visual elements that have the unique property of containing miniature versions of themselves. These images are striking in their beauty and complexity, creating impressive visual effects. Fractals can be found in nature, for example, in the structure of snowflakes, plant leaves, or coastlines. Their use in art and design allows you to create captivating and harmonious compositions that attract attention and arouse interest. Fractal patterns are used in various fields - from computer graphics to architecture, demonstrating their versatility and appeal.

In nature, we can observe amazing analogies when examining the crowns of trees. The pattern of large branches is repeated in the patterns of smaller branches, creating a harmonious structure. Even the leaf petiole resembles a tree trunk, and the stipules resemble its branches. These natural forms illustrate the principle of self-similarity, which can be seen in various natural elements, from plants to mountain ranges.

Blood vessels and nerves in animal bodies are organized according to fractals, ensuring their efficiency and functionality. Fractal structures can be observed not only in biological systems but also in natural objects, such as snowflakes and Romanesco cabbage. This unique cabbage, with its beautiful fractal pattern, attracts attention with its aesthetic appearance and can serve as an example of natural harmony. Fractals are typically characterized by self-similarity, making them an interesting object of study in various scientific disciplines.

Romanesco cabbage. Photo: Reissaamme / Pixabay.com

In architecture, recursion manifests itself in the form of Gothic cathedrals, which display complex and multi-layered structures. These majestic buildings are characterized by repeating elements such as arches, columns, and stained glass windows, creating a sense of infinity and depth. Gothic architecture uses recursive elements to achieve harmony and symmetry, making cathedrals not only architectural masterpieces but also symbols of spiritual sublimity.

Reims Cathedral. Photo: Ruben Holthuijsen / Flickr.com

Built in the 13th century, this cathedral utilizes one of the hallmarks of Gothic architecture: windows decorated with delicate tracery. The main pattern of the partitions is a pointed arch with a central circle supported by two smaller arches. This architectural element not only lends elegance to the building but also symbolizes the Gothic style's aspiration for height and light.

A recursive version of the pattern is featured in the architecture of Lincoln Cathedral. This majestic cathedral, located in Lincoln, England, features complex geometric shapes and elements that are repeated at various levels of the structure. Recursive patterns create a sense of depth and harmony, making Lincoln Cathedral not only a remarkable architectural achievement but also a superb example of recursive principles in design.

Lincoln Cathedral. Photo: Dom Crossley / Flickr.com

The window is designed as a pointed arch with a circle inscribed within it. This circle rests on two other arches. Inside each of these arches is another circle, as well as two smaller arches. Inside these smaller arches are also circles resting on even smaller arches. This architectural solution creates a complex and harmonious composition that attracts attention and emphasizes the aesthetic value of the structure.

St. Peter's Basilica in the Vatican is a striking example of architectural recursion. This majestic structure not only attracts tourists from all over the world but also serves as a symbol of the Catholic faith. Architectural elements of the cathedral, such as the dome, colonnades, and facades, demonstrate a profound connection between the interior space and the exterior architecture. St. Peter's Basilica also reflects the development of architectural styles and technologies, making it an important object for the study of architectural history. A visit to this famous temple offers the opportunity not only to admire its beauty but also to immerse yourself in the rich cultural and religious atmosphere of the Vatican.

St. Peter's Basilica. Photo: Mike McBey / Flickr.com

George Hersey, an American writer and journalist, compared the architectural complex to Chinese secret boxes. He described it as consisting of one macrochurch, four maxi-churches, 16 mini-churches, and 32 micro-churches. A simpler and more accurate description would be to describe the cathedral as recursive.

Recursion is clearly evident in the visual arts, a clear example being Giotto's Stefaneschi Triptych. The central panel of this work depicts Cardinal Stefaneschi holding the triptych itself. This technique creates an effect of infinity, as the triptych repeatedly depicts the same triptych, and so on. This approach not only attracts the viewer's attention but also sparks interest in studying the composition and symbolism of the work. Recursion in art allows for a deeper understanding of the relationship between elements and the creator.

The Stefaneschi Triptych, Giotto. Reverse. Photo: ru.wikipedia.org

An example of contemporary art is the lithograph "Drawing Hands" by the Dutch artist M. C. Escher, who worked in the 20th century. This work exemplifies Escher's unique style, which combines elements of surrealism and optical illusions. The lithograph attracts attention with its complex composition and masterful execution, demonstrating the artist's characteristic themes of self-reflection and infinity. Escher continues to inspire artists and audiences around the world, and his works, such as Drawing Hands, remain relevant and in demand in the art world.

Lithograph Drawing Hands, M.C. Escher. Photo: Renzo Giusti / Flickr.com

To understand recursion, you don't need to visit an art gallery. Just look at the Russian coat of arms. The double-headed eagle depicted on the coat of arms holds a scepter in its right claw, which is also topped by a double-headed eagle. This eagle, in turn, holds its own scepter. Thus, we see an example of recursion in the symbolism of the coat of arms, where each element repeats the previous one. This clearly illustrates the concept of infinite self-repetition inherent in recursion and helps to better understand its essence.

Coat of arms of Russia. Image: ru.wikipedia.org

Recursion can be heard

In music, there are compositions that can be characterized as recursive. In his book "Gödel, Escher, Bach: This Endless Garland," Douglas Hofstadter, an American physicist and author, explains the concept of recursion in detail, using the jig from Johann Sebastian Bach's "French Suite No. 5" as an example. This musical work illustrates how elements repeat and transform, creating complex structures. Recursiveness in music not only emphasizes its mathematical nature but also creates unique emotional responses in listeners.

The first movement of the work repeats the melodic transition from the key of G major to D minor three times, creating the effect of a self-reinventing melody. This transition immerses the listener deeper into the musical atmosphere. The second part of the composition features a contrast—the melody ascends three times from D minor to G major, lending dynamism and vibrancy to the piece.

A programmer might recall the process of calculating the factorial of 3, where a function recursively calls itself three times. This results in three returns with intermediate results, and the final step returns the final value. This approach illustrates the concept of recursion, where a function solves a problem by breaking it down into simpler subproblems, an important aspect of programming. Recursion allows you to effectively organize code and simplifies the implementation of complex algorithms.

Scheme for calculating the factorial of 3

Recursion in linguistics is the ability of a language to create nested sentences and constructions. For example, the sentence "Sasha reads an article about recursion" can be expanded to "Lena watches Sasha read an article about recursion." This sentence can be further transformed into "Lena's friend Petya disapproves of Lena watching Sasha read an article about recursion." Recursive constructions allow for deeper meaning and make text more complex and expressive.

Recursion is considered a characteristic feature of all human languages, with the exception of the Pirahã language spoken in the Brazilian part of the Amazon basin, which raises some doubts among linguists. The ability to recognize and understand recursive structures is considered practically innate in humans, which emphasizes the importance of this feature in the process of language acquisition and communication. This mechanism allows for the creation of complex grammatical constructions and enriches the expressiveness of language, making it more flexible and adaptable to various communication situations.

German scientists conducted experiments on five-month-old infants to study their brain activity using electroencephalography (EEG). During the experiments, they analyzed the infants' responses to nested linguistic structures, both correct and incorrect. Since children at this age have not yet mastered speech, sequences of sounds with different frequencies were used instead of words. The sound frequencies for the related words in the nested structures matched. These studies help to better understand how infants' language abilities develop and how they perceive sound patterns.

Diagram: ScienceAdvances

The sentence "The boy, whom the girl was chasing, kicked the ball" contains two related constructions: the first is "the boy kicked", the second is "the girl "was chasing." These constructions were indicated by sounds with frequencies of 1900 and 1200 Hz, respectively, and separated by a short sound with a frequency of 1500 Hz. Correct language patterns are presented on the left, and incorrect ones on the right. In addition to five-tone sequences, seven-tone nested sequences were also played, allowing for a more detailed exploration of the relationship between language and sound patterns.

For scientific details, please refer to the original publication. However, the key findings of the experiments show that even infant brains react negatively to incorrect constructions.

The sample of 38 participants is insufficient to generalize the results to the entire population, but the theory presented is intriguing.

Recursive algorithms are easy to model using readily available tools

The Matryoshka doll is a striking example of recursion, where each nested doll resembles a doll-box, except for the smallest one, which represents the base case. Thus, the matryoshka doll visually and effectively demonstrates the concept of recursion, where more complex structures are formed from simple elements.

Illustration: Paul Noth / Pinterest

If your goal is to place the blue dot on the smallest doll, you can use a recursive algorithm that can be easily implemented on your fingers. Recursion allows you to break a problem down into simpler subproblems, making the process more efficient. Start by defining the base case where the doll reaches its minimum size, and then gradually add a blue dot, using a recursive call for each iteration. This approach not only simplifies the problem but also makes it more visual and understandable. Using a recursive algorithm, you can achieve an accurate result with minimal effort.

Imagine you are in the last row of a long hall and want to find the total number of rows. Instead of getting up and recounting them, you can use an algorithmic approach. Given your knowledge of recursion, you can develop a solution that will get the desired result without additional effort. The recursive method will help you efficiently determine the number of rows using only your current position and some logic.

You ask the person in front of you how many rows there are. If they say a number, you add two – one row for your neighbor and one row where you are sitting. This gives you the total number of rows. Otherwise, you suggest that this neighbor use your algorithm to determine the number of rows for their neighbor in front.

When all participants in the process are willing to cooperate, the turn will reach the first row, and the result will flow back up the chain. This is achieved thanks to a recursive algorithm, which ensures efficient task execution. Recursion allows complex problems to be divided into simpler subproblems, simplifying data processing and improving system performance. Thus, setting the participants up for friendly interaction and using a recursive approach contribute to the successful completion of the process and obtaining the expected result.

  • Masha, who is sitting in the front row, will answer Sasha, sitting behind her, that there are no rows in front of her.
  • Sasha will add zero and one and answer his neighbor behind Petya that there is one row in front of him (Sasha).
  • Petya will add one more and answer his neighbor Olya that there are two rows in front of him.
  • And so on...
  • Vitalik, sitting in front of you, will say that there are N rows in front of him, which means that he is sitting in the (N + 1)th row and there are N + 2 of them in the room in total.

I suggest paying attention to subject humor. This is a special type of humor that is based on a play on words and situations associated with specific objects or phenomena. It can bring a smile and amusement, bringing a touch of levity to everyday life. Subject-based humor is often used in literature, film, and everyday communication to highlight the comical aspects of ordinary things. Such jokes can be both simple and profound, forcing us to consider familiar things from a new perspective.

Remember when Anton lost his wish? I made him a wish: for two days, he'd put up stickers with the names of all the activities he'd completed in each subject. This will help him better organize his studies and understand what he is working on.

Did he stick another sticker with the inscription "sticked" on it for each new one?