gpt4 book ai didi

Python计算一个表的所有可能组合

转载 作者:太空狗 更新时间:2023-10-29 20:42:22 25 4
gpt4 key购买 nike

我有一个如下所示的表格:

   PotA  PotB  PotC  PotD  PotE
A + + + + +
B - ? + + ?
C + + + + +
D + - + - +
E + + + + +

从这里,我必须找到“+”、“-”和“?”的所有可能组合。对于(PotA 和 PotB)、(PotA 和 PotC)的所有组合,等等,(PotA、PotB 和 PotC),最后到(PotA、PotB、PotC、PotD 和 PotE)。实际上,“Pot”行一直在继续,但为了简化,这里我只显示直到 PotE。

为此,首先,我按如下方式读取文件,然后生成两个组合的所有可能可能性,以计算每种可能性。

def readDatafile():
filename = ("data.txt")
infile = open(filename,'r')

for line in infile.readlines():
line = line.strip()
print (line) # just to check the data, need to carry on from here.

"""Generate all possible permutations for later count"""
def doPermutations(items, n):
if n == 0:
yield ''
else:
for i in range(len(items)):
for base in doPermutations(items, n - 1):
yield str(items[i]) + str(base)

def makeAllPossibleList():
nlength = 2 # This should go outside of the function and will be same as the number of Pots
lpossibility = ['+', '-', '?']
litems = []

for i in doPermutations(lpossibility, int(nlength)):
litems.append(i)

for x in items:
print (x) # This generate all the possible items for combination of two

所以,最终的结果是这样的:

Combination: Possibility Count
PotA, PotB: ++ 3
PotA, PotB: +- 1
PotA, PotB: +? 0
PotA, PotB: -+ 0
PotA, PotB: -- 0
PotA, PotB: -? 1
PotA, PotB: ?+ 0
PotA, PotB: ?- 0
PotA, PotB: ?? 0
PotA, PotC: ...
PotA, PotC: ...
.......
PotA, PotB, PotC, PotD, PotE: +++++ 3
PotA, PotB, PotC, PotD, PotE: ++++- 0
PotA, PotB, PotC, PotD, PotE: ++++? 0
.......

是否有任何好的 python 方法来获取此问题的正确逻辑?我是否必须以标题作为键并以列作为列表的值来读取数据?

我无法得到正确的逻辑。请给我一些帮助。

最佳答案

假设我明白你在追求什么,那么像这样的东西怎么样:

import itertools
import collections

def read_table(filename):
with open(filename) as fp:
header = next(fp).split()
rows = [line.split()[1:] for line in fp if line.strip()]
columns = zip(*rows)
data = dict(zip(header, columns))
return data

table = read_table("data.txt")
pots = sorted(table)

alphabet = "+-?"
for num in range(2, len(table)+1):
for group in itertools.combinations(pots, num):
patterns = zip(*[table[p] for p in group])
counts = collections.Counter(patterns)
for poss in itertools.product(alphabet, repeat=num):
print ', '.join(group) + ':',
print ''.join(poss), counts[poss]

产生:

PotA, PotB: ++ 3
PotA, PotB: +- 1
PotA, PotB: +? 0
PotA, PotB: -+ 0
PotA, PotB: -- 0
PotA, PotB: -? 1
PotA, PotB: ?+ 0
PotA, PotB: ?- 0
PotA, PotB: ?? 0
PotA, PotC: ++ 4
[...]
PotA, PotB, PotC, PotD, PotE: +++++ 3
PotA, PotB, PotC, PotD, PotE: ++++- 0
[...]

请注意,我假设您想要的输出是错误的,因为在这一行中:

PotA, PotB, PotC, PotD, PotE: ++++++ 2

左边有五列,右边有六个 + 符号。

关于Python计算一个表的所有可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20214126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com