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

Saturday, February 23, 2019

Python: Strptime


strptime

String to datetime object = strptime
datetime object to other formats = strftime
Jun 1 2005 1:33PM is equals to %b %d %Y %I:%M%p
%b  - Month as locale’s abbreviated name(Jun)
%d   - Day of the month as a zero-padded decimal number(1)
%Y   - Year with century as a decimal number(2015)
%I   - Hour (12-hour clock) as a zero-padded decimal number(01)
%M  - Minute as a zero-padded decimal number(33)
%p   - Locale’s equivalent of either AM or PM(PM)
 Use slicing to remove unwanted characters if necessary.

Example :
>>> import time
>>> time.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
                 tm_hour=13, tm_min=33, tm_sec=0,
                 tm_wday=2, tm_yday=152, tm_isdst=-1)

Friday, February 15, 2019

Python : Simple CSV reader writer using Pandas

Sample CSV reader /Writer using pandas



import  pandas,os
p="/home/deepak/Python/testData/1.csv"

sheet=pandas.DataFrame( {"rollno":[1,2],"name":["a",'b']})
sheet.to_csv(p)

if(os.path.exists(p)):  
    Obj=pandas.read_csv(p)
    print(Obj.columns) #print all columns
    print(Obj['name'][1]) #Print 1 row 1 col value
    Obj.set_value(0,"name","deepak")
    Obj.to_csv(p)

Sunday, December 16, 2018

Python : Data Driven Automation Framework using JSON Loader

Python : Data Driven Automation Framework using JSON Loader



import json


class json_py():

    def __init__(self,jsonFilePath,**kwargs):

        self.d= self.__readJson(jsonFilePath)

        

    def get_values(self,testCaseName):

        result_dict=self.d[testCaseName][0]

        return(result_dict)

    

    def __readJson(self,sPath):

        try:

            with open(sPath,"r") as F:

                return(json.loads(F.read()))

        except FileNotFoundError:

            print("Please provide correct file path")

        except ValueError:

            print("JSON is invalid")


sPath='D:\\personal\\json_python_2.json'

j=json_py(sPath)


print(j.get_values("testcase3")["data2"])



OutPut:
['hi', 'deepak']

---------------------------------------------------------------------------------------
json_python_2.json

{
"testcase1":[{ "id":1, "data1":["hi","deepak"]}],
"testcase2":[{ "id":2, "data1":["data"]}],
"testcase3":[{ "id":3,
                "data1":["hi","deepak"],
                "data2":["hi","deepak"],
                "data3":[{"key":"value"}]

}]
}

Sunday, April 29, 2018

Python : Super() vs Self

Python : Super() vs Self vs Classname

All 3 can be differentiated wrt to usage inside th child class. 

General Idea:
  1. Assume Class A , having a method m1
  2. Class B  is child of Class A 
  3. Class B has methods m1 ,m2
  4. If you want to call parent method m1 (ie., A().m1()) inside m1,m2 in Class B and use self , it will call the already exsisting method m1() in the same Class B  .
  5. Hence we use super() so that you are specifying python to use parent method.


super()
1.  Used inside child constructor to call parent constructor
2.  Used inside overriding method to call the parent method

self
1. Used to call method and properties of the same class
2. Used to call methods and properties of parent class


className
1. Can be used to call properties and methods of parent class.
2. Parent class name needs to be hardcoded
3. "self" needs to be sent as an arguement.

1.Mainly used inside child constructor to call parent constructor.
https://www.digitalocean.com/community/tutorials/understanding-class-inheritance-in-python-3
class Bird():
    name=None
    def __init__(self,name):
        self.name=name
    def bird_name(self):
        return(self.name)
    def fly(self):
        return("True")

class non_fly(Bird):
    swim=None
    def __init__(self,name,swim):   #Constr overriding
        super().__init__(name)      #call parent constr

       #  Bird.__init__(self, name) 
        self.swim=swim
    def fly(self):                  #Method Overrdiing
        return("false")

peng=non_fly("peng",True)
print(peng.bird_name(),peng.fly(),peng.swim)#inherit

2. Used in overriding method to class the parent method

class a():
    def m(self):
        return("m")


class b(a):       
    def m(self):
        #print(self.m()) #error - infinite loop case as it means m() in class b.
        print(a.m(self)) # here class name is hardcoded and need to send "self"  
        print(super().m()) #BETTER OPTION
B=b()
B.m() 


O/P:
m

 

3. MRO

Ref:
Python - MRO(Method Resolution Order)
https://stackoverflow.com/questions/30041679/python-self-and-super-in-multiple-inheritance


class a():
    def x(self):
        return("a")  
class b():
    def x(self):
        return("b")
class c(a):
    def s(self):
        print(super().x(),self.x())  #a,b

class d(b,c):
    pass
d().s()

print(d.mro()) 
#(<class '__main__.d'>, <class '__main__.b'>, <class '__main__.c'>, <class '__main__.a'>, <class 'object'>)

