Function not returning boolean [duplicate] - python

This question already has answers here:
Why Python recursive function returns None [duplicate]
(1 answer)
Recursive function does not return specified value
(2 answers)
Closed 1 year ago.
I have written a maze solver program. I want the PathFinder function to return True if a path is found and then print the path or else simply return False. But my program always keeps returning False even if a path is found. It would be great if you guys can help me figure this out.
def findPaths(m,path,i,j):
r,c = len(m), len(m[0])
if i == r-1 and j == c-1:
print(path)
return True
#explore
path.append(m[i][j])
# move down
if i != r-1 and m[i+1][j] == '↓ ':
findPaths(m,path,i+2,j)
#move up
if i < 0 and m[i-1][j] == '↑ ':
findPaths(m,path,i-2,j)
#move right
if j != c-1 and m[i][j+1] == '→':
findPaths(m,path,i,j+2)
#move left
if j > 0 and m[i][j-1] == '←':
findPaths(m,path,i,j-2)
path.pop()
def maze(r,c):
m = []
for i in range(r):
row = []
for j in range(1, c + (c)):
rand_num = str(randint(1, 99))
if j % 2 != 0:
if len(rand_num) == 1:
row.append(' ' + rand_num)
else:
row.append(rand_num)
else:
row.append('?')
m.append(row)
up_left_count = r * c // 3
down_right_count = r * c * 2 // 3
for v in range(r + (r - 1)):
vertical_lst = []
for each in range(1, c + c):
if each % 2 == 0:
vertical_lst.append(' ')
else:
vertical_lst.append('? ')
if v % 2 != 0:
m.insert(v, vertical_lst)
idx_i = []
idx_j = []
idx_v_i = []
idx_v_j = []
for i in range(len(m)):
for j in range(len(m[0])):
if i % 2 == 0 and j % 2 != 0:
idx_i.append(i)
idx_j.append(j)
for v_i in range(len(m)):
for v_j in range(len(m[0])):
if v_i % 2 != 0 and v_j % 2 == 0:
idx_v_i.append(v_i)
idx_v_j.append(v_j)
idx_i = list(set(idx_i))
idx_j = list(set(idx_j))
idx_v_i = list(set(idx_v_i))
idx_v_j = list(set(idx_v_j))
for count in range(up_left_count):
i_int = randint(0, len(idx_i) - 1)
j_int = randint(0, len(idx_j) - 1)
if m[i_int][j_int] != '←':
m[idx_i[i_int]][idx_j[j_int]] = '←'
for count_v in range(up_left_count):
i_v_int = randint(0, len(idx_v_i) - 1)
j_v_int = randint(0, len(idx_v_j) - 1)
if m[i_v_int][j_v_int] != '↑':
m[idx_v_i[i_v_int]][idx_v_j[j_v_int]] = '↑ '
for i in range(len(m)):
for j in range(len(m[0])):
if i % 2 == 0 and j % 2 != 0:
if m[i][j] == '?':
m[i][j] = '→'
for i in range(len(m)):
for j in range(len(m[0])):
if i % 2 != 0 and j % 2 == 0:
if m[i][j] != '↑ ':
m[i][j] = '↓ '
m[0][0] = "S"
m[-1][-1] = "D"
for i in range(len(m)):
for j in range(len(m[0])):
print(m[i][j], end=" ")
print()
path = []
return findPaths(m, path, 0,0)
if maze(5,6):
print('True')
else:
print('False')

Related

Output matches expected output. Yet submission is not being accepted

https://www.hackerrank.com/challenges/designer-door-mat/problem
Below is my submission:
n = input().split(' ')
rows, columns = int(n[0]), int(n[1])
if(rows % 2 == 1 and columns == 3*rows):
printale = ''
j = 1
k = rows - 7
for i in range(int(rows/2), -1, -1):
printale = '---'*i + '.|.'*j + '---'*i
if(i == 0):
print('-'*int(j+k/2) + 'Welcome' + '-'*int(j+k/2))
j -= 2
else:
print(printale)
j += 2
for l in range(1, int(rows/2)+1):
printale = '---'*l + '.|.'*j + '---'*l
print(printale)
j -= 2
Is there anything wrong with the code?
Yes, there is. The "WELCOME" in the problem statement is all-caps.

Recursive function that remembers its path in global list python

