在有序数组中查找有序数组

时间:2019-05-26 00:04:25

标签: python

c = [-1, 0, 1, 2, 3, 4]  
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

所需的输出:

fc = [-1,0,1,2,3],[0,1,2,3,4]
fd = [2,3,4,5,6]
fa = []

我想找出在给定间隔的情况下,有序集合在较大集合中有多少次。就我而言,我选择5,因为这是我的扑克游戏。 Set不能正常工作,因为它们需要保持秩序,所以我不知道该用什么。

在我的程序中,我尝试使用for循环,但没有得到。

ns = len(c)-5
nt = range(0,ns)
if ns >= 0:
    for n in nt:
        templist = c[n:n+5]

我只需要一个比较两个列表的函数。

3 个答案:

答案 0 :(得分:1)

将小列表与main的切片进行比较。

c = [-1, 0, 1, 2, 3, 4]
d = [-1,0,2,3,4,5,6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

for sublist in [c, d, a]:
    l = len(sublist)
    i = 0
    while i + l <= len(main):
        if sublist == main[i:i+l]:
            print 'sublist %s matches' % sublist
        i = i + 1

答案 1 :(得分:0)

既不是最佳也不是最佳选择,但是它确实满足了以下要求:

c = [-1, 0, 1, 2, 3, 4]
d = [-1, 0, 2, 3, 4, 5, 6]
a = [-1, 1, 6, 8, 9, 12]
main = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]


def find_in_order(to_find, to_search, num_to_find):
    solutions = []
    for bucket in to_find:
        bucket_solutions = []
        solutions.append(bucket_solutions)
        for thing in [bucket[x:x + num_to_find] for x in range(len(bucket) - num_to_find + 1)]:
            for section in [main[y:y + num_to_find] for y in range(len(to_search) - num_to_find + 1)]:
                if thing == section:
                    bucket_solutions.append(thing)
    return solutions


fc, fd, fa = find_in_order([c, d, a], main, 5)

# fc == [[-1, 0, 1, 2, 3], [0, 1, 2, 3, 4]]
# fd == [[2, 3, 4, 5, 6]]
# fa == []

没有边界检查,因此它可能很脆弱。我也不喜欢如何增加幻数1来使内容对齐。如果您关心速度,则字符串搜索会执行诸如保持滚动校验和仅在校验和匹配时进行比较之类的操作。这留作练习。另外,我在:

sys.version
'3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34) \n[GCC 7.3.0]'

答案 2 :(得分:0)

这是我提供的功能,可能会对您有所帮助。您可以将列表作为参数传递,它将比较列表。

main_set = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
c = [-1, 0, 1, 2, 3, 4]


def compare(cmp_array):
  new_arrays = []
  temp = []
  for pos, i in enumerate(cmp_array):
        for i2 in range(pos, pos+5):
              temp.append(cmp_array[i2])
        new_arrays.append(temp)
        temp = []
        if pos >= len(cmp_array)-5:
              break
  return_arrays = [] 
  for array in new_arrays:
        for pos, i in enumerate(main_set):
              match = True
              if i == array[0]:
                    for pos2 in range(pos, pos+5):
                          if array[pos2-pos] != main_set[pos2]:
                                match = False
                                break
                    if match:
                          return_arrays.append(array)
  return return_arrays

fc = compare(c)

print(fc)