你在一家餐馆工作,他们要你制作冰糕菜单。
提供一个脚本打印每一个可能的冰糕二重奏从一个给定的口味列表。
不要打印两次相同味道的食谱(没有“巧克力巧克力”),也不要打印两次相同的食谱(如果你打印“香草巧克力”,不要打印“巧克力香草”,反之亦然)。
口味如下:
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]>我的代码在这里:
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in FLAVORS:
if len(FLAVORS) >= 2:
for g in FLAVORS:
if g==i:
continue
else:
print(f"{i}, {g}")
FLAVORS.remove(g)我得到的结果:
Banana, Chocolate
Banana, Lemon
Banana, Pistachio
Banana, Raspberry
Banana, Strawberry
Banana, Vanilla
Chocolate, Banana
Chocolate, Lemon
Chocolate, Pistachio
Chocolate, Raspberry
Chocolate, Strawberry
Lemon, Banana
Lemon, Chocolate
Lemon, Pistachio
Lemon, Raspberry
Pistachio, Banana
Pistachio, Chocolate
Pistachio, Lemon的问题是:为什么不提出Pistachio,Raspberry (或者Raspberry,Pistachio)?
发布于 2020-11-10 11:14:01
您可以执行以下操作:
import itertools
for f in itertools.permutations(FLAVORS, 2):
if f[0] <= f[-1]:
print(f)它将输出:
('Banana', 'Chocolate')
('Banana', 'Lemon')
('Banana', 'Pistachio')
('Banana', 'Raspberry')
('Banana', 'Strawberry')
('Banana', 'Vanilla')
('Chocolate', 'Lemon')
('Chocolate', 'Pistachio')
('Chocolate', 'Raspberry')
('Chocolate', 'Strawberry')
('Chocolate', 'Vanilla')
('Lemon', 'Pistachio')
('Lemon', 'Raspberry')
('Lemon', 'Strawberry')
('Lemon', 'Vanilla')
('Pistachio', 'Raspberry')
('Pistachio', 'Strawberry')
('Pistachio', 'Vanilla')
('Raspberry', 'Strawberry')
('Raspberry', 'Vanilla')
('Strawberry', 'Vanilla')条件
f[0] <= f[-1]工作,因为逆转置换总是翻转第一个元素和最后一个元素之间的关系!
发布于 2021-03-08 22:13:32
看看结果,我发现了一个模式,组合本身和所有东西,除了它自己和它之前的口味。我认为这段代码可能是最简单的。
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in FLAVORS:
for j in range(FLAVORS.index(i)+1,len(FLAVORS)):
print(i + ", " + FLAVORS[j])发布于 2020-11-10 11:03:02
问题是,您正在删除循环中的元素,同时在相同的列表上进行滴答。
为了说明为什么会出现问题,让我们检查一下下面的代码:
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
for i in FLAVORS:
print(i)
FLAVORS.remove(i) 您可能希望打印列表中的所有口味,但是却得到:
Banana
Lemon
Raspberry
Vanilla试试这个:
FLAVORS = [
"Banana",
"Chocolate",
"Lemon",
"Pistachio",
"Raspberry",
"Strawberry",
"Vanilla",
]
already_tried = []
for i in FLAVORS:
if len(FLAVORS) >= 1:
for g in FLAVORS:
if g==i or g in already_tried:
continue
else:
print(f"{i}, {g}")
already_tried.append(i)https://stackoverflow.com/questions/64767394
复制相似问题