Python Challenge - Find Xth Number In Order

def getX(x, nums): # write your code here if (nums!=[]) and (type(x)==int) and (x <= len(nums)) and (x>0): return sorted(nums)[x-1] else: return 0 print(getX(2, [6, 3, 5]))

Any idea how to test whether each item in nums is float or int?

ummm, i don’t remember the exact prompt, but it seems everybody is sorting the list in their answers, so my guess is that it asked for the nth largest number in a sequence.

At a bit of a disadvantage without looking at the actual exercise. Might you furnish a link to same with your next post, please?

def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1

def quickSelect(arr, low, high, k):
if low <= high:
pi = partition(arr, low, high)
if pi == k:
return arr[pi]
elif k < pi:
return quickSelect(arr, low, pi - 1, k)
else:
return quickSelect(arr, pi + 1, high, k)
return 0

def getX(x, nums):
if x > len(nums) or len(nums) == 0:
return 0
# Adjust x to be zero-indexed
return quickSelect(nums, 0, len(nums) - 1, x - 1)

Test the function with the provided examples

print(getX(2, [5, 10, -3, -3, 7, 9])) # Output: -3
print(getX(4, [5, 10, -3, -3, 7, 9])) # Output: 7

def getX(x, nums): nums = sorted(nums) if int(x) > len(nums) or len(nums) == 0: return 0 else: return nums[x - 1]

Took longer than expected but here’s my solution. Any feedback is much appreciated :slight_smile:

def getX(x, nums): nums.sort() if x > len(nums) or not nums: return 0 else: return nums[x-1] print(getX(2, [6, 3, -1, 5]))

def getX(x, nums):

write your code here

nums.sort()
t = x - 1
try:
return nums[t]
except:
return 0

print(getX(2, [5, 10, -3 , -3, 7, 9]))

Given that the list of numbers could be very large, I guess it makes sense to only perform the sort after the conditional; I’m unsure if there is a reason to use sorted() over sort() or vice versa, so if anyone knows please comment :slight_smile: :

def getX(x, nums): if (x > len(nums) or nums == []): return 0 else: sorted_numbers = sorted(nums) return sorted_numbers[x-1] print(getX(2, [6, 3, -1, 5]))

If given a list of random values, and we all looking for the nth value in the list, would we be correct in sorting the list, first, or at all? Seems it would jumble up the positions of the values.

The above example only works because the 3 remains in that position after sorting. If we wanted the fourth value, instead of the second we would get the 6 and not the 5 as expected.

Bottom line, this exercise should not require sorting, only validation of x and nums. Keep in mind the zero-indexing so the second number is at index 1, which is noted in your return value, however incorrectly as I recall.

For the following example we will assume that nums in indeed a list or unknown length, and validate only that it is not empty.

def get (x, nums):
    n = len(nums)
    if n and x <= n:
        return nums[x-1]
    return 0

Above we know that len() only returns 0 or some positive integer. When it is zero, if n will be falsy, else we can check x against the length to see that the position does indeed exist.

Just to be sure, please post a link to this exercise so we can test our hypothesis, and confirm the instructions.


As for the unrelated question about which to use, .sort() or sorted(), it depends what we want to take away.

list.sort()

is ‘in-place’ so returns nothing that can be assigned. It sorts the list, proper, in-situ.

>>> nums.sort()
>>> print (nums)
[-1, 3, 5, 6]
>>>
sorted()

makes a copy of the list and then sorts it, yielding an assignable return value, the sorted list.

>>> sorted_nums = sorted(nums)
>>> print (sorted_nums)
[-1, 3, 5, 6]
>>> 

Hi mtf,

Thanks for your reply :slight_smile:

I disagree about the the need for ordering given that the first paragraph of the challenge says:

" Write a function, getX, that given an integer x and a list nums returns the Xth number if the list was in sorted order. In other words, the Xth smallest number."

It seems that we ARE being asked to sort the list.

