To calculate Levenshtein distance, we always choose to use dynamic programming. For this, we will create an edit distance matrix as shown below:
enter image description here
Here is the code:
while True:
try:
a = input()
b = input()
board = [[0 for j in range(len(b)+1)] for i in range(len(a)+1)]
for i in range(len(a)+1):
board[i][0] = i
for j in range(len(b)+1):
board[0][j] = j
for i in range(1, len(a)+1):
for j in range(1, len(b)+1):
if a[i-1] == b[j-1]:
d = 0
else:
d = 1
board[i][j] = min(board[i-1][j]+1,
board[i][j-1]+1,
board[i-1][j-1]+d)
print(board[-1][-1])
except:
break
So my question is when we construct the matrix, why we need to add 1 to len(a) and len(b). Because as shown in the picture before, only the red part is the valid part in the matrix. So I modified my code:
while True:
try:
a = input()
b = input()
board = [[0 for j in range(len(b))] for i in range(len(a))]
for i in range(len(a)):
board[i][0] = i
for j in range(len(b)):
board[0][j] = j
for i in range(1, len(a)):
for j in range(1, len(b)):
if a[i] == b[j]:
d = 0
else:
d = 1
board[i][j] = min(board[i-1][j]+1,
board[i][j-1]+1,
board[i-1][j-1]+d)
print(board[-1][-1])
except:
break
I test this modified code and it still gives the correct answer in most tests. But when both strings are very long, the result will be 1 less. I am very confused about this. Maybe this question is stupid, but I still hope to be answered, thank you. 🙏
The problem with your solution is that you skip a[0] and b[0] case and you have to handle that case first. The original solution handles it with a[i-1] == b[j-1] when i = 1 and j = 1 but you don't
Related
This is a program to print a matrix whose sum of each row , column or diagonal elements are equal.
I have a working code but my program gives same output each time i run it. I need a program to print different matrix output for same input.
def matrix(n):
m = [[0 for x in range(n)]for y in range(n)]
i = n // 2
j = n - 1
num = 1
while num <= (n * n):
if i == -1 and j == n:
j = n - 2
i = 0
else:
if j == n:
j = 0
if i < 0:
i = n - 1
if m[int(i)][int(j)]:
j = j - 2
i = i + 1
continue
else:
m[int(i)][int(j)] = num
num = num + 1
j = j + 1
i = i - 1
print ("Sum of eggs in each row or column and diagonal : ",int(n*(n*n+1)/2),"\n")
for i in range(0, n):
for j in range(0, n):
print('%2d ' % (m[i][j]),end = '')
if j == n - 1:
print()
n=int(input("Number of rows of the matrix : "))
matrix(n)
I am unsure whether this is what you are looking for, but one solution is to add a random number to each value of the matrix, as this doesn't break the property
a matrix whose sum of each row, column or diagonal elements are equal.
Here is how you could do it:
add = random.randint(0, 50)
m = [[v+add for v in row] for row in m]
Moreover, you can rotate and add two magic squares without loosing their property. Therefore, you can rotate the magic square you have and add it to the original. This can add some nonlinearity to the results.
def rotate(m): # 90 degrees counter clockwise
return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1, -1, -1)]
# add the matrix with its rotated version
m = list(map(lambda e: [sum(x) for x in zip(*e)], zip(m, rotate(m))))
I hope this helps!
I have a weird problem where I have 2 seemingly identical lists and yet using one gets one answer and using the other gets a second answer even though they are the same list, just generated by different methods.
try the program below and see that b and c are the same. (print outs on line 8)
then when using b's on line 11,13 and 16 we get an answer of 0.
using c's on line 11,13 and 16 we get an answer of 6.
i've tried this on numerous compliers and cannot understand what aspect python is using to differenciate from b and c. Try it yourself by copying and pasting below(Thanks in advance for helping out!):
def oddCells(n, m, indices):
a = [0]*m
b =[]
for every in range(n):
b +=[a]
c = [ [0] * m for i in range(n) ]
result = 0
print(b,"|",c,b == c)
for e in indices:
for i in range(m):
b[e[0]][i] += 1
for j in range(n):
b[j][e[1]] += 1
for i in range(n):
for j in range(m):
if b[i][j] %2 != 0:
result +=1
return(result)
W =[[0,1],[1,1]]
print(oddCells(2,3,W))
############SECOND VERSION TO COMPARE####################################
def oddCells(n, m, indices):
a = [0]*m
b =[]
for every in range(n):
b +=[a]
c = [ [0] * m for i in range(n) ]
result = 0
print(b,"|",c,b == c)
for e in indices:
for i in range(m):
c[e[0]][i] += 1
for j in range(n):
c[j][e[1]] += 1
for i in range(n):
for j in range(m):
if c[i][j] %2 != 0:
result +=1
return(result)
W =[[0,1],[1,1]]
print(oddCells(2,3,W))
I am trying to convert this pseudocode into python code
1 for j = 2 to A.length
2 i=1
3 while A[j]>A[i]
4 i = i+1
5 key = A[j]
6 for k = to j -i - 1
7 A[j-k] = A[j-k-1]
8 A[i] = key
The program says that i have to take 10 inputs and display it in the sorted array using Insertion sort algorithm Here's what i done at the moment i'm stuck at line 6 how do i convert that to python code
A= [int(i) for i in input ('Enter Number').spilt()]
for j in range(2, len(A)):
i = 1:
while A[j] > A[i]:
i = i+1
key = A[j]
for:#?
A[j-k] = A[j-k-1]
A[i] = key
First of all there is something missing in that line 6:
for k = to j -i - 1
It should read:
for k = 0 to j - i - 1
There are a few things to bear in mind when converting to Python:
In Python the first list element is at index 0, not index 1 as is the case in that pseudo code. So that means you need to subtract one at several places (where it concerns i and j).
Similarly, the range function's second argument (the "end" of the range) is a value that is not included in the range, while in the pseudo code, what follows to is included.
So here is how you could translate the code:
A= [int(i) for i in input ('Enter Number').split()]
for j in range(1, len(A)):
i = 0 # zero-based index
while A[j] > A[i]:
i = i+1
key = A[j]
for k in range(0, j-i):
A[j-k] = A[j-k-1]
A[i] = key
As stated in comments, the loop on k seems overly complex. It could just be:
for k in range(j, i, -1):
A[k] = A[k-1]
And a bit more pythonic would be to replace that for loop with:
A[i+1:j+1] = A[i:j]
Finally, the outer loop can take the index and value (key) with enumerate, which saves a few repetitive list look-ups in the form of A[j]:
for j, key in enumerate(A):
i = 0
while val > A[i]:
i = i+1
A[i+1:j+1] = A[i:j]
A[i] = key
With this for loop, you get one more iteration (with j == 0) which does nothing really, so you may decide to use the original loop.
"You are given an array of n integers and an integer k. Find and print the number of (i,j) pairs where i<j and a[i] + a[j] is evenly divisible by k."
Sample input would be:
6 3
1 3 2 6 1 2
where 6 is n, 3 is k and the second line is the array of integers. The output for this input would be 5.
Here is my code, but i am not passing the test cases and am almost positive it has to do with how i am indexing it.
import sys
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
count=0;
for i in range(n):
curr = n-i
for j in range(curr):
if i < i + j:
if k % (a[i] + a[i+j]) ==0:
count = count + 1
print(count)
Also, followup question: Is this method i am approaching an efficient way of going about it?
you can try this ...
import sys
n,k = input().strip().split(' ')
n,k = [int(n),int(k)]
a = [int(a_temp) for a_temp in input().strip().split(' ')]
print(sum([1 for i in range(n) for j in range(i) if (a[i]+a[j])%k==0]))
k % ... means "k is divisible by ...", not "... is divisible by k".
if i < i + j is not very useful; you're better off doing what furas recommends in comments.
What you need is to make use of itertools.combinations:
from itertools import combinations
count = 0
for i, j in combinations(range(n), 2):
if i < j and (a[i] + a[j]) % k == 0:
print i, j
count += 1
Discussion
range(n) returns a list of indices 0 .. n-1
combinations(range(n), 2) will yield a list of two indices (without duplications)
(a[i] + a[j]) % k == 0 is the test that your asked
Note that combinations will yield pairs of i, j where i is always less than j, but the test i < j is there as a paranoid measure
I'm going to do Matrix Addition on Python.(Not finish). But it shows an error.
m, n = (int(i) for i in raw_input().split())
a = [[0 for i in range(m)] for j in range(n)]
b = [[0 for i in range(m)] for j in range(n)]
c = []
total = []
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
c[i][j] = a[i][j]
#c.append(value)
print a
for i in c:
print i
I want to input
3 3 <-- matrix dimensional m*n
1 2 3 >
3 2 1 > matrix A
1 3 2 >
1 1 1 >
1 1 1 > matrix B
1 1 1 >
and shows as
2 3 4 >
4 3 2 > matrix A + B
2 4 3 >
You are using i in your outer for loop, and it is an int. Then in the loop you have:
value = [int(i) for i in x.split()]
which makes i a string (which is what split returns). Maybe you think there is some sort of scoping inside [ ]? There isn't. You have a name collision, change one of them.
You are using same variable in inner for loop.
for i in range(m):
x = raw_input()
for j in range(n):
# variable i is refering to outer loop
value = [int(p) for p in x.split()]
c[i][j] = a[i][j]
#c.append(value)
print a
for i in c:
print i
Beyond the first two answers you'll have a problem with this statement:
c[i][j] = a[i][j]
When the loop starts i will be 0 and that's so far OK, but c is an empty list and has no iterable at the first position so c[0][0] will return an error.
Get rid of it and uncomment the following line:
#c.append(value)
EDIT:
Your code won't return what you want. You'd better make something like this to create a matrix with the given sides:
for i in range(m):
d = []
for j in range(n):
x = raw_input()
d.append(int(x))
c.append(d)
If you have 3 for both m and n, then you will create matrix with sides 3 x 3 saved in the variable c.
In this way you don't have to split the user input. The user can give a number at a time. And you could even change the following line:
x = raw_input()
to:
x = raw_input("{0}. row, {1}. column: ".format(i+1, j+1))
Try it out!
import time
m, n = (int(i) for i in raw_input().split())
a = []
b = []
total = [[0 for i in range(n)] for j in range(m)]
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
a.append(value)
#print a
for i in range(m):
x = raw_input()
for j in range(n):
value = [int(i) for i in x.split()]
b.append(value)
#print b
for i in range(m):
for j in range(n):
total[i][j] = a[i][j] + b[i][j]
for i in total:
print ' '.join(map(str, i))
time.sleep(2)
OK! I just figured it out! Thank you
you can also hit this error if you declare an int and treat it like a dict
>>> a = []
>>> a['foo'] = 'bar'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not str