I'm really new at Python so I apologize in advance if this is a really dumb question. Pretty much, I'm writing a longest common subsequence algorithm with dynamic programming.
Whenever I try to run it, I get the IndexError: list index out of range, and I don't know why because the array I'm adding values to never changes in size. Code snippet for clarity:
def LCS(sequence1, sequence2):
n = len(sequence1)
m = len(sequence2)
D = [[0 for num in range(0,n)]for number in range(0, m)]
for i in range(1, n):
for j in range(1, m):
if(sequence1[i] == sequence2[j]):
D[i][j] = D[i-1][j-1] + 1
else:
D[i][j] = max(D[i-1][j], D[i][j-1])
print D[n][m]
There seem to be two problems:
In the definition of D, you should swap n and m
D = [[0 for num in range(0, m)] for number in range(0, n)]
You have to print (or better: return) the last element of the matrix
return D[n-1][m-1] # or just D[-1][-1]
The issue is with total rows and columns of the matrix(D). Size should be (m+1)*(n+1) and then loop over the matrix. Otherwise you need to return D[m-1][n-1].
def LCS(sequence1, sequence2):
n = len(sequence1)
m = len(sequence2)
D = [[0 for num in range(0,n+1)]for number in range(0, m+1)]
for i in range(1, n+1):
for j in range(1, m+1):
if(sequence1[i-1] == sequence2[j-1]):
D[i][j] = D[i-1][j-1] + 1
else:
D[i][j] = max(D[i-1][j], D[i][j-1])
print D[n][m]
LCS('abcdef' , 'defjkl')
Related
I want to use dynamic programming to find all subset of an array that sums to a target,like:
arr = [1,3,2,4]
target = 6
output:
[1,3,2],[2,4]
How can i modify the code to get solution? thanks
def CheckSubsetSum(S, M):
n = len(S)
subset = np.array([[True]*(M+1)]*(n+1))
for i in range(0,n):
subset[i,0] = True
for j in range(1,M+1):
subset[0,j] =False
for i in range(1,n+1):
for j in range(1,M+1):
if j<S[i-1]:
subset[i,j] = subset[i-1,j]
else:
subset[i,j] = subset[i-1,j] or subset[i-1,j-S[i-1]]
print(subset)
CheckSubsetSum([1,3,2,4],6)
Generating a hailstone sequence that follows the pattern below:
if x is even -> x/2
if x is odd -> [a]x+[b]
where a and b are integer values {0,...,10}, allowing for 121 possible combinations of a and b. I need to list whether the sequence converges for all 1000 x values
I am using python to solve the problem, I'm a beginner at coding with python but am a quick learner and need guidance on how to resolve
`for n in range(1,1001):
for i in a:
for j in b:
while j != 1 & i != 1:
print ("a:", i, "b:", j)
if j % 2 == 0:
j = j / 2
length = length + 1
else:
n = (n * j) + i
if n == 1:
print (n)
'
the above works in that it runs but it doesn't do what I want. It just keeps looping integer one and wont move past it
I see following problems in your code:
range usage, range does not accept list as argument, you should use for i in a: when a is list, rework all your fors accordingly.
broken while syntax: you have too many :s in your while, should be one : (at end)
possibly broken indentation: note that if is not aligned with corresponding else, keep in mind that in Python language indentation is crucial
j = j / b will produce error - you can't divide int by list
you never define n, thus n = (n * a) + 1 and all other lines with n, will produce errors
Keep in mind that my list of problems might be incomplete
'a = [0,1,2,3,4,5,6,7,8,9,10]
b = [0,1,2,3,4,5,6,7,8,9,10]
for n in range(1,1001):
for i in a:
for j in b:
while j != 1 & i != 1:
print ("a:", i, "b:", j)
if j % 2 == 0:
j = j / 2
length = length + 1
else:
n = (n * j) + i
if n == 1:
print (n)'
updates...I want to still be able to understand when it converges and it won't move to the next value
I'm working on a project which requires me to find sum partitions of a certain value(required_reduction). I have to clear the total_parts list from sublists if any which has any value other than 2. index of combs's sublists.
Example:
required_reduction = 4
combs = [[2,1],[3,2]]
total_parts = [[1,1,1,1],[1,1,2],[2,2],[1,3]]
I can't use [1,3] because it has "3" in it which is not a value contained in 2.elemnt of "combs" sublists which are 1 and 2. "partition" function was taken from stackoverflow, I'm trying to construct rest.
import numpy as np
required_reduction = 16
combs = [[2,4],[3,5],[4,8],[5,13],[8,15],[10,18]]
def partition(number):
answer = set()
answer.add((number, ))
for x in range(1, number):
for y in partition(number - x):
answer.add(tuple(sorted((x, ) + y)))
return answer
total_parts = partition(required_reduction)
total_parts = list(total_parts)
def applicable_partitions(total_partitions, combinations):
selections = [0]
for _ in range(0, len(combinations) - 1):
selections.append(combinations[_][1])
del selections[0]
possible_partitions = np.array(np.zeros(1,int))
for i in range(0, len(total_partitions)-1):
for j in range(0, len(total_partitions[i]) -1):
for k in range(0, len(selections)-1):
if total_partitions[i][j] == selections[k]:
continue
else:
total_partitions.remove(total_partitions[i])
return total_partitions
print(applicable_partitions(total_parts, combs))
I am getting this error :
if total_partitions[i][j] == selections[k]:
IndexError: tuple index out of range.
Can someone see why ?
I am trying to write a Python statement for performing the following task with a table of m rows and n columns.
I have to fill only the top row and bottom row with zeros.
So far I have:
list = []
for i in range(m):
for j in range(n):
I'm not sure what to do next. How can I access just the first and last row? Thank you!
Code based on your provided information :
list = []
for x in range(0, m):
if x == 0 or x == m:
# your code for filling it with zeros
else:
# your code for "Anything can be in other cells"
You can use:
lst = [[0 if i in (0, m-1) else default_val] * n for i in range(m)]
That roughly does the same as:
lst = [] # do not shadow 'list'
for i in range(m):
lst[i] = []
for j in range(n):
lst[i].append(0 if i in (0, m-1) else default_val)
I am a beginner to programming. I always encounter this problem for matrices. Please help me to correct this code and understand the concept behind this. Thank you.
def new_matrix(matrix_size, center_num):
c = matrix_size / 2
if matrix_size % 2 != 0:
p = matrix_size
print("enter a valid size for matrix")
else:
matrix = [[0] * matrix_size for z in range(matrix_size)]
for counting in range(center_num, (matrix_size ** 2) + center_num):
for i in range(2, matrix_size+1):
row = int(c)
column = int(c)
if (i % 2 == 0):
for k in range(1, i + 1): # moving right
column += 1
matrix[column][row] = counting
for k in range(1, i + 1): # moving up
row += 1
matrix[column][row] = counting
else:
for k in range(1, i + 1): # moving left
column -= 1
matrix[column][row] = counting
for k in range(1, i + 1): # moving down
row -= 1
matrix[column][row] = counting
print(matrix)
new_matrix(6, 2)
This issue here seems to be that your indexing is off. The end value in range(n) is n-1, which means that in your for loop when i = matrix_size and then you try to increment the column beyond this, you're trying to assign a value to an index in the matrix that doesn't exist.
You can either try and fix your loop, i.e. reduce it by one, or you can do something like the following,
try:
<your code goes here>
except IndexError:
pass
And then anytime the loop hits an index error it will skip that index and try the next. It's better to fix the code though!