Python计算表的所有可能组合

时间:2013-11-26 10:16:08

标签: python matrix combinations permutation

我的表格如下所示:

   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方法可以为这个问题找到合适的逻辑? 我是否必须将标题作为键和列读取数据作为列表的值?

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

1 个答案:

答案 0 :(得分:16)

假设我理解你所追求的是什么,那么:

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

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