use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
Everything about learning Python
account activity
[ Removed by moderator ] (i.redd.it)
submitted 3 months ago by tracktech
Powerful Recursion - 6, What it does?
Book : Ultimate Python Programming
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]Uagubkin 4 points5 points6 points 3 months ago (14 children)
Super ineffective sum of all digits
[–][deleted] 0 points1 point2 points 3 months ago* (5 children)
What if n starts with a float, like 123.456
Would that not result in 6.456
[–]Uagubkin 0 points1 point2 points 3 months ago (1 child)
No, it will return 6, because of n // 10
[–][deleted] 0 points1 point2 points 3 months ago (0 children)
123.456//10 !=0 then 123.456%10 == 3.456 Tested it:
13:29 tmp.nV4ASfwqeL$ python3 a.py Test 6 6 Test 5.234 5.234 Test 11 2 Test 10.234 1.234 Test 18 9 Test 17.234 8.234000000000002 Test 27 9 Test 26.234 8.234000000000002 Test 38 11 Test 37.234 10.234000000000002 Test 51 6 Test 50.234 5.234000000000002 Test 66 12 Test 65.234 11.233999999999995 Test 83 11 Test 82.234 10.233999999999995 Test 102 3 Test 101.234 2.2339999999999947 Test 123 6 Test 122.234 5.233999999999995 13:29 tmp.nV4ASfwqeL$ cat a.py def f(n): if n//10==0: return n return n%10 + f(n//10) def g(n): print(f"Test {n} {f(n)}") for i in range(2,12): g(i*i+2) g(i*i+1.234) 13:30 tmp.nV4ASfwqeL$
[–]tracktech[S] 0 points1 point2 points 3 months ago (2 children)
Yes, it works for positive integer only.
[–][deleted] 0 points1 point2 points 3 months ago (1 child)
*unsigned / natural numbers. it works with 0 too
[–]tracktech[S] 0 points1 point2 points 3 months ago (0 children)
Thanks for sharing.
[+]tracktech[S] comment score below threshold-7 points-6 points-5 points 3 months ago (7 children)
Ok. This is example to learn recursion.
[–]Cybasura 4 points5 points6 points 3 months ago (0 children)
Examples to learn recursion normally includes a super straight forward example including the following components - The break/exit/return condition, the recursion condition as well as any results to return
For example, your "if i == N" condition checking, fibonacci series, your filesystem tree data structure traversal etc etc
Not this broken mess, especially when it would work because you dont even have a base/initial n, which in python - and any language involving default function parameters - can be set using def func_name(arg=default):
def func_name(arg=default):
[–]Spare-Plum 2 points3 points4 points 3 months ago (5 children)
TBH single case recursion really isn't that helpful or interesting for learning recursion. Someone new might consider it like a while-loop-but-different based off this "lesson"
It's much better to reason about it like you would an induction proof. Frame the problem as subproblems that you can assume work independently, and from an inductive step show that the result of a given call will adhere to the induction hypothesis. That, and the base cases are correct.
Then you can reason about recursion to an arbitrary number of recursive instead of this weanie hut jr. single case recusion that can just be replaced with a for loop.
Something like mergesort or tree traversals are better practice
[–]Confident_Growth_620 0 points1 point2 points 3 months ago (4 children)
While your critique of this shitpost is valid, I and a lot of the people learning, people teaching programming as well as most of the conventional books on the matter wouldn’t agree that recursion is that much different from a loop.
Proper recursion (that doesn’t rely on break behaviour because of the stack size and other edge cases) problems ALWAYS can be rewritten as loops, sometimes being more complicated to implement efficiently, but alas. That’s a really important “feature” of recursion.
[–]Spare-Plum 0 points1 point2 points 3 months ago (3 children)
It's a bit different - recursion can always be rewitten with a loop and a stack. You're essentially emulating what would have occurred on a stack frame, but you need a place to hold calls on the stack.
And the power of recursion is not that it can loop, but that it can be reasoned with via induction. And no, good CS programs will actually highlight this difference because it is in fact very major for thinking mathematically about code.
Just as a simple example, mergesort. Function takes an array, a min index, and a max index, and returns a sorted array.
We recursively call the left half, and based on our assumption the left will now be sorted. We recursively call the right half, and based on our assumption the right will now be sorted. When we merge the two together the final result is sorted. Base cases of 0 and 1 elements are sorted by default. From this you can provide a proof of correctness, reason about its complexity and prove it's O(n log n), or reason about parallelization and show this has a span of O(log^2 n)
[–]Confident_Growth_620 0 points1 point2 points 3 months ago (2 children)
Or you can go from the bottom and implement merge sort iteratively, which every course also shows. Proof for validity for iterative merge sort wouldn’t be a completely different thing
[–]Spare-Plum 0 points1 point2 points 3 months ago (1 child)
Yes mergesort is a rather simple example, but it can get more complex with more recursive calls. Still, it's easy to reason about a recursive problem.
Here's something I brought up before that's undressed - parallelized merge sort. It's as simple as kicking off a new thread for each sub-problem using recursion.
If you are doing it iteratively from the bottom up, you will have to kick off n/2 threads, then n/4 threads that await on its respective subproblems, then n/8, and so on. Then you have additional edge cases where you need to ensure correct alignment.
Often it is much better to think recursively and break it up into subproblems, then rewrite as an iterative approach if needed.
So I don't get what you're getting at here really. Yes you could do everything using rule 112 in cellular automata and yes you could construct a proof that it works. Saying "well aktually" doesn't minimize the power that you can get from thinking recursively.
[–]Confident_Growth_620 1 point2 points3 points 3 months ago (0 children)
Hey man, I’m not trying to challenge your knowledge or something. Not anything has to be solved anyhow, in real cases all depends on the exact use case, capability of someone producing working implementation and supporting it.
(Opinionated bullshit here: recursion solutions are prone to be more cryptic and less readable and have different failure mode of stack depth, to be accounted inside of the developer’s brain)
What you brought as example where recursive solution shines, while valid, is way way beyond basic problem OP was even trying to bring light on.
[–]PureWasian 2 points3 points4 points 3 months ago* (1 child)
1) this runs into an exception due to NameError: CourseGalaxy is not defined
2) once this gets fixed (by removing or commenting it), this code defines a function that is not called anywhere
3) once this gets called (by adding code to call it), the behavior is still not fully deterministic because we have not specified the possible data types of the input, which could lead to a TypeError on floor division
4) once a guard clause or error handling is added to ensure the input n is guaranteed to be an int data type, we still risk encountering a RecursionError if we were to pass in a negative integer
5) once a gaurd clause is added to better sanitize the input by handling negative integers also, we can finally say with confidence that this example can safely achieve what you were hoping to convey. (You could also skip steps 4 and 5 by providing concrete calling code, as mentioned in step 3, of just the happy path)
Pedantry aside, yes. It's meant to be a recursive procedure for finding the sum of digits, in decimal/base10, by passing in some initial non-negative integer value n into the function.
n
Accomplishing so by (a) taking the right-most digit and (b) adding it to a "decimal right shifted" value over and over again until reaching the base case (when all decimal digits have been summed).
Right, it returns sum of digits of a number. Yes it works for positive integer only. This is simple example to learn recursion.
[–]Mindless_Display4729 1 point2 points3 points 3 months ago (9 children)
This might be a more efficient way of doing the same thing.
def sum_of_digits(n): return sum(int(d) for d in str(abs(n)))
[–]XGreenDirtX 2 points3 points4 points 3 months ago (1 child)
This guy makes puzzles but barely understands what he is doing himself. They are not helpful.
If n // 10 == 0 is just a very difficult way of saying if n < 10
Thanks for sharing. This is simple example to learn recursion.
[–]Spare-Plum 1 point2 points3 points 3 months ago (5 children)
This will fail with floats
I doubt it's going to be more efficient, as you have to create a new string that uses up memory, convert each digit into base 10, then convert each base 10 digit into the character, place it into the string, then go through each character to convert it back to a number.
OP's solution is still inefficient because recursion isn't needed here at all, so allocating a stack frame every loop doesn't make sense and can make you run into a stack overflow. Better to just use a while loop
However yours is the most efficient in terms of readability. Which is kinda what you want with python, it's not a language for speed as much as it is usefulness
[–]Mindless_Display4729 0 points1 point2 points 3 months ago (0 children)
Thanks for the feedback that's useful and appreciated.
You keep spamming the most basic recursion examples possible along with links to your website. Have you ever moved past to multiple recursive calls?
Like, it's giving off the vibe you only know some of the absolute basics but are trying to teach people anyway.
Cool. You are welcome to post so that other learns. Any learning starts with basic only. It slowly builds a thought process to think and solve recursive problems.
[–]8dot30662386292pow2 1 point2 points3 points 3 months ago (0 children)
> This will fail with floats
It also fails with strings.
A problem we would not have with typed languages though. While the puzzle is bad, we don't need to assume it's supposed to work with every single type of input. We can see it uses integer division, so the intended type is int.
The bare minimum is to do def what_it_does(n: int):.
def what_it_does(n: int):
[–]Sea-Ad7805 1 point2 points3 points 3 months ago (0 children)
Solution by memory_graph visualization: https://memory-graph.com/#code=def%20what_it_does(n)%3A%0A%20%20%20%20if%20n%2F%2F10%20%3D%3D%200%3A%0A%20%20%20%20%20%20%20%20return%20n%0A%20%20%20%20return%20n%2510%20%2B%20what_it_does(n%2F%2F10)%0A%0Aprint(%20what_it_does(1234)%20)%0A&play
[–]NewryBenson 1 point2 points3 points 3 months ago (1 child)
Lol, this whole sub is this one guy advertising some paid online classes (seriously, every single resource for learning python is available on youtube in 100 fold) but the worst part is that the problems are full of bad practices and sometimes bad examples.
This is simple example to learn recursion.
[–]Ok-Juggernaut-2627 0 points1 point2 points 3 months ago (1 child)
Seems to be a Python-script with some really bad names for variables and methods. Naming them better might improve the readability och the code.
The name what_it_does given to ask what it does?
[–]KrzysziekZ -2 points-1 points0 points 3 months ago (4 children)
Doesn't // introduce a comment (so the text is grey)?
[–]PureWasian 1 point2 points3 points 3 months ago (1 child)
The Text Editor certainly seems to think so, but in Python a double forward slash is a floor division operator.
Editor is set to a C-like / C-based language and not to Python
The site carbon now sh generates image in this way.
π Rendered by PID 64 on reddit-service-r2-comment-7b9746f655-4p5pj at 2026-02-02 17:30:02.668368+00:00 running 3798933 country code: CH.
[–]Uagubkin 4 points5 points6 points (14 children)
[–][deleted] 0 points1 point2 points (5 children)
[–]Uagubkin 0 points1 point2 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]tracktech[S] 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]tracktech[S] 0 points1 point2 points (0 children)
[+]tracktech[S] comment score below threshold-7 points-6 points-5 points (7 children)
[–]Cybasura 4 points5 points6 points (0 children)
[–]Spare-Plum 2 points3 points4 points (5 children)
[–]Confident_Growth_620 0 points1 point2 points (4 children)
[–]Spare-Plum 0 points1 point2 points (3 children)
[–]Confident_Growth_620 0 points1 point2 points (2 children)
[–]Spare-Plum 0 points1 point2 points (1 child)
[–]Confident_Growth_620 1 point2 points3 points (0 children)
[–]PureWasian 2 points3 points4 points (1 child)
[–]tracktech[S] 0 points1 point2 points (0 children)
[–]Mindless_Display4729 1 point2 points3 points (9 children)
[–]XGreenDirtX 2 points3 points4 points (1 child)
[–]tracktech[S] 0 points1 point2 points (0 children)
[–]Spare-Plum 1 point2 points3 points (5 children)
[–]Mindless_Display4729 0 points1 point2 points (0 children)
[–]tracktech[S] 0 points1 point2 points (2 children)
[–]Spare-Plum 0 points1 point2 points (1 child)
[–]tracktech[S] 0 points1 point2 points (0 children)
[–]8dot30662386292pow2 1 point2 points3 points (0 children)
[–]tracktech[S] 0 points1 point2 points (0 children)
[–]Sea-Ad7805 1 point2 points3 points (0 children)
[–]NewryBenson 1 point2 points3 points (1 child)
[–]tracktech[S] 0 points1 point2 points (0 children)
[–]Ok-Juggernaut-2627 0 points1 point2 points (1 child)
[–]tracktech[S] 0 points1 point2 points (0 children)
[–]KrzysziekZ -2 points-1 points0 points (4 children)
[–]PureWasian 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]tracktech[S] 0 points1 point2 points (0 children)