Python Challenge - Find Xth Number In Order

def getX(x, nums): if not nums or len(nums) < x: return 0 nums.sort() return nums[x-1] print(getX(2, [6, 3, -1, 5]))
def getX(x, nums): if len(nums) == 0: return 0 if x > len(nums): return 0 nums.sort() return nums[x-1] print(getX(2, [6, 3, -1, 5])) print(getX(2, [5, 10, -3, -3, 7, 9])) print(getX(4, [5, 10, -3 , -3, 7, 9]))

def getX(x, nums):

write your code here

if x > len(nums) or len(nums) == 0:
return 0
return sorted(nums)[x-1]

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

def getX(x, nums): # write your code here nums.sort() try: return nums[x-1] except: return 0 print(getX(4, [6, 3, -1, 5]))

tried to do 1 line

def getX(x, nums):
  return sorted(nums)[x - 1] if x in range(1, len(nums) + 1) else 0

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

Almost every solution here uses sort which is average O(nlogn).

I don’t see anyone posting the better solution (and the one the problem hints at) that is O(n) by keeping track of the x smallest values and doing one pass of the nums. For example:

def getX(x, nums): # Special cases (min and max are O(N)) if not nums or x > len(nums): return 0 elif x == len(nums): return max(nums) elif x == 1: return min(nums) # Scan nums maintaining smallest 'x' of them # Always note the 'largest of the smallest' and replace it when needed # A max-heap would be even better smallest = nums[0:x] largest_smallest = max(smallest) for i in nums[x:]: if i < largest_smallest: smallest[smallest.index(largest_smallest)] = i largest_smallest = max(smallest) return largest_smallest print(getX(2, [6, 3, -1, 5]))

As it says in the comment there are better ways of managing the “smallest” items, a max heap being probably the best. Note you can’t use a set in case of non-unique numbers. Could use a dict of num->count though.

1 Like
def getX(x, nums): # write your code here if x > 0: nums.sort() if len(nums) == 0: return 0 elif len(nums) < x: return 0 elif len(nums) >= x: index_range = range(x) index_list = [] for i in index_range: index_list.append(i) return nums[index_list[-1]] else: return 0 print(getX(1, [6, 3, -1, 5]))

Using a min-heap is an optimized way to be close to O(n). After heapfying the array, we should extract the top x items to find the xth number

from heapq import heapify, heappop
def getX(x, nums):
if not nums or x > len(nums):
return 0
heapify(nums)
for i in range(x):
xth = heappop(nums)
return xth

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

def getX(x, nums):

nums.sort()
print(nums)

if x > len(nums) or len(nums) == 0:
return 0
else:

m = nums[x-1]
return m

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

def getX(x, nums): # write your code here if x > len(nums) or len(nums) == 0: return 0 else: sorted_nums = nums for i in range(len(sorted_nums)): for j in range(i+1, len(sorted_nums)): if sorted_nums[j] < sorted_nums[i]: sorted_nums[j], sorted_nums[i] = sorted_nums[i], sorted_nums[j] return sorted_nums[x - 1]; print(getX(2, [6, 3, -1, 5])) print(getX(3, [2,5,-7,9,8,10,-10]))

def getX(x, nums):
nums = sorted(nums,)
try:
return nums[x-1]
except IndexError:
return 0

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

This was my solution
how do you post it so that you can see and run the code???

def getX(x, nums):
  nums.sort()
  if x > len(nums) or nums == [] or x == 0 or x < -len(nums) or type(x)==float:
    return 0
  else:
    if x > 0:
      return nums[x-1]
    else:
      return nums[x]
  # write your code here
print(getX(-2.4, [6, 3, -1, 5]))

Paste in your code. Select it all at once and click the </> button in the tool tray of the post editor. That will display it in code sample format.

As for running it, that can be done, but I rather doubt anybody will actually run it so it is just a drain on the page performance of the topic.

Thank you that, looks much better

1 Like

Hi all,

I just completed this challenge with the following code. I think it’s a good solution, but I’m open to any recommendations on making this code more efficient. Thanks!!

def getX(x, nums):
  nums_sorted = sorted(nums)
  print(nums_sorted)
  if x <= 0:
    return 0
  elif x <= len(nums_sorted):
    return nums_sorted[x-1]
  elif nums_sorted == None:
    return 0
  else:
    return 0
  

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

Hi there, generally a good code. Some minor suggestions though:

  1. In the challenge description it is said that function should return 0 if a list of numbers is empty. I don’t think an empty list is equal to None (line 8 in your code), the line shall look like

elif nums_sorted == [ ]

It is not a big deal as you have a “safe net” of else statement which will return 0 for an empty list, but it means that lines 8 and 9 can be omitted alltogether. Please others correct me if I am wrong.

  1. In the case of negative x, that is probably a way of interpretation, but i thought of it as an opposite action to positive x: if positive x will return Xth smalles, than negative x will return Xth largest number

  2. As an additional challenge, you can add function behaviour if x was by mistake not an integer or nums not a list

1 Like

Thank you for the input and the recommended challenge!

I updated my code, but for some reason, the logic doesn’t flow the way it should:

def getX(x, nums):
    nums_sorted = sorted(nums)
    print(nums_sorted)
    if x == type(str):
        print("Input not an integer")
    elif x <= 0:
        return 0
    elif x <= len(nums_sorted):
        return nums_sorted[x-1]
    else:
        return 0

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

def getX(x, nums):
sorted_list = sorted(nums)
if (abs(x) > len(sorted_list)) or (bool(nums) is False):
return 0
if abs(x) <= len(sorted_list):
return sorted_list[x - 1]

print(getX(0, ))