I am working on the following: Write a function that returns nth lowest number of a list (or iterable in general). Return the lowest if second argument not specified Note that if a list contains duplicates, they should be handled before determining nth lowest
I got the following to work fine:
numbers = [8,9, 1,300,5, 54, 54]
def nth_lowest(b, n='N/A'):
nums = set(b)
if n == 'N/A':
return min(b)
else:
nums = sorted(nums)
return nums[n-1]
print(nth_lowest(numbers))
print(nth_lowest('ananasgnasgzynrmas', 6))
print(nth_lowest(numbers, 4))
But I wanted to try to write it without using those built-in SET or MIN functions. Here is what I have:
numbers = [8,9, 1,300,5, 54, 54]
def nth_lowest(b, n='N/A'):
nums = []
new_list = []
for i in b: # instead of using set()
if i not in nums:
nums.append(i)
nums = sorted(nums)
if n == 'N/A':
while b: # instead of using min()
minimum = b[0]
for x in b:
if x < minimum:
minimum = x
new_list.append(minimum)
b.remove(minimum)
return new_list
else:
return nums[n-1]
print(nth_lowest(numbers))
print(nth_lowest('ananasgnasgzynrmas', 6))
print(nth_lowest(numbers, 4))
but it is error'ing out on the following:
return nums[n-1]
IndexError: list index out of range
Any ideas?
min(or equivalent) when the second argument isn't passed. Just use1as the defaultnvalue, and the rest of the code should just work.nisn't supposed to be a number in the list, it's the ordinal of the minimum you're supposed to get, isn't it? You might want a sanity check, as there's no sense in trying to find the-2'th smallest number, nor the 3000th number in a list with only 10 values. But you probably want those checks anyway for the case you're solving by sorting and indexing. No need for the default to be a special case.