繁体   English   中英

检查整数列表中是否存在升序(Python)

[英]Check if there is an ascending order in a list of list of integers (Python)

给出这样的列表列表:

[[2, 7], [1, 4], [0, 5, 6]]

我如何检查此列表中是否存在有效的升序。 例如,这将是 True 因为我可以形成这个订单:

[2,4,5]

我需要一种算法,它可以以某种方式为具有任意大小列表的任意大列表找到有效顺序。 没有 integer 值会重复并且子列表已排序。

编辑:这是我目前尝试过的,但它不会扩展到更大的列表。

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

您可以使用像这样的贪心算法来解决它。

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    

对于每个子列表,找到仍然大于前一个最小元素的最小元素。 如果没有这样的元素,那么就没有上升路径。

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

这是我的答案。

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

这是我的回答:

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

这是我得出的最终解决方案

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

解释:

[[2, 7], [1, 4], [0, 5, 6]] --> [2,4,5] == True
[[1, 3], [7], [2]] --> [1,7,2] == False

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM