python - sorting numbers using recursion -
the purpous of using recursion instead of using for in range(11):
because advantagous start top trying solve specific mathematical problem. function changed returns [n]
that matches criteria.
print(numbers)=[[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]]
why there brackets? print(numbers[7])=indexerror: list index out of range
has brackets?
# function supposed sorting numbers in list def sorting_numbers(n): if n > 1: return [n] + sorting_numbers(n-1) else: return [1] numbers = [] n = 10 numbers = (sorting_numbers(n)) print(numbers)
print(numbers)=[[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]]
why there brackets? print(numbers[7])=indexerror: list index out of range
has brackets?
well if really want use recursion such simple problem - warned it's terribly inefficient , cause maximum recursion depth exceeded
error values of n
close 1000
(python not designed handle recursion efficiently):
def storing_numbers(n): if n > 1: return [n] + storing_numbers(n-1) else: return [1]
or bit shorter:
def storing_numbers(n): return [] if n <= 0 else [n] + storing_numbers(n-1)
notice how build list along way, , base case returns list. use this:
numbers = storing_numbers(10) numbers => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
of course, it'd unrealistic use recursive function building list beyond academic exercise. real-life, practical implementation instead:
list(range(10, 0, -1)) => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
and here's how you'd use list comprehension filtering numbers matching criteria, let's say, numbers:
[x x in range(10, 0, -1) if x % 2 == 0] => [10, 8, 6, 4, 2]
Comments
Post a Comment