The function returns each element as a list instead of one list with the same elements
Input example: [5, 9, 2, 4, 1, 3]
Expected Result: [9, 2, 1]
The function returns each item as a list instead of a single list with the same items as below.
[nine]
[2]
[1]
def divide_digits(a):
"""
This is where the function Document string (docstring) goes.
"""
# make a shallow copy of the int_list and assign it to variable lst_copy
lst_copy = a[:]
# sort lst.copy
lst_copy.sort()
# as long as the lst_copy is not empty:
while lst_copy:
# get/pop the element from the beginning and at the end of the new_list
largest_num = lst_copy.pop()
smallest_num = lst_copy.pop(0)
new_list = []
# perform the division of two these elements
result = largest_num / smallest_num
# round down the result to the nearest integer
# append the result of the division operation to the new list
new_list.append(round(result))
# return the new_list
return new_list
source to share
Problem new_list = []
. You are reinitializing the list every iteration. And you have to back away from return
.
def divide_digits(a):
lst_copy = a[:]
lst_copy.sort()
new_list = [] # <-- this has to go here
while lst_copy:
largest_num = lst_copy.pop()
smallest_num = lst_copy.pop(0)
result = largest_num / smallest_num
new_list.append(round(result)) # <-- on every iteration you append to the new_list
return new_list # <-- when you are done looping, return the new_list
A shorter alternative to your code using a list comprehension would be:
def divide_digits(a):
lst_copy = sorted(a) #<-- `sorted()`, unlike `.sort()` creates a new list
return [round(lst_copy.pop() / lst_copy.pop(0)) for _ in a[::2]]
source to share
Your indentation is wrong. Your return statement is inside a while loop. It must be outside of it, which means that you need to define new_list outside of the loop as well. Try the following:
def divide_digits(a):
"""
This is where the function Document string (docstring) goes.
"""
# make a shallow copy of the int_list and assign it to variable lst_copy
lst_copy = a[:]
# sort lst.copy
lst_copy.sort()
new_list = []
# as long as the lst_copy is not empty:
while lst_copy:
# get/pop the element from the beginning and at the end of the new_list
largest_num = lst_copy.pop()
smallest_num = lst_copy.pop(0)
# perform the division of two these elements
result = largest_num / smallest_num
# round down the result to the nearest integer
# append the result of the division operation to the new list
new_list.append(round(result))
# return the new_list
return new_list
source to share
You can achieve the same result with the following concise solution using list comprehension
:
my_list = [5, 9, 2, 4, 1, 3]
sorted_list = sorted(my_list) # sorted doesn't sort in place, it returns a new sorted list
new_list = [round(sorted_list[-(i+1)] / sorted_list[i]) for i in range(len(sorted_list) // 2)]
Output:
>>> new_list
[9, 2, 1]
source to share