座位安排-我如何只选择邻居的组合



我使用itertools.combinations列出列表的所有可能组合。。。但是我如何只选择邻居,这样用户就都在一起了

list =[1,2,3,4,5,6,7,8,9,10,11,12]
occupied = [2,6,7,11]

剩下的座位有空。。。现在我该如何安排两个人总是坐在可用的座位上。。

1 0
3 4
5 0
0 8
9 10
0 12

正确的组合是(1,3) (3,4) (3,5) (8,9) (9,10) (10,12)(因为它有两个成员…我们可以交换它们…所以有两种可能的方式(。。。目前我总共有28个……我该如何删除其余的……任何指导都将不胜感激/*刚刚添加了我的代码/将numpy导入为np导入itertools从itertools导入排列、组合、组合_with_replacement

def座椅布置(arr(:arry=arr.split(','(larr=[int(x(for x in arry]

total = (larr[0])
occ = larr[1:]  

totals = [x+1 for x in range(0,total)]
print(totals)
for val in totals:
if val in occ:
item= totals.index(val)
totals[item] = 0
print(totals)

#result=列表(筛选器(lambda x:x!=0,总数((result=[如果x!=0,则总数中x为x]打印(结果(

comb = combinations(result,2)
data = itertools.dropwhile(lambda x: x < 5, [3, 12, 7, 1, -5])
print(list(comb))
avl = []
#total there are 8 seats and two users are to be seated next to each other always ...  #moreover the seats are not all consecutive
for i,x in enumerate(totals):
if (i+1)%2 == 0: 
print('even#:',i+1,'is :',x) 
data = itertools.dropwhile()
print(data)
else:
print('odd#:',i+1,'is :',x)

我建议一种方法来验证一对的有效性,关于占用列表和位置

def is_pair_valid(pair, occupied_list):
# check occupied
x, y = min(pair), max(pair)
if x in occupied_list or y in occupied_list:
return False
# check neighbours
diff = y - x
return diff in (2, 1, -2) if x % 2 == 1 else diff in (2, -1, -2)
  • 奇数:另一个应该在距离+2, +1 or -2处(例如31,4,5(
  • 偶数:另一个应该在距离+2, -1 or -2处(例如42,3,6(

然后

values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
occupied = [2, 6, 7, 11]
for p in filter(lambda x: is_pair_valid(x, occupied), combinations(values, r=2)):
print(p)

给出正确的

(1, 3)
(3, 4)
(3, 5)
(8, 10)
(9, 10)
(10, 12)

最新更新