None to Empty List - python

I have to find the sum of two that are equivalent to value s, can't use dictionaries, only sets, arrays, and lists. If none, then I have to return an empty list. This is my code, I tried to remove None using if statement, but it didn't work, not sure if it is because of the None type.
This is the code I tried
def sum_of_two(L,s):
for item in L:
arr = L[:]
arr.remove(item)
if s - item in arr:
sOfTwo = [item, s-item]
if sOfTwo is None:
return []
else:
return sOfTwo
And this is the output
L= [1, 2, 5, 14, 6, 7, 8]
s = 0 sum_of_two(L,s) = None
s = 1 sum_of_two(L,s) = None
s = 2 sum_of_two(L,s) = None
s = 3 sum_of_two(L,s) = [1, 2]
s = 4 sum_of_two(L,s) = None
s = 5 sum_of_two(L,s) = None
s = 6 sum_of_two(L,s) = [1, 5]
s = 7 sum_of_two(L,s) = [1, 6]
s = 8 sum_of_two(L,s) = [1, 7]
s = 9 sum_of_two(L,s) = [1, 8]
s = 10 sum_of_two(L,s) = [2, 8]
s = 11 sum_of_two(L,s) = [5, 6]
s = 12 sum_of_two(L,s) = [5, 7]
s = 13 sum_of_two(L,s) = [5, 8]
s = 14 sum_of_two(L,s) = [6, 8]
s = 15 sum_of_two(L,s) = [1, 14]
s = 16 sum_of_two(L,s) = [2, 14]
s = 17 sum_of_two(L,s) = None
s = 18 sum_of_two(L,s) = None
s = 19 sum_of_two(L,s) = [5, 14]
s = 20 sum_of_two(L,s) = [14, 6]
s = 21 sum_of_two(L,s) = [14, 7]
s = 22 sum_of_two(L,s) = [14, 8]
s = 23 sum_of_two(L,s) = None
s = 24 sum_of_two(L,s) = None
s = 25 sum_of_two(L,s) = None
s = 26 sum_of_two(L,s) = None
s = 27 sum_of_two(L,s) = None

You're missing a return statement outside of the condition. When no return value, the function will return None by default. This has nothing to do with the inner conditions you wrote, which can be deleted. I would also check if the list has less than 2 cells:
def sum_of_two(L,s):
if len(L) < 2:
return []
for item in L:
arr = L[:]
arr.remove(item)
if s - item in arr:
return [item, s-item]
return []

def sum_of_two(L,s):
temp=[]
for item in L:
arr = L[:]
arr.remove(item)
if s - item in arr:
sOfTwo = [item, s-item]
if sOfTwo is None:
return list()
else:
return sOfTwo
for i in range(20):
x=sum_of_two([1, 2, 5, 14, 6, 7, 8],5)
if x == None:
print("[]")
You can use this workaround. Please verify code once again. In below example everything is working perfect
def empty_list():
return list()
l1 = empty_list()
print(l1)
# []

Related

create list with initialized results of variables instead of integer

I would like to know how I could create a list with defined variables.
I tried to create a loop but unfortunately, the content of the new list is only the integer of the variables instead of the value I’ve initialized before.
The result I want to reach is a list of the initialized values without the integer. I have had a result like (integer: value) but this is also not my target. I only want to have the initialized value in the list.
Code:
weight = {}
weight[0] = 16
weight[1] = 4
weight[2] = 12
weight[3] = 5
weight[4] = 9
weight[5] = 2
my_list = []
for i in weight:
my_list.append(i)
print(my_list)
output:
[0, 1, 2, 3, 4, 5]
target:
[16, 4, 12, 5, 9, 2]
What you are doing is initalizing a dictionary and iterating through the keys.
The solution would be:
weight = {}
weight[0] = 16
weight[1] = 4
weight[2] = 12
weight[3] = 5
weight[4] = 9
weight[5] = 2
my_list = []
for i in weight.values():
my_list.append(i)
print(my_list)
Or initalize the elements in an array:
weights = [16, 4, 12, 5, 9, 2]
print(weights)

