Trying to append an array with an IF statement

Question:

firstTeamPlace = [] # This is for where the team placed, 1st, 2nd, 3rd etc
firstTeamTotal = []# This is where the scores are added to make a final score

m = {
    "1": 4,
    "2": 3,
    "3": 2,
    "4": 1,
}
def firstTeamPoints():
    firstTeamTotal.append(m[firstTeamPlace])
        
def tevent1():
    print("This is the relay race event")
    print("Please enter the where each team placed next to their name (1-4)")
    eventaFirstTeam = input(tnames[0])
    firstTeamPlace.append(eventaFirstTeam)

    eventaSecondTeam = input(tnames[1])
    secondTeamPlace.append(eventaSecondTeam)

    eventaThirdTeam = input(tnames[2])
    thirdTeamPlace.append(eventaThirdTeam)

    eventaFourthTeam = input(tnames[3])
    fourthTeamPlace.append(eventaFourthTeam)
    print(firstTeamTotal)

The firstTeamTotal array isn’t being added to when it should be. Idk how to make the array get appended.

Do I need to make only one array

Asked By: Birds

||

Answers:

Simplify your logic:

def firstTeamPoints():
    firstTeamTotal.append(5 - int(firstTeamPlace))

If it turns out to be more complicated, you can use a map:

m = {
    "1": 4,
    "2": 3,
    "3": 2,
    "4": 1,
}
def firstTeamPoints():
    firstTeamTotal.append(m[firstTeamPlace])
Answered By: A.J. Uppal

You can have what you want to do in a faster and more flexible way:

#Some preparation. You can do it manually or with another function

tnames = ['team 1', 'team 2', 'team 3', 'team 4', 'team 5'] 
teamsPlaces = [] # This is for where the teams placed for each event, 1st, 2nd, 3rd etc
teamsTotals = [] # This is where the scores are added to make a final score for each team

#Here we prepare the final scores, with everyone starting from 0
for team in range(len(tnames)):
    teamsTotals.append(0)

def tevent1():
    print("This is the relay race event")
    print("Please enter the where each team placed next to their name (1-4)")
    eventTeamsPlaces = []
    for i in range(len(tnames)):
        teamPos = input(tnames[i])
        eventTeamsPlaces.append(teamPos) #for each event, you will have a list of places
        teamsTotals[i] = teamsTotals[i] + (len(tnames) - int(teamPos))
        
    teamsPlaces.append(eventTeamsPlaces) #and the list of places is appended to the list of places for all the events
    print(teamsTotals)
tevent1()

so that at the end, after two events, your outputs are:

teamsPlaces = [['1', '2', '3', '4', '5'], ['5', '4', '3', '2', '1']]
teamsTotals = [4, 4, 4, 4, 4]

end if you want to have the list of the places for the event number 2 you can just use teamsPlaces[1] which is ['5', '4', '3', '2', '1']

With this approach, you can use this simple function for all the events, without any limit for the number of teams and the number of events.

Answered By: FrancecoMartino
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.