Need Help in solving Binary Search - algorithm

I am trying to solve another Question
I have implemented the binary search function required to solve this problem but i am unable to return the correct value which would help me in solving this question.Here's my code.
Please help me in solving this question.
def BinarySearch(arr,low,high,search):
while(low<=high):
middle=(low+high)/2
int_mid=int(middle)
print(int_mid)
if arr[int_mid]==search:
return int_mid
elif arr[int_mid]>search:
low=int_mid+1
elif arr[int_mid]<search:
high=int_mid-1
return arr[int_mid]
tc=int(input())
while(tc>0):
size=int(input())
A=list(map(int,input().split()))
B=list(map(int,input().split()))
monkiness=[]
for i in range(len(A)):
for j in range(len(B)):
if (j>=i):
y=BinarySearch(B,0,len(B),B[j])
z=BinarySearch(A,0,len(A),A[i])
print(y,z)
if y>=z:
m=j-i
monkiness.append(m)
if len(monkiness)==0:
print(0)
else:
print(monkiness)
maxiumum=max(monkiness)
print(maxiumum)
tc-=1

You don't need binary search here ('here' means code you provided, not problem solution)
Even if you required binary search, BinarySearch is for non-decreasing array, but you have non-increasing array.
The goal is to find solution, that runs in less, than N^2 time, by exploiting the fact, that arrays are sorted.

Related

Algorithm pseudocode

I have the pseudocode:
Algorithm exists(A,n,x):
lo=0
hi=n-1
while hi>=lo:
mid=floor((hi+lo)/2):
if x>A[mid]:
lo=mid+1
else: if x<A[mid]:
hi=mid-1
else:
return True
return False
and the array:
A[0]=1, A[1]=5, A[2]=6, A[3]=10, A[4]=12, A[5]=16, A[6]=17, A[7]=43
Then I have to find what exists(A,4,17) return.
Then we have l0=0 and hi=n-1=4-1=3 then hi>l0.
We get that mid=floor((hi+lo)/2)=floor((3+0)/2)=1 (floor is rounding to 1?).
We see that x<A[1] because 4<5. Then I think the pseudocode return: hi=mid-1=1-1=0?
The code you have written, it is binary search pseudocode. Through binary search, you can search for a number in a sorted array.
In your code, your explanation is wrong. Let me explain why.
Your array: A[0]=1, A[1]=5, A[2]=6, A[3]=10, A[4]=12, A[5]=16, A[6]=17,A[7]=43
Then you want to found exists(A,4,17), according to your algorithm,
A resembles your array, n=4, x=17
So, according to this your explanation in the last line is wrong because after the first iteration the mid=1 and then it will execute if x>A[mid]: condition because,
17 > 5 //as x=17 and A[1]= 5

Huffman decoding (in Scala)

I'm trying to write an algorithm to perform Huffman decoding. I am doing it in Scala - it's an assignment for a Coursera course and I don't want to violate the honor code, so the below is pseudocode rather than Scala.
The algorithm I have written takes in a tree tree and a list of bits bits, and is supposed to return the message. However, when I try it on the provided tree, I get a NoSuchElementException (head of empty list). I can't see why.
I know that my code could be tidied up a bit - I'm still very new to functional programming so I've written it in a way that makes sense to me, rather than, probably, in the most compact way.
def decode(tree, bits) [returns a list of chars]: {
def dc(aTree, someBits, charList) [returns a list of chars]: {
if aTree is a leaf:
if someBits is empty: return char(leaf) + charList
else: dc(aTree, someBits, char(leaf) + charList)
else aTree is a fork:
if someBits.head is 0: dc(leftFork, someBits.tail, charList)
else someBits is 1: dc(rightFork, someBits.tail, charList)
}
dc(tree, bits, [empty list])
}
Thanks in advance for your help. It's my first time on StackOverflow, so I probably have some learning to do as to how best to use the site.
If I understand it correctly, you want to go through forks (with directions from bits) until you will find a leaf. Then you are adding leaf value to your char list and from this point you want to repeat steps.
If I am right, then you should pass original tree to your helper method, not a leftFork or rightFork, which are leafs now.
So it would be something like:
if aTree is a leaf:
if someBits is empty: return char(leaf) + charList
else: dc(tree, someBits, char(leaf) + charList)