Function returning the solution and "None", how to remove the "None" being returned [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 1 year ago.
In my code I cannot understand why python is returning a None at the end. I have tried to close every statement with Exit however I am still getting the None. Here is the output I am getting:
[[6 4 5 3 2 8 7 1 9]
[3 8 7 9 1 6 4 5 2]
[2 9 1 4 5 7 6 3 8]
[5 6 3 2 9 1 8 7 4]
[9 7 8 6 4 5 1 2 3]
[1 2 4 8 7 3 5 9 6]
[7 3 9 5 6 4 2 8 1]
[8 5 6 1 3 2 9 4 7]
[4 1 2 7 8 9 3 6 5]]
None
Here is my current code, could I kindly ask some assistance to identify where I am missing it:
import numpy as np
import copy
def sudoku_solver(sudoku):
start_sudoku = copy.deepcopy(sudoku)
duplicates(sudoku)
solution(start_sudoku, sudoku)
def duplicates(sudoku):
for r in range(9):
line = (sudoku[r, :])
nonzeros = [x for x in line.flatten() if x != 0]
if (len(nonzeros) == len(set(nonzeros))) == False:
array = [[-1 for i in range(9)] for j in range(9)]
return (np.array(array))
return
def solution(start_sudoku, sudoku):
for y in range(9):
for x in range(9):
if sudoku[y][x] == 0:
for n in range(1, 10):
if possible(y, x, n):
sudoku[y][x] = n
solution(start_sudoku, sudoku)
sudoku[y][x] = 0
return
if np.array_equal(sudoku, start_sudoku):
array = [[-1 for i in range(9)] for j in range(9)]
return np.array(array)
return sudoku
your_solution = sudoku_solver(sudoku)
print(your_solution)
Your sudoku_solver function does not return anything, so the default is None, and then in the next line you print that None.
So remove all exit() from your functions, and remove the print you have in there, and make sure the function returns the solution:
def solution(sudoku):
for y in range(9):
for x in range(9):
if sudoku[y][x] == 0:
for n in range(1, 10):
if possible(y, x, n):
sudoku[y][x] = n
result = solution(sudoku)
if result is not None: # Get out of recursion: we have a solution!
return result
sudoku[y][x] = 0
return # No solution here
# If we get here, we have filled the sudoku completely: return it
return sudoku
And return that also in sudoku_solver:
def sudoku_solver(sudoku):
if duplicates(sudoku):
return # Not valid
return solution(sudoku)
And duplicates should return a boolean: False = no duplicates, True = duplicates. I will leave that for you to do as it is not difficult to change the code in that way.
Addendum
From your attempts and edits to the question, it turns out you still have return statements without any value, or no return statements at all.
Here is a working version:
def possible(y, x, n):
for i in range(0, 9):
if sudoku[y][i] == n:
return False
for i in range(0, 9):
if sudoku[i][x] == n:
return False
x0 = (x // 3) * 3
y0 = (y // 3) * 3
for i in range(0, 3):
for j in range(0, 3):
if sudoku[y0 + i][x0 + j] == n:
return False
return True
def duplicates(sudoku):
for row in sudoku:
row = [x for x in row if x]
if (len(row) != len(set(row))):
return True # there are duplicates
for i in range(9):
col = [row[i] for row in sudoku if row[i]]
if (len(col) != len(set(col))):
return True # there are duplicates
for i in range(0, 9, 3):
for j in range(0, 9, 3):
box = sudoku[i][j:j+3] + sudoku[i+1][j:j+3] + sudoku[i+2][j:j+3]
box = [x for x in box if x]
if (len(box) != len(set(box))):
return True # there are duplicates
def solution(sudoku):
for y in range(9):
for x in range(9):
if sudoku[y][x] == 0:
for n in range(1, 10):
if possible(y, x, n):
sudoku[y][x] = n
result = solution(sudoku)
if result is not None:
return result
sudoku[y][x] = 0
return
return sudoku
def sudoku_solver(sudoku):
if duplicates(sudoku):
raise ValueError("Invalid Sudoku: it has duplicates")
return solution(sudoku)
sudoku = [[0, 0, 0, 3, 2, 8, 7, 1, 9],
[3, 8, 7, 9, 1, 6, 4, 5, 2],
[2, 9, 1, 4, 5, 7, 6, 3, 8],
[5, 6, 3, 2, 9, 1, 8, 7, 4],
[0, 7, 8, 6, 4, 5, 1, 2, 3],
[1, 2, 4, 8, 7, 3, 5, 9, 6],
[7, 3, 9, 5, 6, 4, 2, 8, 1],
[8, 5, 6, 1, 3, 2, 9, 0, 7],
[4, 1, 2, 7, 8, 9, 3, 6, 5]]
your_solution = sudoku_solver(sudoku)
print(your_solution)
As sudoku_solver function does not return anything your_solution will be None. The solved table is printed in solution function.
At the end you are printing sudoku_solver which is None.
your_solution runs the function sodoku_solver(), which does not have a return statement. In python, a function with no return statement returns None. So by printing the your_solution, you are printing None.
If you want the solution returned in the function sodoku_solver(), return sodoku in solution() and change the last line in the sodoku_solver() function to return solution(start_sudoku, sudoku)

python group multiple similar if statement

How to group a large amount of similar if else statement or is writing like the following good practice?
if len(G72List) > 1 and G72List[1] != "":
G7201Value = G72List[1]
else:
G7201Value = ""
if len(G72List) > 5 and G72List[5] != "":
G7205Value = G72List[5]
else:
G7205Value = ""
if len(G72List) > 6 and G72List[6] != "":
G7206Value = G72List[6]
else:
G7206Value = ""
if len(G72List) > 7 and G72List[7] != "":
G7207Value = G72List[7]
else:
G7207Value = ""
if len(G72List) > 8 and G72List[8] != "":
G7208Value = G72List[8]
else:
G7208Value = ""
if len(G72List) > 9 and G72List[9] != "":
G7209Value = G72List[9]
else:
G7209Value = ""
if len(G72List) > 10 and G72List[10] != "":
G7210Value = G72List[10]
else:
G7210Value = ""
A series of variable names that differ only by number can be refactored into a dict (or possibly a list if you're starting at 0 and incrementing by 1). Then the repetition can be factored out into a for loop.
GValue = {}
for i in [1, *range(5, 11)]:
if len(G72List) > i and G72List[i] != "":
GValue[7200+i] = G72List[i]
else:
GValue[7200+i] = ""
I've found this way to demo what you could do:
from contextlib import suppress
G7201Value = G7205Value = G7206Value = G7207Value = G7209Value = G7210Value = 'empty'
for i in range(12):
G72List = [_ for _ in range(i)]
print(G72List)
with suppress(IndexError):
G7201Value = G72List[1]
G7205Value = G72List[5]
G7206Value = G72List[6]
G7207Value = G72List[7]
G7208Value = G72List[8]
G7209Value = G72List[9]
G7210Value = G72List[10]
print(
G7201Value,
G7205Value,
G7206Value,
G7207Value,
G7209Value,
G7210Value
)
Output:
$ python3 g27.py
[]
empty empty empty empty empty empty
[0]
empty empty empty empty empty empty
[0, 1]
1 empty empty empty empty empty
[0, 1, 2]
1 empty empty empty empty empty
[0, 1, 2, 3]
1 empty empty empty empty empty
[0, 1, 2, 3, 4]
1 empty empty empty empty empty
[0, 1, 2, 3, 4, 5]
1 5 empty empty empty empty
[0, 1, 2, 3, 4, 5, 6]
1 5 6 empty empty empty
[0, 1, 2, 3, 4, 5, 6, 7]
1 5 6 7 empty empty
[0, 1, 2, 3, 4, 5, 6, 7, 8]
1 5 6 7 empty empty
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1 5 6 7 9 empty
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
1 5 6 7 9 10
Simple but efficient ;-)
Let me explain:
You where trying to see if the list was long enough, then checking if the value at the index you where looking to extract from had a value, then assign it, or set the value to "". you do not need to do this, you can just initialise the variables all at once with an empty string.
After, using contextlib.suppress(IndexError), allows the section of code indented after suppress to proceed as long as IndexError is not raised ;-)
Disclaimer:
for i in range(12):
G72List = [_ for _ in range(i)]
print(G72List)
was just for the purpose of the demo, to show you the behaviour with a list of various lenght.

How to get many sums stepping through varying length lists that have specific orders?

My Problem:
I have a list of lists. These lists are varying length e.g. [[2, 1, 5, 3], [2,4,8]
For each item in each list I need to print its sum with the next list item, then the next 2 list items, until I print the sum of all of the list items. Then I move to the second list item and do the same until I have reached the last list item.
The output I need is:
My Desired Output:
2 + 1 = 3
2 + 1 + 5 = 8
2 + 1 + 5 + 3 = 11
1 + 5 = 6
1 + 5 + 3 = 9
5 + 3 = 8
2 + 4 = 6
2 + 4 + 8 = 14
4 + 8 = 12
My (bad) Attempt:
I have tried for hours but have not been able to get close. I was doing something along the lines of the below code but I am wondering if I need to make a recursive function??
for cluster in [[2, 1, 5, 3], [2,4,8]]:
for trip in cluster:
for trip_cluster_index in range(len(cluster)):
if trip != cluster[trip_cluster_index]:
print(cluster, trip, cluster[trip_cluster_index])
O(n^3)
list_sum = [[2, 1, 5, 3], [2,4,8]]
list_out = []
for l in list_sum:
for i in range(1, len(l)):
aux = l[i-1]
for j in range(i, len(l)):
aux += l[j]
list_out.append(aux)
print(list_out)
[3, 8, 11, 6, 9, 8, 6, 14, 12]
O(n^2)
list_sum = [[2, 1, 5, 3], [2,4,8]]
list_out = []
for l in list_sum:
list_1 = []
aux = l[0]
for i in range(1, len(l)):
aux += l[i]
list_1.append(aux)
list_out.extend(list_1)
sum_list = 0
for j in range(0, len(list_1)-1):
sum_list += l[j]
list_2 = [x-sum_list for x in list_1[j+1:]]
list_out.extend(list_2)
print(list_out)
[3, 8, 11, 6, 9, 8, 6, 14, 12]
Inverted O(n^3)
list_sum = [[2, 1, 5, 3], [2,4,8]]
list_out = []
for l in list_sum:
for i in range(0,len(l)-1):
aux = sum(l[i:])
list_out.append(aux)
for j in range(len(l)-1,i+1,-1):
aux -= l[j]
list_out.append(aux)
print(list_out)
[11, 8, 3, 9, 6, 8, 14, 6, 12]
This should give you what you want.
n = -1
listy = [[1,1,1],[2,2,2],[3,3,3]]
for l in listy:
while n < len(listy)-1:
n +=1
total = sum(l) + sum(listy[n])
print(total)
I assumed that your output must contain the whole equations, and this is what I came up with:
L=[[2, 1, 5, 3], [2,4,8]]
for i in L:
for j in range(len(i)):
for k in range(j+2, len(i)+1):
print(' + '.join([str(n) for n in i[j:k]]), '=', sum(i[j:k]))
Hope it is what you were looking for!

If column A repeats, sum column 2

I have two columns and if column A repeats I want to sum the values of column B.
A = {1 2 3 3 4 4 4}
B = {1 2 3 4 5 6 7}
the result should look like:
A B
1 1
2 2
3 7
4 18
My code:
for i in range(len(a)):
r= np.sqrt(((x-x[j])**2)+((y-y[j])**2)))
if r <= A[i] <= r-5:
B=np.abs((r-0.007)-b[i])
A1 = [1, 2, 3, 3, 4, 4, 4]
B1 = [1, 2, 3, 4, 5, 6, 7]
A2 = []
B2 = []
for i in range(len(A1)):
if A1[i] != A1[i + 1]:
A2.append(A1[i])
B2.append(B1[i])
else:
j = i + 1
sum = B1[i]
while j < len(A1) and A1[i] == A1[j]:
sum += B1[j]
del A1[j]
del B1[j]
A2.append(A1[i])
B2.append(sum)
if j >= len(A1):
break
print A2
print B2
output is:
[1, 2, 3, 4]
[1, 2, 7, 18]
I think the easiest way would be using the following algorithm:
def create_buckets(l):
return [0]*(max(l)+1)
def fill_buckets(A, B):
buckets = create_buckets(A)
for i in range(len(A)):
buckets[A[i]] += B[i]
return buckets
A = [1, 2, 3, 3, 4, 4, 4]
B = [1, 2, 3, 4, 5, 6, 7]
output = fill_buckets(A, B)
for i in range(len(output)):
if output[i] != 0:
print(i, output[i])
We make a list with zero's. It's length is equal to the largest value of A+1. (this way, we have every value of A as an index in the list) These are buckets.
We loop over A. Let's say we get value X on index Y in the loop:
• We check the value on list B with the same index (Y)
• We add that value to the buckets, on index X (value of A on index Y)
We print every value of the buckets that is not zero (or you can make another default value if you want to allow zeros).
I think this is the simplest solution.
A1 = [1, 2, 3, 3, 4, 4, 4]
B1 = [1, 2, 3, 4, 5, 6, 7]
A2 = []
B2 = []
A2.append(A1[0])
B2.append(B1[0])
for i in range(len(A1)-1):
if A1[i] != A1[i+1]:
A2.append(A1[i+1])
B2.append(B1[i+1])
else:
A2.pop()
A2.append(A1[i+1])
b = B2.pop()
B2.append(b+B1[i+1])
print A2
print B2
Output:
A2 = [1,2,3,4]
B2 = [1,2,7,18]

Categories