Friday, October 11, 2019

Python Crash Basic Course

1. Installation

Step 1: https://www.python.org/  -->Download-->Install it

2. Numbers
>>> 2+6
8
>>> 3+4
7
>>> 3*20
60
>>> 12/4
3.0
>>> 8+2*10
28
>>> (8+2)*10
100
>>> 18/4
4.5
>>> 18%2
0
>>> 18%4
2
>>> 5*5*5
125
>>> 5**5
3125
>>> 5**3
125

Variables:
>>> tuna=5
>>> 20+tuna
25
>>> bacon=18
>>> bacon/tuna
3.6

3.Strings
>>> ' ' or " "
' '
>>> "CCR is a credit card project"
'CCR is a credit card project'
>>> 'ccr is a credit project'
'ccr is a credit project'
>>> 'i don't think she is 18'
  File "", line 1
    'i don't think she is 18'
           ^
SyntaxError: invalid syntax
>>> "i don't think she is 18"
"i don't think she is 18"
>>> "Duntbi "hrllo" ok"
  File "", line 1
    "Duntbi "hrllo" ok"
                 ^
SyntaxError: invalid syntax
>>> 'Duntbi "hrllo" ok'
'Duntbi "hrllo" ok'
>>> firstName="Bucky"
>>> firstName+"Roberts"
'BuckyRoberts'
>>> firstName+'Roberts'
'BuckyRoberts'
>>> firstName+'Robert'
'BuckyRobert'
>>> firstName*3
'BuckyBuckyBucky'
>>> pritn('c:\desktop\nnew one')
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'pritn' is not defined
>>> pritn("c:\desktop\nnew one")
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'pritn' is not defined
>>> 'i don\'t this credit'
"i don't this credit"
>>> "i don\'t this credit"
"i don't this credit"
>>> "i don\"t this credit"
'i don"t this credit'
>>> print('hello')
hello
>>> print('c:\deskto/n newline')
c:\deskto/n newline
>>> print('c:\desktop \n newline')
c:\desktop
 newline
>>> print('c:\desktop\n newline')
c:\desktop
 newline
>>> print(r'c:\desktop\n newline')
c:\desktop\n newline


4.Slicing the String

>>> user='tune worker'
>>> user[0]
't'
>>> user[5]
'w'
>>> user[-1]
'r'
>>> user[2:7]
'ne wo'
>>> user[-3]
'k'
>>> user[:7]
'tune wo'
>>> user[:]
'tune worker'
>>> print('decide')
decide
>>> len("tune")
4
>>> len(user)
11

5.List
players=[29.54,56,45,67]
players[2]
players[2]=88
players+[91,92,93] -->not permanant
players.append(20)
players[:2]=[0.0]
players[:2]=[]
players[:]
6.pycharm download
https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows&code=PCC

7.if elif else
age=27
if age<21: br="">    print('No beers for you')
name="Lucy"
if name is "Bucky":
    print("Hi Bucky")
elif name is "Lilly":
    print("Hi Lilly")
else:
    print("please signup the correct name")
please signup the correct name
foods =['bacon','tuna','hari','beef','oil']
for f in foods:
    print(f)
    print(len(f))
bacon
5
tuna
4
hari
4
beef
4
oil
3
8.for,range while
for f in foods[:2]:
    print(f)
    print(len(f))
for x in range(10):
    print(x)
for x in range(5,12):
    print(x)
for x in range(5,40,5):
    print(x)

b=5
while b
<10: br="">    print("hi")

    b+=1

9.break and continue

#break and continuemagicNum=26for n in range(101):
    if n is magicNum:
        print(n,'this is magic number')
        break    else:
        print(n)
26 this is magic number

num=[2,5,12,13,17]
for n in range(1,20):
    if n is num:
        continue    print(n)


10.Functions and Return values,Default arguments:

def beg():
    print('beg,function all')
beg()
beg()
beg()

beg,function all
beg,function all
beg,function all

def bitcoin_to_us(btc):
    amount=btc*527    print(amount)
bitcoin_to_us(3.85)
bitcoin_to_us(1.25)

2028.95
658.75

def allow_dating_age(myage):
    girl_age=myage/2+7    return girl_age
bourn=allow_dating_age(33)
print(bourn,"or elder")

23.5 or elder

def get_gender(sex='Unknown'):
    if sex is 'm':
        sex='male'    elif sex is 'f':
        sex='female'    print(sex)

get_gender('m')
get_gender('f')
get_gender()

male
female
Unknown

#Keyword argumentsdef dumb(name='Nethra',action='at',item='time'):
    print(name,action,item)
dumb()
dumb('San','fix','cool')
dumb(item='awesome')

Nethra at time
San fix cool
Nethra at awesome

