, , , . , , n > 0 ( while, while). ( ) , , while, . , n/10.
, :
def digits(n):
, n 0, , , :
if n <= 0:
return []
Now, in the recursive case, you want to add n% 10 to the list and call your function again, only you want to call it with another n, changed just like in your while loop:
else:
return [n%10]+digits(n/10)
So, if you follow this, for each recursive case you get a list containing n% 10, then it will add the result of a new call, which will be either (n / 10)% 10 or an empty list, For example, running this function with n = 100 will look like this:
newlist = digits(100)
newlist = [100%10]+digits(100/10)
newlist = [100%10]+([10%10] + digits(10/10))
newlist = [100%10]+([10%10] + ([1%10] + digits(10/10)))
newlist = [100%10]+([10%10] + ([1%10] + ([])))
newlist = [0,0,1]
Nested parsers are used to show how function digits will be overwritten by the built-in ones.
source
share