Before I start, I've searched for a long time trying to find a solution!
I'm trying to create a function that will return the longest matching sequence of words within 2 strings of different lengths.
from difflib import SequenceMatcher
file_1 = 'i took a walk around the world to ease my troubled mind i left my body lying somewhere in the sands of time i watched the world float to the dark side of the moon i feel there is nothing i can do yeah i watched the world float to the dark side of the moon after all i knew it had to be something to do with you i really dont mind what happens now and then as long as youll be my friend at the end if i go crazy then will you still call me superman if im alive and well will you be there holding my hand ill keep you by my side with my superhuman might kryptonite'
file_3 = 'when i was young i took a walk around the woods i found that i was both taller and smaller than the trees returning to my home i set out for the desert i journeyed for long days and nights my spirit left my body and i left my body lying somewhere in the sands of time unburdened by physical form i watched the world float away from me and into the vast moonlight'
match = SequenceMatcher(None, file_1, file_3).find_longest_match(0, len(file_1), 0, len(file_3))
print(file_1[match.a: match.a + match.size])
This currently prints out "i took a walk around the wo"
What it should print is "i left my body lying somewhere in the sands of time"
The alternative solution I've found is as below:
def longestSubstringFinder(string1, string2):
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
for j in range(len2):
lcs_temp=0
match=''
while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]):
match += string2[j+lcs_temp]
lcs_temp+=1
if (len(match) > len(answer)):
answer = match
return answer
However, this also doesn't return what I want, as it prints "nd i left my body lying somewhere in the sands of time".
Any help would be greatly appreciated.
Related
I came across this problem, and the first thing that comes to my mind is use TSP.
A person is visiting a new country which has several states. Each state has cities connected via bidirectional roads.
States are divided into cities such that for any two cities A and B,if it is possible to go from A to B by a road and then return to A,A and B belong to the same state.
furthemore,everytime a person enters a new state, you need to pay a cost of 1 $.For travelling on roads that belong to same state there is no cost.
Given an image where cities are represented by colored dots and roads by straight lines, what is the minimum cost a person needs to pay so that he visits every city in every state.
For the image part, I think we can convert it to a graph by using some online library(recommendations on how to do this will be appreciated).
Also, if anyone could give me some ideas/suggestions on how to go about solving the problem, or if they have seen something similar, would be appreciated.
Enclosed are some images that illustrate the graph
I also tried using opencv flood fill to compute the results as mentioned in the comments but it seems I am getting the incorrect result.
import cv2
import numpy as np
img=cv2.imread('graph1.png',cv2.IMREAD_GRAYSCALE)
M,N=img.shape
n_objects=0
for i in range(M):
for j in range(N):
if img[i,j]==255:
n_objects+=1
cv2.floodFill(img,None,(j,i),n_objects)
print(n_objects)
for the first image,expected output is 6,but this returns 3 as the result.Any ideas what can be done to improve the result
The entire prosa about cities etc. is just a red herring. It's not even a graph problem.
It's a basic flooding algorithm on the image which you need:
N = 0
While any pixel != White
Flood with white from pixel
N++
If N > 1
Return N - 1
Else
Return 0
Effectively you only count the number of connected regions which don't correspond to the background color.
With code I can get points of the person's nose, shoulders and hips. I am trying to figure out how to check if someone is facing the camera.
There are some easy ideas, but they all run into trouble when I add that the person can come closer or move further away.
Failed Attempts:
shoulder distance: turning makes it smaller, but so does walking away.
Shoulder to Hip Ratio should work, but it only makes a meaningful change after a large turn. I suppose there might be some noise in the code.
I have an intuition to compare the area of the torso (shoulders and hips) to the height of the torso? Not sure how to quantify it or if there is a better idea?
This is not a question specific to one programming language, more of a mathematically conceptual, though just in case, I'm using C++ on Visual Studio.
Basically, my current code draws a line, that starts at the centre (of the window), and ends at my mouse position at any time, every frame - I end up with a line that follows my mouse, starting from the centre.
My question is, how would I end up with the exact same system, except that no matter how far my mouse goes from the centre, the line will still follow the direction of the vector 'centerToMouse', but its length will only ever be 100 units (once the distance between MousePos and centre exceeds 100), such that I end up with a line that follows (extends/shrinks) my mouse, but once I reach above 100 units away from the centre, the line stays 100 units long as long as my mouse is further than 100 away.
I'm sorry if the question is badly phrased, in my head it makes sense, and I don't know how else to word it.
I don't necessarily need a code answer for C++, just the concept. I've tried a few methods involving normalizing, unit vectors etc. But I'm just stuck.
Thanks a lot for taking the time!
Paraphrasing from my above comment:
radius = 100;
angle = atan2(mouse_position.y-center.y, mouse_position.x-center.x);
if (distance(center, mouse_position) < radius){
line_position = mouse_position;
}
else{
line_position = center + Vector(radius*cos(angle), radius*sin(angle));
}
I am working on solving snake boxing itself problem. I believe that If I use Breadth-First Search (BFS) to make a move, it can reduce the risk of being boxed greatly. My question is how many possible empty spaces (connected) I should look for to make sure that this move will not result in boxing myself.
The distance you have to look to see if you are boxed in is always going to depend on the size/position of the snake. The only way to be 100% sure is to search all moves in advance, and avoid moves that lead the snake to be boxed in. That said, you might have better luck with a depth-first search over breadth-first, because it can rapidly find a dead end (if it exists). Then avoid those moves. In your second example, depth-first would quickly find that moving "up" is a dead end.
I think the number of moves deep you need to search the game tree is related to the square area the snake can contain when it encircles itself. For example, a length 12 snake:
----
|00|
|00|
91--
If the snake goes up (north), it can still live but only if it then goes east. if it goes north again, then it dies.
The maximum area a snake can contain is: (length/4 - 1)^2. When this is fractional, you probably want to round up.
I have a grid based game (platformer) where I've based everything on tiles. I have tiles that are solid and liquid. I'm trying to find of a good way to make water tiles simulate water in a rough way.
At the moment I have the current system:
When a water tile is added above another water tile, it adds 1 to the water tile below. The number indicates the pressure.
Here's how it looks like at the moment:
[0] <- This water tile has 0 in pressure.
[1] <- This water tile has 1 in pressure.
if I add another water tile next to the bottom one, it searches from left, right and above if there are any water tiles and inheritates the biggest pressure around it.
Example:
[0]
[1][1]
And here's a bigger example after adding few water tiles:
[0][0]
[1][1][1][1]
[2][2][2][2][2]
Then I make every water tile that has pressure that is equal or bigger than 1 try to move left/right if there's free space, then set pressure to 0 and check if it can inheritate pressure around itself from neighbor water tiles if there are any.
This system works very well, except for the case when water tiles are removed from the top.
If I remove the top water tiles from the last example:
[1][1][1][1]
[2][2][2][2][2]
Then we have the top row with pressure 1, it should have 0 there now and the bottom row should have 1.
Is there some smarter system I can implement to do this more proper?
The following are the restrictions:
Each tile can only check its neighbors tiles.
Tile can have any function defined.
Tile can have any variable to store data.
Can you guys come up with a better system that works better than mine?
The usual test case I do is:
[]
[] should become [][]
[]
[]
[] should become [][][]
[]
[][][] should become [][][][]
Assuming the game runs for a while.
Any suggestions would be more than welcome!
Maybe you could forget about pressures (since you are not really using them as pressures) and simply use a bool tryMove or something like that.
Each simulation step should be broken in two substeps:
First loop in tiles:
If space below is free, set tryMove to true, finish this tile.
If has tile above, set tryMove to true else set tryMove to false.
If any neighbor is trying to move, set tryMove to true.
Second loop in tiles:
If trying to move and space below is free, move tile down, set
tryMove to false, finish tile.
If trying to move and can move sideways (free space to left or
right) set neighbors tryMove as false, move it, set this tryMove as false, finish tile.
I think this should fix your issue.
If you have the resources to support it, I recommend a recursive function that tries pushing tiles left and right from above. If the function finds another tile below, it can try displacing that tile to either side. The best method would be to start stepping left and right, one tile at a time. If it keeps finding water tiles, then it keeps going. Eventually it will either run out of tiles to check (ends up at a wall) or will find a water tile with free space to move over. After multiple iterations, the water should push outward and make room for the higher water to fall down.
Let me reclarify the left then right nature of the recursion. Essentially, once the function makes it to the base level of the water, it should start choosing water tiles, alternating left and right. So it will first check the tile directly left, then directly right, then two left, then two right, etc. If it finds an air tile, it should do a displacement of the nearest water tile. If it finds something else (usually a wall) it should give up on that side. Once it's given up on both sides, you should consider other behaviors instead, such as the topmost water randomly traveling around over the surface.
If you really want the behavior to seem natural, I highly recommend a random variable deciding whether it checks left or right first. Otherwise you will probably end up with strangely regular recurring patterns.