Python 3.3 Sorting a tuple list with multiple keys

I'm having a bit of a problem (encountered during a Project Euler problem) in that I have a list of lists of tuples e.g.
[...
[(-119, 359), (668, -609), (-358, -494)],
[(440, 929), (968, 214), (760, -857)],
[(-700, 785), (838, 29), (-216, 411)],
[(-770, -458), (-325, -53), (-505, 633)],
...]
What I want to do is sort them by the tuple with the smallest first value, but if they are equal to then compare the second values and order by the smallest of these. I've been looking about and can't seem to find a way to do this. The only thing I have found is the old python 2.x version of sorted where it is given a cmp argument.
Any help would be much appreciated,
Regards,
Ybrad
Edit:
I just realised the above is worded slightly incorrectly. What I want to do is sort the tuples within each sub-list, not the list of lists as a whole.
You can very easily do that as:
a = [sorted(i) for i in a]
>>> print a
[[(-358, -494), (-119, 359), (668, -609)],
[(440, 929), (760, -857), (968, 214)],
[(-700, 785), (-216, 411), (838, 29)],
[(-770, -458), (-505, 633), (-325, -53)]]
For your second request, you can do it as:
a = [sorted(i, key=lambda i: (i[0], -i[1])) for i in a]

Depth-Limited Search Recursive Pseudocode

I'm looking at a pseudocode implementation of Depth-Limited Search, and I'm having trouble understanding it.
The pseudocode is:
Function Recursive-DLS(node, problem, limit)
cutoff-occurred? = false
if Goal-Test(problem, State[node]) then return node
else if Depth[node] = limit then return cutoff
else for each successor in Expand(node, problem) do
result = Recursive-DLS(successor, problem, limit-1)
if result = cutoff then cutoff-occurred? = true
else if result != failure then return result
if cutoff-occurred? then return cutoff else return failure
Im mainly having trouble understanding the reason for recurring the algo with limit-1 for every successor. Can someone run through this with me? Some graphical explanation would be nice haha.
I'm going to look at other sources in the meantime. Thanks for reading!
The pseudo-code appears to be wrong. (It's actually possible for the base case to never be encountered if the node depth/limit values skip eachother - being simultaneously increased and decreased in each recursive call.)
The recursive case was written with the limit - 1 so a base case can be reached (instead of "limit", think "remaining").
However, the base case for the limit is if Depth[node] = limit then return cutoff. Following David Chan's suggestion it should be if 0 = limit then return cutoff, which would agree with the limit - 1 in the recursive case.
Alternatively, just pass limit in the recursive case and leave the current base case alone.

substring search

I've recently been trying to investigate the various ways to do substring searches and have stumbled upon the following article http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_string_search_algorithm. I was wondering if there are any other common/efficient algorithms out there that anyone can suggest/show?
Thanks much
The most obvious would be Boyer-Moore or some variant such as Boyer-Moore-Horspool. For some situations, it's also worth considering Knuth-Morris-Pratt.
KMP algorithim is efficient in substring search if the text is small.
complexity O(n).
for easy understanding
http://jakeboxer.com/blog/2009/12/13/the-knuth-morris-pratt-algorithm-in-my-own-words/
In my opinion by far the most intuitave and easy to understand is Robin Karp Algorithm
Here is a simple python implementation
def computeHash(p):
return sum ([ value*10**index for (index,value) in enumerate(p[::-1]) ])
def getPosition(string,subString):
kh=computeHash(subString)
lk=len(subString)
ans=[]
for i in enumerate(string):
if len(string[i[0]:i[0]+lk])<lk:
break
else:
if computeHash(string[i[0]:i[0]+lk])==kh:
ans.append((i[0],i[0]+lk))
return ans
def main():
s="hello world" #string
ss="wor" #sub string
print getPosition(map(ord,s),map(ord,ss))
if __name__=="__main__":
main()

Resources