building a simple Sudoku print in python - python

What i'm trying to do is write a code in python which will print a simple Sudoku (solved for now).
I started with a 4 on 4, but planing on 9 on 9 after that.
I managed to make the numbers to not repeat other numbers horizontal and vertical, the problem is how to make them not repeat other numbers within their "box".
Example:
4 3 2 1
3 2 1 4
1 4 3 2
2 1 4 3
Expected:
4 3 2 1
2 1 4 3
1 4 3 2
3 2 1 4
Code:
import random
# preforming 1st check if the giving number already exist in the list sq
# which is created in main
def chk1(num):
while num in sq:
num = random.randint(1,4)
return num
# preforming 2nd check if the giving number already exist in the current index
# of each list that is in sud which is created in main
def chk2(num, i, y):
x = 0
curr = 0
while x != i:
if num != sud[curr][y]:
x +=1
curr +=1
else:
num = random.randint(1,4)
x = 0
curr = 0
return num
# creating the structure of 4 lists in the list sud using the 1st & 2nd check
# each round a unique list is created and is appended to anther list.
def main():
global sq, sud
curry = 0
currx = 0
sq = []
sud = []
for i in range(4):
for y in range(4):
num = random.randint(1,4)
num = chk1(num)
if curry == 1 & currx == 1:
num = chk2(num, i, y)
sq.append(num)
if curry == 0:
curry +=1
sud.append(sq)
if currx == 0:
currx +=1
sq = []
return sud
# printing the final output of main function by line
for line in main():
print(line)
Thanks in advance