#Flexible number of Argumentsdef add_num(*args):
    total=0    for a in args:
        total+=a
    print(total)

add_num(3)
add_num(3,32)
add_num(3,43,5345.22)

 3
35
5391.22

#Unpacking argsdef health_cal(age,apple_ate,cig):
    answer=(100-age)+(apple_ate*3.5)-(cig*2)
    print(answer)
bucking_date=[27,20,0]
health_cal(bucking_date[0],bucking_date[1],bucking_date[2])
health_cal(*bucking_date)
143.0 143.0
#Setgroceries={'alva','lattu','orange','apple'}
print(groceries)
if 'apple' in groceries:
    print('Your item is matched')
else:
    print('please try again')
{'lattu', 'alva', 'orange', 'apple'} Your item is matched Dictionaries
classmates={'A':'apple','B':'ball','c':'carot'}
print(classmates)
print(classmates['A'])
for k,v in classmates.items():
    print(k,v)
apple A apple B ball c carot Module:
import tuna
tuna.fish()
import random
x=random.randrange
print(x)
#Modulesdef fish():
    print('I am tuna fish')
Reading and Writing Files
fw=open('sample.txt','w')
fw.write("Hardwork should never faile\n")
fw.write("truth will never loose")
fw.close()

fr=open('sample.txt','r')
text=fr.read()
print(text)
fr.close()
Hardwork should never faile truth will never loose Read the images:
import urllib.request
import random
def def_img(url):
    name=random.randrange(1,1000)
    full_img=str(name)+'jpg'    urllib.request.urlretrieve(url,full_name)

def_img("https://www.youtube.com/watch?v=WJbu2Ib3ozE")
Download the file from browser
from urllib import request
goog_url="https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv"def download_stock_date(csv_url):
    response=request.urlopen(csv_url)
    csv=response.read()
    csv_str=str(csv)
    lines=csv_str.split("\\n")
    print(lines)
    dest_url=r'C:\\Users\\Nethra\\PycharmProjects\\PythonExercise\\goog.csv'    fx=open(dest_url,"w")
    for line in lines:
        print(line)


lambda function
lambda arguments:expression

 lambda x,y:x+y

 map:

map(function,sequence)

 a=[1,2,3,4]

def square(x)

   return x*x

 map(square,a)

in python 3 ,it will be returned to the iterator

