Can generators be recursive?

Try this: def recursive_generator(lis): yield lis[0] yield from recursive_generator(lis[1:]) for k in recursive_generator([6,3,9,1]): print(k) I should point out this doesn’t work because of a bug in your function. It should probably include a check that lis isn’t empty, as shown below: def recursive_generator(lis): if lis: yield lis[0] yield from recursive_generator(lis[1:]) In case you are on … Read more

Convert a series of parent-child relationships into a hierarchical tree?

This requires a very basic recursive function to parse the child/parent pairs to a tree structure and another recursive function to print it out. Only one function would suffice but here’s two for clarity (a combined function can be found at the end of this answer). First initialize the array of child/parent pairs: $tree = … Read more

List all the files and folders in a Directory with PHP recursive function

Get all the files and folders in a directory, don’t call function when you have . or … Your code : <?php function getDirContents($dir, &$results = array()) { $files = scandir($dir); foreach ($files as $key => $value) { $path = realpath($dir . DIRECTORY_SEPARATOR . $value); if (!is_dir($path)) { $results[] = $path; } else if ($value … Read more

Is recursion a feature in and of itself?

To answer your specific question: No, from the standpoint of learning a language, recursion isn’t a feature. If your professor really docked you marks for using a “feature” he hadn’t taught yet, that was wrong. Reading between the lines, one possibility is that by using recursion, you avoided ever using a feature that was supposed … Read more