Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, November 12, 2016

It ebooks Rest Api

Itebooks which is one of the popular sources for programming books.

They have exposed couple of REST Apis as GET request.

One of it is send request to it based on the book id.

Below is the code to get the details of the book:


Sunday, September 25, 2016

Project Euler #8 - Largest Product in a series - Python

n = map(int, raw_input().split()) #To read the number of digits and 
                                  #k consecutive numbers
num = int(raw_input()) # To read the digit
#print n[1]
#print num
stri = str(num)
product = 0
for i in xrange(len(stri) - n[1] + 1):
        temp = 1
        k = i
        for j in range(n[1]):        
            temp = temp * int(stri[k])
            k = k + 1
           
        if(temp > product):
            product = temp
            #print product
print product  

Saturday, August 27, 2016

Longest Increasing Sequence using python


import sys
import copy

#Binary search
def binary(s, num):
#print "in binary s:"  + str(s)
#print "in binary num:" + str(num)
    l = len(s)
    mid = l/2
    #print "in binary s:" + str(s)
    #print "in binary num:" + str(num)
    #print "s[mid]:" + str(s[mid])
    if((l!=0) and  (l == 1)):
    if(s[mid] < num):
    return s[mid]

    if((l!=0) and (l != 1)):
   if ((s[mid] >= num) and (s[mid - 1 ] < num)):
       return s[mid - 1]
   elif ((s[mid] > num) and (s[mid - 1] > num)):
       return binary(s[:mid -1] , num)
   else:
       return binary(s[mid:], num)
     
 
 
t = int(raw_input())
for p in xrange(0,t):
    n = int(raw_input())
    arr = map(int, raw_input().split())
#maxlen in  worst case would be 1 and end element index is 0.
    maxlen = 1
    bestend = 0

    s = []
    LIS = []
    s.append(arr[bestend])
    LIS.append(s)
    #LIS[-1].append(s)
    #print s
    #print LIS

    #To get last elements of all lists
    #print max(LIS, key=len)[-1]
    # to get the last element of the max length in the list
     
 
    for i in xrange(1,n):
        #print "arr[i]:" + str(arr[i])
        #print "list end element to compare:" + str(max(LIS, key=len)[-1])
        if(arr[i] > max(LIS, key=len)[-1]):
         
            seq = copy.deepcopy(LIS)
         
            max(seq, key=len).append(arr[i])        

            LIS.append(max(seq, key=len))
            #print "post updated LIS:" + str(LIS)
         
         
     
        else:
         
            seq = copy.deepcopy(LIS)
            last_elem = [x[-1] for x in seq]
            val_greater_elem = binary(sorted(last_elem), arr[i])
            if val_greater_elem in last_elem:
                ind = last_elem.index(val_greater_elem)
                #print "Index of ele:" + str(ind)# to get index of the ele to append
                #print "seq ind to append:" + str(seq[ind][-1])
                seq[ind].append(arr[i])#replace element
                #print "updated seq:" + str(seq)
                #print "updated seq index:" + str(seq[ind])
                #print "Length of seq:" + str(len(seq[ind]))
                len_of_updated = len(seq[ind])
                k = [x for x in LIS if (len(x) == len_of_updated)]
                [LIS.remove(l) for l in k]
                #print "post discard LIS:" + str(LIS)
                LIS.append(seq[ind])
                #print "post updated LIS:" + str(LIS)
     
    print len(max(LIS, key=len))
    print "Final subseq:" + str(max(LIS, key=len))
 
     
stdin:
1
16
0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15            

Output:
6
Final subseq: [0 2 6 9 11 15]
    

Binary search to find largest smaller element than given value python

import sys
def binary(s, num):
    l = len(s)
    mid = l/2
    #print "in binary s:" + str(s)
    #print "in binary num:" + str(num)
    #print "s[mid]:" + str(s[mid])
    if((l!=0) and  (l == 1)):
     if(s[mid] < num):
     return s[mid]
        #else:
#return None
    if((l!=0) and (l != 1)):
    if ((s[mid] >= num) and (s[mid - 1 ] < num)):
        return s[mid - 1]
    elif ((s[mid] > num) and (s[mid - 1] > num)):
        return binary(s[:mid -1] , num)
    else:
        return binary(s[mid:], num)


lst = [8,0]

print binary(sorted(lst), 4)

Output:

0

Sunday, June 19, 2016

Artificial Intelligence using python