Note :
1. d().s()
2. goes to s() in class c
3. super() = wrt current class ie., super() of class c = class a .Therefore "a"
4. self - check if 1st parent has mentioned method , if not it goes to next parent .There class b has method x. Therefore "b"

Saturday, March 17, 2018

Python : OOPS important Concepts

Python: OOPS important Concepts
static and class method
'''static method : 

1.cannot access any properties
2. Can have no parameters at all.
Class method: 
1) Similar to static method but can use class properties .
2) Must have a reference to a class object as the first parameter’’’
class stat_test():
    var="private" #properties
    def method(self):
        return ("normal method")  
    @staticmethod
    def static_method(self):
            return(self.var)    
    @classmethod
    def class_method(self):
           return(self.var)
            
print(stat_test().method())   
#print(stat_test.static_method()) #error
print(stat_test.class_method())
print("#========#Access Modifiers(Encapsulation) DUNDEE =======")
private: "__" at the beginning and at most “_” at end
protected: "_" at the beginning and at most “_” at end (Convention only)
Restricted": "__a__" at beginning and at end

E.g.: print ("adasdsa".__len__()) #__name__ = inbuilt functions
'''
class a:
    pubv="pub"
    _prov="pro"
    __priv="priv"   
    def __init__(self):
        pass
    def pubm(self):
        return(self.pubv)
    def _prom(self):
        return(self._prov)      
    def __prim(self):
        return(self.__priv)         
 
class b(a):
    def __init__(self):
        pass 
    def priv(self):
        return(self.__priv)    
    def prov(self):
        return(self._prov)              
    def prim(self):
        return(self.__privm())
    def prom(self):
        return(self._prom())
    def pubm(self):
        return(super().pubm())

A=a()       
print(A.pubv,A._prov)
#print(A.__priv) # Error
print(A.pubm(),A._prom())
#print(A.__prim()) # Error

B=b()
#print(B.priv()) # Error
print(B.prov())
#print(B.prim()) # error
print(B.prom())
print("#====Constructor/Method Overriding and Inheritance===")

#Note : Overloading does not exist in python , only overriding exist
class Bird():
    name=None
    def __init__(self,name):
        self.name=name
    def bird_name(self):
        return(self.name)
    def fly(self):
        return("True")

class non_fly(Bird):
    swim=None
    def __init__(self,name,swim):        #Constr overriding
        super().__init__(name)              #call parent constr
       #  Bird.__init__(self, name) 
        self.swim=swim
   def swim(self):
        print(self.bird_name(),self.swim) #Method inheritance
    def fly(self):                                                  #Method Overrdiing
        return("false")

