This community-built FAQ covers the “Find Xth Number In Order” code challenge in Python. You can find that challenge here, or pick any challenge you like from our list.
Top Discussions on the Python challenge Find Xth Number In Order
There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply () below.
If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.
Join the Discussion. Help a fellow learner on their journey.
Ask or answer a question about this exercise by clicking reply () below!
You can also find further discussion and get answers to your questions over in Language Help.
Agree with a comment or answer? Like () to up-vote the contribution!
If the input x is greater than the length of the list, or nums is empty, return 0 .
When you click the Test Code button, your code is run with 10 test cases. Evidently some of those cases include a value for x that is out of range (greater than the length of the list).
I coded a sorting algorithm instead of using .sort()
algorithm:
Copy the list, and Create a empty list that will hold the sorted values.
For the copy, find the minimum, remove it, and append it to the list for the sorted values; repeat.
my code
def sorted_copy(nums): # O(n^2), not in-place sorting
copy = nums.copy()
sorted = []
length = len(copy)
for n in range(length): # iterates n times
m = min(copy) #iterates between 0 and n times
copy.remove(m) #iterates between 0 and n times
sorted.append(m)
return sorted
def getX(x, nums):
sorted_nums = sorted(nums)
length = len(sorted_nums)
if (x > 0 and x <= length):
return sorted_nums[x - 1]
elif (x >= -length and x < 0):
return sorted_nums[x]
else:
return 0
print(getX(2, [6, 3, -1, 5]))
I know there’s more efficient algorithms out there.
Has anyone coded a bubble sort or another sorting algorithm for this challenge?