Your code may get stuck if it generates a partial set of incompatible numbers. Try this one - it uses recursion and steps back if fails to place another digit:
import numpy as np
def build_sudoku(sudoku=None, i=None):
if sudoku is None:
sudoku = np.zeros((9, 9), dtype=int)
i = 80
if i < 0:
return sudoku
s = sudoku.copy()
r, c = i // 9, i % 9
row, col = s[r, :], s[:, c]
square = g[r//3 * 3:r//3 * 3+3, c//3 * 3:c//3 * 3+3].flatten()
valid = [v for v in np.arange(1, 10) if v not in set([*row, *col, *square])]
np.random.shuffle(valid)
for v in valid:
s[r, c] = v
result = fill_one(s, i-1)
if result is not None:
return result
return None
build_sudoku()
array([[3, 1, 5, 8, 4, 2, 9, 7, 6],
[2, 8, 7, 5, 9, 6, 3, 4, 1],
[9, 4, 6, 1, 7, 3, 2, 8, 5],
[5, 6, 4, 7, 2, 8, 1, 9, 3],
[7, 9, 1, 3, 5, 4, 8, 6, 2],
[8, 2, 3, 6, 1, 9, 4, 5, 7],
[6, 3, 2, 9, 8, 7, 5, 1, 4],
[1, 7, 8, 4, 3, 5, 6, 2, 9],
[4, 5, 9, 2, 6, 1, 7, 3, 8]])

The problem you've presented is much nearer to the Magic Square problem then the actual sudoku (sum of rows, sum of columns + sum in small squares). Therefore, I am providing you example of magic square implementation example from GeeksforGeeks:
def generateSquare(n):
# 2-D array with all
# slots set to 0
magicSquare = [[0 for x in range(n)]
for y in range(n)]
# initialize position of 1
i = n / 2
j = n - 1
# Fill the magic square
# by placing values
num = 1
while num <= (n * n):
if i == -1 and j == n: # 3rd condition
j = n - 2
i = 0
else:
# next number goes out of
# right side of square
if j == n:
j = 0
# next number goes
# out of upper side
if i < 0:
i = n - 1
if magicSquare[int(i)][int(j)]: # 2nd condition
j = j - 2
i = i + 1
continue
else:
magicSquare[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1 # 1st condition
# Printing magic square
print ("Magic Squre for n =", n)
print ("Sum of each row or column",
n * (n * n + 1) / 2, "\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (magicSquare[i][j]),
end = '')
# To display output
# in matrix form
if j == n - 1:
print()
n = 7
generateSquare(n)

Related

Find the sum of two arrays

I am trying to find the sum of two lists/arrays in Python.
For example:
You are given with two random integer lists as lst1 and lst2 with size n and m respectively. Both the lists contain numbers from 0 to 9(i.e. single digit integer is present at every index).
The idea here is to represent each list as an integer in itself of digits N and M.
You need to find the sum of both the input list treating them as two integers and put the result in another list i.e. output list will also contain only single digit at every index.
Following is the code which I have tried:
def list_sum(lst1, n, lst2, m) :
i, j, sum, carry = 0, 0, 0, 0
new_lst = []
if n == 0 and m == 0:
new_lst.append(0)
elif n > 0 and m>0:
while n > 0 and m > 0:
sum = lst1[n - 1] + lst2[m - 1] + carry
if sum >= 10:
carry = 1
else:
carry = 0
new_lst.append(sum % 10)
n -= 1
m -= 1
while n > 0:
if (lst1[n-1] + carry) >= 10:
new_lst.append((lst1[n-1] + carry) % 10)
carry = 1
else:
new_lst.append(lst1[n-1])
carry = 0
n -= 1
while m > 0:
if (lst2[m-1] + carry) >= 10:
new_lst.append((lst2[m-1] + carry) % 10)
carry = 1
else:
new_lst.append(lst1[m-1])
carry = 0
m -= 1
if carry == 1:
new_lst.append(1)
new_lst.reverse()
elif n == 0 and m > 0:
new_lst.append(0)
new_lst = new_lst + lst2
elif n > 0 and m == 0:
new_lst.append(0)
new_lst = new_lst + lst1
print(new_lst)
however I feel I am missing something here and which is not giving me proper answer for the combination. Sometimes it errors list out of index error. I don't know why.
The example input:
n = 3
lst1 = [6, 9, 8]
m = 3
lst2 = [5, 9, 2]
output:
[1, 2, 9, 0]
Here, each element is summed and then if the sum >=10 then we get a carry = 1 and which will be added with the next sum.
i.e
1. 8+2= 10 >=10 hence carry=1 in first sum
2. 9+9+1( carry) = 19 >=10 hence carry=1
3. 6+5+1( carry) = 12>=10 hence carry=1
4. upend the carry to next position as 1
Hence resultant list would be [1, 2, 9, 0]
What can I try next?
Well, all other answers are awesome for adding 2 numbers (list of digits).
But in case you want to create a program which can deal with any number of 'numbers',
Here's what you can do...
def addNums(lst1, lst2, *args):
numsIters = [iter(num[::-1]) for num in [lst1, lst2] + list(args)] # make the iterators for each list
carry, final = 0, [] # Initially carry is 0, 'final' will store the result
while True:
nums = [next(num, None) for num in numsIters] # for every num in numIters, get the next element if exists, else None
if all(nxt is None for nxt in nums): break # If all numIters returned None, it means all numbers have exhausted, hence break from the loop
nums = [(0 if num is None else num) for num in nums] # Convert all 'None' to '0'
digit = sum(nums) + carry # Sum up all digits and carry
final.append(digit % 10) # Insert the 'ones' digit of result into final list
carry = digit // 10 # get the 'tens' digit and update it to carry
if carry: final.append(carry) # If carry is non-zero, insert it
return final[::-1] # return the fully generated final list
print(addNums([6, 9, 8], [5, 9, 2])) # [1, 2, 9, 0]
print(addNums([7, 6, 9, 8, 8], [5, 9, 2], [3, 5, 1, 7, 4])) # [1, 1, 2, 7, 5, 4]
Hope that makes sense!
If I understand correctly you want it like this:
[6, 9, 8], [5, 9, 2] -> 698 + 592 = 1290 -> [1, 2, 9, 0]
In that case my first idea would be to turn the numbers into strings, combine them to one string
and turn it into an int, then add both values together and turn into a list of integers again...
you can try this:
def get_sum_as_list(list1, list2):
first_int = int(''.join(map(str,list1)))
second_int = int(''.join(map(str,list2)))
result = [int(num) for num in str(first_int+second_int)]
return result
Here's one possible solution:
(i) join each list to create a pair of string representation of integers
(ii) convert them to integers,
(iii) add them,
(iv) convert the sum to string
(v) separate each digit as ints
def list_sum(lst1, lst2):
out = []
for i, lst in enumerate([lst1, lst2]):
if len(lst) > 0:
out.append(int(''.join(str(x) for x in lst)))
else:
if i == 0:
return lst2
else:
return lst1
return [int(x) for x in str(out[0]+out[1])]
list_sum([6,9,8],[5,9,2])
Output:
[1, 2, 9, 0]
Two other answers show solutions repeatedly converting between lists of int and strings and ints. I think this is a bit cheating and completely hides the algorithm.
Here I present a solution that manipulates the lists of ints directly to build a third list of ints.
from itertools import chain, repeat # pad list with 0 so they are equal size
from operator import add # add(x,y) = x+y
def padded(l1, l2):
"padded([1, 2, 3], [1, 2, 3, 4, 5]) --> [0, 0, 1, 2, 3], [1, 2, 3, 4, 5]"
padded1 = chain( repeat(0, max(0, len(l2)-len(l1))), l1 )
padded2 = chain( repeat(0, max(0, len(l1)-len(l2))), l2 )
return padded1, padded2
def add_without_carry_same_size(l1, l2):
"add_without_carry([6, 9, 8], [5, 9, 2]) --> [11, 18, 10]"
return map(add, l1, l2)
def flatten_carry(l):
"flatten_carry([11, 18, 10]) --> [1, 2, 9, 0]"
c = 0
for i in range(len(l)-1, -1, -1):
c, l[i] = divmod(c + l[i], 10)
if c > 0:
l[:] = [c] + l
def list_add(l1, l2):
'''
list_add([6, 9, 8], [5, 9, 2]) --> [1, 2, 9, 0]
list_add([9, 9, 9, 9, 9], [1]) --> [1, 0, 0, 0, 0, 0]
'''
p1, p2 = padded(l1, l2)
l3 = list(add_without_carry_same_size(p1, p2))
flatten_carry(l3)
return l3
Relevant documentation:
builtin function map;
itertools.chain;
itertools.repeat;
operator.add;
builtin function divmod.
Tried the following logic
def list_sum(lst1, n, lst2, m, output):
i, j, k, carry = n - 1, m - 1, max(n, m), 0
while i >= 0 and j >= 0:
output[k] = (lst1[i] + lst2[j] + carry) % 10
carry = (lst1[i] + lst2[j] + carry) // 10
i = i - 1
j = j - 1
k = k - 1
while i >= 0:
output[k] = (lst1[i] + carry) % 10
carry = (lst1[i] + carry) // 10
i = i - 1
k = k - 1
while j >= 0:
output[k] = (lst2[j] + carry) % 10
carry = (lst2[j] + carry) // 10
j = j - 1
k = k - 1
output[0] = carry
print(output)
where the output parameter in the above code it taken from below
outputSize = (1 + max(n, m))
output = outputSize * [0]
and called the function
list_sum(lst1, n, lst2, m, output)
You don't mention how long your lists will be. So considering they aren't going to be that long (anyway, python can handle bignums), why not making a simple sum operation? In the end that's what the code should emulate.
import numpy as np
lst1 = [6, 9, 8]
lst2 = [5, 9, 2]
lst1_len = len(lst1)
lst2_len = len(lst2)
if lst1_len >= lst2_len:
lst2 = [0] * (lst1_len - lst2_len) + lst2
else:
lst1 = [0] * (lst2_len - lst1_len) + lst1
common_len = len(lst1)
lst1_val = sum(np.array(lst1) * np.array([10**(-x) for x in range(-common_len + 1, 1)]))
lst2_val = sum(np.array(lst2) * np.array([10**(-x) for x in range(-common_len + 1, 1)]))
total = lst1_val + lst2_val
total_as_list = [int(x) for x in str(total)]
where
print(total_as_list)
[1, 2, 9, 0]
Code:
def addNums(*args):
nums=[]
for i in args:
if i:
i = list(map(str,i)) # Converts each element int to string['6', '9', '8'] , ['5', '9', '2']
add=int(''.join(i)) # Joins string and convert to int 698 ,592
nums.append(add) # Appends them to list [698, 592]
Sum = str(sum(nums)) # Sums the values and convert to string '1290'
result=list(map(int,Sum)) # Converts to list with each converted to int[1,2,9,0]
return result
print(addNums([6, 9, 8], [5, 9, 2]))
print(addNums([7, 6], [5, 9], [3, 5],[7, 4]))
print(addNums([]))
Output:
[1, 2, 9, 0]
[2, 4, 4]
[0]

How to write a function which calculates product of even elements in the list from n to m position in python?

This is what I have tried already, but it only shows me two values, I want to see all even values in that interval, is that possible?
eL = [8, 2, 4, 5, 6, 10]
m = []
n = []
for x in eL:
if x % 2 == 0 and x == eL[0]:
m.append(x)
for x in eL:
if x % 2 == 0 and x == eL[4]:
n.append(x)
print(m, n)
For example,
For the list [8, 2, 4, 5, 6,10]
and n = 1 and m = 3
the result should be 2 · 4
And for n = 0, m = 3
the result should be 8 · 2 · 4
And for n = 2, m = 4 it should be 4 · 6.
Here is the code:
eL = [8, 2, 4, 5, 6, 10]
m = 1
n = 3
result = []
for x in eL:
if x % 2 == 0 and (eL.index(x) >= m and eL.index(x) <= n):
result.append(x)
print(result)
You can use .index and >=, <=
Or (thanks to the comment by Tal J. Levy)
eL = [8, 2, 2, 4, 5, 6, 10]
m = 1
n = 3
result = []
for x in eL[m:n+1]:
if x % 2 == 0:
result.append(x)
print(result)
Just loop it around like this: for x in eL[m:n+1]:
Product of even numbers from n to m indexes:
>>> from functools import reduce
>>> from operator import mul
>>> n, m = 1, 4
>>> lst = [1, 2, 3, 4, 5]
>>> sublst = lst[n:m]
>>> evens = [i for i in sublst if i % 2 == 0]
>>> reduce(mul, evens, 1)
8

I need the sum of numbers from a for-loop that is NOT in a list in Python

I'm having a problem returning the sum. I keep getting zero.
I commented the print results for better understanding. Again, my code is returning 0, and not 11.
A = [1, 5, 2, 1, 4, 0]
def solution(A):
start = [i - j for i, j in enumerate(A)]
start.sort() #[-4, -1, 0, 0, 2, 5]
for i in range(0, len(A)):
pair = 0
end = i + A[i] #1, 6, 4, 4, 8, 5
count = bisect_right(start, end) #4, 6, 5, 5, 6, 6
count_1 = count-1 #3, 5, 4, 4, 5, 5
count_2 = count_1 - i #3, 4, 2, 1, 1, 0
pair += count_2 #??????? I need the above added together like this 3+4+2+1+1+0 since
that's the answer.
return pair
print(solution(A))
As you've written in the comments, the last count2 is zero.
You're adding zero to zero, the loop ends, and you return zero.
You need to start the counter outside the loop, or you can sum outside too, like so
counts = []
for i, x in enumerate(A):
counts.append(bisect_right(start, i + x) - 1 - i)
return sum(counts)
Which could be rewritten
return sum(bisect_right(start, i + x) - 1 - i for for i, x in enumerate(A))

Python - how does the variable affect the loop

I am wondering why there is a different result when I change from arr[n] in version 1 to n in version 2:
Version 1
def summer_69(arr):
list_sum2 = 0
n = 0
for arr[n] in range(arr[n] == 6, (arr[n]== 9) + 1):
list_sum2 += arr[n]
print(list_sum2)
summer_69([1, 3, 5])
summer_69([4, 5, 6, 7, 8, 9])
Result for Version 1
0
0
Version 2
def summer_69(arr):
list_sum2 = 0
n = 0
for n in range(arr[n] == 6, (arr[n]== 9) + 1):
list_sum2 += arr[n]
print(list_sum2)
summer_69([1, 3, 5])
summer_69([4, 5, 6, 7, 8, 9])
Result for Version 2
1
4
that's not how range works.
in this line:
for n in range(arr[n] == 6, (arr[n]== 9) + 1):
arr[n] == 6 and (arr[n]== 9) + 1 are returning truth values because == is a comparison operator so n here at best takes values 0 or 1.
you want
for n in range(6, 10):
so that the value of n iterates from 6 to 9, range() being inclusive to the left and exclusive to the right

How to replace K-values of list by skipping 9 from startend

I have a number lets make it a list s = [1,6,9,2,3,2,7,3,6,8,4,1,9,0,0,3,6,8]
and I have k = 4
What I want is to replace 4-values of list s with number 9 which dont have number 9.
means at position 2 ,we have 9,so skip that and replace next one.
Output should be like: [9,9,9,9,9,2,7,3,6,8,4,1,9,0,0,3,6,8]
With this code I am unable to skip 9's in it:
x= [1,6,9,2,3,2,7,3,6,8,4,1,9,0,0,3,6,8]
k = 4
def elements_replaced(lst, new_element, indices):
return [new_element if i in indices else e for i, e in enumerate(lst)]
output = elements_replaced(x,9,range(k))
print output
you can try:
>>> s = [1,6,9,2,3,2,7,3,6,8,4,1,9,0,0,3,6,8]
>>> k = 4
>>> for index,number in enumerate(s):
if k > 0:
if number != 9:
s[index] = 9
k = k-1
else :
break
>>> s
[9, 9, 9, 9, 9, 2, 7, 3, 6, 8, 4, 1, 9, 0, 0, 3, 6, 8]
You can also use list comprehensions. This will get inefficient if your input list is large relative to the number of nines.
from itertools import chain, repeat
s = [1,6,9,2,3,2,7,3,6,8,4,1,9,0,0,3,6,8]
nines = chain([9] * 4, repeat(None))
result = [x if x == 9 else next(nines) or x for x in s]
print(result)
# [9, 9, 9, 9, 9, 2, 7, 3, 6, 8, 4, 1, 9, 0, 0, 3, 6, 8]
x = [1,6,9,2,3,2,7,3,6,8,4,1,9,0,0,3,6,8]
k = 4
a = 0
while k and a < len(x):
if x[a] != 9:
x[a] = 9
k -= 1
a += 1
x= [1,6,9,2,3,2,7,3,6,8,4,1,9,0,0,3,6,8]
k = 4
def elements_replaced(lst, new_element, indices):
for index, value in enumerate(lst):
if index in indices and value != new_element:
lst[index] = new_element
return lst
output = elements_replaced(x,9,range(k+1))
print (output)

Categories

Resources