so, list(map(square,a)

 map(lambda x:x*x,a)

 b=[1,1,1,1]

 tuple(map(lambda x,y:x+y,a,b))

Regular expression:

"^python"

"com$"

. ->matches single character

[^1-9]

'x*'->zero or more occurance

'x+'-> one or more occurance

'x?'-> zero or one occurence

'x{2}'->exactl 2 occurance

'x{5,}'=5 or more occurance

'x{5,8}'-> between 5 and 8

a|b

()

\s ->matcher the space

\S-> matcher the non white space

\d

\D


Ex:

str1='my name is alice'

str1.replace("alice","john")

str2="main street broad road"

str.replace("road","rd")

RE function:

match
search
final
replace
sub 


import replace
line="peg:cat i love cats"
#match=re.match(pattern,string,)
match=re.match(r"pet:\w\w\w",line)
match.group(0)
match=re.search(r"pet:\w\w\w",line)
match
match.group(0)
match is looking the beginning the string
search is looking the entire string in which taking first match
findall-gloable search

line="pet:cat i love cats pet:cow i line"

find=re.findall(r"pet:\w\w\w",line)

s=re.split(r"pet:\w\w\w",line)

svar=re.sub

str1="john@abc.com and alice@pqr.com"

var=re.sub(r"@\w+","@xyz",str1)



Looping with Index:

color=['red','blue','yellow']

for i in color:

  print(i)

for i in range(len(color))

  print(i,color[i])


for i,j in enumerate(color,1)

  print(i,j)

 negative with looping index:

list1=[1,2,3,4]

list[-3]====>list[2]

list1.insert(-3,10)

list1[-3:-1]

del list1[-1]


List vs Dictionary:

list-linear datastructure

dictionary-associate datastructure

list2=[2,3,4,"hello"]

list1[3]

dict1={1:'one',2:'two',3:'three'}

dict1[2]

String Functions
>>> str1="hello welcome to amuls acadamy"
>>> str1.capitalize()
'Hello welcome to amuls acadamy'
>>> str2="Welcome to HCL"

>>> str2.capitalize()
'Welcome to hcl'

>>> str1="""johny johny yes papa
... eating sugar no papa
... telling lie no papa
... opn your mouth haha"""

>>> st1.count('no')
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'st1' is not defined


>>> st1.count("no")
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'st1' is not defined


>>> str1="google.com"
>>> str1.endswith('com')
True

>>> str1.endswith('m')
True

>>> str1.endswith('org')
False

>>> str1="amuls academy"
>>> str1
'amuls academy'
>>> str1.find('y')

>>> str1.find('aca')

>>> str1.find('ca')

>>> len(str1)

>>> str1.split()
['amuls', 'academy']
>>> str2="Hello welcom to amuls Academy"
>>> str2.split()
['Hello', 'welcom', 'to', 'amuls', 'Academy']
>>> str2.split('o')
['Hell', ' welc', 'm t', ' amuls Academy']

>>> str2.title()
'Hello Welcom To Amuls Academy'

>>> str2='WELCOME'
>>> str2.lower()
'welcome'
>>> str2.islower()
False
>>> str2
'WELCOME'

>>> str1.islower()
False
>>> str1="amuls academy"
>>> str1.islower()
True
>>> str1.upper()
'AMULS ACADEMY'
>>> str2
'WELCOME'
>>> str2.isupper()
True
>>> str3="Amuls"
>>> str3.upper()
'AMULS'
>>> str1="hello WElcme to AMULS academy"
>>> str1.swapcase()
'HELLO weLCME TO amuls ACADEMY'

>>> str1="hello wlcome nish"
>>> str1.replace('nisha','amuls')
'hello wlcome nish'
>>> str1.replace('nish','amuls')
'hello wlcome amuls'
>>> str1.replace('o','r')
'hellr wlcrme nish'
>>> str1.isdigit()
False
>>> str2='123g'
>>> str2.isdigit()
False
>>> str3='1234567'
>>> str3.isdigit()
True
>>> str3.isalpha()
False
>>> str2.isalpha()
False
>>> str1.isalpha()
False
>>> str4="hello"
>>> str4.isalpha()
True

>>> str1='aaaaaaaahelloaaaaaaa'
>>> str1.strip('a')
'hello'
>>> str1='!!!!!!!!hello!!!!!!!'
>>> str1.lstrip('!')
'hello!!!!!!!'
>>> str1.rstrip('!')
'!!!!!!!!hello'
>>>

Dictionaries:

>>> temp={}
>>> temp['sun']=33.4
>>> temp['mon']=45
>>> temp['tue']=30
>>> temp
{'sun': 33.4, 'mon': 45, 'tue': 30}
>>> mail_address={'amul':'amul@gmail.com','ram':'ram@gmail.com'}
>>> mail_address
{'amul': 'amul@gmail.com', 'ram': 'ram@gmail.com'}
>>> mail_address.keys()
dict_keys(['amul', 'ram'])
>>> mail_address.values()
dict_values(['amul@gmail.com', 'ram@gmail.com'])
>>> mail_address['amul']
'amul@gmail.com'


>>> dict()
{}
>>> num={1:'one',2:'two',3:'three'}
>>> numbers=dict(num)
>>> numbers
{1: 'one', 2: 'two', 3: 'three'}
>>> len(numbers)
3
>>> del num[2]
>>> num
{1: 'one', 3: 'three'}
>>> numbers
{1: 'one', 2: 'two', 3: 'three'}
>>> 1 in num
True
>>> 2 in num
False

>>> my_dict={1:"apple",2:'ball',3:"cat"}
>>> my_dict
{1: 'apple', 2: 'ball', 3: 'cat'}
>>> my_dict={}
>>> my_dict[1]="apple"
>>> my_dict[2]="bat"
>>> my_dict[3]="cat"
>>> my_dict
{1: 'apple', 2: 'bat', 3: 'cat'}
>>> d=dict([(1,"apple"),(2,"ball")])
>>> d
{1: 'apple', 2: 'ball'}
>>> a=[1,2,3,4]
>>> b=["apple","ball","cat","dog"]
>>> my_dict={}
>>> for i in range(len(a)):
...     my_dict[a[i]]=b[i]
...
>>> my_dict
{1: 'apple', 2: 'ball', 3: 'cat', 4: 'dog'}
>>> my_dict.keys()
dict_keys([1, 2, 3, 4])
>>> my_dict.values()
dict_values(['apple', 'ball', 'cat', 'dog'])
>>> my_dict[3]
'cat'
>>> my_dict["apple"]
Traceback (most recent call last):
  File "", line 1, in
KeyError: 'apple'
>>> my_dict.get(1)
'apple'
>>> my_dict.get("apple")
>>> my_dict
{1: 'apple', 2: 'ball', 3: 'cat', 4: 'dog'}
>>> my_dict.get(5)
>>> my_dict[5]
Traceback (most recent call last):
  File "", line 1, in
KeyError: 5
>>> my_dict[4]="dog"
>>> my_dict
{1: 'apple', 2: 'ball', 3: 'cat', 4: 'dog'}
>>> my_dict[2]="bat"
>>> len(my_dict)
4
>>> my_dict
{1: 'apple', 2: 'bat', 3: 'cat', 4: 'dog'}
>>>


>>> #fromkeys(iterable,value)
...
>>> list1=[1,2,3,4]
>>> dict.fromkeys(list1)
{1: None, 2: None, 3: None, 4: None}
>>> {}.fromkeys(range(1,7),10)
{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}
>>>

>>> students
{'john': 20, 'ria': 21, 'ann': 22, 'anable': None}
>>> students.setdefault('roo',10)
10
>>> students
{'john': 20, 'ria': 21, 'ann': 22, 'anable': None, 'roo': 10}

>>> #Dictionary.update(dictionary)
...
>>> dict1={1:"a",2:"b"}
>>> list1=[3,"c"]
>>> dict1.update([list1])
>>> dict1
{1: 'a', 2: 'b', 3: 'c'}
>>> dict1.update(x=3,y=2,z=4)
>>> dict1
{1: 'a', 2: 'b', 3: 'c', 'x': 3, 'y': 2, 'z': 4}
>>>

>>> my_dict={1:"a",2:"b",3:"c",4:"d"}
>>> del my_dict[2]
>>> my_dict
{1: 'a', 3: 'c', 4: 'd'}
>>> my_dict.pop(1)
'a'
>>> my_dict
{3: 'c', 4: 'd'}
>>> my_dict.clear()
>>> my_dict
{}
>>> del my_dict
>>> my_dict
Traceback (most recent call last):
  File "", line 1, in
NameError: name 'my_dict' is not defined
>>>

File Handling
>>> #open(filename,mode)

>>> text_file=open("text.txt",'w')
>>> text_file.write("hello file")
10
>>> text_file.close()
>>> text_file=open("text.txt","a")
>>> text_file.write("welcome to amuls acadamy")
24
>>> text_file.close()
>>> text_file=open("text.txt","r")
>>> print(text_file.read())
hello filewelcome to amuls acadamy
>>> text_file.close()

Renaming and Deleting the file

>>> text_file.close()
>>> import os
>>> os.rename("text.txt","new_file.txt")
>>> os.getcwd()
'C:\\Users\\Nethra'
>>> os.remove("new_file.txt")

Managing Directory:
>>> import os
>>> os.mkdir("c:\\Users\\Nethra\\Desktop\\new")
>>> os.getcwd()
'C:\\Users\\Nethra'
>>> os.chdir("c:\\Users\\Nethra\\Desktop\\new")
>>> os.getcwd()
'c:\\Users\\Nethra\\Desktop\\new'
>>> os.mkdir('amul')
>>> os.listdir()
['amul']
>>> os.listdir("c:\\")
['$Recycle.Bin', '$WINDOWS.~BT', 'Config.Msi', 'Documents and Settings', 'hadoop', 'hiberfil.sys', 'hp', 'Intel', 'pagefile.sys', 'PerfLogs', 'Program Files', 'Program Files (x86)', 'ProgramData', 'Recovery', 'swapfile.sys', 'SWSetup', 'System Volume Information', 'SYSTEM.SAV', 'tmp', 'Users', 'Windows']
>>> os.rmdir("amul")

Exception Handling

>>> raise ValueError(4)
Traceback (most recent call last):
  File "", line 1, in
ValueError: 4
>>> raise NameError
Traceback (most recent call last):

>>> try:
...     num=int(input("Enter a number"))
...     if num<=0:
...        raise ValueError("That is not positive number")
... except ValueError as error:
...     print("error")
...
Enter a number -2
error
>>> import math
>>> num=int(input("input:"))
input:104
>>> try:
...    result=math.factorial(num)
...    print(result)
... finally:
...    print("goodbye!")
...
10299016745145627623848583864765044283053772454999072182325491776887871732475287174542709871683888003235965704141638377695179741979175588724736000000000000000000000000
goodbye!

Class and Objects

>>> def display(name):
...   print("hello",name)
...   return
...
>>> display("sam")
hello sam
>>> display("amul")
hello amul
>>> #class and objects
...
>>> class person:
...   pass
...
>>> #main
... p=person()
>>> print(p)
<__main__ .person="" 0x02852bb0="" at="" object="">

Methods:

>>> class person:
...    def __init__(self,name):
...        self.name=name
...    def display(self):
...       print("hello",self.name)
...
>>> person("amul").display()
hello amul

Instance variables
The variable belongs to the object 
Class variable belongs to the class

Inheritance

>>> class animal:
...   def eating(self):
...     print("eating")
...
>>> class dog(animal):
...   def display(self):
...     print("ok")
...
>>> d=dog()
>>> d.eating()
eating
>>> d.display()
ok


Multilevel inheritance:

>>> class person:
...   def display(self):
...     print("hello,this is class person")
...
>>> class employee(person):
...    def printing(self):
...       print("hello,this is derived class employee")
...
>>> class programmer(employee):
...    def show(self):
...      print("hello, this is another derived class programmer")

>>> p1=programmer()
>>> p1.display()
hello,this is class person
>>> p1.printing()
hello,this is derived class employee
>>> p1.show()
hello, this is another derived class programmer

Multiple Inheritance:
>>> class land_animal:
...   def printing(self):
...      print("this animal lives on land")
...
>>> class water_animal:
...    def display(self):
...      print("this animal lives in water")
...
>>> class frog(land_animal,water_animal):
...   pass
...
>>> f1=frog()
>>> f1.printing()
this animal lives on land
>>>
>>> f1.display()
this animal lives in water

Method overriding:
>>> class A:
...   def display(self):
...    print("methid belongs to class A")
...
>>> class B(A):
...   def display(self):
...     print("method belongs to class B")
...
>>> b1=B()
>>> b1.display()
method belongs to class B
>>>

Encapsulation:
To prevent the data modification accidently
Private
Public

>>> class car:
...   def __int__(self):
...    self._updatessoftware()
...   def derive(self):
...    print("driving")
...   def __updatessoftware(self):
...     print("updating software")
...
>>> b=car()
>>> b.derive()
driving
>>> b.__updatessoftware()
Traceback (most recent call last):
  File "", line 1, in
AttributeError: 'car' object has no attribute '__updatessoftware'

Private variable

>> class car:
...   __maxspeed=0
...   __name=""
...   def __init__(self):
...     self.__maxspeed=200
...     self.__name="supercar"
...   def drive(self):
...      print("driving")
...      print(self.__maxspeed)
...   #def setspeed(self,speed):
...     # self.__maxspeed=speed
...    #print(self.__maxspeed)
...
>>> redcar=car()
>>> redcar.drive()
driving
200
>>> redcar.__maxspeed=100
>>> redcar.drive()
driving
200
>>>

Ploymorphism

>>> class dog:
...   def sound(self):
...     print("bow bow")
...
>>> class cat:
...    def sound(self):
...      print("meow")
...
>>> def makesound(animaltype):
...   animaltype.sound()
...
>>> catobj=cat()
>>> dogobj=dog()
>>> makesound(catobj)
meow
>>> makesound(dogobj)
bow bow

Methods:
>>> import time
>>> time.time()
1571593375.0245504
>>> time.localtime(time.time())
time.struct_time(tm_year=2019, tm_mon=10, tm_mday=20, tm_hour=23, tm_min=13, tm_sec=33, tm_wday=6, tm_yday=293, tm_isdst=0)
>>> time.asctime()
'Sun Oct 20 23:16:50 2019'
>>>

>>> tuple1 = (1993,6,8,9,20,0,0,0)
>>> time.mktime(tuple1)
Traceback (most recent call last):
  File "", line 1, in
TypeError: mktime(): illegal time tuple argument
>>> import time
>>> time.mktime(tuple1)
Traceback (most recent call last):
  File "", line 1, in
TypeError: mktime(): illegal time tuple argument
>>> time.localtime(time.mktime(tuple1))
Traceback (most recent call last):
  File "", line 1, in
TypeError: mktime(): illegal time tuple argument


>>> import time
>>> print("hello people")
hello people
>>> time.sleep(5)
>>> time.sleep(10)

calendar:
>>> import calendar
>>> print(calendar.month(2000,4))
     April 2000
Mo Tu We Th Fr Sa Su
                1  2
 3  4  5  6  7  8  9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
>>> print(calendar.year(2020))
Traceback (most recent call last):
  File "", line 1, in
AttributeError: module 'calendar' has no attribute 'year'
>>> print(calendar.calendar(2020))
                                  2020

      January                   February                   March
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                      1  2                         1
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       2  3  4  5  6  7  8
13 14 15 16 17 18 19      10 11 12 13 14 15 16       9 10 11 12 13 14 15
20 21 22 23 24 25 26      17 18 19 20 21 22 23      16 17 18 19 20 21 22
27 28 29 30 31            24 25 26 27 28 29         23 24 25 26 27 28 29
                                                    30 31
       April                      May                       June
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                   1  2  3       1  2  3  4  5  6  7
 6  7  8  9 10 11 12       4  5  6  7  8  9 10       8  9 10 11 12 13 14
13 14 15 16 17 18 19      11 12 13 14 15 16 17      15 16 17 18 19 20 21
20 21 22 23 24 25 26      18 19 20 21 22 23 24      22 23 24 25 26 27 28
27 28 29 30               25 26 27 28 29 30 31      29 30
        July                     August                  September
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
       1  2  3  4  5                      1  2          1  2  3  4  5  6
 6  7  8  9 10 11 12       3  4  5  6  7  8  9       7  8  9 10 11 12 13
13 14 15 16 17 18 19      10 11 12 13 14 15 16      14 15 16 17 18 19 20
20 21 22 23 24 25 26      17 18 19 20 21 22 23      21 22 23 24 25 26 27
27 28 29 30 31            24 25 26 27 28 29 30      28 29 30
                          31
      October                   November                  December
Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su      Mo Tu We Th Fr Sa Su
          1  2  3  4                         1          1  2  3  4  5  6
 5  6  7  8  9 10 11       2  3  4  5  6  7  8       7  8  9 10 11 12 13
12 13 14 15 16 17 18       9 10 11 12 13 14 15      14 15 16 17 18 19 20
19 20 21 22 23 24 25      16 17 18 19 20 21 22      21 22 23 24 25 26 27
26 27 28 29 30 31         23 24 25 26 27 28 29      28 29 30 31
                          30
>>> calendar.weekday(2017,3,9)
3
>>> calendar.weekday(2017,10,20)
4
>>> calendar.weekday(2019,10,20)
6
>>> calendar.weekday(2019,20,10)
Traceback (most recent call last):
  File "", line 1, in
  File "C:\Users\Nethra\lib\calendar.py", line 117, in weekday
    return datetime.date(year, month, day).weekday()
ValueError: month must be in 1..12
>>> calendar.weekday(2019,10,20)
6
>>> calendar.isleap(2020)
True
>>> calendar.isleap(2019)
False
>>> calendar.leapdays(2000,2020)
5
>>> calendar

>>> help(calendar)


set:
Its mutable, unordered and non dublicated

frozenset- unmutable

>>> fruits={'apple','banana'}
>>> fruits
{'apple', 'banana'}
>>> fruits.add('grapes')
>>> fruits
{'apple', 'banana', 'grapes'}
>>> animal=frozenset(['tiger','lion'])
>>> animal.add('cat')
Traceback (most recent call last):
  File "", line 1, in
AttributeError: 'frozenset' object has no attribute 'add'
>>> num={1,2,3,1,2,3,3,4,5,6}
>>> num
{1, 2, 3, 4, 5, 6}
>>> emptyset={}
>>> type(emptyset)

>>> emptyset=set()
>>> type(emptyset)

>>> num={1,2,3,4}
>>> num1=set(num)
>>> num1
{1, 2, 3, 4}


>>> num={1,2,3,1,2,3,3,4,5,6}
>>> num
{1, 2, 3, 4, 5, 6}
>>> emptyset={}
>>> type(emptyset)

>>> emptyset=set()
>>> type(emptyset)

>>> num={1,2,3,4}
>>> num1=set(num)
>>> num1
{1, 2, 3, 4}
>>> set1={1,2,3,4,'hello'}
>>> 6 in set1
False
>>> 4 in set1
True
>>> set1.add(6)
>>> set1
{1, 2, 3, 4, 6, 'hello'}
>>> set1.remove(4)
>>> set1
{1, 2, 3, 6, 'hello'}
>>> set2={1,'apple'}
>>> set1|set2
{1, 2, 3, 6, 'hello', 'apple'}
>>> set1.clear()
>>> set1

set()

>>> A={1,2,3,4}
>>> B={1,5,7,3}d
>>> A&B
{1, 3}
>>> A - B
{2, 4}
>>> B-A
{5, 7}
>>> A^B
{2, 4, 5, 7}
>>> len(A)
4
>>> len(B)
4
>>> C=A.copy()
>>> C
{1, 2, 3, 4}

Type  and dir function
{1, 2, 3, 4}
>>> type(1)

>>> type(1.44)

>>> list1=[]
>>> type(list1)

>>> help(type);
Help on class type in module builtins:


dir()
dir(math)

Iterators:

>>> list1=[5,1.2,"hello"]
>>> for i in list1:
...   print(i)
...
5
1.2
hello
>>> for i in {1,2,3,'g'}:
...   print(i)
...
1
2
3
g
>>> for i in (1,2.3,4.5,6):
...   print(i)
...
1
2.3
4.5
6
>>> for i in 'hello':
...   print(i)
...
h
e
l
l
o
>>> iter(list1)

>>> iterator=iter(list1)
>>> next(iterator)
5
>>> next(iterator)
1.2
>>> next(iterator)
'hello'
>>> fruits=['apple','orange','graps']
>>> i=0
>>> while i...    print(fruits[i])
...    i=i+1
...
apple
orange
graps

>>> i=0
>>> while i...    print(fruits[i])
...    i=i+1
...
Traceback (most recent call last):
  File "", line 2, in
TypeError: 'set' object is not subscriptable


>>> def print_each(iterable):
...    iterator=iter(iterable)
...    while true:
...      try:
...         item=next(iterator)
...      except stopItration:
...         break
...      else:
...         print(item)
...
>>> print_each(['Red','orange'])

Traceback (most recent call last):

Generators:
>>> def fib(mymax):
...   a,b=0,1
...   while True:
...     c=a+b
...     if c...        print("before yield keyword")
...        yield c
...        print("after yeild keyword")
...        a=b
...        b=c
...     else:
...        break
...
>>> gen=fib(10)
>>> next(gen)
before yield keyword
1
>>> next(gen)
after yeild keyword
before yield keyword
2
>>> next(gen)
after yeild keyword
before yield keyword
3
>>> next(gen)
after yeild keyword
before yield keyword
5
>>> next(gen)
after yeild keyword
before yield keyword
8
>>> next(gen)
after yeild keyword
Traceback (most recent call last):
  File "", line 1, in
StopIteration

Regular Expression:
>>> str1="my name is alice"
>>> str1.replace("alice","john")
'my name is john'
>>> str2="main street broad road"
>>> str2.replace("road","rd")
'main street brd rd'
>>> str2[0:17]+str2[17:].replace("road","rd")
'main street broad rd'

>>> import re
>>> line="pet:cat i love cats"
>>> #match=re.match(pattern,string.)
...
>>> match=re.match(r"pet:\w\w\w",line)
>>> match

>>> match.group(0)
'pet:cat'
>>> match=re.search(r"pet:\w\w\w",line)
>>> match

>>> match.group(0)
'pet:cat'
>>> line="i love cats pet:cat"
>>> var=re.match(r"pet:\w\w\w",line)
>>> var.group(0)
Traceback (most recent call last):
  File "", line 1, in
AttributeError: 'NoneType' object has no attribute 'group'
>>> var=re.search(r"pet:\w\w\w",line)
>>> var

>>> var.group(0)
'pet:cat'
>>> line="pet:cat i love cats pet:cow"
>>> var=re.search(r"pet:\w\w\w",line)
>>> var

>>> var.group(0)
'pet:cat'
>>> var=re.findall(r"pet:\w\w\w",line)
>>> var
['pet:cat', 'pet:cow']
>>> var=re.search(r"pet:\w\w\w",line)
>>> var
>>> import re
>>> line="i love cats pet:cat i love cows, pet:cow thank you"
>>> s=re.split(r"pet:\w\w\w",line)
>>> s
['i love cats ', ' i love cows, ', ' thank you']
>>> str1="john@abc.com and alice@pqr.com"
>>> var= re.sub(r"@\w+","@xyz",str1)
>>> var
'john@xyz.com and alice@xyz.com'



>>> def counter(c):
...    if c<=0:
...       return c
...    else:
...       return c+counter(c-1)
...
>>> counter(5)
15
>>> counter(3)
6
xError: invalid syntax
>>> def fact(n):
...   if n==1:
...      return 1
...   else:
...     return n*fact(n-1)
...
>>> fact(10)
3628800
>>> fact(4)
24


Range and XRange function

>>> range(1,6)
range(1, 6)
>>> type(range(6))



Range and Xrange-->in python 2
In python 3, we placed xrange to range function in python3

Append vs Extend

>>> range(1,6)
range(1, 6)
>>> type(range(6))

>>> a=[1,2,3]
>>> a.append(10)
>>> a
[1, 2, 3, 10]
>>> a.extend("amul")
>>> a
[1, 2, 3, 10, 'a', 'm', 'u', 'l']
>>> len(a)
8
>>> b=[1,22,333]
>>> b.extend("hello")
>>> b
[1, 22, 333, 'h', 'e', 'l', 'l', 'o']
>>> len(b)
8

Lambda Function
>>> a=[1,2,3,4]
>>> def square(x):
...    return x*x
...
>>> map(square,a)

>>> list(map(square,a))
[1, 4, 9, 16]
>>> map(lambda x:x*x,a)
>>> list(map(lambda x:x*x,a))
[1, 4, 9, 16]
>>> map(lambda x,y:x+y,a,b)

>>> b=[1,2,2,2]
>>> tuple(map(lambda x,y:x+y,a,b))
(2, 4, 5, 6)

List comprehension

>>> num=[1,2,3,4]
>>> 10*num
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]
>>> [x*10 for x in num]
[10, 20, 30, 40]
>>> words=["hello",'a','amuls']
>>> [x.upper() for x in words]
['HELLO', 'A', 'AMULS']
>>> str1="amul12334"
\
>>> [x for x in str1 if x.isdigit()]
['1', '2', '3', '3', '4']
>>> [x for x in str1 if x.isalpha()]
['a', 'm', 'u', 'l']
>>> list1=[[1,2,3],[4,5,6],['a','b']]
>>> [x[0] for x in list1]
[1, 4, 'a']
>>> def square(x):
...    return x*x
...
>>> [square(x) for x in range(1,11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> a=[1,2,3,4]
>>> b=[10,1,6]
>>> [x+y for x in a for y in b]
[11, 2, 7, 12, 3, 8, 13, 4, 9, 14, 5, 10]
>>> c=[1,2,3,4]
>>> [a[i]+c[i] for i in range(0,len(a))]
[2, 4, 6, 8]
>>>

>> #[expression for item in iterable]
...
>>> [x for i in range(1,11)]
[10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
>>> #[expression for item in iterable if conditional]
...
>>> #[expression if condiitonal else stmnt for item in iterable]
...
>>> [x for x in range(1,11)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [x for x in range(1,11) if x%2==0]
[2, 4, 6, 8, 10]
>>> [x if x>2 else x+1 for x in range(1,11)]
[2, 3, 3, 4, 5, 6, 7, 8, 9, 10]


>>> list1=[]
>>> for i in range(1,11):
...    list1.append(i)
...
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [x for x in range(1,11)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> num=[1,2,2.3,4.5]
>>> list(map(lambda x:int(x),num))
[1, 2, 2, 4]
>>> [int(x) for x in num]
[1, 2, 2, 4]
>>> import timeit
>>> timeit.timeit('list(map(lambda x:int(x),num))')

>>> list(filter(lambda x:x%2==0,range(1,11)))
[2, 4, 6, 8, 10]
>>> [x for x in range(1,11) if x%2==0]
[2, 4, 6, 8, 10]
>>> import functools
>>> functools.reduce(lambda x,y:x+y,[1,2,3,4])
10
>>> sum([x for x in [1,2,3,4]])
10

>>> list1=[]
>>> for i in range(1,11):
...    list1.append(i)
...
>>> list1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [x for x in range(1,11)]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> num=[1,2,2.3,4.5]
>>> list(map(lambda x:int(x),num))
[1, 2, 2, 4]
>>> [int(x) for x in num]
[1, 2, 2, 4]
>>> import timeit
>>> timeit.timeit('list(map(lambda x:int(x),num))')

>>> list(filter(lambda x:x%2==0,range(1,11)))
[2, 4, 6, 8, 10]
>>> [x for x in range(1,11) if x%2==0]
[2, 4, 6, 8, 10]
>>> import functools
>>> functools.reduce(lambda x,y:x+y,[1,2,3,4])
10
>>> sum([x for x in [1,2,3,4]])
10
>>> def mul(a,b):
...   return a*b
...
>>> print(mul(2,3))
6
>>> print(__name__)
__main__
>>> if __name__='__main__':
  File "", line 1
    if __name__='__main__':
               ^
SyntaxError: invalid syntax
>>> if __name__=='__main__':
...    print(mul(2,3))
...    print(__name__)
...
6
__main__



Bitwise operator
>>> #Bitwise AND
...
>>> a=20
>>> b=4
>>> a&b
4
>>> a|b
20
>>> a^b
16
>>> bin(10)
'0b1010'
>>>

>>> ~a
-21
>>> ~50
-51
>>> bin(0b11101011)
'0b11101011'
-234
>>> a=20
>>> a<<2 br="">80
-21
>>> a>>2
5
<2 br="">
<2 br="">shallow copy:
<2 br="">>>> import copy
>>> list1=[1,2,3,4]
>>> list2=copy.copy(list1)
>>> list2.append("a")
>>> list1
[1, 2, 3, 4]
>>> list2
[1, 2, 3, 4, 'a']
>>> list2[0]='q'
>>> list2
['q', 2, 3, 4, 'a']
>>> list1
[1, 2, 3, 4]

drawback:nested list

deep copy:
>>> import copy
>>> list1=[1,2,3,4]
>>> list2=copy.deepcopy(list1)
>>> list2
[1, 2, 3, 4]
>>> id(list1)==id(list2)
False
>>> list2.append(10)
>>> list2
[1, 2, 3, 4, 10]
>>> list1
[1, 2, 3, 4]
>>> list1=[[1,2],3,4]
>>> list2=copy.deepcopy(list1)
>>> list1
[[1, 2], 3, 4]
>>> list2[0][1]="ram"
>>> list2
[[1, 'ram'], 3, 4]
>>> list1
[[1, 2], 3, 4]

immutable object-->assignment operator
mutable object->shallow copy
nested mutable object->deep copy

No comments:

Post a Comment

Python Challenges Program

Challenges program: program 1: #Input :ABAABBCA #Output: A4B3C1 str1="ABAABBCA" str2="" d={} for x in str1: d[x]=d...