簡體   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