Open essepuntato opened 4 years ago
We didn't talk about the reverse() method in the classroom (different from reversed(), because it returns a list and not an iterator), so there's probably a smarter way to do this exercise.
def my_range(stop_number):
output_range_object = list()
current_number = stop_number
while current_number >= 1:
output_range_object.append(current_number - 1)
current_number -= 1
output_range_object.reverse()
return output_range_object
def test_my_range(stop_number, expected):
result = my_range(stop_number)
if result == expected:
return True
else:
return False
print(test_my_range(5, [0, 1, 2, 3, 4]))
# It prints True
Replying to https://github.com/comp-think/2019-2020/issues/19#issuecomment-549853632 by @sntcristian:
I didn't understand what the if len(output_range) != 0
control is for. I think it works even without it
Right! I haven't thought it was that simple.
def my_range(stop_number):
output = list()
i = 0
while i < stop_number:
output.append(i)
i += 1
return output
def test_my_range(input, expected):
return my_range(input) == expected
print(test_my_range(5, range(5)))
Hi all,
please find attached my personal solution – also available online:
# Test case for the function
def test_my_range(stop_number, expected):
result = my_range(stop_number)
if expected == result:
return True
else:
return False
# Code of the function
def my_range(stop_number):
l = list()
while stop_number > 0:
stop_number = stop_number - 1
l.insert(0, stop_number)
return l
# Tests
print(test_my_range(0, []))
print(test_my_range(1, [0]))
print(test_my_range(4, [0, 1, 2, 3]))
Please be aware that, formally speaking, range(5)
is not a list. Thus, checking if the object returned by the function range
is a list will return False anyway.
Thanks for the heads-up about the range
function @essepuntato. I mistakenly used a Python 2.7 interpreter for testing my solution to this one and it worked fine on that (since in Python 2 range
used to create lists instead of iterators).
def my_range(num): output_list = [] '''n = 0
'''while n < num:
'''''output_list.append(n) '''''''''n = n+1 ''''''return output_list print(my_range(10) == list(range(10)))
Write in Python the function
def my_range(stop_number)
which behave like the built-in functionrange()
introduced in Section "Insertion sort" and returns a proper list, and accompany the function with the related test case. It is not possible to use the built-in functionrange()
in the implementation.