peng=non_fly("peng",True)
print(peng.bird_name(),peng.fly(),peng.swim)#inheritance
#O/P: peng false True
print("#==========#polymorphism===================")
#Polymorphism (Duck Typing)
'''In a duck-typed language (if it looks like a duck and quacks like a duck, it's a duck)
If the object  have the methods, then execute  else it raises a run-time error.’’’
class Duck():
   def quack(self):
      print ("Duck Quack")

class Mallard():
    def quack(self):
        print ("Mallard Quack")

#Polymorphism
for i in [Duck(), Mallard()]:
   i.quack()
print("#=============Abstract Class ==========")
#( At least 1 method is abstract,entire class = abstract class)
from abc import ABC, abstractmethod
class Abstract(ABC):
    @abstractmethod
    def foo(self):
        pass

#a=Abstract()#uncomment below to raise exception 
print("#=========Diamond problem============")
class Duck():
   def quack(self):
      print ("Duck Quack")
class Mallard():
    def quack(self):
        print ("Mallard Quack")
class c(Duck,Mallard):
                  def c(self):
                                    super().quack()
print(c().c()) #O/p = Duck Quack (as Duck appears 1st)
print("#=========super vs self vs class name============")
super()
1.  Used inside child constructor to call parent constructor
2.  Used inside overriding method to call the parent method
self
1. Used to call method and properties of the same class
2. Used to call methods and properties of parent class
3. Cannot be used inside overriding constructor or method as it creates infinite loop.
className
1. Can be used to call properties and methods of parent class.
2. Parent class name needs to be hardcoded
3. "self" needs to be sent as an arguement.
print(#=========multiple inheritance============")
class a():
    x="1"
    def a(self):
        return("2")
class b():
    y="3"
    def b(self):
        return("4") 
class c(a,b):
    z="5"
    def c(self):
        print(self.x,self.y,self.z,self.a(),self.b())
C=c()
C.c()
print(C.x,C.y,C.a(),C.b())

Friday, November 24, 2017

Python : Pretty print JSON

Pretty print JSON 

 

import json
 

json_data = '["foo", {"bar":["baz", null, 1.0, 2]}]'
 parse = json.loads(json_data )
print json.dumps(parse , indent=4, sort_keys=True)







Result :  
 
[
    "foo",
    {
        "bar": [
            "baz",
            null,
            1.0,
            2
        ]
    }
]

Python : Important code snippets

Important code Snippets
==============Data and Time: ==============
import datetime
print (datetime.datetime.now().day) # Result : 11
==============sorting reverse in list==============
liste=[1,5,9,2,3]
liste.sort(key=None, reverse=False)
Method2
Print(liste[::-1]
==============remove duplicates in list==============
l=[1,5,5,9,"a","b"]
liste=list(set(l))
==============Regex==============
import re
if(re.search(“.*ant.*”,”antelope”)):     #search
   print(True)
print(re.sub(r”expr”,string))              #replace
print(len(re.findall(“expr”,string))      #count
==============locals()==============
def test():
    a = 1
    b = 2
    c= 3
    return locals()
s=test()
print(s) #o/p:
(a,1) ,(b,2),(c,3),
print (type(s)) #
result : dict
==============Ranged if Condition==============
r=300
if (r in range(200,210,1)):
    print (True)
else:
    print(False)
or
if(200<r<210):
==============Validate type ==============
if isinstance(d,dict):print("hi")
if(type(d)==dict) :print(“True”)
====Higher order  functions (function name as) ====
def a():
    print("hi")
def b(func):
    func()
b(a) #
result :hi
====Higher order class (function name as) ====
class deco :   
    def func1(self):
        print ("funct1") 
    def func2(self,var):
        print(var)
              
def some_func(obj):
    obj(deco)
def some_func2(obj,var):
    obj(deco,var) 
  
some_func(deco.func1) #
O/p funct1
some_func2(deco.func2,"33") 
#O/p: 33
==============Keyword Arguments in a Function==============
def a(a=5,b): #wrong - non keyword args follow keyword ie., b should come before a
    print(a,b)
def a(b,a=5): #Correct
    print(a,b)
a(b=3,a=1)    #Result - 31
a(1,2)        #Result - 12
a(a=4,4)     #Error - non Keyword argument should come before keyword argument

=========List and tuple Arbitrary Argument in Function==============

def a(*a):
    for i in a:
        print(i)
a([1,2,3])
a((1,2,3))

Result:
[1,2,3]
(1,2,3)
==============Create sequential lists in 1 line==============
x=list(range(51,60,2))     #[51, 53, 55, 57, 59]
==============Slicing techniques==============
a=list(range(1,5))           #[1,2,3,4]
print(a[::-1])                                    #[4,3,2,1]  -reverse
print(a[::2])                   #[1,3]
print(a[::-2])                                    #[3,1]
print(a[1:-1:1])              #[2,3]
print(a[1:-1:-1])             #[]
print(a[-1:1:-1)]             #[4,3]
==============List into sublist or 1D to 2D==============
a=list(range(1,5))           #[1,2,3,4]
res=[a[i:i+2] for i in range(0,len(a),2)] #[[1,2][3,4]]
method2
m=[[i for i in range(j,j+3)] for j in range(1,7,3)]
#m = [[1, 2, 3], [4, 5, 6]]
===========Transpose a matrix using list comprehensions==============
n=[[m[i][j] for i in range(0,len(m))] for j in range(0,len(m[0]))]
Zip Matrix Transpose
n=list(zip(*m))              #list(zip(m[0],m[1])
Zip Combine 2 lists
a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
Combine sublists in 1 List
m = [[1, 2, 3], [4, 5, 6]]
l=m[0]+m[1]                 #l=[1,2,3,4,5,6]
List values into string
method 1 :List into string in 1 line
   l  = [1,2,3,7]
    print ("".join([str(x) for x in l] )

method 2:
    l = [1,2,3,7]
    for i in l:
        data=data+i
    print(data)

==============Type Conversions==============
s="deepak"
s=set(list(tuple(s)))
==============Dictionary (Format similar to JSON)
d={'a':'1','b':1}                     #dictionary creation
print(d.keys() , d.values() ) #['a', 'b'][2,3]),
print( 'a' in d)                        #True (list,set,tuple,str)
print(d.items())                   #'a':'1','b':1
d[“key”]=””value”              #access individual val
==============Add 2 Dictionaries==============
Res={**d1,**d2}
==============Exchange 2 variables==============
a,b=b,a
Count occurrences in a list in 1 line using re
import re
l=[1,1,2,4,4,4]
s=set(l)
res=[ len(re.findall(str(i),str(l)))  for i in s]           # [2, 1, 3]
==============Fibnocci -0,1,1,2,3,5,8…==============
res=[0,1]
for i in range(0,5,1):
    res=res+[res[-2]+res[-1]]
print(res)
==============Unit test==============
 1.”test” suffixed for unittest class.
 2. import unittest and class under test
 3. To run untitestuse:
D:\>C:\Python34\python.exe -m unittest testfile.area_test.circle_area_test

import unittest
class area():
 def circle_area(self,r):
  return(3.14*r**2)

class area_test(unittest.TestCase):
 def circle_area_test(self):
  a=area()
  self.assertAlmostEqual(a.circle_area(0),1)
  self.assertAlmostEqual(a.circle_area(0),0)
  self.assertRaises(valueError,a.circle_area(0),0)