ich eine Tabelle, die unten wie folgt aussieht:Python zählt alle möglichen Kombinationen für eine Tabelle
PotA PotB PotC PotD PotE
A + + + + +
B - ? + + ?
C + + + + +
D + - + - +
E + + + + +
Von hier aus habe ich alle möglichen Kombinationen von „+“ zu finden, „-“ und „?“ für alle Kombinationen von (PotA und PotB), (PotA und PotC) und so weiter (PotA, PotB und PotC) und schließlich zu (PotA, PotB, PotC, PotD und PotE). Tatsächlich läuft die "Pot" -Reihe weiter, aber hier zeige ich nur PotE zur Vereinfachung.
Um dies zu tun, zuerst lese ich die Datei wie folgt, und dann, generieren Sie alle möglichen Möglichkeiten für eine Kombination von zwei für jede Möglichkeit zählen.
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
So würde das Endergebnis aussehen:
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
.......
Gibt es eine gute Python-Methode die richtige Logik für dieses Problem zu umgehen? Muss ich die Daten mit den Headern als Schlüssel und Spalten als Wert einer Liste lesen?
Ich kann keine richtige Logik bekommen. Bitte geben Sie mir Hilfe.
Werfen Sie einen Blick auf http://docs.python.org/3.3/library/itertools.html, vor allem http://docs.python.org/3.3/library/itertools.html#itertools.permutations –
Okay, ich versuche zu lernen. – Karyo
['collections.Counter'] (http://docs.python.org/2/library/collections.html#collections.Counter) oder [' collections.defaultdict'] (http://docs.python.org/ 2/library/collections.html # collections.defaultdict) kann für das Zählen hilfreich sein. – user2357112