Questions tagged [recursion]
Recursion is a kind of function call in which a function calls itself. Such functions are also called recursive functions. Structural recursion is a method of problem solving where the solution to a problem depends on solutions to smaller instances of the same problem.
recursion
47,082
questions
2052
votes
29
answers
612k
views
What is tail recursion?
Whilst starting to learn lisp, I've come across the term tail-recursive. What does it mean exactly?
1103
votes
10
answers
294k
views
What is tail call optimization?
Very simply, what is tail-call optimization?
More specifically, what are some small code snippets where it could be applied, and where not, with an explanation of why?
708
votes
19
answers
1.0m
views
What is the maximum recursion depth, and how to increase it?
I have this tail recursive function here:
def recursive_function(n, sum):
if n < 1:
return sum
else:
return recursive_function(n-1, sum+n)
c = 998
print(recursive_function(...
591
votes
10
answers
683k
views
Recursively look for files with a specific extension
I'm trying to find all files with a specific extension in a directory and its subdirectories with my Bash (Ubuntu 10.04 LTS (Lucid Lynx) release).
This is what's written in a script file:
#!/bin/bash
...
576
votes
15
answers
140k
views
What is the most efficient/elegant way to parse a flat table into a tree?
Assume you have a flat table that stores an ordered tree hierarchy:
Id Name ParentId Order
1 'Node 1' 0 10
2 'Node 1.1' 1 10
3 'Node 2' 0 ...
563
votes
22
answers
551k
views
How to recursively find and list the latest modified files in a directory with subdirectories and times
Operating system: Linux
Filesystem type: ext3
Preferred solution: Bash (script/one-liner), Ruby, or Python
I have several directories with several subdirectories and files in them. I need to make a ...
452
votes
21
answers
198k
views
Way to go from recursion to iteration
I've used recursion quite a lot during my many years of programming to solve simple problems, but I'm fully aware that sometimes you need iteration due to memory/speed problems.
So, sometime in the ...
445
votes
12
answers
667k
views
How to search a string in multiple files and return the names of files in Powershell?
I have started learning powershell a couple of days ago, and I couldn't find anything on google that does what I need so please bear with my question.
I have been asked to replace some text strings ...
417
votes
7
answers
464k
views
Determining complexity for recursive functions (Big O notation)
I have a Computer Science Midterm tomorrow and I need help determining the complexity of these recursive functions. I know how to solve simple cases, but I am still trying to learn how to solve these ...
377
votes
13
answers
196k
views
Is recursion ever faster than looping?
I know that recursion is sometimes a lot cleaner than looping, and I'm not asking anything about when I should use recursion over iteration, I know there are lots of questions about that already.
...
348
votes
30
answers
386k
views
Recursively list files in Java
How do I recursively list all files under a directory in Java? Does the framework provide any utility?
I saw a lot of hacky implementations. But none from the framework or nio
334
votes
6
answers
13k
views
Try-finally block prevents StackOverflowError
Take a look at the following two methods:
public static void foo() {
try {
foo();
} finally {
foo();
}
}
public static void bar() {
bar();
}
Running bar() clearly ...
290
votes
8
answers
121k
views
Does Python optimize tail recursion?
I have the following piece of code which fails with the following error:
RuntimeError: maximum recursion depth exceeded
I attempted to rewrite this to allow for tail recursion optimization (TCO). ...
275
votes
10
answers
311k
views
Is log(n!) = Θ(n·log(n))?
I am to show that log(n!) = Θ(n·log(n)).
A hint was given that I should show the upper bound with nn and show the lower bound with (n/2)(n/2). This does not seem all that intuitive to me. Why would ...
272
votes
31
answers
185k
views
Recursion or Iteration?
Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palindrome.
I have seen many ...
270
votes
13
answers
354k
views
How to do a recursive sub-folder search and return files in a list?
I am working on a script to recursively go through subfolders in a mainfolder and build a list off a certain file type. I am having an issue with the script. It's currently set as follows:
for root, ...
257
votes
8
answers
110k
views
What exactly is a reentrant function?
Most of the times, the definition of reentrance is quoted from Wikipedia:
A computer program or routine is
described as reentrant if it can be
safely called again before its
previous invocation has ...
254
votes
14
answers
360k
views
List files recursively in Linux CLI with path relative to the current directory
This is similar to this question, but I want to include the path relative to the current directory in unix. If I do the following:
ls -LR | grep .txt
It doesn't include the full paths. For example, ...
245
votes
6
answers
45k
views
Anonymous recursive PHP functions
Is it possible to have a PHP function that is both recursive and anonymous? This is my attempt to get it to work, but it doesn't pass in the function name.
$factorial = function( $n ) use ( $...
236
votes
20
answers
93k
views
Understanding recursion [closed]
I'm having major trouble understanding recursion at school. Whenever the professor is talking about it, I seem to get it but as soon as I try it on my own it completely blows my brains.
I was trying ...
236
votes
18
answers
115k
views
Can every recursion be converted into iteration?
A reddit thread brought up an apparently interesting question:
Tail recursive functions can trivially be converted into iterative functions. Other ones, can be transformed by using an explicit ...
233
votes
4
answers
137k
views
How can I create nonexistent subdirectories recursively using Bash?
I am creating a quick backup script that will dump some databases into a nice/neat directory structure and I realized that I need to test to make sure that the directories exist before I create them. ...
221
votes
15
answers
146k
views
How to make a recursive lambda
I am writing the following recursive lambda function:
#include <iostream>
#include <functional>
auto term = [](int a)->int {
return a*a;
};
auto next = [](int a)->int {
return +...
220
votes
12
answers
98k
views
Nested defaultdict of defaultdict
Is there a way to make a defaultdict also be the default for the defaultdict? (i.e. infinite-level recursive defaultdict?)
I want to be able to do:
x = defaultdict(...stuff...)
x[0][1][0]
{}
So, I ...
218
votes
4
answers
145k
views
Breadth First Vs Depth First
When Traversing a Tree/Graph what is the difference between Breadth First and Depth first? Any coding or pseudocode examples would be great.
180
votes
9
answers
71k
views
Recursion in Angular directives
There are a couple of popular recursive angular directive Q&A's out there, which all come down to one of the following solutions:
manually incrementally 'compile' HTML based on runtime scope ...
176
votes
18
answers
351k
views
Loop through all nested dictionary values?
I'm trying to loop through a dictionary and print out all key value pairs where the value is not a nested dictionary. If the value is a dictionary I want to go into it and print out its key value ...
173
votes
7
answers
45k
views
Implications of foldr vs. foldl (or foldl')
Firstly, Real World Haskell, which I am reading, says to never use foldl and instead use foldl'. So I trust it.
But I'm hazy on when to use foldr vs. foldl'. Though I can see the structure of how ...
170
votes
17
answers
379k
views
How to search by key=>value in a multidimensional array in PHP
Is there any fast way to get all subarrays where a key value pair was found in a multidimensional array? I can't say how deep the array will be.
Simple example array:
$arr = array(0 => array(id=&...
168
votes
37
answers
545k
views
Java recursive Fibonacci sequence
Please explain this simple code:
public int fibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
I'm ...
163
votes
21
answers
163k
views
How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP? [duplicate]
How do I delete a directory and its entire contents (files and subdirectories) in PHP?
163
votes
9
answers
149k
views
self referential struct definition?
I haven't been writing C for very long, and so I'm not sure about how I should go about doing these sorts of recursive things... I would like each cell to contain another cell, but I get an error ...
147
votes
23
answers
324k
views
Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP
I have made a function that finds all the URLs within an html file and repeats the same process for each html content linked to the discovered URLs. The function is recursive and can go on endlessly. ...
141
votes
21
answers
87k
views
javascript: recursive anonymous function?
Let's say I have a basic recursive function:
function recur(data) {
data = data+1;
var nothing = function() {
recur(data);
}
nothing();
}
How could I do this if I have an ...
132
votes
6
answers
126k
views
GDB corrupted stack frame - How to debug?
I have the following stack trace. Is it possible to make out anything useful from this for debugging?
Program received signal SIGSEGV, Segmentation fault.
0x00000002 in ?? ()
(gdb) bt
#0 0x00000002 ...
130
votes
10
answers
122k
views
recursion versus iteration
Is it correct to say that everywhere recursion is used a for loop could be used? And if recursion is usually slower what is the technical reason for ever using it over for loop iteration?
And if it ...
126
votes
8
answers
20k
views
How exactly does tail recursion work?
I almost understand how tail recursion works and the difference between it and a normal recursion. I only don't understand why it doesn't require stack to remember its return address.
// tail ...
125
votes
12
answers
118k
views
How to [recursively] Zip a directory in PHP? [duplicate]
Directory is something like:
home/
file1.html
file2.html
Another_Dir/
file8.html
Sub_Dir/
file19.html
I am using the same PHP Zip class used in PHPMyAdmin http://trac....
121
votes
20
answers
223k
views
List all the files and folders in a Directory with PHP recursive function
I'm trying to go through all of the files in a directory, and if there is a directory, go through all of its files and so on until there are no more directories to go to. Each and every processed item ...
121
votes
40
answers
227k
views
What is recursion and when should I use it?
One of the topics that seems to come up regularly on mailing lists and online discussions is the merits (or lack thereof) of doing a Computer Science Degree. An argument that seems to come up time and ...
121
votes
14
answers
152k
views
Find all occurrences of a key in nested dictionaries and lists
I have a dictionary like this:
{
"id": "abcde",
"key1": "blah",
"key2": "blah blah",
"nestedlist": [
{
...
121
votes
7
answers
134k
views
Simplest way to do a recursive self-join?
What is the simplest way of doing a recursive self-join in SQL Server?
PersonID | Initials | ParentID
1 CJ NULL
2 EB 1
3 MB 1
4 SW 2
...
120
votes
18
answers
33k
views
Understanding how recursive functions work
As the title explains I have a very fundamental programming question which I have just not been able to grok yet. Filtering out all of the (extremely clever) "In order to understand recursion, you ...
117
votes
37
answers
225k
views
How to find all combinations of coins when given some dollar value [closed]
I found a piece of code that I was writing for interview prep few months ago.
According to the comment I had, it was trying to solve this problem:
Given some dollar value in cents (e.g. 200 = 2 ...
116
votes
55
answers
145k
views
Real-world examples of recursion [closed]
What are real-world problems where a recursive approach is the natural solution besides depth-first search (DFS)?
(I don't consider Tower of Hanoi, Fibonacci number, or factorial real-world problems....
116
votes
9
answers
6k
views
Is recursion a feature in and of itself?
...or is it just a practice?
I'm asking this because of an argument with my professor: I lost credit for calling a function recursively on the basis that we did not cover recursion in class, and my ...
116
votes
6
answers
11k
views
Why are functions in OCaml/F# not recursive by default?
Why is it that functions in F# and OCaml (and possibly other languages) are not by default recursive?
In other words, why did the language designers decide it was a good idea to explicitly make you ...
115
votes
7
answers
54k
views
Can generators be recursive?
I naively tried to create a recursive generator. Didn't work. This is what I did:
def recursive_generator(lis):
yield lis[0]
recursive_generator(lis[1:])
for k in recursive_generator([6,3,9,...
113
votes
4
answers
134k
views
Why does my recursive function return None?
I have this function that calls itself:
def get_input():
my_var = input('Enter "a" or "b": ')
if my_var != "a" and my_var != "b":
print('You didn\'t type "a" or "b". Try again.')
...
111
votes
9
answers
74k
views
One-liner to recursively list directories in Ruby?
What is the fastest, most optimized, one-liner way to get an array of the directories (excluding files) in Ruby?
How about including files?