The below code is to reach a goal in a board game with robot at position with value 'r' and goal with value 'g' in the row* column board.

Below are the conventions for the code to solve the problem.


m - size of grid
grid - position of the board(in row * col)
g - goal position
r - robot current postion in the board


#!/bin/python
def find_m_position(grid):
for row in range(m):
for col in range(m):
if grid[row][col] == 'r':
return (row,col)

def find_p_postion(grid):
for row in range(m):
for col in range(m):
if grid[row][col] == 'g':
return (row, col)


def PathtoGoal(n,grid):
#print all the moves here
#pass
row_m, col_m = find_m_position(grid)
row_p, col_p = find_p_postion(grid)

while((row_m != row_p) and (col_m != col_p)):
diff_row = row_m - row_p
diff_col = col_m - col_p
if(diff_row < 0):
print "DOWN"
row_m = row_m + 1


else:
print "UP"
row_m = row_m - 1

if(diff_col > 0):
print "LEFT"
col_m = col_m - 1
else:
print "RIGHT"
col_m = col_m + 1


return None

m = input()

grid = []
for i in xrange(0, m):
grid.append(raw_input().strip())

#print grid

PathtoGoal(m,grid)



Sunday, March 6, 2016

Project Euler - Problem 2 - Sum of even Fibonaaci numbers

def euler2(n):

su = 0
lst = []
for i in xrange(1,n,3):
    if(i == 1):
        res = 2
    elif (i == 4):
        res = 8
    else:
        res = 4* lst[-1]+ lst[-2]


    if(res < n):
        lst.append(res)

    else:
        break


print sum(lst)

Count the Squares between any two numbers

import math

def get_squares(n1, n2): #Given n1, n2 are the numbers both inclusive

       print int(math.floor(math.sqrt(n2)) - math.ceil(math.sqrt(n1))) + 1

Saturday, January 23, 2016

Print triangle shape using python


k = 5
for j in range(5 ,0, -1):
 if(j < k):
  print ((" " * (k - j)) + ("*" + " ") * (j))
 else:
  print  ("*" + " ") * (j)
#print "Done with descending"
for x in range(1, 6):

 if(x < k):
  print ((" " * (k - x - 1)) + ("*" + " ") * (x + 1))

Saturday, November 14, 2015

String contains in python

s = "A nice string search 234"
res = ""
items = ['a', '4', '6']
for x in items:
#print x
if s.find(x) == -1:
res = x + " is not in given string"
print  res
else:
res = x + " is in given string"
print res

Wednesday, June 17, 2015

Remove punctation from the text - Python


import re
import string
def removePunctuation(text):
   
    #converts to lowercase
    text1 = text.lower()
   
    #removes punctuation
    #punctation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
    text2 =  re.sub('[%s]' % string.punctuation, ' ' ,text1)

    #removes leading and trailing spaces
    text3 = text2.strip()
    return text3


   

print removePunctuation("'The best investments today,'")
print removePunctuation("Misery in Paradise;")

Output:

the best investments today
misery in paradise

Monday, June 15, 2015

Program to find two largest numbers using Python

nums = [10, 90, 80, 60, 50]
maxone = 0
maxtwo = 0
for x in nums:
if(maxone < x):
maxtwo = maxone
maxone = x

elif (maxtwo < x):
maxtwo = x

print "First two largest numbers"
print "First largest number:", maxone
print "First largest number:", maxtwo


output:

First two largest numbers
First largest number: 90
First largest number: 80

Friday, June 12, 2015

Conversion of decimal to hexadecimal, binary and octal in Python

#num= int(input("Enter a decimal number:))
num = 15
print "Decimal value of given number:", num

print "Octal value of", num, ":",oct(num)
print "Binary value of", num, ":",bin(num)
print "Hexadecimal value of", num, ":",hex(num)


Output:

Decimal value of given number: 15
Octal value of 15 : 017
Binary value of 15 : 0b1111
Hexadecimal value of 15 : 0xf

To interchange key value pairs of a dictionary object in Python

dt = {'a': '1', 'b' : '2', 'c': '3', 'd': '4'}
print "Original dictionary:", dt
dt1 = {}
for (x, y) in dt.iteritems():
(x,y) = (y,x)
dt1.update(dict([(x,y)]))
print "After interchanging key value pairs:", dt1

Output:

Original dictionary: {'a': '1', 'c': '3', 'b': '2', 'd': '4'}
After interchanging key value pairs: {'1': 'a', '3': 'c', '2': 'b', '4': 'd'}

