Electric
Electric

Reputation: 537

Calculation from text file

I have a text file containing:

SKT:SSG:2:1
NJW:UIA:1:0
SKT:TRP:3:2
SSG:NJW:0:2

I want to calculate the number of wins by each team corresponding to the number in the text file. Example:

SKT: 2
NJW: 2
UIA: 0
SSG: 0

Here's what i have so far:

fileName = input("Enter the file name:")
match = open(fileName)
table = []

for line in match:
    contents = line.strip().split(':')
    table.append(contents)
dictionary = {}
for line in table:
    #how do i code the index of the team and it's score?
    .
    .

just a moment to test my understanding, if i were to calculate how many times each team wins, i have to ensure python is able to read that for example, SKT had a score of 2 against SSG of score 1 in game 1,which makes SKT the winner. Therefore, count + 1

however, I'm confused on how would i place the index of the team name corresponding to it's score. Any help is appreciated. Regards.

Upvotes: 2

Views: 1246

Answers (3)

TrakJohnson
TrakJohnson

Reputation: 2087

Using collections.defaultdict simplifies the procedure:

import collections

scores = collections.defaultdict(int)
for line in table:
    teamA,teamB,scoreA,scoreB = line.split(':')
    # even if scores does not have the team key, += will create it
    scores[teamA] += int(scoreA)
    scores[teamB] += int(scoreB)

Upvotes: 1

galaxyan
galaxyan

Reputation: 6111

you can create a dict to store all the team winning score.

res = {}
for line in match:
   team1,team2,score1,score2 = line.split(':')
   if team1 not in res: res[team1] = 0
   if team2 not in res: res[team2] = 0
   if int(score1) == int(score2):
      continue 
   else:
      winner = team1 if int(score1) > int(score2) else team2
      res[winner] += 1

Upvotes: 1

eyllanesc
eyllanesc

Reputation: 243907

You could use a dictionary.

fileName = input("Enter the file name:")
match = open(fileName)

d = {}
for line in match:
    x, y, sx, sy = line.split(":")

    if not x in d:
        d[x] = 0
    if not y in d:
        d[y] = 0
    if sx > sy:
        d[x] += 1
    elif sx < sy:
        d[y] += 1


print(d)

Result:

{'SKT': 2, 'SSG': 0, 'NJW': 2, 'UIA': 0, 'TRP': 0}

Upvotes: 1

Related Questions