Issues with final output - python

Expected Output :
I was working on the functions to get the code for elementary cellular automaton. I got all the outputs correct but I could not get my desired output printed.
def main():
N= int(input("Enter number of steps,N:"))
C= int(input("Enter number of cells,C:"))
i_list=list(map(int,input("Enter the indices of occupied cells (space-separated):").split()))
cell= [0]*C
for i in i_list:
cell[int(i)] = 1
displayCells(cell)
for step in range(N):
newCells = updateCells(cell)
displayCells(newCells)
cells = []
cells += newCells # concatenates new state to new list
def displayCells(Cells):
for cell in Cells:
if cell == 1:
print("#", end='')
def updateCells(cells):
nc = [] # makes a new empty list
nc += cells # copy current state into new list
for a in range(1, len(nc)-1):
if nc[a-1] == 1 and nc[a] == 1 and nc[a+1] == 1:
nc[a] = 0
elif nc[a-1] == 1 and nc[a] == 1 and nc[a+1] == 0:
nc[a] = 1
elif nc[a-1] == 1 and nc[a] == 0 and nc[a+1] == 1:
nc[a] = 1
elif nc[a-1] == 1 and nc[a] == 0 and nc[a+1] == 0:
nc[a] = 0
elif nc[a-1] == 0 and nc[a] == 1 and nc[a+1] == 1:
nc[a] = 1
elif nc[a-1] == 0 and nc[a] == 1 and nc[a+1] == 0:
nc[a] = 1
elif nc[a-1] == 0 and nc[a] == 0 and nc[a+1] == 1:
nc[a] = 1
else:
nc[a] = 0
return nc
main()
I expect the output to be the loop that follows the rule of updateCells function and draw the # whenever the program sees 1.

Related

