Re: Returning from a multiple stacked call at once
On 12Dec2020 07:39, ast wrote: >In case a function recursively calls itself many times, >is there a way to return a data immediately without >unstacking all functions ? Not really. Do you have an example where this is inconvenient? There are alternatives, for example passing in a Queue and put()ing the data onto the queue. It's quite dependent on what you're trying to do though. Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Letter replacer - suggestions?
On 12Dec2020 01:49, Bischoop wrote: >On 2020-12-07, Grant Edwards wrote: >> On 2020-12-07, MRAB wrote: >>> Avoid a 'bare' except unless you _really_ mean it, which is >>> virtually never. Catch only those exceptions that you're going to >>> handle. >> >> And sometimes "handling" is just printing some extra stuff and then >> re-raising the original exception: >> >> try: >> something(): >> except: >> print() >> raise > >Noted, thanks. Also note that the exception itself is very interesting. So: except Exception as e: print(, e) raise Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
In article , Bischoop wrote: >I've also convert the choice to int() but doesn't help. Oh.. did not read this yet. How did you do this? In both places after the input or during the comparison? If so, in which version? Only the first version would work. The other two are just plain wrong. -- [J|O|R] <- .signature.gz -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
On 2020-12-12, Oscar wrote: > In article , > Bischoop wrote: >>I've also convert the choice to int() but doesn't help. > > Oh.. did not read this yet. How did you do this? In both places after > the input or during the comparison? If so, in which version? Only the > first version would work. The other two are just plain wrong. after the input, https://bpa.st/BFJA -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning from a multiple stacked call at once
In article <5fd465b5$0$8956$426a7...@news.free.fr>, ast wrote: >Hello > >In case a function recursively calls itself many times, >is there a way to return a data immediately without >unstacking all functions ? If you are referring to your "are you ok?" problem, please read up on recursion and when and how to use it. You were doing it completely wrong. You only call a function from *whitin itself* if you need recursion. It's quite hard to explain in a few words, so just google it. I'm sure there are many great explanations around. -- [J|O|R] <- .signature.gz -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
I've also convert the choice to int() but doesn't help. -- https://mail.python.org/mailman/listinfo/python-list
To check if number is in range(x,y)
I need to check if input number is 1-5. Whatever I try it's not working. Here are my aproaches to the problem: https://bpa.st/H62A What I'm doing wrong and how I should do it? -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
In article , Bischoop wrote: > >I need to check if input number is 1-5. Whatever I try it's not working. >Here are my aproaches to the problem: https://bpa.st/H62A > >What I'm doing wrong and how I should do it? You need to learn about types. ;-) Input returns a string. That string is not in the range you compare it to. You need to convert it to an int: choice = int(input.. ) This is assuming you want a whole number. You compare it against the list of numbers [1, 2, 3, 4, 5]. If 2.4 is also a valid number, you need a different comparison. 2.4 is not in this list. So first you should get your requirements straight.. ;-) -- [J|O|R] <- .signature.gz -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
Got it solved here: https://bpa.st/BFJA -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning from a multiple stacked call at once
Le 12/12/2020 à 09:18, Cameron Simpson a écrit : On 12Dec2020 07:39, ast wrote: In case a function recursively calls itself many times, is there a way to return a data immediately without unstacking all functions ? Not really. Do you have an example where this is inconvenient? There are alternatives, for example passing in a Queue and put()ing the data onto the queue. It's quite dependent on what you're trying to do though. Cheers, Cameron Simpson I don't really need it. I was just wondering and guessed it was not feasible. Here is a code where it would be useful. This code looks for a path in a graph. If the found path is long, say 100 nodes, then path_finder calls itself recursively 100 times, and has to unstack 100 times to provide the found path. It could be returned immediately. def path_finder(graph, start, end, path=[]): if start in path: return None if start == end: return path + [start] # Found ! if start not in graph: return None path = path + [start] for node in graph[start]: found_path = path_finder(graph, node, end, path) if found_path: return found_path return None graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} path_finder(graph, 'A', 'D') -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning from a multiple stacked call at once
Le 12/12/2020 à 17:10, Oscar a écrit : In article <5fd465b5$0$8956$426a7...@news.free.fr>, ast wrote: Hello In case a function recursively calls itself many times, is there a way to return a data immediately without unstacking all functions ? If you are referring to your "are you ok?" problem, please read up on recursion and when and how to use it. You were doing it completely wrong. You only call a function from *whitin itself* if you need recursion. It's quite hard to explain in a few words, so just google it. I'm sure there are many great explanations around. not understood. -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning from a multiple stacked call at once
On 2020-12-12 07:39, ast wrote: > In case a function recursively calls itself many times, > is there a way to return a data immediately without > unstacking all functions ? Not that I'm aware of. If you use recursion (and AFAIK, Python doesn't support tail-recursion), you pay all the pushes & pay all the pops. If you convert it to an iterative algorithm, you can bail early with items still in the work queue: while queue: item = queue.get() if test(item): print(f"Found it, bailing early with {len(queue)} item(s)") break more = process(item) if more: queue.extend(more) -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
On 2020-12-12 15:12, Bischoop wrote: > I need to check if input number is 1-5. Whatever I try it's not > working. Here are my aproaches to the problem: https://bpa.st/H62A > > What I'm doing wrong and how I should do it? A range is similar to a list in that it contains just the numbers listed: >>> r = range(10) >>> 2 in r True >>> 2.5 in r False >>> r = range(1, 10, 2) >>> 2 in r False >>> list(r) [1, 3, 5, 7, 9] It also doesn't automatically convert from the string inputs you're getting from the input() function: >>> s = "5" >>> s in r False >>> int(s) in r True Additionally, note that the endpoint of the range is exclusive so >>> r = range(1, 10) >>> 10 in r False >>> list(r) [1, 2, 3, 4, 5, 6, 7, 8, 9] If you want numeric-range checks, Python provides the lovely double-comparison syntax: >>> x = 5 >>> 2 < x < 10 True >>> x = 5.5 >>> 2 < x < 10 True >>> s = "5" >>> 2 < s < 10 Traceback… >>> 2 < int(s) < 10 True Hopefully this gives you the hints that you need to troubleshoot. -tkc -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning from a multiple stacked call at once
ast wrote at 2020-12-12 07:39 +0100: >In case a function recursively calls itself many times, >is there a way to return a data immediately without >unstacking all functions ? Python does not have "long jump"s (out of many functions, many loop incarnations). In some cases, you can use exceptions to emulate "long jump"s. -- https://mail.python.org/mailman/listinfo/python-list
RE: Returning from a multiple stacked call at once
As always, it may be useful to know WHY the questioner wants to skip intermediate functions already in progress and jump back to some unspecified earlier level. There is a reason why functions are "stacked" and there are data structures that really may need to be unwound. But if the question is not about some sort of "efficiency" or speed but about ways to write the code so once something has been found, it can fairly directly return, that does have answers. Tail recursion is an example, sometimes real as in the function is overlaid and there is no need to return and sometimes sort of simulated with overhead remaining but it looks like it returned. If all the functions written are your own, then simply calling your next function that you want to be the return value (from anywhere applicable in the function, not just the end, is easy enough to write as: return(next_function(args)) It will still unwind but logically will act as if it just returns without the need for the functions to be written with lots of if statements or twisted logic so nothing much gets done after the right result is obtained. And, of course, there are exceptions. If you raise an exception that you know will not be caught until you reach the level where you do catch it, you can sort of sail through any of the functions between and bypass any logic that might otherwise be there for a normal return. Arguably it might be better to write your code carefully so upon success, it unwinds easily and only in low probability cases look for an abrupt exit. And for a really abrupt exit, there is a way to shut down the program very abruptly perhaps even too abruptly. -Original Message- From: Python-list On Behalf Of Dieter Maurer Sent: Saturday, December 12, 2020 12:20 PM To: ast Cc: python-list@python.org Subject: Re: Returning from a multiple stacked call at once ast wrote at 2020-12-12 07:39 +0100: >In case a function recursively calls itself many times, is there a way >to return a data immediately without unstacking all functions ? Python does not have "long jump"s (out of many functions, many loop incarnations). In some cases, you can use exceptions to emulate "long jump"s. -- https://mail.python.org/mailman/listinfo/python-list Scanned by McAfee and confirmed virus-free. Find out more here: https://bit.ly/2zCJMrO -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
On 2020-12-12 at 10:51:00 -0600, Tim Chase wrote: > If you want numeric-range checks, Python provides the lovely > double-comparison syntax: > > >>> x = 5 > >>> 2 < x < 10 > True Not just numbers: >>> 'm' < 'n' < 'o' True >>> 'one' < 'one point five' < 'two' True Okay, so the second one is a trap, but you get the idea. ;-) -- https://mail.python.org/mailman/listinfo/python-list
Re: Function returns old value
Bischoop writes: > On 2020-12-12, Joe Pfeiffer wrote: >> Bischoop writes: >> >>> I've function asking question and comparing it, if is not matching 'yes' >>> it does call itself to ask question again. The problem is that when >>> function is called second time it returns old value or with additional >>> else statement it returns none. >>> >>> Code: https://bpa.st/KVGA >> >> It calls itself again, but what does it return in that case? > > I've stated it returns old value that I've input first time, anyway > output is also inluded in a paste but since you've asked: Sorry, my question wasn't clear. What I meant was, "in your return statement, what are you returning"? You need to be returning the value from the recursive call. > def question(): > ask = input("Are you OK?:").lower() > if ask != 'yes': > question() > return ask > > print (question()) > > #output: > Are you OK?:no > Are you OK?:no > Are you OK?:yes > no > > --- > #Another way with 'elif' statment returns none > > > def question(): > ask = input("Are you OK?:").lower() > if ask != 'yes': > question() > elif ask == 'yes': > return ask > > print (question()) > > #output: > Are you OK?:no > Are you OK?:yes > None > > #Tried also nested > functions, same results: > > def question(): > ask = input("Are you > OK?:").lower() > > def > check_question(n): > if ask > != > 'yes': > > question() > > else: > > return > > ask > > > m > > = > > check_question(ask) > > print > > (m) > > question() > > > #output: > > Are > > you > > OK?:no > > Are > > you > > OK?:yes > > None > > > Process > > finished > > with > > exit >
Re: Returning from a multiple stacked call at once
On 13/12/2020 05:46, ast wrote: Le 12/12/2020 à 09:18, Cameron Simpson a écrit : On 12Dec2020 07:39, ast wrote: In case a function recursively calls itself many times, is there a way to return a data immediately without unstacking all functions ? Not really. Do you have an example where this is inconvenient? There are alternatives, for example passing in a Queue and put()ing the data onto the queue. It's quite dependent on what you're trying to do though. I don't really need it. I was just wondering and guessed it was not feasible. [somewhat simplified] The way Python handles recursion is to add a "frame" every time the function is called. The "frame" contains all the data-items for the function. Think of the frames as stacked on top of each other: frame n frame n+1 frame n+2 ... NB you can 'see' this when viewing an exception tracing its way from a deeply-nested function, to the function which called it, to the function which called that, etc. This is how node-1's attributes are kept separate from node-2's. If you think that only the 'current frame' as being visible at any stage of the program's execution, it will suit our purposes for-now. One effect of a "return" is to close the current frame (and to carry any return-value 'back' to the previous frame). Per comment (below), if this function recurses 100 times, then there will be 100 frames. Accordingly, there need to be 100 returns to close each of those frames. NB Python offers reflective facilities to inspect all of this, if you really want to see what happens 'under the hood/bonnet'. Here is a code where it would be useful. This code looks for a path in a graph. If the found path is long, say 100 nodes, then path_finder calls itself recursively 100 times, and has to unstack 100 times to provide the found path. It could be returned immediately. > ... Recursion may not be the best tool/tactic here. As you observe, it has to be 'unwound'! Assuming the objectives are: 1 trace through a graph 2 locate an identified node 3 note (and make available 'later') the path through the graph to reach said node. The logic for (1) and (2) has been done. For (3), consider using a "stack". This is a ComSc term (in case you've not studied such), and is the same concept as the 'stack of frames' (above). 1 Create a list "stack". 2 Walk the network. 3 Upon 'arrival' at a node, add the node to the 'stack' by appending relevant detail(s) to the list. 4 If the node is 'the end', stop walking. If the 'walk' is a loop (cf recursion), the 'stop' becomes a (single) "break". If the identified node is found 50-nodes 'in', or 100-nodes, that will be the length of the list/stack. (which BTW will require less storage than the same number of recursion-frames) Now, back to ComSc (again, with apologies for appearing to 'talk-down', if you've studied this stuff but let's help anyone else 'following along at home'), when it comes to using the list/stack, if you start with the found-node and work your way 'back' to the start-node, this will require working from the list[ -1 ] element, back to the zero-th element. Accessing each element is known as "popping the stack", and you will find a Python list.method() enacting such - but be careful about the working-backwards logic! Conversely, if the ensuing functionality wants to 'start' from the start-node and walk 'forward' through the graph to the found-node; then that process will start at list[ 0 ], per most collection-processing. In which case, rather than a "stack", we are looking at a "queue" (per @Cameron). Thus, a "stack" accepts additions to 'the end', and "pops" data from the same 'end' ("LIFO" = last-in, first-out). Whereas a "queue" also adds to 'the end', but processes/pops from the beginning ("FIFO" = first-in, first-out). If this ComSc-stuff is 'new', then plenty of books and web-sites discuss such data-structures... -- Regards =dn -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning from a multiple stacked call at once
On 12Dec2020 17:46, ast wrote: >Le 12/12/2020 à 09:18, Cameron Simpson a écrit : >>On 12Dec2020 07:39, ast wrote: >>>In case a function recursively calls itself many times, >>>is there a way to return a data immediately without >>>unstacking all functions ? >> >>Not really. Do you have an example where this is inconvenient? >>There are alternatives, for example passing in a Queue and put()ing >>the data onto the queue. [...] > >I don't really need it. I was just wondering and guessed it was >not feasible. Well, it is feasible. Kinda. Regardless, the stack need to unwind. You _could_ abuse exceptions to do that in a single go: class CompletedOperation(Exception): def __init__(self, value): self.value = value ... in your function ... raise CompletedOperation(the_value) ... at the calling end ... try: call_the_function() except CompletedOperation as e: value = e.value else: ... value not found ... or obvious variations where that try/except it done by the outermost function invocation, concealing it from users. But usually you just return the value from the innermost call and return that in turn: def f(): for subpart in ... stuff ...: value = f(subpart) if value is not None: return value return None which searches some data structure and returns nonNone on finding something, None if not found. >Here is a code where it would be useful. This code looks for a >path in a graph. >If the found path is long, say 100 nodes, then path_finder calls >itself recursively 100 times, and has to unstack 100 times to >provide the found path. It could be returned immediately. The above code returns efficiently. But there's a cascade of returns. WRT to the below code, I thought I'd restate what DL Neil has said: you can often make these things nonrecursive by maintaining a queue or stack of pending tasks. A recursive function keeps it state in the call stack, but you needn't do that: def f(node,...): pending = [node] while pending: node = pending.pop(0) if node is the one you're looking for: return node pending.extend(children of the node here ...) return None This keeps a queue of unexamined nodes in pending. You could make that a stack by replacing the .pop(0) with .pop(). That will be more efficient (remove the leading element of a list is comparatively expensive) but changes the search order. Anyway, this is what DL Neil is referring to: a nonrecursive function with a data structure to hold the coming work, which a recursive function would process by calling itself instead of saving the undone task (chid nodes, here). Cheers, Cameron Simpson -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning from a multiple stacked call at once
On 13/12/20 5:46 am, ast wrote: Here is a code where it would be useful. This code looks for a path in a graph. Recursion is probably not the best way to solve this problem in CPython, because it imposes a limit on the number of nested calls (in order to detect runaway recursion). By default the limit is about 1000. So if you have a large graph with a path more than 1000 steps long, you can hit the recursion limit. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Unable to pass dict from json.
Here https://bpa.st/YBVA I've working code with dictionary only if used dict from the code (it's commented now) but when I load it I can print it from load function (line 14) but at all have not a clue how to pass the data so could use them. I've learnt a lot when making it but here I'm completetly stuck, was trying do solve it for a whole day and it's just a death wall for me. -- Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: To check if number is in range(x,y)
On 2020-12-12, Tim Chase wrote: > > Hopefully this gives you the hints that you need to troubleshoot. > > -tkc > > > > Yes it explains a lot. Thanks -- https://mail.python.org/mailman/listinfo/python-list
Re: Unable to pass dict from json.
On Sat, Dec 12, 2020 at 4:05 PM Bischoop wrote: > > Here https://bpa.st/YBVA I've working code with dictionary only if used > dict from the code > (it's commented now) but when I load it I can print it from load > function (line 14) but at all have not a > clue how to pass the data so could use them. > I've learnt a lot when making it but here I'm completetly stuck, was > trying do solve it for a whole day and it's just a death wall for me. > I too recommend cutting and pasting minimal code into your e-mail, instead of referring to a URL; URL's used this way are a common attack vector. -- https://mail.python.org/mailman/listinfo/python-list
Re: Unable to pass dict from json.
On 2020-12-13 00:01, Bischoop wrote: Here https://bpa.st/YBVA I've working code with dictionary only if used dict from the code (it's commented now) but when I load it I can print it from load function (line 14) but at all have not a clue how to pass the data so could use them. I've learnt a lot when making it but here I'm completetly stuck, was trying do solve it for a whole day and it's just a death wall for me. It would be better to use a loop instead of recursion in load_options when asking for the choice. load_json returns the data, so just have load_options return it and then pass it in to the functions that need it. There's no need to make 'load_json' and the others local to 'load_from_file', and similarly for save_tofile. -- https://mail.python.org/mailman/listinfo/python-list
To whom he want to set breakpoint on negative line number in pdb
I use .pdbrc file to help debugging. To avoid editing this file frequently when source was modified, I need this feature. I modify the checkline function in pdb.py from ... line = linecache.getline(filename, lineno, globs) if not line: to ... lines = linecache.getlines(filename, globs) if lineno < 0: lineno = len(lines) + lineno + 1 # change to a valid positive number, or not if 1 <= lineno <= len(lines): line = lines[lineno-1] else: line = '' if not line: ... This modification is mostly the copy of the getline function body except the added line. It will not influence the original pdb usage in anyway. --Jach -- https://mail.python.org/mailman/listinfo/python-list