Starting in Python

Asked

Viewed 134 times

2

I made a program to see which team gets the last relegation position in the Brazilian championship.

In the end when I put to order the results, they come out logically by results. How to go back to initial string (e.g., instead of 22, appear "time18")?

I know it’s not the best way to make the code but it’s what my knowledge has provided.

time18 = input('Entre com o time 18° posição: ')
time17 = input('Entre com o time 17° posição:')
time16 = input('Entre com o time 16° posição:')
time15 = input('Entre com o time 15° posição:')
time14 = input('Entre com o time 14° posição:')
time13 = input('Entre com o time 13° posição:')
time12 = input('Entre com o time 12° posição:')

var18  = float(input("pontuação dos ultimos 5 jogos do %s: " %(time18)))
var17 = float(input("pontuação dos ultimos 5 jogos do %s: " %(time17)))
var16 = float(input("pontuação dos ultimos 5 jogos do %s: " %(time16)))
var15 = float(input("pontuação dos ultimos 5 jogos do %s: " %(time15)))
var14 = float(input("pontuação dos ultimos 5 jogos do %s: " %(time14)))
var13 = float(input("pontuação dos ultimos 5 jogos do %s: " %(time13)))
var12 = float(input("pontuação dos ultimos 5 jogos do %s: " %(time12)))

P18 = (var18 / 15)
P17 = (var17 / 15)
P16 = (var16 / 15)
P15 = (var15 / 15)
P14 = (var14 / 15)
P13 = (var13 / 15)
P12 = (var12 / 15)

J = float(input('Quantidades de jogos que faltam para a competição terminar: '))

JF = J*3

PF18 = JF*P18
PF17 = JF*P17
PF16 = JF*P16
PF15 = JF*P15
PF14 = JF*P14
PF13 = JF*P13
PF12 = JF*P12

resultados = PF18, PF17 , PF16 , PF15 ,PF14, PF13,PF12 
resultados_ordenados = sorted(resultados)

print (resultados_ordenados)

3 answers

3


As it begins, the first tip is use better names for variables. For example, var18 is a too generic name, which says nothing about the same, maybe pontos or pontuacao be better.

Since you are saving the same type of information several times (name and punctuation of several teams), it is best to use a list, instead of having multiple variables. In this case, each element in the list will have the information of a team, and for this we can use tuples.

One way to do it would be:

times = [] # lista dos times
for i in range(12, 19):
    nome_time = input(f'Entre com o time da {i}° posição: ')
    pontos = int(input(f"pontuação dos últimos 5 jogos do {nome_time}: "))
    times.append( (nome_time, pontos) ) # cada time é uma tupla contendo o nome e a pontuação

I used f-strings to format messages, which are available since Python 3.6, but if you are using a previous version, you can switch to:

nome_time = input('Entre com o time da {}° posição: '.format(i))
pontos = int(input("pontuação dos últimos 5 jogos do {}: ".format(nome_time)))

In the code above, times starts with an empty list ([]), and I make a for in the range(12, 19) (the first number is included and the second not, so it will iterate by the numbers 12, 13, 14, 15, 16, 17 and 18).

Then I read the team information: the name and the score. Note that I switched float for int. Use float makes more sense when you can have numbers with decimals, but football team scores are always whole numbers (there’s no way a team gets 10.47 points).

Then, to add the information in the list, I use the method append, and as a parameter I pass a tuple containing the name and the score. Note that there is a pair of parentheses that seems redundant, but it is not. Without these parentheses it would be:

times.append(nome_time, pontos) 

And this gives error because we are passing two parameters to append, but he only accepts one. By putting times.append( (nome_time, pontos) ), I am indicating that what I want to add is (nome_time, pontos), which is a tuple containing the name and score of a team.

That is, in the end times will be a list containing several tuples, each tuple containing the team name and its respective score.


For the missing games, I also traded float for int, because the amount of games is also an integer number:

jogos_que_faltam = int(input('Quantidades de jogos que faltam para a competição terminar: '))

