First Element Out Of Order On A List
For the list [1,4,6,8,2,10] it should return 2 For the list [1,6,7,9,3,10] it should return 3 It should return the first number that smaller then his last, first to be in wrong or
Solution 1:
Simply keep the last checked element in the list and check if the current element in the list is smaller or not.
defout_of_order(lst):
before = 0for y in lst:
if y < before:
return y
before = y
print(out_of_order([1,4,6,8,2,10]))
print(out_of_order([1,6,7,9,3,10]))
Solution 2:
Your second version is already correct - you just need to return the value rather than printing it:
defout_of_orders(lst):
for a, b inzip(lst, lst[1:]):
if b < a:
return b
Solution 3:
See the answer of Christian Berendt for a faster solution.
The most important problem with your first code is that it should check lst[a]
instead of a
. A fix:
defout_of_order(lst):
for a inrange(0,len(lst)):
for b inrange(a+1,len(lst)):
if(lst[b]<lst[a]):
print(lst[b])
returnprint("none")
out_of_order([1,6,7,9,3,10])
Post a Comment for "First Element Out Of Order On A List"