loop for, and arrays in python - python

VALOR_VETOR = 6
nota1 = []
nota2 = []
nota3 = []
mediaAluno = []
soma1 = 0
soma2 = 0
soma3 = 0
somaMedia = 0
mediaTurma = 0
print("Digite as notas dos alunos\n\n")
for i in range (VALOR_VETOR):
print(f"Aluno {i}")
valor = float(input(f"Nota 1: "))
nota1.append(valor)
valor = float(input(f"Nota 2: "))
nota2.append(valor)
valor = float(input(f"Nota 3: "))
nota3.append(valor)
valor = (nota1 + nota2 + nota3)/3
mediaAluno.append(valor)
print (f"Nota final = {mediaAluno[i]:.1f}")
for i in range (VALOR_VETOR):
soma1 = soma1 + nota1
soma2 = soma2 + nota2
soma3 = soma3 + nota3
somaMedia = somaMedia + mediaAluno
mediaProva1 = soma1/VALOR_VETOR
print(f"A media da primeira prova é = {mediaProva1:.1f}")
mediaProva2 = soma2/VALOR_VETOR
print(f"A media da segunda prova é = {mediaProva2:.1f}")
mediaProva3 = soma3/VALOR_VETOR
print(f"A media da primeira prova é = {mediaProva1:.1f}")
mediaTurma = somaMedia/VALOR_VETOR
I am a python learner
try, searched, but could not do.
please help me.
line 23, in
valor = (nota1 + nota2 + nota3)/3
TypeError: unsupported operand type(s) for /: 'list' and 'int'

When you use the '+' operator with lists it will return a list with all the 3
lists concatenated
for example:
l1 = [1,2]
l2 = [5,7]
l = l1 + l2 # [1,2,5,4]
I think you expect to get l =[6,9]
also the operator '/' is not defined for a list
so l/3 will return an error
if you want to to sum individual elements in a list you can use below code
i used for loop for clarity but you can use list comprehension or lambda or ...
l =[]
for i in range(len(l1)):
l.append(l1[i] + l2[i])
""" to make the division we can use the same for loop or make another
loop"""
for x in range(len(l)):
l[x] = l[x]/3

valor = (nota1 + nota2 + nota3)/3 //error
try this line of code as:
valor=(sum(nota1)+sum(nota2)+sum(nota3))/3 //it should work

Related

Cant figure out this error -> IndexError: list index out of range

