Search Results

Search found 1553 results on 63 pages for 'tail recursion'.

Page 2/63 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Scheme. Tail recursive ?

    - by n00b
    Hi guys, any tail-recursive version for the below mentioned pseudocode ? Thanks ! (define (min list) (cond ((null? list '()) ((null? (cdr list)) (car list)) (#t (let ((a (car list)) (b (min (cdr list))) ) (if (< b a) b a) ) ) ) )

    Read the article

  • How can I best study a problem to determine whether recursion can/should be used?

    - by user10326
    In some cases, I fail to see that a problem could be solved by the divide and conquer method. To give a specific example, when studying the find max sub-array problem, my first approach is to brute force it by using a double loop to find the max subarray. When I saw the solution using the divide and conquer approach which is recursion-based, I understood it but ok. From my side, though, when I first read the problem statement, I did not think that recursion is applicable. When studying a problem, is there any technique or trick to see that a recursion based (i.e. divide and conquer) approach can be used or not?

    Read the article

  • Is recursion ever faster than looping?

    - by Carson Myers
    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. What I'm asking is, is recursion ever faster than a loop? To me it seems like, you would always be able to refine a loop and get it to perform more quickly than a recursive function because the loop is absent constantly setting up new stack frames. I'm specifically looking for whether recursion is faster in applications where recursion is the right way to handle the data, such as in some sorting functions, in binary trees, etc.

    Read the article

  • Adding tail behaviour where enter adds blank lines to less

    - by gonvaled
    I love less, which I can use to follow logs with the +F flag (or the ShiftF hotkey), search forwards and backwards, and generally move freely through the document. But there is one thing missing in less: usually I am at the end of the file, and I want to see new things happening. In tail -f I would just hit enter several times, and new log lines would just appear clearly separated from old lines. Is it possible to add this to less? How?

    Read the article

  • Best tools for "ssh tail -f" style log file monitoring and analysis

    - by dougnukem
    I'm looking for a tool to monitor custom PHP Error logs/Apache and possibly Java logs on remote development servers. I'm not looking for a full production log system like Splunk, but something that's a little more flexible than an ssh terminal doing a "tail -f". Perhaps something that will: * Monitor multiple log files to my local machine for searching/analysis later * Allow "alerts" when certain strings appear in the log * Provide some kind of tabbed/dashboard view of the multiple logs being monitored (in total less than 10 logs).

    Read the article

  • Tail-recursive merge sort in OCaml

    - by CFP
    Hello world! I’m trying to implement a tail-recursive list-sorting function in OCaml, and I’ve come up with the following code: let tailrec_merge_sort l = let split l = let rec _split source left right = match source with | [] -> (left, right) | head :: tail -> _split tail right (head :: left) in _split l [] [] in let merge l1 l2 = let rec _merge l1 l2 result = match l1, l2 with | [], [] -> result | [], h :: t | h :: t, [] -> _merge [] t (h :: result) | h1 :: t1, h2 :: t2 -> if h1 < h2 then _merge t1 l2 (h1 :: result) else _merge l1 t2 (h2 :: result) in List.rev (_merge l1 l2 []) in let rec sort = function | [] -> [] | [a] -> [a] | list -> let left, right = split list in merge (sort left) (sort right) in sort l ;; Yet it seems that it is not actually tail-recursive, since I encounter a "Stack overflow during evaluation (looping recursion?)" error. Could you please help me spot the non tail-recursive call in this code? I've searched quite a lot, without finding it. Cout it be the let binding in the sort function? Thanks a lot, CFP.

    Read the article

  • Recursion Vs Loops

    - by sachin
    I am trying to do work with examples on Trees as given here: http://cslibrary.stanford.edu/110/BinaryTrees.html These examples all solve problems via recursion, I wonder if we can provide a iterative solution for each one of them, meaning, can we always be sure that a problem which can be solved by recursion will also have a iterative solution, in general. If not, what example can we give to show a problem which can be solved only by recursion/Iteration? --

    Read the article

  • NSTask Tail -f Using objective C

    - by Bach
    I need to read the last added line to a log file, in realtime, and capture that line being added. Something similar to Tail -f. So my first attempt was to use Tail -f using NSTask. I can't see any output using the code below: NSTask *server = [[NSTask alloc] init]; [server setLaunchPath:@"/usr/bin/tail"]; [server setArguments:[NSArray arrayWithObjects:@"-f", @"/path/to/my/LogFile.txt",nil]]; NSPipe *outputPipe = [NSPipe pipe]; [server setStandardInput:[NSPipe pipe]]; [server setStandardOutput:outputPipe]; [server launch]; [server waitUntilExit]; [server release]; NSData *outputData = [[outputPipe fileHandleForReading] readDataToEndOfFile]; NSString *outputString = [[[NSString alloc] initWithData:outputData encoding:NSUTF8StringEncoding] autorelease]; NSLog (@"Output \n%@", outputString); I can see the output as expected when using: [server setLaunchPath:@"/bin/ls"]; How can i capture the output of that tail NSTask? Is there any alternative to this method, where I can open a stream to file and each time a line is added, output it on screen? (basic logging functionality)

    Read the article

  • Get last n lines of a file with Python, similar to tail

    - by Armin Ronacher
    I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom. So I need a tail() method that can read n lines from the bottom and supports an offset. What I came up with looks like this: def tail(f, n, offset=0): """Reads a n lines from f with an offset of offset lines.""" avg_line_length = 74 to_read = n + offset while 1: try: f.seek(-(avg_line_length * to_read), 2) except IOError: # woops. apparently file is smaller than what we want # to step back, go to the beginning instead f.seek(0) pos = f.tell() lines = f.read().splitlines() if len(lines) >= to_read or pos == 0: return lines[-to_read:offset and -offset or None] avg_line_length *= 1.3 Is this a reasonable approach? What is the recommended way to tail log files with offsets?

    Read the article

  • Ending tail -f started in a shell script

    - by rangalo
    I have the following. A Java process writing logs to the stdout A shell script starting the Java process Another shell script which executes the previous one and redirects the log I check the log file with the tail -f command for the success message. Even if I have exit 0 in the code I cannot end the tail -f process. Which doesn't let my script to finish. Is there any other way of doing this in Bash? The code looks like the following. function startServer() { touch logfile startJavaprocess > logfile & tail -f logfile | while read line do if echo $line | grep -q 'Started'; then echo 'Server Started' exit 0 fi done }

    Read the article

  • Process arbitrarily large lists without explicit recursion or abstract list functions?

    - by Erica Xu
    This is one of the bonus questions in my assignment. The specific questions is to see the input list as a set and output all subsets of it in a list. We can only use cons, first, rest, empty?, empty, lambda, and cond. And we can only define exactly once. But after a night's thinking I don't see it possible to go through the arbitrarily long list without map or foldr. Is there a way to perform recursion or alternative of recursion with only these functions?

    Read the article

  • Using JSP to Tail a file

    - by nick
    Is there a way to use JSP to create a file tail like Linux's "tail -f" and cache the results? That is, can I read the last X items, cache, and then read again if I get a request that exceeds some timeout?

    Read the article

  • Recursion in an ASP.NET MVC view

    - by Dennis Palmer
    I have a nested data object for a set of items within categories. Each category can contain sub categories and there is no set limit to the depth of sub categories. (A file system would have a similar structure.) It looks something like this: class category { public int id; public string name; public IQueryable<category> categories; public IQueryable<item> items; } class item { public int id; public string name; } I am passing a list of categories to my view as IQueryable<category>. I want to output the categories as a set of nested unordered list (<ul>) blocks. I could nest foreach loops, but then the depth of sub categories would be limited by the number of nested foreach blocks. In WinForms, I have done similar processing using recursion to populate a TreeView, but I haven't seen any examples of using recursion within an ASPX MVC view. Can recursion be done within an ASPX view? Are there other view engines that include recursion for view output?

    Read the article

  • SQL server recursive query error.The maximum recursion 100 has been exhausted before statement completion

    - by ienax_ridens
    I have a recursive query that returns an error when I run it; in other databases (with more data) I have not the problem. In my case this query returns 2 colums (ID_PARENT and ID_CHILD) doing a recursion because my tree can have more than one level, bit I wanna have only "direct" parent. NOTE: I tried to put OPTION (MAXRECURSION 0) at the end of the query, but with no luck. The following query is only a part of the entire query, I tried to put OPTION only at the end of the "big query" having a continous running query, but no errors displayed. Error have in SQL Server: "The statement terminated.The maximum recursion 100 has been exhausted before statement completion" The query is the following: WITH q AS (SELECT ID_ITEM, ID_ITEM AS ID_ITEM_ANCESTOR FROM ITEMS_TABLE i JOIN ITEMS_TYPES_TABLE itt ON itt.ID_ITEM_TYPE = i.ID_ITEM_TYPE UNION ALL SELECT i.ID_ITEM, q.ID_ITEM_ANCESTOR FROM q JOIN ITEMS_TABLE i ON i.ID_ITEM_PADRE = q.ID_ITEM JOIN ITEMS_TYPES_TABLE itt ON itt.ID_ITEM_TYPE = i.ID_ITEM_TYPE) SELECT ID_ITEM AS ID_CHILD, ID_ITEM_ANCESTOR AS ID_PARENT FROM q I need a suggestion to re-write this query to avoid the error of recursion and see the data, that are few.

    Read the article

  • Is there any limit to recursion in lisp?

    - by Isaiah
    I enjoy using recursion whenever I can, it seems like a much more natural way to loop over something then actual loops. I was wondering if there is any limit to recursion in lisp? Like there is in python where it freaks out after like 1000 loops? Could you use it for say, a game loop? Testing it out now, simple counting recursive function. Now at 7000000! Thanks alot

    Read the article

  • SEO & SEM Long Tail Keyword Marketing Strategy

    Long tail marketing strategies for SEO & SEM often return higher conversion rates by up to 200% as compared to short tail generic keyword terms. These long tail keyword terms can be extremely profitable for SEM (search engine marketing) in terms of lower cost or bid for keywords and larger returns on pay per click investment.

    Read the article

  • SEO - How to Optimise For Long-Tail Queries

    There is a great deal of value in the long-tail of search. The long-tail is basically a query that is over three or four keywords long. Good examples of long-tail queries include "cheap flights to Japan May" or "buy back doors UK." Both of these terms exhibit a great deal of user intent - this means the users behind both terms are very far down the buying cycle and are looking for a website on which they can transact and buy a flight to Japan or purchase a back door.

    Read the article

  • Python recursive function error: "maximum recursion depth exceeded"

    - by user283169
    I solved Problem 10 of Project Euler with the following code, which works through brute force: def isPrime(n): for x in range(2, int(n**0.5)+1): if n % x == 0: return False return True def primeList(n): primes = [] for i in range(2,n): if isPrime(i): primes.append(i) return primes def sumPrimes(primelist): prime_sum = sum(primelist) return prime_sum print (sumPrimes(primeList(2000000))) The three functions work as follows: isPrime checks whether a number is a prime; primeList returns a list containing a set of prime numbers for a certain range with limit 'n', and; sumPrimes sums up the values of all numbers in a list. (This last function isn't needed, but I liked the clarity of it, especially for a beginner like me.) I then wrote a new function, primeListRec, which does exactly the same thing as primeList, to help me better understand recursion: def primeListRec(i, n): primes = [] #print i if (i != n): primes.extend(primeListRec(i+1,n)) if (isPrime(i)): primes.append(i) return primes return primes The above recursive function worked, but only for very small values, like '500'. The function caused my program to crash when I put in '1000'. And when I put in a value like '2000', Python gave me this: RuntimeError: maximum recursion depth exceeded. What did I do wrong with my recursive function? Or is there some specific way to avoid a recursion limit?

    Read the article

  • Tail recursion and memoization with C#

    - by Jay
    I'm writing a function that finds the full path of a directory based on a database table of entries. Each record contains a key, the directory's name, and the key of the parent directory (it's the Directory table in an MSI if you're familiar). I had an iterative solution, but it started looking a little nasty. I thought I could write an elegant tail recursive solution, but I'm not sure anymore. I'll show you my code and then explain the issues I'm facing. Dictionary<string, string> m_directoryKeyToFullPathDictionary = new Dictionary<string, string>(); ... private string ExpandDirectoryKey(Database database, string directoryKey) { // check for terminating condition string fullPath; if (m_directoryKeyToFullPathDictionary.TryGetValue(directoryKey, out fullPath)) { return fullPath; } // inductive step Record record = ExecuteQuery(database, "SELECT DefaultDir, Directory_Parent FROM Directory where Directory.Directory='{0}'", directoryKey); // null check string directoryName = record.GetString("DefaultDir"); string parentDirectoryKey = record.GetString("Directory_Parent"); return Path.Combine(ExpandDirectoryKey(database, parentDirectoryKey), directoryName); } This is how the code looked when I realized I had a problem (with some minor validation/massaging removed). I want to use memoization to short circuit whenever possible, but that requires me to make a function call to the dictionary to store the output of the recursive ExpandDirectoryKey call. I realize that I also have a Path.Combine call there, but I think that can be circumvented with a ... + Path.DirectorySeparatorChar + .... I thought about using a helper method that would memoize the directory and return the value so that I could call it like this at the end of the function above: return MemoizeHelper( m_directoryKeyToFullPathDictionary, Path.Combine(ExpandDirectoryKey(database, parentDirectoryKey)), directoryName); But I feel like that's cheating and not going to be optimized as tail recursion. Any ideas? Should I be using a completely different strategy? This doesn't need to be a super efficient algorithm at all, I'm just really curious. I'm using .NET 4.0, btw. Thanks!

    Read the article

  • Linux tail only whole words

    - by Andrew
    Hello, I need to print last 20 characters of string, but only whole words. Delimiter is a space "". Let's consider this example: string="The quick brown fox jumps over the lazy dog" echo $string | tail -c20 returns s over the lazy dog. And I need it to return over the lazy dog instead. Do you know how to accomplish that? Thanks!

    Read the article

  • Recognizing Tail-recursive functions with Flex+Bison and convert code to an Iterative form

    - by Viet
    I'm writing a calculator with an ability to accept new function definitions. Being aware of the need of newbies to try recursive functions such as Fibonacci, I would like my calculator to be able to recognize Tail-recursive functions with Flex + Bison and convert code to an Iterative form. I'm using Flex & Bison to do the job. If you have any hints or ideas, I welcome them warmly. Thanks!

    Read the article

  • Is this implementation truely tail-recursive?

    - by CFP
    Hello everyone! I've come up with the following code to compute in a tail-recursive way the result of an expression such as 3 4 * 1 + cos 8 * (aka 8*cos(1+(3*4))) The code is in OCaml. I'm using a list refto emulate a stack. type token = Num of float | Fun of (float->float) | Op of (float->float->float);; let pop l = let top = (List.hd !l) in l := List.tl (!l); top;; let push x l = l := (x::!l);; let empty l = (l = []);; let pile = ref [];; let eval data = let stack = ref data in let rec _eval cont = match (pop stack) with | Num(n) -> cont n; | Fun(f) -> _eval (fun x -> cont (f x)); | Op(op) -> _eval (fun x -> cont (op x (_eval (fun y->y)))); in _eval (fun x->x) ;; eval [Fun(fun x -> x**2.); Op(fun x y -> x+.y); Num(1.); Num(3.)];; I've used continuations to ensure tail-recursion, but since my stack implements some sort of a tree, and therefore provides quite a bad interface to what should be handled as a disjoint union type, the call to my function to evaluate the left branch with an identity continuation somehow irks a little. Yet it's working perfectly, but I have the feeling than in calling the _eval (fun y->y) bit, there must be something wrong happening, since it doesn't seem that this call can replace the previous one in the stack structure... Am I misunderstanding something here? I mean, I understand that with only the first call to _eval there wouldn't be any problem optimizing the calls, but here it seems to me that evaluation the _eval (fun y->y) will require to be stacked up, and therefore will fill the stack, possibly leading to an overflow... Thanks!

    Read the article

  • How to implement tail calls in a custom VM

    - by DeadMG
    How can I implement tail calls in a custom virtual machine? I know that I need to pop off the original function's local stack, then it's arguments, then push on the new arguments. But, if I pop off the function's local stack, how am I supposed to push on the new arguments? They've just been popped off the stack.

    Read the article

  • Implement "tail -f" in C++

    - by Hamming
    Hi! I want to create a small code in C++ with the same functionality as "tail-f": watch for new lines in a text file and show them in the standard output. The idea is to have a thread that monitors the file Is there an easy way to do it without opening and closing the file each time?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >