diff --git a/python_DS/README.md b/python_DS/README.md new file mode 100644 index 00000000000..586550f38c0 --- /dev/null +++ b/python_DS/README.md @@ -0,0 +1,27 @@ +HASHING- +The hash() method returns the hash value of an object if it has one. + +* Hash values are just integers which are used to compare dictionary keys during a dictionary lookup quickly. + +* Internally, hash() method calls __hash__() method of an object which are set by default for any object. We'll look at this later. + +* The syntax of hash() method is: + hash(object) + +* How hash() works for custom objects? + +* hash() method internally calls __hash__() method. So, any objects can override the __hash__() for custom hash values. + +* But for correct hash implementation, __hash__() should always return an integer. And, both __eq__() and __hash__() methods have to be implemented. + +BINARY SEARCH- +* Search a sorted array by repeatedly dividing the search interval in half. + +* Begin with an interval covering the whole array. + +* If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. + +* Otherwise narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. + + + diff --git a/python_DS/binary_search.py b/python_DS/binary_search.py new file mode 100644 index 00000000000..cdbf3c81a20 --- /dev/null +++ b/python_DS/binary_search.py @@ -0,0 +1,40 @@ +# Python Program for binary search. + +# Returns index of x in arr if present, else -1 +def binarySearch (arr, l, r, x): + + # Check base case + if r >= l: + + mid = l + (r - l)/2 + + # If element is present at the middle itself + if arr[mid] == x: + return mid + + # If element is smaller than mid, then it + # can only be present in left subarray + elif arr[mid] > x: + return binarySearch(arr, l, mid-1, x) + + # Else the element can only be present + # in right subarray + else: + return binarySearch(arr, mid+1, r, x) + + else: + # Element is not present in the array + return -1 + + # Test array +arr = [ 20, 30, 40, 10, 50 ] +x = 10 + +# Function call +result = binarySearch(arr, 0, len(arr)-1, x) + +if result != -1: + print "Element is present at index %d" % result +else: + print "Element is not present in array" + diff --git a/python_DS/hash.py b/python_DS/hash.py new file mode 100644 index 00000000000..b466fc0cc62 --- /dev/null +++ b/python_DS/hash.py @@ -0,0 +1,15 @@ +#example of hashfunction +class Person: + def __init__(self, age, name): + self.age = age + self.name = name + + def __eq__(self, other): + return self.age == other.age and self.name == other.name + + def __hash__(self): + print('The hash is:') + return hash((self.age, self.name)) + +person = Person(23, 'Adam') +print(hash(person))