Search Results

Search found 1157 results on 47 pages for 'recursive descent'.

Page 15/47 | < Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >

  • Should not a tail-recursive function also be faster?

    - by Balint Erdi
    I have the following Clojure code to calculate a number with a certain "factorable" property. (what exactly the code does is secondary). (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (factor-9 (quot n 10)))))) Now, I'm into TCO and realize that Clojure can only provide tail-recursion if explicitly told so using the recur keyword. So I've rewritten the code to do that (replacing factor-9 with recur being the only difference): (defn factor-9 ([] (let [digits (take 9 (iterate #(inc %) 1)) nums (map (fn [x] ,(Integer. (apply str x))) (permutations digits))] (some (fn [x] (and (factor-9 x) x)) nums))) ([n] (or (= 1 (count (str n))) (and (divisible-by-length n) (recur (quot n 10)))))) To my knowledge, TCO has a double benefit. The first one is that it does not use the stack as heavily as a non tail-recursive call and thus does not blow it on larger recursions. The second, I think is that consequently it's faster since it can be converted to a loop. Now, I've made a very rough benchmark and have not seen any difference between the two implementations although. Am I wrong in my second assumption or does this have something to do with running on the JVM (which does not have automatic TCO) and recur using a trick to achieve it? Thank you.

    Read the article

  • Recursive breadth-first travel function in Java or C++?

    - by joejax
    Here is a java code for breadth-first travel: void breadthFirstNonRecursive(){ Queue<Node> queue = new java.util.LinkedList<Node>(); queue.offer(root); while(!queue.isEmpty()){ Node node = queue.poll(); visit(node); if (node.left != null) queue.offer(node.left); if (node.right != null) queue.offer(node.right); } } Is it possible to write a recursive function to do the same? At first, I thought this would be easy, so I came out with this: void breadthFirstRecursive(){ Queue<Node> q = new LinkedList<Node>(); breadthFirst(root, q); } void breadthFirst(Node node, Queue<Node> q){ if (node == null) return; q.offer(node); Node n = q.poll(); visit(n); if (n.left != null) breadthFirst(n.left, q); if (n.right != null) breadthFirst(n.right, q); } Then I found it doesn't work. It is actually does the same thing as this: void preOrder(Node node) { if (node == null) return; visit(node); preOrder(node.left); preOrder(node.right); } Has any one thought about this before?

    Read the article

  • How to change a recursive function for count files and catalogues?

    - by user661999
    <?php function scan_dir($dirname) { $file_count = 0 ; $dir_count = 0 ; $dir = opendir($dirname); while (($file = readdir($dir)) !== false) { if($file != "." && $file != "..") { if(is_file($dirname."/".$file)) ++$file_count; if(is_dir($dirname."/".$file)) { ++ $dir_count; scan_dir($dirname."/".$file); } } } closedir($dir); echo "There are $dir_count catalogues and $file_count files.<br>"; } $dirname = "/home/user/path"; scan_dir($dirname); ?> Hello, I have a recursive function for count files and catalogues. It returns result for each catalogue. But I need a common result. How to change the script? It returns : There are 0 catalogues and 3 files. There are 0 catalogues and 1 files. There are 2 catalogues and 14 files. I want: There are 2 catalogues and 18 files.

    Read the article

  • Apply rewrite rule for all but all the files (recursive) in a subdirectory?

    - by user784637
    I have an .htaccess file in the root of the website that looks like this RewriteRule ^some-blog-post-title/ http://website/read/flowers/a-new-title-for-this-post/ [R=301,L] RewriteRule ^some-blog-post-title2/ http://website/read/flowers/a-new-title-for-this-post2/ [R=301,L] <IfModule mod_rewrite.c> RewriteEngine On ## Redirects for all pages except for files in wp-content to website/read RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !/wp-content RewriteRule ^(.*)$ http://website/read/$1 [L,QSA] #RewriteRule ^http://website/read [R=301,L] RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> My intent is to redirect people to the new blog post location if they propose one of those special blog posts. If that's not the case then they should be redirected to http://website.com/read. Nothing from http://website.com/wp-content/* should be redirected. So far conditions 1 and 3 are being met. How can I meet condition 2?

    Read the article

  • Recursive N-way merge/diff algorithm for directory trees?

    - by BobMcGee
    What algorithms or Java libraries are available to do N-way, recursive diff/merge of directories? I need to be able to generate a list of folder trees that have many identical files, and have subdirectories with many similar files. I want to be able to use 2-way merge operations to quickly remove as much redundancy as possible. Goals: Find pairs of directories that have many similar files between them. Generate short list of directory pairs that can be synchronized with 2-way merge to eliminate duplicates Should operate recursively (there may be nested duplicates of higher-level directories) Run time and storage should be O(n log n) in numbers of directories and files Should be able to use an embedded DB or page to disk for processing more files than fit in memory (100,000+). Optional: generate an ancestry and change-set between folders Optional: sort the merge operations by how many duplicates they can elliminate I know how to use hashes to find duplicate files in roughly O(n) space, but I'm at a loss for how to go from this to finding partially overlapping sets between folders and their children. EDIT: some clarification The tricky part is the difference between "exact same" contents (otherwise hashing file hashes would work) and "similar" (which will not). Basically, I want to feed this algorithm at a set of directories and have it return a set of 2-way merge operations I can perform in order to reduce duplicates as much as possible with as few conflicts possible. It's effectively constructing an ancestry tree showing which folders are derived from each other. The end goal is to let me incorporate a bunch of different folders into one common tree. For example, I may have a folder holding programming projects, and then copy some of its contents to another computer to work on it. Then I might back up and intermediate version to flash drive. Except I may have 8 or 10 different versions, with slightly different organizational structures or folder names. I need to be able to merge them one step at a time, so I can chose how to incorporate changes at each step of the way. This is actually more or less what I intend to do with my utility (bring together a bunch of scattered backups from different points in time). I figure if I can do it right I may as well release it as a small open source util. I think the same tricks might be useful for comparing XML trees though.

    Read the article

  • Non recursive way to position a genogram in 2D points for x axis. Descendant are below

    - by Nassign
    I currently was tasked to make a genogram for a family consisting of siblings, parents with aunts and uncles with grandparents and greatgrandparents for only blood relatives. My current algorithm is using recursion. but I am wondering how to do it in non recursive way to make it more efficient. it is programmed in c# using graphics to draw on a bitmap. Current algorithm for calculating x position, the y position is by getting the generation number. public void StartCalculatePosition() { // Search the start node (The only node with targetFlg set to true) Person start = null; foreach (Person p in PersonDic.Values) { if (start == null) start = p; if (p.Targetflg) { start = p; break; } } CalcPositionRecurse(start); // Normalize the position (shift all values to positive value) // Get the minimum value (must be negative) // Then offset the position of all marriage and person with that to make it start from zero float minPosition = float.MaxValue; foreach (Person p in PersonDic.Values) { if (minPosition > p.Position) { minPosition = p.Position; } } if (minPosition < 0) { foreach (Person p in PersonDic.Values) { p.Position -= minPosition; } foreach (Marriage m in MarriageList) { m.ParentsPosition -= minPosition; m.ChildrenPosition -= minPosition; } } } /// <summary> /// Calculate position of genogram using recursion /// </summary> /// <param name="psn"></param> private void CalcPositionRecurse(Person psn) { // End the recursion if (psn.BirthMarriage == null || psn.BirthMarriage.Parents.Count == 0) { psn.Position = 0.0f; if (psn.BirthMarriage != null) { psn.BirthMarriage.ParentsPosition = 0.0f; psn.BirthMarriage.ChildrenPosition = 0.0f; } CalculateSiblingPosition(psn); return; } // Left recurse if (psn.Father != null) { CalcPositionRecurse(psn.Father); } // Right recurse if (psn.Mother != null) { CalcPositionRecurse(psn.Mother); } // Merge Position if (psn.Father != null && psn.Mother != null) { AdjustConflict(psn.Father, psn.Mother); // Position person in center of parent psn.Position = (psn.Father.Position + psn.Mother.Position) / 2; psn.BirthMarriage.ParentsPosition = psn.Position; psn.BirthMarriage.ChildrenPosition = psn.Position; } else { // Single mom or single dad if (psn.Father != null) { psn.Position = psn.Father.Position; psn.BirthMarriage.ParentsPosition = psn.Position; psn.BirthMarriage.ChildrenPosition = psn.Position; } else if (psn.Mother != null) { psn.Position = psn.Mother.Position; psn.BirthMarriage.ParentsPosition = psn.Position; psn.BirthMarriage.ChildrenPosition = psn.Position; } else { // Should not happen, checking in start of function } } // Arrange the siblings base on my position (left younger, right older) CalculateSiblingPosition(psn); } private float GetRightBoundaryAncestor(Person psn) { float rPos = psn.Position; // Get the rightmost position among siblings foreach (Person sibling in psn.Siblings) { if (sibling.Position > rPos) { rPos = sibling.Position; } } if (psn.Father != null) { float rFatherPos = GetRightBoundaryAncestor(psn.Father); if (rFatherPos > rPos) { rPos = rFatherPos; } } if (psn.Mother != null) { float rMotherPos = GetRightBoundaryAncestor(psn.Mother); if (rMotherPos > rPos) { rPos = rMotherPos; } } return rPos; } private float GetLeftBoundaryAncestor(Person psn) { float rPos = psn.Position; // Get the rightmost position among siblings foreach (Person sibling in psn.Siblings) { if (sibling.Position < rPos) { rPos = sibling.Position; } } if (psn.Father != null) { float rFatherPos = GetLeftBoundaryAncestor(psn.Father); if (rFatherPos < rPos) { rPos = rFatherPos; } } if (psn.Mother != null) { float rMotherPos = GetLeftBoundaryAncestor(psn.Mother); if (rMotherPos < rPos) { rPos = rMotherPos; } } return rPos; } /// <summary> /// Check if two parent group has conflict and compensate on the conflict /// </summary> /// <param name="leftGroup"></param> /// <param name="rightGroup"></param> public void AdjustConflict(Person leftGroup, Person rightGroup) { float leftMax = GetRightBoundaryAncestor(leftGroup); leftMax += 0.5f; float rightMin = GetLeftBoundaryAncestor(rightGroup); rightMin -= 0.5f; float diff = leftMax - rightMin; if (diff > 0.0f) { float moveHalf = Math.Abs(diff) / 2; RecurseMoveAncestor(leftGroup, 0 - moveHalf); RecurseMoveAncestor(rightGroup, moveHalf); } } /// <summary> /// Recursively move a person and all his/her ancestor /// </summary> /// <param name="psn"></param> /// <param name="moveUnit"></param> public void RecurseMoveAncestor(Person psn, float moveUnit) { psn.Position += moveUnit; foreach (Person siblings in psn.Siblings) { if (siblings.Id != psn.Id) { siblings.Position += moveUnit; } } if (psn.BirthMarriage != null) { psn.BirthMarriage.ChildrenPosition += moveUnit; psn.BirthMarriage.ParentsPosition += moveUnit; } if (psn.Father != null) { RecurseMoveAncestor(psn.Father, moveUnit); } if (psn.Mother != null) { RecurseMoveAncestor(psn.Mother, moveUnit); } } /// <summary> /// Calculate the position of the siblings /// </summary> /// <param name="psn"></param> /// <param name="anchor"></param> public void CalculateSiblingPosition(Person psn) { if (psn.Siblings.Count == 0) { return; } List<Person> sibling = psn.Siblings; int argidx; for (argidx = 0; argidx < sibling.Count; argidx++) { if (sibling[argidx].Id == psn.Id) { break; } } // Compute position for each brother that is younger that person int idx; for (idx = argidx - 1; idx >= 0; idx--) { sibling[idx].Position = sibling[idx + 1].Position - 1; } for (idx = argidx + 1; idx < sibling.Count; idx++) { sibling[idx].Position = sibling[idx - 1].Position + 1; } }

    Read the article

  • how can I code a recursive query in an Entity Framework model?

    - by Greg
    Hi, I have a model which includes NODES, and RELATIONSHIPS (that tie the nodes together, via a parent_node, child_node arrangement). Q1 - Is there any way in EF / Linq-to-entities to perform a query on nodes (e.g. context.Nodes..) to find say "all parents" or "or children" in the graph? Q2 - If there's not in Linq-to-entities, is there any other way to do this other than writing a method that manually goes through and doing it? Q3 - If manual is the only way to do it, should I be concerned about the number of database hits that will be going out to the database as the method keeps recursing through the data? Or more specifically, is there any EF caching type feature that might assist here in ensuring the method is performance from a "number of database hits" point of view? thanks thanks

    Read the article

  • What is the best way to translate this recursive python method into Java?

    - by Simucal
    In another question I was provided with a great answer involving generating certain sets for the Chinese Postman Problem. The answer provided was: def get_pairs(s): if not s: yield [] else: i = min(s) for j in s - set([i]): for r in get_pairs(s - set([i, j])): yield [(i, j)] + r for x in get_pairs(set([1,2,3,4,5,6])): print x This will output the desire result of: [(1, 2), (3, 4), (5, 6)] [(1, 2), (3, 5), (4, 6)] [(1, 2), (3, 6), (4, 5)] [(1, 3), (2, 4), (5, 6)] [(1, 3), (2, 5), (4, 6)] [(1, 3), (2, 6), (4, 5)] [(1, 4), (2, 3), (5, 6)] [(1, 4), (2, 5), (3, 6)] [(1, 4), (2, 6), (3, 5)] [(1, 5), (2, 3), (4, 6)] [(1, 5), (2, 4), (3, 6)] [(1, 5), (2, 6), (3, 4)] [(1, 6), (2, 3), (4, 5)] [(1, 6), (2, 4), (3, 5)] [(1, 6), (2, 5), (3, 4)] This really shows off the expressiveness of Python because this is almost exactly how I would write the pseudo-code for the algorithm. I especially like the usage of yield and and the way that sets are treated as first class citizens. However, there in lies my problem. What would be the best way to: 1.Duplicate the functionality of the yield return construct in Java? Would it instead be best to maintain a list and append my partial results to this list? How would you handle the yield keyword. 2.Handle the dealing with the sets? I know that I could probably use one of the Java collections which implements that implements the Set interface and then using things like removeAll() to give me a set difference. Is this what you would do in that case? Ultimately, I'm looking to reduce this method into as concise and straightforward way as possible in Java. I'm thinking the return type of the java version of this method will likely return a list of int arrays or something similar. How would you handle the situations above when converting this method into Java?

    Read the article

  • Does a recursive Ant task exist to recover properties from external file?

    - by Julia2020
    Hi, I ve got a problem in getting properties with ant from a properties file. With a simple target like this in my build.xml, i'd like to get at least two properties path1 and path2. I'd like to have a generic target to get this two properties.... in order to avoid modifying the build.xml (just adding a new prop) Any suggestions? Thanks in advance ! build.xml : <target name="TEST" description="test ant"> <property file="dependencies.properties"/> <svn> <export srcUrl="${path.prop}" destPath="${workspace}/rep/" /> </svn> </target> dependencies.properties : path1.prop = /path/to/src1 path2.prop = /path/to/src2

    Read the article

  • Recursive multiline sed - remove beginning of file until pattern match.

    - by yaya3
    I have nested subdirectories containing html files. For each of these html files I want to delete from the top of the file until the pattern <div id="left- This is my attempt from osx's terminal: find . -name "*.html" -exec sed "s/.*?<div id=\"left-col/<div id=\"left-col/g" '{}' \; I get a lot of html output in the termainal, but no files contain the substitution or are written Thanks

    Read the article

  • What is wrong with this recursive Windows CMD script? It won't do Ackermann properly

    - by boost
    I've got this code that I'm trying to get to calculate the Ackermann function so that I can post it up on RosettaCode. It almost works. I thought maybe there'd be a few batch file wizards on StackOverflow. ::echo off set depth=0 :ack if %1==0 goto m0 if %2==0 goto n0 :else set /a n=%2-1 set /a depth+=1 call :ack %1 %n% set t=%errorlevel% set /a depth-=1 set /a m=%1-1 set /a depth+=1 call :ack %m% %t% set t=%errorlevel% set /a depth-=1 if %depth%==0 ( exit %t% ) else ( exit /b %t% ) :m0 set/a n=%2+1 if %depth%==0 ( exit %n% ) else ( exit /b %n% ) :n0 set /a m=%1-1 set /a depth+=1 call :ack %m% %2 set t=%errorlevel% set /a depth-=1 if %depth%==0 ( exit %t% ) else ( exit /b %t% ) I use this script to test it @echo off cmd/c ackermann.cmd %1 %2 echo Ackermann of %1 %2 is %errorlevel% A sample output, for Test 1 1, gives: >test 1 1 >set depth=0 >if 1 == 0 goto m0 >if 1 == 0 goto n0 >set /a n=1-1 >set /a depth+=1 >call :ack 1 0 >if 1 == 0 goto m0 >if 0 == 0 goto n0 >set /a m=1-1 >set /a depth+=1 >call :ack 0 0 >if 0 == 0 goto m0 >set/a n=0+1 >if 2 == 0 (exit 1 ) else (exit /b 1 ) >set t=1 >set /a depth-=1 >if 1 == 0 (exit 1 ) else (exit /b 1 ) >set t=1 >set /a depth-=1 >set /a m=1-1 >set /a depth+=1 >call :ack 0 1 >if 0 == 0 goto m0 >set/a n=1+1 >if 1 == 0 (exit 2 ) else (exit /b 2 ) >set t=2 >set /a depth-=1 >if 0 == 0 (exit 2 ) else (exit /b 2 ) Ackermann of 1 1 is 2

    Read the article

  • How can I perform an idiomatic non-recursive flatten in ruby?

    - by nasmorn
    I have a method that returns an array of arrays. For convenience I use collect on a collection to gather them together. arr = collection.collect {|item| item.get_array_of_arrays} Now I would like to have a single array that contains all the arrays. Of course I can loop over the array and use the + operator to do that. newarr = [] arr.each {|item| newarr += item} But this is kind of ugly, is there a better way?

    Read the article

  • Java: Combination of recursive loops which has different FOR loop inside; Output: FOR loops indexes

    - by vvinjj
    currently recursion is fresh & difficult topic for me, however I need to use it in one of my algorithms. Here is the challenge: I need a method where I specify number of recursions (number of nested FOR loops) and number of iterations for each FOR loop. The result should show me, something simmilar to counter, however each column of counter is limited to specific number. ArrayList<Integer> specs= new ArrayList<Integer>(); specs.add(5); //for(int i=0 to 5; i++) specs.add(7); specs.add(9); specs.add(2); specs.add(8); specs.add(9); public void recursion(ArrayList<Integer> specs){ //number of nested loops will be equal to: specs.size(); //each item in specs, specifies the For loop max count e.g: //First outside loop will be: for(int i=0; i< specs.get(0); i++) //Second loop inside will be: for(int i=0; i< specs.get(1); i++) //... } The the results will be similar to outputs of this manual, nested loop: int[] i; i = new int[7]; for( i[6]=0; i[6]<5; i[6]++){ for( i[5]=0; i[5]<7; i[5]++){ for(i[4] =0; i[4]<9; i[4]++){ for(i[3] =0; i[3]<2; i[3]++){ for(i[2] =0; i[2]<8; i[2]++){ for(i[1] =0; i[1]<9; i[1]++){ //... System.out.println(i[1]+" "+i[2]+" "+i[3]+" "+i[4]+" "+i[5]+" "+i[6]); } } } } } } I already, killed 3 days on this, and still no results, was searching it in internet, however the examples are too different. Therefore, posting the programming question in internet first time in my life. Thank you in advance, you are free to change the code efficiency, I just need the same results.

    Read the article

  • Elegant way for a recursive C++ template to do something different with the leaf class?

    - by Costas
    I have a C++ class template that makes an Array of pointers. This also gets typedefed to make Arrays of Arrays and so on: typedef Array<Elem> ElemArray; typedef Array<ElemArray> ElemArrayArray; typedef Array<ElemArrayArray> ElemArrayArrayArray; I would like to be able to set one leaf node from another by copying the pointer so they both refer to the same Elem. But I also want to be able to set one Array (or Array of Arrays etc) from another. In this case I don't want to copy the pointers, I want to keep the arrays seperate and descend into each one until I get to the leaf node, at where I finally copy the pointers. I have code that does this (below). When you set something in an Array it calls a CopyIn method to do the copying. But because this is templated it also has to call the CopyIn method on the leaf class, which means I have to add a dummy method to every leaf class that just returns false. I have also tried adding a flag to the template to tell it whether it contains Arrays or not, and so whether to call the CopyIn method. This works fine - the CopyIn method of the leaf nodes never gets called, but it still has to be there for the compile to work! Is there a better way to do this? #include <stdio.h> class Elem { public: Elem(int v) : mI(v) {} void Print() { printf("%d\n",mI); } bool CopyIn(Elem *v) { return false; } int mI; }; template < typename T > class Array { public: Array(int size) : mB(0), mN(size) { mB = new T* [size]; for (int i=0; i<mN; i++) mB[i] = new T(mN); } ~Array() { for (int i=0; i<mN; i++) delete mB[i]; delete [] mB; } T* Get(int i) { return mB[i]; } void Set(int i, T* v) { if (! mB[i]->CopyIn(v) ) { // its not an array, so copy the pointer mB[i] = v; } } bool CopyIn(Array<T>* v) { for (int i=0; i<mN; i++) { if (v && i < v->mN ) { if ( ! mB[i]->CopyIn( v->mB[i] )) { // its not an array, so copy the pointer mB[i] = v->mB[i]; } } else { mB[i] = 0; } } return true; // we did the copy, no need to copy pointer } void Print() { for (int i=0; i<mN; i++) { printf("[%d] ",i); mB[i]->Print(); } } private: T **mB; int mN; }; typedef Array<Elem> ElemArray; typedef Array<ElemArray> ElemArrayArray; typedef Array<ElemArrayArray> ElemArrayArrayArray; int main () { ElemArrayArrayArray* a = new ElemArrayArrayArray(2); ElemArrayArrayArray* b = new ElemArrayArrayArray(3); // In this case I need to copy the pointer to the Elem into the ElemArrayArray a->Get(0)->Get(0)->Set(0, b->Get(0)->Get(0)->Get(0)); // in this case I need go down through a and b until I get the to Elems // so I can copy the pointers a->Set(1,b->Get(2)); b->Get(0)->Get(0)->Get(0)->mI = 42; // this will also set a[0,0,0] b->Get(2)->Get(1)->Get(1)->mI = 96; // this will also set a[1,1,1] // should be 42,2, 2,2, 3,3, 3,96 a->Print(); }

    Read the article

  • PCRE (recursive) pattern that matches a string containing a correctly parenthesized substring. Why d

    - by Anton N. Petrov
    Well, there are other ways (hmmm... or rather working ways) to do it, but the question is why does this one fail? / \A # start of the string ( # group 1 (?: # group 2 [^()]* # something other than parentheses (greedy) | # or \( (?1) \) # parenthesized group 1 ) # -group 2 + # at least once (greedy) ) # -group 1 \Z # end of the string /x Fails to match a string with nested parentheses: "(())"

    Read the article

  • How to handle recursive parent/child problems like this?

    - by lsdude
    In web dev I come across these problems a lot. For example, we have a giant list of URLs that are in this format: /businesses /businesses/food /businesses/food/wendys /businesses/food/wendys/chili /businesses/food/wendys/fries /businesses/food/wendys/chicken-nuggets /businesses/pharmacy/cvs /businesses/pharmacy/cvs/toothpaste /businesses/pharmacy/cvs/toothpaste/brand ... and then we need to output each one, where the parent category is in h1 tags, the child is in h2 tags, and the children of that are in h3 tags. I can handle this but I feel my code is messy. I'm sure there is a design pattern I can use? Langs are ruby/php usually. how would you handle this?

    Read the article

  • How do I make a recursive list that checks company rankings?

    - by Sera
    I have a set of companies in rank order. I want my rule to check if the companies in a specified list are in rank order, and for the rule to recur until all companies in the list have been checked. I currently have the following: isOrder([]). isOrder([COM1,COM2|T]) :- rank(COM1,D), rank(COM2,E), D<E, print("in order"), isOrder([COM2|T]). However, this does not seem to work. Sometimes, the recursion goes on forever without ending, and sometimes the recursion doesn't work at all. This is when I vary the code to try and get the correct answer. Can anybody help me? I have just started Prolog and my understanding of it is severely limited. Any help would be greatly appreciated.

    Read the article

  • Returning a list in this recursive coi function in python.

    - by Nate
    Hello. I'm having trouble getting my list to return in my code. Instead of returning the list, it keeps returning None, but if I replace the return with print in the elif statement, it prints the list just fine. How can I repair this? def makeChange2(amount, coinDenomination, listofcoins = None): #makes a list of coins from an amount given by using a greedy algorithm coinDenomination.sort() #reverse the list to make the largest position 0 at all times coinDenomination.reverse() #assigns list if listofcoins is None: listofcoins = [] if amount >= coinDenomination[0]: listofcoins = listofcoins + [coinDenomination[0]] makeChange2((amount - coinDenomination[0]), coinDenomination, listofcoins) elif amount == 0: return listofcoins else: makeChange2(amount, coinDenomination[1:], listofcoins)

    Read the article

< Previous Page | 11 12 13 14 15 16 17 18 19 20 21 22  | Next Page >