With regard to the sort() vs sorted() issue, yes agreed, and I’m guessing that you, like I, aren’t seeing any particular reason why we should choose one over the other for this particular challenge?

Edit: Link to original challenge as requested https://www.codecademy.com/code-challenges/code-challenge-find-xth-number-in-order-python

1 Like

Okay, I see what the challenge is, now. It’s not just to “find the xth number if the list was in sorted order”, it is to do it as close to O(n) as possible. This is a head scratcher, given that sorting is O(n log n).

return sorted(nums)[x-1]

is the first thing to come to mind. Perhaps my mind is having difficulty wrapping around the linear complexity.

Notice above we can return the output from sorted(). We could not do that with .sort(). It also has no side effect on the original list, which is left in tact and unsorted.

Ah ok so that would seem to make sorted() used the way you suggest the more elegant solution - thanks I should’ve experimented to see if I could use it directly without storing in a variable first!

Really appreciate your feedback @mtf, thankyou :slight_smile:

1 Like

My code, quite happy to have been able to come up with the solution without peeking, I am actually starting to code on my own.

def getX(x, nums):
  #resolving particular cases for empty list or xth number exceeding length of list
  if len(nums) == 0 or x > len(nums):
    return 0
  else:
    nums.sort()
    return(nums[x - 1])#Takes into account that Python starts counting from 0

# test cases
print(getX(2, []))
print(getX(2, [5, 10, -3, -3, 7, 9]))
print(getX(10, []))
def getX(x, nums): # write your code here nums = sorted(nums) if x>len(nums) or nums==[]: return 0 else: return nums[x-1] print(getX(2, [6, 3, -1, 5]))

I noticed an edge case that wasn’t accounted for in the original problem or the code tester.

The code submitted below passed the code tester without issue

def getX(x, nums):
  # write your code here
  
  #take care of edge cases first
  if x > len(nums):return 0
  if nums == []:return 0
  #Sort number list in asc order
  nums.sort()
  return nums[x-1] #return xth number, index is x-1 

However, i noticed after the fact that if i call the function with x = 0 my function returns the last number in the sorted list.

For example

print(getX(0, [5, 10, -3 , -3, 7, 9]))

would print 10 in the console.

I noticed that most of the code submitted in this forum would yield a similar output. Although my code does pass the code tester it seems pretty clear this violates the spirit of the challenge.

simple fix to the code obviously would be

if x == 0: return 0
def getX(x, nums): # write your code here if len(nums) < 1 or x > len(nums): # Check if the list is more than 1 and if X is more than the number of items in the list, if so then it returns 0 return 0 return sorted(nums)[x-1] # Sorts the list and also grabs the X position one, I had added -1 because it uses index and in this case we want the element number which starts at 1 print(getX(4, [5, 10, -3 , -3, 7, 9]))

If the length of the array is 0 or x is greater than the length of the array return 0.
With that out of the way, sort the array in ascending order.
Remember to deduct 1 from x

def getX(x, nums):
  # write your code here
  if x>len(nums) or len(nums) == 0:
    return 0
  nums_sorted = sorted(nums)
  return nums_sorted[x-1]

print(getX(2, [6, 3, -1, 5]))

def getX(x, nums):
# Check if the list is empty or x is out of range
if not nums or x > len(nums):
return 0

# Sort the list
sorted_nums = sorted(nums)

# Return the Xth smallest number (1-based index)
return sorted_nums[x - 1]

Test cases

print(getX(2, [6, 3, -1, 5])) # Output: 3
print(getX(2, [5, 10, -3, -3, 7, 9])) # Output: -3
print(getX(4, [5, 10, -3, -3, 7, 9])) # Output: 7
print(getX(7, [5, 10, -3, -3, 7, 9])) # Output: 0 (x is greater than the length)
print(getX(1, )) # Output: 0 (empty list)

def getX(x, nums):
nums1 = sorted(nums)
if x > len(nums):
return 0
elif len(nums) == 0:
return 0
elif x <= len(nums):
return nums1[x-1]

print(getX(4, [6, 3, -1, 5]))