So i have been working on this code for a while and i cant fin a solution to this problem and i was wondering if anyone in here could help me solve this? The problem is supposed to be in the method "hent_celle" where it takes in a coordinate from a grid and returns the object that is in that position.
The error is:
Traceback (most recent call last):
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 105, in <module>
print(testobjekt._sett_naboer(2,1))
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 64, in
_sett_naboer nabo_u_kol = self.hent_celle(rad+1,kol)
File "/Users/cc/Documents/Python/Oblig8/rutenettto.py", line 43, in hent_celle
return self._rutenett[rad][kol] IndexError: list index out of range
And the code is:
from random import randint
from celle import Celle
class Rutenett:
def init(self,rader,kolonner):
self._ant_rader = int(rader)
self._ant_kolonner = int(kolonner) self._rutenett = []
def _lag_tom_rad(self):
liste = []
for x in range(self._ant_kolonner):
liste.append(None)
return liste
def _lag_tomt_rutenett(self):
liste2 = []
for x in range(self._ant_rader):
liste_ = self._lag_tom_rad()
liste2.append(liste_)
self._rutenett = liste2
def lag_celle(self,rad,kol):
celle = Celle()
tilfeldig_tall = randint(0,100)
if tilfeldig_tall <= 33:
celle.sett_levende()
return celle
else:
return celle
def fyll_med_tilfeldige_celler(self):
for x in self._rutenett:
for y in x:
rad = int(self._rutenett.index(x))
kol = int(x.index(y))
self._rutenett[rad][kol] = self.lag_celle(rad,kol)
def hent_celle(self,rad,kol):
if rad > self._ant_rader or kol > self._ant_kolonner or rad < 0 or kol < 0:
return None
else:
return self._rutenett[rad][kol]
def tegn_rutenett(self):
for x in self._rutenett:
for y in x:
print(y.hent_status_tegn(), end="")
def hent_alle_celler(self):
liste = []
for x in self._rutenett:
for y in x:
liste.append(y)
return liste
def _sett_naboer(self,rad,kol):
cellen = self.hent_celle(rad,kol)
# lik linje
nabo_v_rad = self.hent_celle(rad,kol-1)
nabo_h_rad = self.hent_celle(rad,kol+1)
# under
nabo_u_kol = self.hent_celle(rad+1,kol)
nabo_u_kol_h = self.hent_celle(rad+1,kol+1)
nabo_u_kol_v = self.hent_celle(rad+1,kol-1)
# over
nabo_o_kol = self.hent_celle(rad-1,kol)
nabo_o_kol_h = self.hent_celle(rad-1,kol+1)
nabo_o_kol_v = self.hent_celle(rad-1,kol-1)
liste = [nabo_v_rad,nabo_h_rad,nabo_u_kol_h,nabo_u_kol_v,nabo_o_kol,nabo_o_kol_h,nabo_o_kol_v]
#print(liste)
#print(nabo_o_kol_h)
for x in liste:
if x == None:
pass
else:
cellen._naboer.append(x)
return cellen._naboer
def antall_levende(self):
teller = 0
for x in self._rutenett:
for y in x:
if y._status == "doed":
pass
else:
teller +=1
return teller
testobjekt = Rutenett(3,3)
testobjekt._lag_tomt_rutenett()
testobjekt.fyll_med_tilfeldige_celler()
print(testobjekt._sett_naboer(2,1))
I just cant figure out why the list index is out of range
Pyhton list indexes start at 0, which means a list with 10 elements will use indices 0-9. Assuming self._ant_rader and self._ant_kolonner are the number of rows and columns, then rad and kol would need to be less than those values and cannot be the same value, or you get an index out of bounds error.
Fixed version of the method:
def hent_celle(self,rad,kol):
if rad >= self._ant_rader or kol >= self._ant_kolonner or rad < 0 or kol < 0:
return None
else:
return self._rutenett[rad][kol]
As you can see, the > has been replaced with >= instead. This means indices which are out of bounds will return None.

How to print the time of execution PYTHON

I have this code, but I want to print the time that a specific part of it takes.
The block of code that I want to know the time is between:
def TSP(lista2d):
import copy
origen = input("Ciudad de origen: ")
resultado = [int(origen)]
iteracion, indicador = int(origen) - 1, 0
distancia, copia = [], copy.deepcopy(lista2d)
for j in range(1, len(lista2d)):
for x in range(len(lista2d)):
lista2d[x][iteracion] = 999
distancia.append(min(lista2d[iteracion]))
for i in range(len(lista2d)):
if min(lista2d[iteracion]) == lista2d[iteracion][i]:
indicador = i
lista2d[indicador][iteracion] = 999
resultado.append(indicador + 1)
iteracion = indicador
resultado.append(int(origen))
a = copia[resultado[-2] - 1][int(origen) - 1]
distancia.append(a)
print("El camino mas corto: " + str(resultado) + "\nCosto total: " + str(sum(distancia)))
TSP([[999,100,150,140,130,120,78,150,90,200,180,190,160,135,144,300,60,77,87,90],
[100,999,200,180,190,160,135,144,90,150,140,130,120,78,300,160,88,99,87,95],
[150,200,999,167,156,169,123,134,156,177,155,188,176,143,192,146,170,152,176,122],
[140,180,167,999,190,198,213,321,252,123,234,111,112,114,167,189,203,205,234,300],
[130,190,156,190,999,333,300,178,167,143,200,111,156,267,299,152,100,90,97,99],
[120,160,169,198,333,999,480,389,412,500,253,222,333,378,287,273,266,255,199,201],
[78,135,123,213,300,480,999,140,150,143,177,194,166,200,181,154,177,133,122,109],
[150,144,134,321,178,389,140,999,149,129,129,136,156,177,141,186,175,153,133,122],
[90,90,156,252,167,412,150,149,999,89,82,83,60,124,59,78,89,99,100,123],
[200,150,177,123,143,500,143,129,89,999,99,200,254,233,211,197,183,154,167,169],
[180,140,155,234,200,253,177,129,82,99,999,77,88,89,289,222,311,471,122,109],
[190,130,188,111,111,222,194,136,83,200,77,999,91,90,93,106,132,100,98,35],
[160,120,176,112,156,333,166,156,60,254,88,91,999,102,103,107,111,113,200,101],
[135,78,143,114,267,378,200,177,124,233,89,90,102,999,77,79,201,166,173,102],
[144,300,192,167,299,287,181,141,59,211,289,93,103,77,999,55,103,105,101,201],
[300,160,146,189,152,273,154,186,78,197,222,106,107,79,55,999,76,78,84,92],
[60,88,170,203,100,266,177,175,89,183,311,132,111,201,103,76,999,93,102,29],
[77,99,152,205,90,255,133,153,99,154,471,100,113,166,105,78,93,999,88,65],
[87,87,176,234,97,199,122,133,100,167,122,98,200,173,101,84,102,88,999,333],
[90,95,122,300,99,201,109,122,123,169,109,35,101,102,201,92,29,65,333,999]])
You can use 'time.time()' for example
Start_time = time.time()
End_time = time.time()
Diff_time = End_time()-Start_time()