I have problem with function:
tested_zeros = [(-1, -1)]
def reveal_zeros(x, y):
board_visible[y*row+x] = board[y*row+x]
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
for zero in tested_zeros:
if zero != (p, o):
tested_zeros.append((p, o)) <--broke part in my 'super' idea xD
if board[o*row+p] == " ":
return reveal_zeros(p, o)
so what is doing is checking if in array 'board[(x, y)]' is zero and its neighbors, when it is, its copying it to 'board_visible', the problem is that it bugs in (0, 0),[and calling it endlessly] so my idea was adding list tested_zeros so he remembers which points it tested but recursive function does not works that way :), and i know i can check last by(x, y) but it will loop somewhere else.
My question is how to handle this?
Here is my whole code:
import random
import numpy as np
row = 10
col = row
mine_list = list()
board = list()
board_visible = list()
num = 0
is_over = False
def get_num_of_mines():
global num
while True:
print("Podaj liczbe min: \n(z zakresu od 1 do ", (row * col) - 1, ")")
num = int(input())
if 1 <= num <= (row * col) - 1:
return num
else:
print("Błędna liczba. Podaj poprawną z zakresu")
def deploy_mines():
global mine_list
mine_x = random.randint(0, row - 1)
mine_y = random.randint(0, col - 1)
par = mine_x, mine_y
for l in mine_list:
if par == l:
return deploy_mines()
return mine_x, mine_y
def number_of_neighboring_mines(x, y):
global mine_list
num_of_neighbors = 0
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
par = p, o
for l in mine_list:
if par == l:
num_of_neighbors += 1
if num_of_neighbors == 0:
return " "
else:
return num_of_neighbors
def add_bomb(x, y):
for l in mine_list:
if (x, y) == l:
board.append("*")
return False
return True
def create_board():
global mine_list, num, board_visible
for k in range(0, num):
mine_list.append(deploy_mines())
for i in range(0, col):
for j in range(0, row):
if add_bomb(i, j):
board.append(number_of_neighboring_mines(i, j))
for i in range(0, col):
for j in range(0, row):
board_visible.append(chr(9552))
def show_board():
for l in range(0, col+1):
print('{0:2d}'.format(l), end="\t")
print()
for l in range(0, col):
print('{0:2d}'.format(l+1), end=" ")
print(np.split(np.asarray(board), row)[l])
def print_board():
for l in range(0, col+1):
print('{0:2d}'.format(l), end="\t")
print()
for l in range(0, col):
print('{0:2d}'.format(l+1), end=" ")
print(np.split(np.asarray(board_visible), row)[l])
tested_zeros = [(-1, -1)]
def reveal_zeros(x, y):
board_visible[y*row+x] = board[y*row+x]
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
for zero in tested_zeros:
if zero != (p, o) or zero is None:
print(p, o)
tested_zeros.append((p, o))
if board[o*row+p] == " ":
return reveal_zeros(p, o)
def reveal_squares(x, y):
global is_over
if board[y*row+x] == "*":
show_board()
print("Koniec gry!")
is_over = True
elif board[y*row+x] == " ":
reveal_zeros(x, y)
else:
board_visible[y*row+x] = board[y*row+x]
def sapper():
get_num_of_mines()
create_board()
while not is_over:
print_board()
reveal_squares(int(input("Podaj współrzędną x: "))-1, int(input("Podaj
współrzędną y: "))-1)
sapper()
I came up with a working function:
def reveal_zeros(x, y, steps):
board_visible[y*row+x] = board[y*row+x]
can_return = True
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o < row and p < col:
for i in steps:
if (p, o) == i:
can_return = False
if board[o*row+p] == " " and can_return:
return reveal_zeros(p, o, steps + [(p, o)])
if p == x or o == y or o < 0 or p < 0 or not can_return:
can_return = True
continue
return
Here is a sapper simulation with no winning.

Update Dictionary in python

I want to inset new key,value pair into a variable that was not previously defined
Here is what i want to do:
def drawboard(nextmove):
result = nextmove
pos = 1
print result
for i in range(7):
for j in range(7):
if (j == 0 or i % 2 == 0 or j % 2 == 0):
print '*',
if (i % 2 != 0 and j % 2 != 0):
print pos,
pos += 1
if (j == 6):
print '\n'
move = raw_input("Input you move(i.e. x,3[position, your symbol]: ")
if move == 'q':
exit()
calcres(move)
def calcres(move):
nextmove = dict([move.split(',')])
drawboard(nextmove)
drawboard({0: 0})
Inside drawboard function i want to concatenate nextmove with result, and save all the moves inside the result finally. I tried initializing result = {} but as expected that removes all items from result and re-initializes it resulting only one item inside that dictionary.
Use setdefault to initialize the result dictionary value to an empty list whenever the key is not present
def drawboard(nextmove):
result.setdefault(nextmove[0],[]).append(nextmove[1])
pos = 1
#print result
for i in range(7):
for j in range(7):
if (j == 0 or i % 2 == 0 or j % 2 == 0):
print '*',
if (i % 2 != 0 and j % 2 != 0):
print pos,
pos += 1
if (j == 6):
print '\n'
move = raw_input("Input you move(i.e. x,3[position, your symbol]: ")
if move == 'q':
exit()
calcres(move)
def calcres(move):
nextmove = move.split(',')
drawboard(nextmove)
result = {}
drawboard([0,0])

returning values in python

i have a code which looks like this
def monokode(b):
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
print 0,0,j,
elif j < 0:
j = j*-1
if j < 10:
print 1,0,j,
elif j >= 10 and j < 100:
print 1,j,
else:
print 1,j,
elif j >= 10 and j < 100:
print 0,j,
else:
print 0,j,
h = 0
if i >= len(b):
f = 1
else:
h=h+1
now, i want to make all the statements that print right now, return their value instead. but after some tries, i've realised that i don't know enough about the return statement to use it properly. how can i make the program return multiple values in a long line and then print them afterwards?
UPDATED ANSWER:
Okay as I understand the question you're wanting to make your function return multiple variables and then print them?
I agree with most of the other replies. Store the objects you want to print in a list then call
print ', '.join(list)
right before you return whatever values from the program:
like this:
def monokode(b):
printspool=[]
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
printspool.append([0,0,j])
elif j < 0:
j = j*-1
if j < 10:
printspool.append([1,0,j])
elif j >= 10 and j < 100:
printspool.append([1,j])
else:
printspool.append([1,j])
elif j >= 10 and j < 100:
printspool.append([0,j])
else:
printspool.append([0,j])
h = 0
if i >= len(b):
f = 1
else:
h=h+1
#Now here I'll print out everything contained in the printspooler list
for node in printspooler:
print ','.join(node)
#This is where you would
return Whatevervariable, Whatevervariable2, Whatevervariable3 etc...
Collect your values into a list instead, then return that list:
def yourfunction(your_arguments):
results = []
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
results.extend([0,0,j])
elif j < 0:
j = j*-1
if j < 10:
results.extend([1,0,j])
elif j >= 10 and j < 100:
results.extend([1,j])
else:
results.extend([1,j])
elif j >= 10 and j < 100:
results.extend([0,j])
else:
results.extend([0,j])
h = 0
if i >= len(b):
f = 1
else:
h=h+1
return results
You can use return and say many variable names...
return a, b, c
and what is returned is a tuple in the same order..
eg. return 1, 2, 3
will be (1, 2, 3)
and you can directly print call_fn() # if this returns those values
From what I understand, you can to store the values into a list:
def myfunc(…)
…
myList=[]
while f == 0:
if g[h]== b[i]:
i = i + 1
j = h - e
if j >= 100:
j = (e-h + len(g))*-1
elif j <= -100:
j = (e-h - len(g))*-1
if j < 10 and j >=0:
myList.extend([0,0,j])
elif j < 0:
j = j*-1
if j < 10:
myList.extend([1,0,j])
elif j >= 10 and j < 100: #this test
myList.extend([1,j])
else:
myList.extend([1,j])
elif j >= 10 and j < 100: #and this one
myList.extend([0,j])
else:
myList.extend([0,j])
h = 0
if i >= len(b):
f = 1
else:
h=h+1
return myList
and then print myFunc(…), or maybe something like
results = myFunc(…)
for r in results:
print r,
Edit: I've marked 2 tests that I think are unnecessary, since in the èlse part, you print the same thing

Python says: "IndexError: string index out of range."

I am making some practice code for a game similar to the board game, MasterMind-- and It keeps coming out with this error, and I can't figure out why it's doin it. Here's the code:
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)
Okay, the Guess is specified to be 4 integers, and the Answer is a list containing 4 numbers. They both have the same 'len' after the code, so i don't have a clue.
The point of this code is to turn the Answer into a string of 4 numbers, and see if any of those numbers match thoise of the guess, and return how many total matches there are.
See if this helps
def Guess_Almost (Guess, Answer):
a = ''.join([str(v) for v in Answer])
g = str(Guess)
n = 0
am = 0
if len(g) >= 5 and len(a) >=4:
while n < 5:
if g[n] == a[0]:
am = am + 1
if g[n] == a[2]:
am = am + 1
if g[n] == a[3]:
am = am + 1
if g[n] == a[3]:
am = am + 1
n = n + 1
return(am)

Categories