Somebody please help me find the maximum (longest) connected component (not diagonally, only bottom, top, left and right) in a matrix. My code does not work, I have been tying to solve this problem for 24 hours.
For first version:
What's idea? For example, take one element with value '1' and change its value to '2' and look for the other '1' around. Change their ('1' around) value to 3. Take one elem with value '3', look for '1' around, change '1' to '4', etc. All elements > 1 are calculated (l) and compared with the intermediate value of the largest component (comps[u], comps[1] for initial '1').
import random
n = int(input())
m = int(input())
#create and output matrix with elems 1-4
a = [[0]*(m+2) for i in range(n+2)]
b = [[0]*(m+2) for i in range(n+2)]
for i in range(n+2):
for j in range(m+2):
if i == 0 or i == n+1 or j == 0 or j == m+1:
a[i][j] = -100
for i in range(1, n+1):
for j in range(1, m+1):
s = random.randint(1, 4)
a[i][j] = s
for i in range(1, n+1):
for j in range(1, m+1):
print(a[i][j], end = " ")
print()
comps = [0]*5 #counter of longest components
u = 1 #it is value of the elem, adjacent elems whith which we well check
def main(u):
if u == 5: return()
global a
global b
k = 0
l = 0
global m
global n
global comps
for i in range(1, n+1):
for j in range(1, m+1):
if a[i][j] == u and k == 0:
b[i][j] = 2
k+=1
elif a[i][j] == u:
b[i][j] = 1
k+=1
w = m//2
v = n//2
#a[v][w] = u
#b[v][w] = 2
p = True
c = 2
while p:
for h in range(1, n+1):
for hh in range(1, m+1):
if b[h][hh] == c and b[h-1][hh] == 1:
b[h-1][hh] = c+1
c += 1
if b[h][hh] == c and b[h+1][hh] == 1:
b[h+1][hh] = c+1
c += 1
if b[h][hh] == c and b[h][hh-1] == 1:
b[h][hh-1] = c+1
c += 1
if b[h][hh] == c and b[h][hh+1] == 1:
b[h][hh+1] = c+1
c += 1
else:
b[h][hh] = 2
if c not in b:
p = False
break
for x in range(1, n+1):
for y in range(1, m+1):
if b[x][y] > 1:
l += 1
b[x][y] = 0
a[x][y] = 0
if l > comps[u]:comps[u] = l
if k == l:
u+=1
main(u)
main(u)
maxk = max(comps)
for i in range(1,5):
if comps[i] == maxk:
print('The length of the longest con. comp. for digit ', i, ' is ', comps[i])
And second version with recursion, it's does not work either.
import random
n = int(input())
m = int(input())
a = [[0]*(m+2) for i in range(n+2)]
b = [[0]*(m+2) for i in range(n+2)]
def deep_find(q, o):
global b
global ww
ww += 1
t = q
d = o
b[t][d] = 0
if t <= n and b[t+1][d] == 1:
deep_find(t+1, d)
if t >= 1 and b[t-1][d] == 1:
deep_find(t-1, d)
if d<= m and b[t][d+1] == 1:
deep_find(t, d+1)
if d>= 1 and b[t][d-1] == 1:
deep_find(t, d-1)
print(ww)
return()
for i in range(n+2):
for j in range(m+2):
if i == 0 or i == n+1 or j == 0 or j == m+1:
a[i][j] = -100
for i in range(1, n+1):
for j in range(1, m+1):
s = random.randint(1, 4)
a[i][j] = s
for i in range(1, n+1):
for j in range(1, m+1):
print(a[i][j], end = " ")
print()
comps = [0]*5
u = 1
while u!=5:
k = 0
for i in range(1, n+1):
for j in range(1, m+1):
if a[i][j] == u:
b[i][j] = 1
k+=1
p = True
while p:
for i in range(1, n+1):
for j in range(1, m+1):
if b[i][j] == 1:
t = i
d = j
ww = 0
deep_find(t, d)
p = False
break
if ww>comps[u]: comps[u] = ww
if ww == k: u += 1
maxk = max(comps)
for i in range(1,5):
if comps[i] == maxk:
print( i, comps[i])
Related
So I tried coding a program to solve NQueen problem in python. It is only outputing correct response for n as 1 or 5. It doesn't throw an error or anything for the rest of numbers.
Here is the code:
import numpy as np
def isSafe(arr, row, col, n):
for ind in range(row):
if(arr[ind][col] == 1):
return False
x = row
y = col
while x >= 0 and y >= 0:
if arr[x][y] == 1:
return False
x -= 1
y -= 1
x = row
y = col
while x >= 0 and y < n:
if arr[x][y] == 1:
return False
x -= 1
y += 1
return True
def nQueen(arr, row, n):
if row >= n:
return True
for col in range(n):
if isSafe(arr,row,col,n) == True:
arr[row][col] = 1
if nQueen(arr, row+1, n) == True:
return True
return False
def main():
n = int(input("Enter the size of board: "))
arr = np.zeros((n,n)).astype(int)
if nQueen(arr, 0, n):
for x in range(n):
for y in range(n):
print(arr[x][y], end='\t')
print("\n")
else:
print("No Solution: ")
if __name__ == '__main__':
main()\
Using Lists:
import numpy as np
def isSafe(arr, row, col, n):
for ind in range(row):
if(arr[ind][col] == 1):
return False
x = row
y = col
while x >= 0 and y >= 0:
if arr[x][y] == 1:
return False
x -= 1
y -= 1
x = row
y = col
while x >= 0 and y < n:
if arr[x][y] == 1:
return False
x -= 1
y += 1
return True
def nQueen(arr, row, n):
if row >= n:
return True
for col in range(n):
if isSafe(arr,row,col,n) == True:
arr[row][col] = 1
if nQueen(arr, row+1, n) == True:
return True
return False
def main():
n = int(input("Enter the size of board: "))
arr = [[0]*n]*n
if nQueen(arr, 0, n):
for x in range(n):
for y in range(n):
print(arr[x][y], end='\t')
print("\n")
else:
print("No Solution: ")
if __name__ == '__main__':
main()
I tried using every single integer from 0 to 20 but only 1 and 5 seemed to output something while any other number just outputted "No Solution".
Also, The lists one doesnt even output an answer for 5, just 1
When you determine that an assignment arr[row][col] is not safe, you never reset it for future tests.
def nQueen(arr, row, n):
if row >= n:
return True
for col in range(n):
if isSafe(arr,row,col,n) == True:
arr[row][col] = 1 # Put a queen here
if nQueen(arr, row+1, n) == True:
return True
arr[row][col] = 0 # Take it back; it didn't work here
return False
I've written these two functions to return a letters 'A' and 'H' as a stars pattern. Is there any way to print them next each other or should I rewrite the code to print them as one pattern?
rows = 8
cols = 8
sym = '*'
thick = 2
def A(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if (i == 0 or i == 1) and j != 1 and j != 0:
tmp += sym
elif i > 1 and j == 0 or j == cols - 1:
tmp += sym * thick
elif i == 3 or i == 4:
tmp += sym
else:
tmp += ' '
tmp += '\n'
return tmp
def H(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if j == 0 or j == 7:
tmp += sym * thick
if i != 3 and (i != 4):
tmp += ' '
elif (i == 3 and j != 7) or (i == 4 and j != 7):
tmp += sym
tmp += '\n'
return tmp
str = H(rows, cols, sym, thick)
str += A(rows, cols, sym, thick)
print(str)
The output is:
There are 3 general solutions:
Add logic to split the returned strings in to lines, than recombine them
Add logic to print the returned strings line by line
Use the pycurses module to create a separate window for each character and print them there.
I will demonstrate method #1 here as it is the simplest:
#you need this if you plan on letters of different height
from itertools import zip_longest
rows = 8
cols = 8
sym = '*'
thick = 2
def A(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if (i == 0 or i == 1) and j != 1 and j != 0:
tmp += sym
elif i > 1 and j == 0 or j == cols - 1:
tmp += sym * thick
elif i == 3 or i == 4:
tmp += sym
else:
tmp += ' '
tmp += '\n'
return tmp
def H(rows, cols, sym, thick):
tmp = ''
for i in range(rows):
for j in range(cols):
if j == 0 or j == 7:
tmp += sym * thick
if i != 3 and (i != 4):
tmp += ' '
elif (i == 3 and j != 7) or (i == 4 and j != 7):
tmp += sym
tmp += '\n'
return tmp
h = H(rows, cols, sym, thick)
a = A(rows, cols, sym, thick)
s = ""
#if your letters are guaranteed to be same height, you can use regular zip
for line in zip_longest(h.split('\n'), a.split('\n'), fillvalue=''):
s += line[0] + ' ' + line[1] + '\n'
print(s)
Notice I changed your str var to s because str is a built in function in Python and you should not use it for your own variable names!
Also, all lines in "H" except middle to have a space at the end.
This is a bug in your H function, but should be easy to fix for you.
Here is alternative solution:
from operator import add
h = H(rows, cols, sym, thick)
a = A(rows, cols, sym, thick)
# horizontal join
res = '\n'.join(map(add, h.split('\n'), a.split('\n')))
print(res)
which yields:
** ** ******
** ** ******
** ** ** **
*********************
*********************
** ** ** **
** ** ** **
** ** ** **
The inconsistencies in spacing come from the fact, that you add no padding to the H bar.
I tried to implement merge-sort in Python. Somehow this piece of code runs correctly (and pretty fast), but I don't know why: There is no return-statement in mergeSort()
from sys import stdin
def mergeSort(A):
if len(A) > 1:
m = int(len(A)/2)
L = A[:m]
R = A[m:]
mergeSort(L)
mergeSort(R)
l = 0
r = 0
a = 0
while l < len(L) and r < len(R):
if L[l] < R[r]:
A[a] = L[l]
l += 1
else:
A[a] = R[r]
r += 1
a += 1
while l < len(L):
A[a] = L[l]
l += 1
a += 1
while r < len(R):
A[a] = R[r]
r += 1
a += 1
def main():
A = []
for line in stdin:
A.append(int(line))
mergeSort(A)
print(A)
if __name__ == "__main__":
main()
I am trying to perform dynamic programming for approximate pattern matching in this code.Once the matrix is created,I am trying to trace back to my answer using the function trace.But when I run the program,the trace function is not returning any result and the program isn't getting terminated.
class Structure :
def __init__(self):
self.vertical =[]
self.horizontal =[]
self.diagnol=[]
def merge(self, s):
for i in s.vertical :
self.vertical.append(i)
for i in s.horizontal :
self.horizontal.append(i)
for i in s.diagonal:
self.diagonal.append(i)
def __str__(self):
return "horizontal \n"+str(self.horizontal) +"\n vertical \n"+str(self.vertical)+"\n diagonal"+str(self.diagonal)
def posList(pattern, text): #determine the positions in the matrix
retList = list()
textList = [x for x in text.strip()]
for i, char1 in enumerate(pattern):
textPos = [j for j, char2 in enumerate(textList) if char1==char2]
for j in textPos:
retList.append((i+1,j+1))
return retList
def trace(M,text,pattern,k) :
positions=posList(pattern,text)
struct = Structure()
for i in range(0,2):
for j in range(0,7):
while M[i,j]<=k and M[2,j]!=0:
if M[i,j] == M[i,j-1]+1:
struct.horizontal.append(j)
j -= 1
elif M[i,j] == M[i-1,j]+1:
struct.vertical.append(i)
i -= 1
elif (i+1,j+1)in positions and M[i,j]==M[i-1,j-1] :
struct.diagonal.append((i,j))
i -= 1
j -= 1
elif (i+1,j+1) not in positions and M[i,j]==M[i-1,j-1]+1 and M[i,j]==M[i-1,j]+1:
struct.vertical.append(i)
i-=1
print "error"
elif (i+1,j+1) not in positions and M[i,j]==M[i-1,j-1]+1 and M[i,j]==M[i,j-1]+1:
struct.horizontal.append(j)
j-=1
elif M[i,j]==M[i-1,j]+1 and M[i,j]==M[i,j-1]+1:
struct.vertical.append(i)
elif M[i,j]==M[i-1,j]+1 and M[i,j]==M[i,j-1]+1 and M[i,j]==M[i-1,j-1]+1:
struct.vertical.append(i)
i-=1
else :
pass
return struct
text='ACAGCAG'
pattern='GC'
n = len(pattern)
m = len(text)
text1=list(text)
pattern1=list(pattern)
M = [[0 0 0 0 0 0 0 0],[1 1 1 1 0 1 1 0],[2 2 1 2 1 0 1 1]]
#perform traceback
s= trace(M,text,pattern,1)
print s
s = trace(M, w, seq, max, 0, n-1)
print str(s)
print seq
result=real_string(s)
print "".join(result)
Can anyone suggest me where I maybe going wrong in the function ?
I've been trying to rearrange the string by reversing a particular strings consecutively from the given string input and the limit is given as input.
for example
limit is 3
if input is Hellothegamestarts
output must be Heltolhegemastastr
and it is saved in separate array
The code is:
while True:
t = int(input())
if t == 0:
break
string = raw_input()
string = string.encode('utf-8')
leng = len(string)
r = t/leng
m = []
leng = 0
for i in range(r):
if r % 2 == 0:
l = 0
l = leng + t
for i in range(t):
temp = string[l]
m.append(temp)
l = l - 1
r = r + 1
leng = leng + t
else:
l = 0
l = leng
for i in range(t):
temp = string[l]
m.append(temp)
l = l + 1
r = r + 1
leng = leng + t
print m
the output i got is [] and asks for next input for t.
Any help is appreciated.
Take the blocks in chunks of 3s, and reverse the odd ones, eg:
import re
s = 'Hellothegamestarts'
r = ''.join(
el if idx % 2 == 0 else el[::-1]
for idx, el in enumerate(re.findall('.{,3}', s))
)
# Heltolhegemastastr
Maybe you can try -
t = int(input())
if t == 0:
break;
string = raw_input()
m = ''
leng = len(string)
i = 0
while i < leng:
if (i/t) % 2 != 0:
m = m + string[i+t-1:i-1:-1]
else:
m = m + string[i:i+t]
i = i + t
print(m)
Alternatively you can try this
def myfunc(s, count):
return [''.join(x) for x in zip(*[list(s[z::count]) for z in range(count)])]
a='Hellothegamestarts'
lst=myfunc(a,3)
print "".join([i if lst.index(i) in range(0,len(lst),2) else i[::-1] for i in lst])
myfun i didn't write it.It's from here