Search This Blog

Tuesday, February 11, 2014

To get maximum number without using if else

__author__ = 'nitin'

def get_max(a,b):
    c=a-b
    k=c>>31 & 0x1
    max_value=a-k*c
    return max_value

print get_max(1100,200)

The idea is to check if the value of c is negative. In virtually all modern computers, numbers are stored in a format called two's complement in which the highest bit of the number is 0 if the number is positive and 1 if the number is negative. Moreover, most ints are 32 bits. (c >> 31) shifts the number down 31 bits, leaving the highest bit of the number in the spot for the lowest bit. The next step of taking this number and ANDing it with 1 (whose binary representation is 0 everywhere except the last bit) erases all the higher bits and just gives you the lowest bit. Since the lowest bit of c >> 31 is the highest bit of c, this reads the highest bit of c as either 0 or 1. Since the highest bit is 1 iff c is 1, this is a way of checking whether c is negative (1) or positive (0). Combining this reasoning with the above, k is 1 if a < b and is 0 otherwise.

Program to find element in a sorted matrix

__author__ = 'nitin'

def find_elem_sorted_matrix(mat,M,N,elem):
    row=0
    col=N-1
    while row=0:
        if mat[row][col]==elem:
            return True
        elif mat[row][col]>elem:
            col=col-1
        else:
            row=row+1
    return False

amatrix=[[3,5,8],[6,7,10],[9,11,12]]
rows=len(amatrix)
cols=len(amatrix[0])
print find_elem_sorted_matrix(amatrix,rows,cols,8)

My Profile

My photo
can be reached at 09916017317