Python Function "Not Defined" in VSCODE [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 days ago.
This post was edited and submitted for review 2 days ago.
Improve this question
class Hand:
def __init__(self, hand):
self.hand = hand
def rank_to_index_converter(rank):
if rank == 2:
return 0
elif rank == 3:
return 1
elif rank == 4:
return 2
elif rank == 5:
return 3
elif rank == 6:
return 4
elif rank == 7:
return 5
elif rank == 8:
return 6
elif rank == 9:
return 7
elif rank == 10:
return 8
elif rank == 'J':
return 9
elif rank == 'Q':
return 10
elif rank == 'K':
return 11
elif rank == 'A':
return 1
else:
raise ValueError
def suit_to_index_converter(suit):
if suit == 'C':
return 0
elif suit == 'D':
return 1
elif suit == 'H':
return 2
elif suit == 'S':
return 3
else:
raise ValueError
def is_consecutive(hand):
### BEGIN YOUR SOLUTION
first = 0
string = ""
count = 0
for x in hand:
#print(x[0])
if x[0] == ("J"):
if first != 10 and (count != 0):
return False
string = x[0]
elif x[0] == ("Q"):
if string != "J" and (count != 0):
return False
string = x[0]
elif x[0] == ("K"):
if string != "Q" and (count != 0):
return False
string = x[0]
elif x[0] == ("A"):
if string != "K" and (count != 0):
return False
string = x[0]
elif x[0] != ("J" or "Q" or "K" or "A"):
if (x[0] != (first + 1)) and (count != 0):
if (hand[0][0] != "A"):
return False
first = x[0]
count = count + 1
return True
def is_suit(hand):
suit = hand[0][1]
for x in hand:
if x[1] != suit:
return False
return True
def is_flush(hand):
return is_suit(hand) and not is_consecutive(hand)
def is_four_of_a_kind(hand):
count = 0
pair_num = 0
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
for x in lst:
if x == 4:
return True
return False
def is_full_house(hand):
count = 0
pair_num = 0
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
three_pair = False
pair = False
for x in lst:
if x == 3:
three_pair = True
if x == 2:
pair = True
if three_pair and pair:
return True
return False
def is_flush(hand):
count = 0
while count < (len(hand) - 2):
if hand[count][1] != hand[count + 1][1]:
return False
count += 1
return True
def is_straight(hand):
if is_consecutive(hand) and not is_suit(hand):
return True
return False
def is_three_of_a_kind(hand):
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
three_pair = False
for x in lst:
if x == 3:
three_pair = True
if three_pair and not is_full_house(hand) and not is_suit(hand):
return True
return False
def is_two_pair(hand):
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
two_pair = False
counter = 0
switch = 0
while counter != len(lst):
if lst[counter] == 2:
switch = 1
if lst[counter] == 2 & switch == 1:
two_pair = True
if two_pair and not is_full_house(hand) and not is_suit(hand) and not is_four_of_a_kind(hand) and not is_three_of_a_kind(hand):
return True
return False
def is_pair(hand):
lst = [0 for i in range(13)]
for x in hand:
index = rank_to_index_converter(x[0])
lst[index] += 1
pair = False
for x in lst:
if x == 2:
pair = True
if pair and not is_full_house(hand) and not is_suit(hand):
return True
return False
def maximum_value(hand):
sum = 0
for x in hand:
sum += rank_to_index_converter(x[0])
return sum
The is_full_house function uses the rank_to_index_converter function. The rank_to_index_converter function is defined above the is_full_house function. Why am I receiving an error that the rank_to_index_converter function is not defined?
I am lost on where to proceed; therefore, I haven't tried anything, besides copying and pasting the rank_to_index_converter function into the is_full_house function; however, it is more convenient if the rank_to_index_converter is a separate function. That is why I want to solve this issue.

Code returns TypeError and I'm not sure why

The code below returns 'TypeError: 'int' object is not subscriptable' when move_pas is called. The thnig is, is that the code affecting this is also in move_ag, but when I call that there is no error and I cant figure out why that is. I'm running this in python3.9.2 in vscode if that matters. Thanks in advance. (sorry for bad english)
import random
char_list = []
stance_list = []
spot_list = []
status_list = []
amount_list = []
def remake_name_list():
global name_list
name_list = ["Josh", "Jeff", "Lisa", "Addie", "Jack", "John", "Zac", "Evan", "Brayden", "Seb", "Sab", "Nick", "Dom", "Rex", "James", "Robert",
"John", "Michael", "William", "David", "Richard", "Joseph", "Thomas", "Charles", "Christopher", "Daniel", "Matthew", "Anthoney", "Mark"]
remake_name_list()
def gen(amount):
for i in range(0, amount):
rand = random.choice(name_list)
char_list.append(rand)
name_list.remove(rand)
rand = random.randint(0, 8)
if rand == 8:
stance_list.append("aggressive")
elif rand != 8:
stance_list.append("passive")
rand = random.randint(0, amount*2)
spot_list.append(rand)
amount_list.append(2)
amount_list.append(2)
rand = random.randint(1, 2)
if rand == 1:
amount_list.append(2)
elif rand == 2:
pass
for i in range(0, max(spot_list)):
if spot_list.count(i) >= 3:
amount_list.clear()
gen(amount)
def move_ag(amount_list, stance_list):
if 'aggressive' in stance_list:
for i in range(0, len(char_list)):
if stance_list[i] == "aggressive":
am = spot_list.count(spot_list[i])
if am == 1:
stance_list[i] = 2
amount_list[spot_list[i]] -= 2
elif am == 2:
stance_list[i] = 1.5
amount_list[spot_list[i]] -= 1.5
def move_pas(amount_list, stance_list):
if 'passive' in stance_list:
for i in range(0, len(char_list)):
if stance_list[i] == "passive":
am = spot_list.count(spot_list[i])
if am == 1:
stance_list[i] = 2
amount_list[spot_list[i]] -= 2
elif am == 2:
if amount_list[i] == 1:
stance_list = 1
amount_list[spot_list[i]] -= 1
if amount_list[i] == 2:
stance_list = 1
amount_list[spot_list[i]] -= 1
if amount_list[i] == 0.5:
stance_list = 0.5
amount_list[spot_list[i]] -= 0.5
amount = 10
gen(amount)
move_ag(amount_list, stance_list)
move_pas(amount_list, stance_list)
print(stance_list)
print(amount_list)
The way that you have it:
def move_pas(amount_list, stance_list):
if 'passive' in stance_list:
for i in range(0, len(char_list)):
if stance_list[i] == "passive":
am = spot_list.count(spot_list[i])
if am == 1:
stance_list[i] = 2
amount_list[spot_list[i]] -= 2
elif am == 2:
if amount_list[i] == 1:
stance_list = 1 #------------------------- here
amount_list[spot_list[i]] -= 1
if amount_list[i] == 2:
stance_list = 1 #------------------------- here
amount_list[spot_list[i]] -= 1
if amount_list[i] == 0.5:
stance_list = 0.5 #----------------------- here
amount_list[spot_list[i]] -= 0.5
If any of the if statements is met the stance_list is changed to an integer (1 or 0.5). So the next time the loop goes on it will meet this statement if stance_list[i] == "passive" and will tell you that a integer cannot be subscripted (Which is to be expected).
I assume what you want to do is to change the i-th element of stance_list to that number. Like this:
def move_pas(amount_list, stance_list):
if 'passive' in stance_list:
for i in range(0, len(char_list)):
print(stance_list)
if stance_list[i] == "passive":
am = spot_list.count(spot_list[i])
if am == 1:
stance_list[i] = 2
amount_list[spot_list[i]] -= 2
elif am == 2:
if amount_list[i] == 1:
stance_list[i] = 1 #------------------------- here
amount_list[spot_list[i]] -= 1
if amount_list[i] == 2:
stance_list[i] = 1 #------------------------- here
amount_list[spot_list[i]] -= 1
if amount_list[i] == 0.5:
stance_list[i] = 0.5 #----------------------- here
amount_list[spot_list[i]] -= 0.5

function called in main() funcion isn't updating global variables' values

I defined the function 'actualizar_contadores()' and when called inside the main() function, its supossed to update the values of all the variables that were defined at the beginning of the script. First I didnt pass the actual variables as parameters to the function but that resulted in a "local variable referenced before assignment" error. Then I passed the references as parameters and that problem was gone but when I wanted to see the results they werent updated. I tried returning a tuple and assigning it to the variables in order to update their values, but it isnt working either and I get the local variable referenced before assignment error again. What can I do?
cant_motos = cant_autos = cant_camiones = 0
recaudacion_total = recaudacion_efectivo = recaudacion_telepeaje = 0
pasadas_primera_hora = pasadas_segunda_hora = pasadas_tercera_hora = pasadas_cuarta_hora = 0
cont_efectivo = cont_telepeaje = 0
patente_actual = ""
patente_nueva = ""
def actualizar_contadores(vehiculo, forma_de_pago, cant_motos,
cant_autos, cant_camiones,recaudacion_efectivo,
recaudacion_telepeaje,cont_efectivo,cont_telepeaje):
if vehiculo == "Moto":
cant_motos += 1
if forma_de_pago == 1:
recaudacion_efectivo += 20
cont_efectivo += 1
elif forma_de_pago== 2:
recaudacion_telepeaje += 20
cont_telepeaje += 1
elif vehiculo == "Auto":
cant_autos += 1
if forma_de_pago == 1:
recaudacion_efectivo += 40
cont_efectivo += 1
elif forma_de_pago == 2:
recaudacion_telepeaje += 40
cont_telepeaje += 1
elif vehiculo == "Camion":
cant_camiones += 1
if forma_de_pago == 1:
recaudacion_efectivo += 80
cont_efectivo += 1
elif forma_de_pago == 2:
recaudacion_telepeaje += 80
cont_telepeaje += 1
def main():
# menu principal
opcion = pedir_opcion(menu_principal, 4)
while opcion != 4:
while opcion != 3:
if opcion == 1:
carga = pedir_opcion(menu_ingreso_datos, 2)
print("Ingrese la siguiente operacion: ")
opcion = pedir_opcion(menu_principal, 4)
elif opcion == 2:
if carga == 1:
diferencia = 0
tiempo_inicial = time.time()
while diferencia < 32:
contar_pasadas(diferencia, pasadas_primera_hora,
pasadas_segunda_hora,
pasadas_tercera_hora,
pasadas_cuarta_hora)
tipo_vehiculo = pedir_opcion(menu_vehiculos, 3)
if tipo_vehiculo == 1:
vehiculo = "Moto"
elif tipo_vehiculo == 2:
vehiculo = "Auto"
elif tipo_vehiculo == 3:
vehiculo = "Camion"
forma_de_pago = pedir_opcion(menu_forma_de_pago, 2)
if forma_de_pago == 2:
patente = pedir_patente()
patente_nueva = definir_patente_nueva(patente)
actualizar_contadores(vehiculo, forma_de_pago, cant_motos,
cant_autos, cant_camiones, cont_efectivo,
cont_telepeaje, recaudacion_efectivo,
recaudacion_telepeaje)
tiempo_final = time.time()
diferencia = tiempo_final - tiempo_inicial
elif carga == 2:
vehiculos = "Moto", "Auto", "Camion"
formas_de_pago = "Efectivo", "Telepeaje"
diferencia = 0
tiempo_inicial = time.time()
while diferencia < 4:
contar_pasadas(diferencia, pasadas_primera_hora,
pasadas_segunda_hora,
pasadas_tercera_hora,
pasadas_cuarta_hora)
vehiculo = random.choice(vehiculos)
forma_de_pago = random.choice(formas_de_pago)
aviso_pasada = "{}. Pago con {}. Hora de pasada: {}.".format(vehiculo,
forma_de_pago,
str((round(diferencia / 60) + 1)))
if forma_de_pago == "Telepeaje":
patente = generar_patente()
aviso_pasada += "Patente: {}".format(patente)
patente_nueva = definir_patente_nueva(patente)
print(aviso_pasada)
actualizar_contadores(vehiculo, forma_de_pago, cant_motos,
cant_autos, cant_camiones, cont_efectivo,
cont_telepeaje, recaudacion_efectivo,
recaudacion_telepeaje)
tiempo_final = time.time()
diferencia = tiempo_final - tiempo_inicial
time.sleep(random.randint(0,1))
pago_mayor_uso = forma_de_pago_mas_usada(cont_telepeaje, cont_efectivo)
promedio_pasadas_por_hora = round((cant_autos + cant_motos + cant_camiones) / 4, 2)
hora_pico = definir_hora_pico(pasadas_primera_hora,
pasadas_segunda_hora,
pasadas_tercera_hora,
pasadas_cuarta_hora)
recaudacion_total = recaudacion_efectivo + recaudacion_telepeaje
pases_totales = cant_motos + cant_autos + cant_camiones
print("Ingrese la siguiente operacion: ")
opcion = pedir_opcion(menu_principal, 4)
main()```
You should not pass global vars to functions by parameters. Use global keyword.
Here is an example:
x = 10
y = 20
def myFunc():
global x
x = 3
y = 2
myFunc()
print(x, y) # output: 3 20

string indices must be integers Battle ships codewars kata

Im getting this error when inputting my code in codewars. "Traceback:in module
in damaged_or_sunk
IndexError: list index out of range". However, when I try my code in spyder3, it works just fine. there are no indicators as to where this error is in the function damaged_or_sunk though.
def damaged_or_sunk (board, attacks):
a = sum(x.count(1) for x in board)
b = sum(x.count(2) for x in board)
c = sum(x.count(3) for x in board)
a1 = 0
b1 = 0
c1 = 0
points = 0
sunk = 0
damaged = 0
not_touched = 0
for each in attacks:
rand_row = each[0]
rand_col = each[1]
if board[rand_row][rand_col] == 1:
a1 += 1
elif board[rand_row][rand_col] == 2:
b1 += 1
elif board[rand_row][rand_col] == 3:
c1 += 1
else:
pass
if a1 == a:
points += 1
sunk += 1
elif a1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if b1 == b:
points += 1
sunk += 1
elif b1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
if c1 == c:
points += 1
sunk += 1
elif c1 == 0:
points -= 1
not_touched += 1
else:
points += 0.5
damaged += 1
return '{\'sunk\': %s, \'damaged\': %s, \'not_touched\': %s, \'points\': %s}' %(sunk, damaged, not_touched, points)
The couples in attacks contains (x, y) coordinates which must be list index.
I make the assumption that they are randomly generated, make sure that:
0 <= x < len(board[0])
0 <= y < len(board)
all( len(board[0]) == len(board[row]) for row in board)

Beginner in Python, can't get this for loop to stop

Bit_128 = 0
Bit_64 = 0
Bit_32 = 0
Bit_64 = 0
Bit_32 = 0
Bit_16 = 0
Bit_8 = 0
Bit_4 = 0
Bit_2 = 0
Bit_1 = 0
Number = int(input("Enter number to be converted: "))
for power in range(7,0,-1):
if (2**power) <= Number:
place_value = 2**power
if place_value == 128:
Bit_128 = 1
elif place_value == 64:
Bit_64 = 1
elif place_value == 32:
Bit_32 = 1
elif place_value == 16:
Bit_16 = 1
elif place_value == 8:
Bit_8 = 1
elif place_value == 4:
Bit_4 = 1
elif place_value == 2:
Bit_2 = 1
elif place_value ==1:
Bit_1 = 1
Number = Number - (place_value)
if Number == 0:
print ("Binary form of"),Number,("is"),Bit_128,Bit_64,Bit_32,Bit_16,Bit_8,Bit_4,Bit_2,Bit_1
I want this loop to move to the next 'power' value when it fails the first if condition, but when I run it in an interpreter, the program keeps on running despite the first condition not being true. I only want it to move on the next conditions if the first condition turns out to be true.
How can I do this? This is my first "big" program in python, and I'm having a hard time figuring this out. Any tips would be appreciated. Btw, the program is meant to convert any number from 1-255 to binary form.
If you want a loop to go to the next value, all you need to do is use the continue keyword:
...
for power in range(7,0,-1):
if (2**power) <= Number:
place_value = 2**power
continue
...
Just using "break" statement , to break the current loop when the condition is satisfied.

Categories

Resources