Related
i have a problem with finding the solution to make searching algorithm on a list that have various type of item, especially with nested list.
def fib(n):
if n < 1:
return 1
elif n == 1 :
return 1
else:
return fib(n-1) + fib(n-2)
def fibonaccisearch(arr,x,q):
p = 0
p += q
n = 0
while p > 0:
while fib(n) < len(arr) and p != 0:
n = n + 1
offset = -1
while (fib(n) > 1) and p > 0:
i = min(offset + fib(n-2), len(arr) - 1)
if type(arr[i]) == list:
countingx(arr[i])
z = stringdata2.count(x)
print(f"{x} found1 at index:", i,"kolom ke -",fibonaccisearch(arr[i],x,z))
arr[i] = 'this is x'
p -= 1
elif (x > arr[i]):
n = n-1
offset = i
elif (x < arr[i]):
n = n-2
elif (x == arr[i]):
print(arr[i])
print(f"{x} found2 at index :", i)
p -= 1
arr[i] = 'this is x'
while p == 1:
z = 0
z += i
while z > -1:
if arr[z] != x:
z -= 1
else:
print(f"{x} found3 at index :", z)
arr[z] = 'this is X'
z = -1
p -= 1
else:
print()
if (fib(n-1) and arr[offset + 1] == x):
p -= 1
return offset + 1
return -1
def countingx(data):
global stringdata2
global list1
stringdata1 = []
stringdata2 = []
list1 = []
stringdata1.extend(data)
while True:
if len(stringdata1) == 0:
break
elif type(stringdata1[0]) == str:
stringdata2.append(stringdata1[0])
stringdata1.pop(0)
else:
list1.extend(stringdata1[0])
stringdata1.pop(0)
stringdata1.extend(list1)
list1.clear()
arr = ['b','a', ['c', 'a'], 'd', ['a', 'e', 'c'], 'a']
x = 'a'
countingx(arr)
print(stringdata2)
q = stringdata2.count(x)
print(arr)
fibonaccisearch(arr,x,q)
this is my code i dont know whats wrong with it i completely lost my mind trying to find the solution, i try to modified it the closes i find is, the code find the way to find the 'a' in the index 2 column 1, index 4 column 0, and index 5 but skips the 'a' in the index 1, i tried to fix it but it still dont works.
I need to define a function with Python where given a non-empty array A of N (sorted in non-decreasing order) integers and integer K, checks whether A contains numbers 1, 2, …, K (every number from 1 to K at least once) and no other numbers.
This is the function I wrote, but I am getting some unexpected errors as:
print(solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,11,13,14,14,15], 15))
True
Above should be FALSE, 12 is missing
Function:
def solution(A, K):
n = len(A)
for i in range(K-1):
if (A[i] != A[i + 1] and A[i] + 1 != A[i + 1]):
return False
if (A[0] != 1 or A[n - 1] != K):
return False
else:
return True
Any ideas how to solve it changing a max of 2 lines from the code above? Thank you
PD: Working for the moment
def solution(A, K):
n = len(A)
for i in range(n - 1):
if (A[i] != A[i + 1] and A[i] + 1 != A[i + 1]):
return False
if (A[0] != 1 or A[n - 1] != K):
return False
else:
return True
This works:
def isInArray(el, arr):
for i in arr:
if el == i: return True
return False
def solution(arr, k):
l = len(A)
if l < k: return False
for i in range(1, k+1):
if not isInArray(i, arr): return False
return True
Use sets:
set(A) == set(range(1, K+1))
Example:
A = [1, 3, 2, 2, 4, 5, 1]
B = [1, 2, 2, 4, 5, 1] # 3 is missing
C = [1, 3, 9, 2, 4, 5, 1] # 9 is extra
K = 5
set(A) == set(range(1, K+1))
# True
set(B) == set(range(1, K+1))
# False
set(C) == set(range(1, K+1))
# False
using a loop
This is assuming that the input list is sorted!
def solution(l, k):
prev = 0
for x in l:
if x > k or x > prev+1:
return False
prev = x
return True
solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,11,13,14,14,15], 15)
# False
solution([1,2,3,4,5,5,5,6,7,8,8,9,10,10,11,11,11,12,13,14,14,15], 15)
# True
solution([1,2,3,4,5,6], 5)
# False
if space complexity of O(N) is allowed then here is a solution
# your code goes here
def solution(A, K):
array = [0 for i in range(K+1)]
for i in A:
if i>K or i<1:
return False
array[i] += 1
count = 0
for i in array[1:]:
if i==0:
return False
return True
I'm a beginner in Leetcode & Python and I tried to solve the N-Queen Problem. Below is the solution in Python which passed submission
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
def isSafe(row, x_col):
# check row
for x in range(n):
if placed[row][x] is True and x != x_col:
return False
# check column
for x in range(n):
if placed[x][x_col] is True and x != row:
return False
# check diagnol
i, j = row, x_col
while i > 0 and j < n - 1:
if placed[i - 1][j + 1] is True:
return False
i -= 1
j += 1
i, j = row, x_col
while i < n - 1 and j < 0:
if placed[i + 1][j - 1] is True:
return False
i -= 1
j += 1
# #check offdiagnol
i, j = row, x_col
while i > 0 and j > 0:
if placed[i - 1][j - 1] is True:
return False
i -= 1
j -= 1
i, j = row, x_col
while i < n-1 and j < n-1:
if placed[i][j] is True:
return False
i += 1
j += 1
return True
def process(currconfig, matrix, n, row):
#base condition
if row == n:
curr = []
for x in range(n):
curr.append(currconfig[x])
totalconfig.append(currconfig)
return
for x_col in range(n):
if isSafe(row, x_col):
path = x_col * '.' + 'Q' + (n - x_col - 1) * '.'
currconfig.append(path)
matrix[row][x_col] = True
#process recursively called
process(currconfig, matrix, n, row + 1)
currconfig.pop()
matrix[row][x_col] = False
configuration = []
totalconfig = []
placed = [[False for _ in range(n)] for _ in range(n)]
process(configuration, placed, n, 0)
return totalconfig
a = Solution()
print(a.solveNQueens(4))
I only have a doubt about the base condition of the process function. In the process function's base condition I initially did this and got empty Lists appended to totalconfig no matter what, CASE I:
def process(currconfig, matrix, n, row):
if row == n:
totalconfig.append(currconfig)
return
so spent a few hours trying to get around the problem and weirdly enough for me this worked, CASE II :
def process(currconfig, matrix, n, row):
if row == n:
curr = []
for x in range(n):
curr.append(currconfig[x])
totalconfig.append(currconfig)
return
I don't get why the CASE I did not work but CASE II worked. What am I missing...How is "currconfig" in CASE I different from "curr" in CASE II
it looks like you are not using functions (methods) in classes correctly.
Basically, the first argument is the self which refers to itself. In your case, currconfig is self.
So presumably the function should have looked like this:
def process(self, currconfig, matrix, n, row): # <---added self
if row == n:
totalconfig.append(currconfig)
return
I need to find the biggest sequence of zeros next to each other (up down left right).
for example in this example the function should return 6
mat = [[1,**0**,**0**,3,0],
[**0**,**0**,2,3,0],
[2,**0**,**0**,2,0],
[0,1,2,3,3],]
the zeros that i marked as bold should be the answer (6)
the solution should be implemented without any loop (using recursion)
this is what i tried so far
def question_3_b(some_list,index_cord):
y = index_cord[0]
x = index_cord[1]
list_of_nums = []
def main(some_list,index_cord):
y = index_cord[0]
x = index_cord[1]
def check_right(x,y):
if x + 1 < 0:
return 0
if some_list[y][x+1] == 0:
main(some_list,(y,x+1))
else:
return 0
def check_left(x,y):
if x -1 < 0:
return 0
if some_list[y][x - 1] == 0:
main(some_list,(y, x - 1))
def check_down(x,y):
if y + 1 < 0:
return 0
try:
if some_list[y + 1][x] == 0:
main(some_list,(y + 1, x))
except:
print("out of range")
def check_up(x,y):
counter_up = 0
if y - 1 < 0:
return 0
if some_list[y - 1][x] == 0:
counter_up += 1
main(some_list,(y - 1, x))
list_of_nums.append((x,y))
right = check_right(x,y)
down = check_down(x,y)
left = check_left(x,y)
up = check_up(x, y)
main(some_list,index_cord)
print(list_of_nums)
question_3_b(mat,(0,1))
Solution #1: classic BFS
As I mention in a comment, you can tackle this problem using BFS (Breadth First Search), it will be something like this:
# This function will give the valid adjacent positions
# of a given position according the matrix size (NxM)
def valid_adj(i, j, N, M):
adjs = [[i + 1, j], [i - 1, j], [i, j + 1], [i, j - 1]]
for a_i, a_j in adjs:
if 0 <= a_i < N and 0 <= a_j < M:
yield a_i, a_j
def biggest_zero_chunk(mat):
answer = 0
N, M = len(mat), len(mat[0])
# Mark all non zero position as visited (we are not instrested in them)
mask = [[mat[i][j] != 0 for j in range(M)] for i in range(N)]
queue = []
for i in range(N):
for j in range(M):
if mask[i][j]: # You have visited this position
continue
# Here comes the BFS
# It visits all the adjacent zeros recursively,
# count them and mark them as visited
current_ans = 1
queue = [[i,j]]
while queue:
pos_i, pos_j = queue.pop(0)
mask[pos_i][pos_j] = True
for a_i, a_j in valid_adj(pos_i, pos_j, N, M):
if mat[a_i][a_j] == 0 and not mask[a_i][a_j]:
queue.append([a_i, a_j])
current_ans += 1
answer = max(answer, current_ans)
return answer
mat = [[1,0,0,3,0],
[0,0,2,3,0],
[2,0,0,2,0],
[0,1,2,3,3],]
mat2 = [[1,0,0,3,0],
[0,0,2,3,0],
[2,0,0,0,0], # A slight modification in this row to connect two chunks
[0,1,2,3,3],]
print(biggest_zero_chunk(mat))
print(biggest_zero_chunk(mat2))
Output:
6
10
Solution #2: using only recursion (no for statements)
def count_zeros(mat, i, j, N, M):
# Base case
# Don't search zero chunks if invalid position or non zero values
if i < 0 or i >= N or j < 0 or j >= M or mat[i][j] != 0:
return 0
ans = 1 # To count the current zero we start at 1
mat[i][j] = 1 # To erase the current zero and don't count it again
ans += count_zeros(mat, i - 1, j, N, M) # Up
ans += count_zeros(mat, i + 1, j, N, M) # Down
ans += count_zeros(mat, i, j - 1, N, M) # Left
ans += count_zeros(mat, i, j + 1, N, M) # Right
return ans
def biggest_zero_chunk(mat, i = 0, j = 0, current_ans = 0):
N, M = len(mat), len(mat[0])
# Base case (last position of mat)
if i == N - 1 and j == M - 1:
return current_ans
next_j = (j + 1) % M # Move to next column, 0 if j is the last one
next_i = i + 1 if next_j == 0 else i # Move to next row if j is 0
ans = count_zeros(mat, i, j, N, M) # Count zeros from this position
current_ans = max(ans, current_ans) # Update the current answer
return biggest_zero_chunk(mat, next_i, next_j, current_ans) # Check the rest of mat
mat = [[1,0,0,3,0],
[0,0,2,3,0],
[2,0,0,2,0],
[0,1,2,3,3],]
mat2 = [[1,0,0,3,0],
[0,0,2,3,0],
[2,0,0,0,0], # A slight modification in this row to connect two chunks
[0,1,2,3,3],]
print(biggest_zero_chunk(mat.copy()))
print(biggest_zero_chunk(mat2.copy()))
Output:
6
10
Notes:
The idea behind this solution is still BFS (represented mainly in the count_zeros function). Also, if you are interested in using the matrix values after this you should call the biggest_zero_chunk with a copy of the matrix (because it is modified in the algorithm)
For example:
a list just like m=[[2,3],[3,4],[1,2],[4,7],[1,7]]
every element is a little list[x,y], x is not equal to y.
if element a and b in m follow: a[1]==b[0], then a and b will "combined into" c=[a[0],b[1]],
after that,a and b will remove from m,
and c will added into m.
of course,length of m reduced by one.
my question is :
after several times combined oprations,
is there same element exist in new m?
if yes, return True else return False.
I write a demo below
from random import choice
def combine_two(a,b):
c = [None,None]
if a[1]==b[0]:
c[0]=a[0]
c[1]=b[1]
elif b[1] == a[0]:
c[0]=b[0]
c[1]=a[1]
return c
def fusion(list):
ss = list[:]
nn = len(ss)
for i in range(100):
ele_1 = choice(ss)
ele_2 = choice(ss)
c = combine_two(ele_1,ele_2)
if c != [None,None]:
ss.remove(ele_1)
ss.remove(ele_2)
ss.append(c)
return ss
def check(list):
n = len(list)
for i in range(n):
for j in range(n):
if i != j:
if list[i][0] == list[j][0] and list[i][1] == list[j][1]:
return False
return True
jj = [[2,3],[3,4],[1,2],[4,7],[11,13],[1,7]]
m = fusion(jj)
print m
n = check(m)
print n
but my fusion function is a workaround.
if the input list is very long. it will go wrong.
I have no idea of how to handle 2 element at a time Intelligently.
is there a better way to achieve this function?
Sort list second element thus can use binary search, after combine, replace one, but should move the other. Codes below:
def combine_two(a ,b):
c = [None ,None]
if b[1] == a[0]:
c[0 ] =b[0]
c[1 ] =a[1]
elif a[1] == b[0]:
c[0 ] =a[0]
c[1 ] =b[1]
return c
def binary_find(val, list):
left = 0
right = len(list)
while right - left >= 0:
mid = (left + right) / 2
if list[mid][1] > val:
right = mid - 1
elif list[mid][1] < val:
left = mid + 1
else:
return mid
return -1
def fusion_new(list):
src = list[:]
src.sort(lambda x, y: x[1] - y[1] if x[1] != y[1] else x[0] - y[0])
while True:
i = 0
merge_num = 0
while i < len(src):
elem_1 = src[i]
ref_val = elem_1[0]
##find the match case in src
index = binary_find(ref_val, src)
if index >= 0 and index != i:
elem_2 = src[index]
c = combine_two(elem_1, elem_2)
src[i] = c
src.pop(index)
merge_num += 1
else:
i += 1
if merge_num < 1:
break
return src
def check_new(list):
temp = list[:]
temp.sort(lambda x, y: x[0] - y[0] if x[0] != y[0] else x[1] - y[1])
for i in range(len(temp)-1):
if temp[i] == temp[i+1]:
return False
return True
jj = [[2 ,3] ,[3 ,4] ,[1 ,2] ,[4 ,7] ,[11 ,13] ,[1 ,7]]
m = fusion_new(jj)
print m
n = check_new(m)
print n