I'm trying to make a simple number solver of 4 numbers. The solver replaces the "0" with a number between 1-4. All numbers in the one layered grid must be unique.
Start [2, 0, 3, 0]
The end result should be [2, 1, 3, 4]
or [2, 4, 3, 1]
I need to know how to create a loop that does this? The loop should check the 0s and replace them with the correct number, cycling through 1-4, and then print the correct grid list.
import numpy as np
grid = [2, 0, 3, 0]
#checks that the number is not the same as existing number
def possible(y,n):
if grid[y] == n:
return False
else:
return True
# loop that checks all 4 numbers and then replaces the 0's with the correct number
for num in grid:
if possible == False:
for n in grid(1,4):
print(grid)
This will output a valid solution:
grid = [2, 0, 3, 0]
all_nums = {1,2,3,4}
for i in range(len(grid)):
if grid[i] == 0:
non_zero_numbers_already_taken = set()
for j in range(len(grid)):
if grid[j] != 0:
non_zero_numbers_already_taken.add(grid[j])
# assigns an available number to replace the 0 at index i
grid[i] = (all_nums - non_zero_numbers_already_taken).pop()
print(grid)
# output : [2, 1, 3, 4]
You can adapt the logic to output all possible solutions..
This is an alternative
def replace_zeros(plist):
numbers = [4,3,2,1]
outcome = []
for num in plist:
if num in numbers:
numbers.remove(num)
print(f'these are the missing numbers: {numbers}')
for num in plist:
if num == 0:
outcome.append(numbers.pop())
else:
outcome.append(num)
return outcome
new_grid = replace_zeros([1,0,3,0])
print(new_grid)
#these are the missing numbers: [4,2]
# [1,2,3,4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.