TypeError: '>' not supported between instances of 'int' and 'list'

Im having problem with this code right here, how can i change the list to an int so that it can be processed. I tried multiple variation that can turn the list into integer but nothing is working. Thanks
items = []
if option == 'y':
length = 50
items = [randrange(-100, 101 + 1) for i in range(length)]
else:
print('wrong, bye')
exit()
subset2 = 2
print('\nset: {' + ', '.join(map(str, items)) + '}')
items = list(map(int, items))
overallHighestSum = 0
while subset2 != length:
sets = []
currentHighestSum = 0
for i in range(length):
if length > i + subset2 - 1:
terms = []
termSum = 0
terms = list(map(int, terms))
for j in range(length):
currentItem = items[j + 1]
terms.append(currentItem)
sets.append(terms)
if sum(terms) > currentHighestSum:
currentHighestSum = sum(terms)
if sum(terms) > overallHighestSum:
overallHighestSum = sum(terms)
overallHighestSum = terms
You are changing the contents of overallHighestSum in
if sum(terms) > overallHighestSum:
overallHighestSum = sum(terms)
overallHighestSum = terms
remove overallHighestSum = terms and make it as follows:
if sum(terms) > overallHighestSum:
overallHighestSum = sum(terms)

While loop without expected behavior

I am starting in Python. In the current code, A1 is "returned" infinitely, as if there was no sum of the variable célula. What can I do to get a "return" from A1 and A2?
import xlwings as xw
wb = xw.Book(r'C:\Users\Guilh\bin\teste\Contabilização Automática\myproject\myproject.xlsx')
sht = wb.sheets[0]
def buscar():
linha = '1'
célula = 'A' + linha
valor_célula = sht.range(célula).value
while valor_célula != None:
print('A1')
linha = int(linha) + 1
célula = 'A' + str(linha)
else:
print('A2')
You have neglected to update valor_célula and thus are stuck in the while loop.
I believe you want to update your code to be:
def buscar():
linha = '1'
célula = 'A' + linha
valor_célula = sht.range(célula).value
while valor_célula != None:
print('A1')
linha = int(linha) + 1
célula = 'A' + str(linha)
valor_célula = sht.range(célula).value # Update Value
else:
print('A2')

How invert the result used the method sort

I need a feedback, I don't know how to invert the result. I mean for example if I have a 289 that the result is a 982.
def numeros4s():
numero_n = int(input("ingresar un numero porfavor: "))
listax = []
listax.append(numero_n **2) #recordar siempre poner formulas dentro del parentesis
print "la raiz cuadrada de: ",numero_n," es: ",listax
numeros4s()
number = 123
int("".join(reversed(str(number))))
# 321
>>> num = 289
>>> reversed_num = int(str(num)[::-1])
>>> reversed_num
982
If you just want to reverse a number, that would be this:
n = 289
n_str = str(n)
print(''.join(reversed(n_str)))
Another way
def reverse(num):
result = 0
while num > 0:
result = result * 10 + num % 10
num /= 10
return result
print(reverse(18539)) # --> 93581

Categories

Resources