Given a list of lists like this:
[[2, 7], [1, 4], [0, 5, 6]]
How can I check if there is a valid ascending order in this list. For example this would be True because I can form this order:
[2,4,5]
I need an algorithm which can somehow find a valid order for an arbitrarily large list with lists of any size. No integer value will repeat and sublists are sorted.
edit: This is what I have currently tried but it won't scale to larger lists.
allNumbers = [[2, 7], [1, 4], [0, 5, 6]]
smallest = min(allNumbers[0])
largest = max(allNumbers[2])
for n in allNumbers[1]:
if smallest < n < largest:
return True
You can solve it by using a greedy algorithm like this.
a = [[2, 7], [1, 4], [0, 5, 6]]
current = min(a[0])
possible = True
for l in a[1:]:
possible = False
for i in l:
if i >= current:
possible = True
current = i
break
if not possible:
break
print(possible) #returns True
For each sublist, find the smallest element that's still larger than the previous smallest. If there's no such element, then there's no ascending path.
from math import inf
def ascend(xss):
smallest = -inf
path = []
for xs in xss:
smallest = min(x for x in xs if x > smallest)
path.append(smallest)
return path
>>> ascend([[2, 7], [1, 4], [0, 5, 6]])
[2, 4, 5]
>>> ascend([[2, 7], [1, 4], [0, 5, 6], [0]])
Traceback (most recent call last):
...
ValueError: min() arg is an empty sequence
Here is my answer.
def tell_if_the_lists_are_in_order(lists):
min_first = min(lists[0]) # for empty input, return True.
prev_min = min_first
for sublist in lists[1:]:
min_num = min(sublist)
max_num = max(sublist)
if max_num <= prev_min:
return False
prev_min = min(x for x in sublist if x > prev_min)
return True
Here is my answer:
def IsAscending(list):
ascend = True
int a;
for i in list:
if i == 0:
a = list[i]
else:
if list[i] >= a:
a = list[i]
else:
ascend = False
return ascend
Here is the final solution I derived
def validList(chLocations):
ascendingOrder = []
smallest = min(chLocations[0])
maximum = max(chLocations[-1])
ascendingOrder.append(smallest)
chLocations = chLocations[1:]
for i in range(len(chLocations)-1):
for number in chLocations[i]:
if number > max(ascendingOrder):
ascendingOrder.append(number)
break
ascendingOrder.append(maximum)
if sorted(ascendingOrder) == ascendingOrder:
return True
else:
return False
>>> validList([[2, 7], [1, 4], [0, 5, 6]])
True
>>> validList([[1, 3], [7], [2]])
False
Explanation:
[[2, 7], [1, 4], [0, 5, 6]] --> [2,4,5] == True
[[1, 3], [7], [2]] --> [1,7,2] == False
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.