Wednesday, June 10, 2015

Sorting a list with out sort/sorted functions - Python

lst = [1,0,4,5,6,7,8,0,0,0]

print(lst)
cou = len(lst)
for i in range(cou):
    for j in range(1, cou-i):
       #descending
        """if lst[j] > lst[j-1]:
            (lst[j-1], lst[j]) = (lst[j], lst[j-1])"""
        #ascending  
        if lst[j] < lst[j-1]:
            (lst[j-1], lst[j]) = (lst[j], lst[j-1])
print(lst)

Reverse each word in a sentence - Python

# your code goes here

st = "This is awesome!"

st1 = st.split(" ")
st2 = ''
st3 = []

print st1

for y in st1:
#print y
ls = len(y)
for x in range(len(y)):
st2 = st2 + y[ls - 1 -x]
st2 = st2 + ' '
st3.append(st2)
print ' '.join(st3)

Reverse a sentence in python

st = "This is awesome!"
st1 = ''
ls = len(st)
for x in range(len(st)):
st1 = st1 + st[ls - 1- x]
print st1

Reverse a string - Python

st = "awesome!"
st1 = ''
ls = len(st)
for x in range(len(st)):
st1 = st1 + st[ls - 1- x]
print st1

Length of a string with out len() function - Python

st = " This is awesome!"
count = 0

for x in st:
count = count + 1
print count
if(len(st) == count):
print "it works!"

Tuesday, October 7, 2014

Regular expressions with Python

This is post on getting and writing programs with regular expressions using python as programming language.

There would be many theoretical intro of why do we use regualar expressions. In simple, regex are used for parsing data either in search engine or web scraping.

Regular expressions: The following line of code is the syntax of regex in python.
Regexp<name> = regexp.search()

Before getting into the lines of code let's have a glance at the patterns.

Quick patterns:
[abc]
A single character of: a, b, or c
[^abc]
Any single character except: a, b, or c
[a-z]
Any single character in the range a-z
[a-zA-Z]
Any single character in the range a-z or A-Z
^
Start of line
$
End of line
\A
Start of string
\z
End of string
.
Any single character
\s
Any whitespace character
\S
Any non-whitespace character
\d
Any digit
\D
Any non-digit
\w
Any word character (letter, number, underscore)
\W
Any non-word character
\b
Any word boundary


(…)
Capture everything enclosed
(a|b)
a or b
a?
Zero or one of a
a*
Zero or more of a
a+
One or more of a
a{3}
Exactly 3 of a
a{3,}
3 or more of a
a{3,6}
Between 3 and 6 of a
a{ ,6}
Not more than 6 of a







For any pattern  :

? – A regex followed by ? implies zero or one of the occurrence
*-   A regex followed by *implies Zero or more of the occurrence (Used for optional )
+ - A regex followed by + implies one or more occurrence
{x, y} – A regex with boundaries repeat itself in between x and y
{x, }  - A regex with lower bound is >/ x
{, y} – A regex wit upper bound  is  </ y
{x} – A regex with exact x times

Using # is a comment
Using \# in a regexp matches for the character #.

. : Matches any character except \n
\. : Matches only dot

Special case in escape character:
For the regexp [-a-zA-Z]: It considers hypen(–) as a character and looks for it.


With Python:

R with regular expressions in python:

Using r ‘regexp’ turns off backslash impact of python in the expression

Re library:

To work with regular expressions in python we need to import ‘re’ library into our code and is as below:
import re

If a regular expression looks like this:

Pattern = r’^[A-Z][a-z]{2}\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$’

It might be difficult to revisit the code and to debug this. Python avoids this with multiline expression using VERBOSE mode.

Pattern = r’’’
               ^
                [A-Z][a-z]{2}
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
$
               ‘’’


Exp = re.compile(pattern, re.VERBOSE) or
Exp = re.compile(pattern, re.X)

Simple example code for Regular expression


import sys
import re

address_pattern = r'''
^
(?P<Address1>P\.*O\.*\s*(BOX|Box|box)\s\d{1,5}) # address1 field

(?P<City>\s*\w*\W*\s*\w*\W*\s*\w*\W*\s*) # text between address and zip code

$
'''

address_reg_exp = re.compile(address_pattern, re.VERBOSE)

text = "PO Box 1055 Jefferson City, MO 65102"


match = address_reg_exp.search(text)

g = match.groups()
if match:
print match.group('Address1')
print match.group('City')