我正在创建一个boardgame排名系统,我有一个.CSV列表,上面列出了在boardgame之夜击败其他人的人。打败一个打败了另一个人的人算是胜利。我需要刮这个CSV文件,找到那些被胜利者打败的人打败的人,然后附加数据并排序。你知道吗
我可以打开、创建、获取数据并写入文件,但当我尝试编写各种版本的代码时,我似乎无法获得正确的输出。你知道吗
import csv
import collections
#get the contents of the input.csv file
WINLOSE = {}
with open('input.csv') as f2:
for line in f2:
winners,losers = line.strip().split(',')
WINLOSE[winners] = losers
new_items = set()
RESULTS = collections.namedtuple('RESULTS', ['winners', 'losers'])
#Write to the output file.
with open('output.csv', 'w') as f1:
writer = csv.DictWriter(winners, losers)
#pseudo code -- if any name in the winner cell appears in the
#loser cell,
#copy all of the losers associated with that cell to the people
#who beat that
#cell
if cell.losers = any-cell.winners:
append the losers associated with the winners cell
for row in new_items:
writer.writerow(row._asdict())
输入csv如下所示:
Winners,Losers
John,Amanda
Mark,Eddy
Amanda,Chad
Becky,Michael
Michael,Steve
Eddy,Fred
Michael, Stuart
Edwardo, Patricia
Michael, Buzz
Mark, Charlie
Amanda, Brandon
Brandon, Dirk
输出csv应如下所示:
Winners,Losers
John,Amanda
John,Chad
John, Brandon
John, Dirk
Mark,Eddy
Mark,Fred
Mark, Charlie
Amanda,Chad
Becky,Michael
Becky,Steve
Michael,Steve
Michael, Stuart
Michael, Buzz
Eddy,Fred
Edwardo, Patricia
Amanda, Brandon
Brandon, Dirk
例如,johnbeatamanda和amandabeatchad,因此我们需要添加johnbeatchad的条目。你知道吗
在有向无环图(DAG)中寻找所有可能的起始-终止路径是一个问题。你知道吗
发布的代码的问题是dict必须具有唯一的键;当您添加
Mark: John
然后Mark: Ted
时,第一个图形关系将被删除。它不是一个好的图形结构。你知道吗我推荐
igraph
模块。建立你的图形,每个玩家代表一个节点,每个游戏代表一条从赢家到输家的边。你知道吗现在要找到不败玩家的节点就很简单了。跟踪每个可用路径,记录每一对可能的优胜劣汰传递性。跟踪您在路径上访问过的所有节点;每个访问过的节点都将击败您以后遇到的任何节点。你知道吗
这足以让你动起来吗?你知道吗
您可以构建一个dict,将每个胜利者映射到一个失败者列表,遍历dict的键/胜利者,使用一个生成器函数递归地生成胜利者的失败者,并输出结果的胜利者/失败者对:
对于示例输入,输出文件将包含:
相关问题 更多 >
编程相关推荐