And for the calculations, just go through the list of teams and create another list with the result of the accounts:

pf = [] # não entendi o que é "PF", então deixei com esse nome mesmo
for time in times:
    # time[0] é o nome do time, time[1] é a pontuação
    pf.append( (time[0],  (time[1] / 15) * jogos_que_faltam * 3 ) )

Well, I said to give better names to variables, but as I did not understand what it is PF, I don’t know what would be a better name for her.

Anyway, pf is also a list, containing the result of the account for each team. I confess that I did not understand the logic of these accounts, but anyway I did the same calculation here.

For each team, I create another tuple containing the name (time[0]) and the result of the (time[1] is the score that was read in the first for, and I use this value to do the math).

At the end of this loop, pf will be a list, in which each element is a tuple containing the team name and the result of the accounts. To sort it by the result, just do:

resultados = sorted(pf, key=lambda x: x[1])
print(resultados) # imprime [ ('time 1', valor), ('time 2', valor), etc... ]

The second parameter of function sorted is a lambda indicating what will be used as a criterion to sort the list. In this case, I used x[1] (as each element x from the list is a tuple, I take the value that is at position 1, which in this case is the result of the accounts - remembering that the team name is at index zero, and the result of the account is at index 1, so x[1]).

If you want a list containing only values (without team names), just use map:

# se quiser somente os valores
resultados_somente_valores = list(map(lambda x: x[1], resultados))
print(resultados_somente_valores)

And if you want a list with only the names of the teams:

# se quiser somente os nomes
resultados_somente_nomes = list(map(lambda x: x[0], resultados))
print(resultados_somente_nomes)

Finally, to know which team was relegated, just take the last value of the list:

# último time
ultimo_time = resultados[-1]
print(ultimo_time)
print(f'time {ultimo_time[0]} foi rebaixado, resultado: {ultimo_time[1]}')

Lists accept negative indexes, then -1 corresponds to the last element in the list (-2 is the penultimate, -3 is the antepenultimate, etc).

  • Bro, it was too top, perfect! That’s what I was researching msm... Only that gave a little problem... The list ta returning the team with more pts, I tried to change -1 p/ -7, but generates the following error: Traceback (Most recent call last): File "app2.py", line 16, in <module> ultimo_time = results[-7] Indexerror: list index out of range

  • @Dionatan Error with -7 is because the list does not have 7 elements. If you want the first of the list, use resultados[0]

0

The @hkotsubo helped me, follow the code, thank you very much msm!

times = [] # lista dos times
for i in range(12, 13):
    nome_time = input(f'Entre com o time da {i}° posição: ')
    pontos = int(input(f"pontuação dos últimos 5 jogos do {nome_time}: "))
    ptsA = int(input(f"pontuação total do {nome_time}: "))
    times.append( (nome_time, pontos, ptsA) ) # cada time é uma tupla contendo o nome e a pontuação
    
jogos_que_faltam = int(input('Quantidades de jogos que faltam para a competição terminar: '))
    
pf = [] 
for time in times:
    # time[0] é o nome do time, time[1] é a pontuação
    pf.append( (time[0],  (time[1] / 15) * jogos_que_faltam * 3 + time[2]) )
    
    resultados = sorted(pf, key=lambda x: x[1])
    
    # se quiser somente os nomes
    resultados_somente_nomes = list(map(lambda x: x[0], resultados))
    print(resultados_somente_nomes)
    
    # último time
    ultimo_time = resultados[0]
    print(f'O {ultimo_time[0]} foi rebaixado: {ultimo_time[1]}')

0

@Dionathan welcome to the community! with the type of variable you are using has no way, you need some other type of variable, I would use a list or a tuple, take a look at types of structure of data that exists in python.

PF18 = (JF*P18, "Time 18") # ou PF18 = [JF*P18, "Time 18"]
# ...

resultados = PF18, PF17 , PF16 , PF15 ,PF14, PF13,PF12 
resultados_ordenados = sorted(resultados)

print (resultados_ordenados)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.