Complete Unit 3
Complete Unit 3
TYPES OF FUNCTIONS:
1. BUILT IN FUNCTION
2. USER-DEFINED FUNCTIONS
3. BUILT-IN FUNCTION:
print(),input(),sqrt(),abs(),
A. USER-DEFINED FUNCTION:
'''docstring
'''
statement(s)
In [8]:
name=str(input("Enter the name:"))
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
return()
greet(name)
print(greet.__doc__)
def function_name():
.........
.........
.........
.......
.......
function_name()
.......
.......
.......
RETURN STATEMENT
In [13]:
def greet():
print("Hello")
print(greet())
Hello
None
In [19]:
def greet():
return "Hello"
greet()
'xyz'
Out[19]:
In [28]:
num=int(input("Enter the number: "))
def squ(num):
''' This functions returns
the square of a given number
'''
return num**2
print(squ(num))
print(squ.__doc__)
In [1]:
#define a function to calculate Simple Interest:
def sim_int(p,r,t):
si=p*r*t/100
return si
s=sim_int(1000,10,3)
print("Simple Interest is=",s)
print("Simple Interest is=",sim_int(500,12,6))
pi=int(input("Enter the Principle: "))
ri=int(input("Enter the Rate: "))
td=int(input("Enter the Time: "))
sim=sim_int(pi,ri,td)
print("Simple Interest is=",sim)
In [6]:
#define a function to check whether a number is divisble by another number
def div(x,y):
if x%y==0:
print(x,"is divisble by",y)
else:
print(x,"is not divisble by",y)
div(12,4)
div(8,3)
div(9999,3)
12 is divisble by 4
8 is not divisble by 3
9999 is divisble by 3
In [7]:
#define a function to check whether a number is divisble by another number
def div(x,y):
if x%y==0:
return True
else:
return False
x=13
y=4
t=div(x,y)
print(x,"is divisble",y,":",t)
13 is divisble 4 : False
In [8]:
#define a function to count the number of digit for a given integer number
def count_digit(n):
count=0
while n>0:
n=n//10
count=count+1
return count
print("Number of digit: ",count_digit(12431241489612489))
print("Number of digit: ",count_digit(124))
In [9]:
#Write a program to calculate value of nCr
#step-1
#define a function to compute factorial
def fact(x):
f=1
for i in range(1,x+1):
f=f*i
print("Factorial of",x,"is=",f)
#step-2
#receive input from the user n and r
#step-3
#calculating nCr with the help of fact function
#step-4
#printing the final output
print("value of",n,"C",r,"is",c)
In [10]:
#Write a program to calculate value of nCr
#step-1
#define a function to compute factorial
def fact(x):
f=1
for i in range(1,x+1):
f=f*i
return f
#step-2
#receive input from the user n and r
#step-3
#calculating nCr with the help of fact function
#step-4
#printing the final output
print("value of",n,"C",r,"is",c)
In [11]:
print(sim_int(1000,10))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9980/922703614.py in <module>
----> 1 print(sim_int(1000,10))
In [12]:
print(sim_int(1000,10,5,78))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9980/2376813292.py in <module>
----> 1 print(sim_int(1000,10,5,78))
In [19]:
#Function to understand the concept of pass by reference in mutable data type
y=[10,20,30] #y is a list
print("Before changing values are:",y)
change(y) #y is an actual paramter
print("After changing the values are:",y)
In [1]:
#Function to understand the concept of pass by reference in immutable data types
y='NIET' #y is a string
print("Before changing string is:",y)
change(y) #y is an actual paramter
print("After changing string is:",y)
In [3]:
#Function to understand the concept of pass by reference in immutable data types
y=(1,'regional',333,'lion') #y is tuple
print("Before changing string is:",y)
change(y) #y is an actual paramter
print("After changing string is:",y)
~\AppData\Local\Temp/ipykernel_4932/48792912.py in change(x)
2
3 def change(x): #x is formal parameter
----> 4 x[1]='mohit'
5 print("String inside the function: ",x)
6 return
In [4]:
#Function to understand the concept of pass by reference in immutable data types
y=10 #y is a number
print("Before changing number is:",y)
change(y) #y is an actual paramter
print("After changing number is:",y)
In [5]:
# Demonstration of required positional arguments
# All the required positional arguments are necessary to be passed at the time of fun
def pos_arg(a,b,c):
print(a,b,c)
return
5 10 15
In [7]:
# Demonstration of required positional arguments
# All the required positional arguments are necessary to be passed at the time of fun
def pos_arg(a,b,c):
print(a,b,c)
return
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4932/2920327708.py in <module>
6 return
7
----> 8 pos_arg(5,10) #Less parameters are passed as per the mentioned in definition
In [8]:
# Demonstration of required positional arguments
# All the required positional arguments are necessary to be passed at the time of fun
def pos_arg(a,b,c):
print(a,b,c)
return
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4932/1748090421.py in <module>
6 return
7
----> 8 pos_arg(5,10,15,20) #More parameters are passed as per the mentioned in defin
ition
KEYWORD ARGUMENTS:
1.Keyword arguments are passed at the time of function call! 2.The caller identifies the arguments
by the parameter name which are mentioned as keyword at time of function call. 3.This allows to
place arguments out of order because the Python interpreter can use the keywords provided to
match the values with parameters.
Note: A non keyword/positional argument can be followed by keyword argument, but keyword
argument can not be followed by non keyword/positional argument.
In [20]:
# Demo of keyword arguments:
def keyword(a,b,c): # keyword arguments are not defined in function definition
print("a=",a)
print("b=",b)
print("c=",c)
return
a= 1
b= 2
c= 3
a= 10
b= 20
c= 30
a= 100
b= 400
c= 300
In [4]:
# Demo of keyword arguments:
def keyword(a,b,c): # keyword arguments are not defined in function definition
print("a=",a)
print("b=",b)
print("c=",c)
return
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_10796/2184526207.py in <module>
6 return
7
----> 8 keyword(100,b=300,a=400) #order must be maintained in the mixture of reqpos a
nd keyword
In [11]:
# Demo of keyword arguments:
def keyword(a,b,c): # keyword arguments are not defined in function definition
print("a=",a)
print("b=",b)
print("c=",c)
return
In [14]:
#Usage of keyword arguments
def person(name,age):
print(name)
print(age-5)
person(age=28,name='aakash')
aakash
23
In [7]:
#Usage of keyword arguments
print(5,6,7,end="++",sep='**')
print()
print(5,6,7,sep="##",end='@@')
5**6**7++
5##6##7@@
In [ ]:
print(obj,sep,end,file,flush) #all the parameters have some default value associated
DEFAULT ARGUMENT:
1.When an argument is given a default value while defining a function, it will be called a default
argument. 2.The default value will be considered if a value is not passed in the function call for
that argument.
In [18]:
#Demo of default argument
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 9/104
2/9/22, 10:36 AM CS Lecture-1
def project(name,language='python'):
print("project",name,"is developed using",language)
return
Python provides a facility to define a function even when number of arguments are not fixed. A
function having variable number of arguments can be defined by using variable-length-
argument.
This argument is prefixed with a special character asterisk (* or **) in function definition !
An asterisk (*) is placed before the variable name that holds the values of all non-keyword
variable arguments. This tuple remains empty if no additional arguments are specified during the
function call.
This argument will hold all the unspecified non-keyword arguments in the function definition by
packing them in a tuple. Non-keyword arguments will be prefixed with single asterisk in the
function definition.
Ex: *var_args
In [1]:
#demo of non-keyword variable length argument:
def var_len(*var): #variable length arguments can recieve zero or more than zero para
print("All the parameters are packed in tuple:",var) # Tuple will be created for
print("Accessing tuple elements one by one: ")
for v in var: #Loop can be used to access elements of tuple one by one
print (v)
return
var_len(10)
var_len(10,20,30,40,50)
In [2]:
var_len()
In [5]:
#fixing the number of arguments to at least one with variable length argument
def var_len1(pos,*var): #here one positional argument is required so function can rec
print("One position arguments: ",pos) #we have to manage positional argument sepe
print("Remaining parameters are packed in tuple: ",var) #a tuple will created for
print("Acessing tuple element one by one: ")
for v in var: #Loop can be used to access elements of tuple one by one
print(v)
return
var_len1()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4456/3094496204.py in <module>
9 return
10
---> 11 var_len1()
In [4]:
var_len1(100,200,300,400,500)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 11/104
2/9/22, 10:36 AM CS Lecture-1
In [1]:
# A function to add all the numbers provided by user at the time of
# function calling.
# function must receive at least one parameter
def add_param(first,*num):
add=first #first value which is passed through req positional arg. is added
for i in num:
add=add+i
return add
x=add_param(10,20,40,50)
print("Addition of the numbers is: ",x)
print("Addition of the numbers is: ",add_param(5))
print("Addition of the numbers is: ",add_param())
In [2]:
add_param(10,20,30,40,first=100)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9816/3236942631.py in <module>
----> 1 add_param(10,20,30,40,first=100)
In [3]:
add_param(first=100,10,20,30,40)
In [6]:
#Create a function to compute hcf of the given natural numbers:
def hcf_var(*num):
if len(num)==0: #when there is no parameter is passed in function calling
print("HCF is not possible")
HCF= 10
HCF= 4
HCF= 4
HCF is not possible
HCF= None
In [8]:
#Create a function to compute hcf of the given natural numbers without else:
def hcf_var(*num):
if len(num)==0: #when there is no parameter is passed in function calling
print("HCF is not possible")
return
print("HCF= ",hcf_var(10))
print("HCF= ",hcf_var(12,20,))
print("HCF= ",hcf_var(20,12,8))
print("HCF= ",hcf_var())
HCF= 10
HCF= 4
HCF= 4
HCF is not possible
HCF= None
1.This argument will hold all the unspecified keyword arguments in the function definition by
packing them in a dictionary. Keyword-arguments will be prefixed with double asterisk in the
function definition. Ex: **var_kwargs
In [9]:
#Demo of variable length keyword arguments
def var_key(**vark): #It accept all the zero or more keyword arguments
#all the keyword arguments will be packed in a dictionary as key
#and value pair under the name vark
print("All the keyword arguments are: ",vark)
return
var_key(a=10,b=20,c=30)
var_key() #It will create a blank dictionary
var_key(10)
All the keyword arguments are: {'a': 10, 'b': 20, 'c': 30}
All the keyword arguments are: {}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9816/418519626.py in <module>
9 var_key(a=10,b=20,c=30)
10 var_key() #It will create a blank dictionary
---> 11 var_key(10)
In [15]:
#Accessing individual keyword arg in a function def having var. len. keywords
def var_key1(**vark1):
for v in vark1: #for loop will iterate through only keys of the dictionary
print(v,vark1[v]) #values can be accessed by indexing on keys
return
var_key1(a=10,b=20,c=30)
a 10
b 20
c 30
STUDENT CHECK
1. Create a function to convert distance from feet to inches to cm.
2. Create a function to find the smallest number among three numbers.
3. Create a function to reverse a number and also check whether number is pallindrome or not.
4. Create a function to check whether a number is prime or not.
In [1]:
#Program to compute hcf/gcd of two numbers:
if a<b:
h=a
while True:
if a%h==0 and b%h==0:
print(h,"is HCF of",a,b)
break
h=h-1
In [2]:
def hcf(a,b):
if a<b:
h=a
else:
h=b
while True:
if(a%h==0 and b%h==0):
return h
h=h-1
In [5]:
def prime(n):
for i in range(2,n):
if n%i==0:
print(n,"is not a prime number")
break
else:
print(n,"is a prime number")
return
x=int(input("Enter a number: "))
prime(x)
Enter a number: 9
9 is not a prime number
All variables in a program may not be accessible at all locations in that program. This depends on
where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular
identifier. There are two basic scopes of variables in Python:
This means that local variables can be accessed only inside the function in which they are
declared, whereas global variables can be accessed throughout the program body by all
functions. When you call a function, the variables declared inside it are brought into scope.
In [6]:
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print("Outside the function global total : ", total)
In [10]:
#Scope of variable
a=10 #it is a global variable as it is not defined inside the body of function
def scope():
print("Value of global a is accessed inside the function scope:",a)
a=20 # once we define a variable inside the function body it becomes local
#so same name global can not be access from the function.
scope()
print("VAlue of outside the function: ",a)
---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_11504/2267888031.py in <module>
9 return
10
---> 11 scope()
12 print("VAlue of outside the function: ",a)
~\AppData\Local\Temp/ipykernel_11504/2267888031.py in scope()
2 a=10 #it is a global variable as it is not defined inside the body of functio
n
3 def scope():
----> 4 print("Value of global a is accessed inside the function scope:",a)
5 a=20 # once we define a variable inside the function body it becomes loca
l
6 #so same name global can not be access from the function.
In [8]:
#Scope of variable
a=10 #it is a global variable as it is not defined inside the body of function
def scope():
a=20 # once we define a variable inside the function body it becomes local
#so same name global can not be access from the function.
print("Value of global a is accessed inside the function scope:",a)
scope()
print("VAlue of outside the function: ",a)
In [13]:
#How to modify a global variable inside the body of function it becomes
#We have to write global statement
def scope():
global a # it allow to access and modify the global variable inside the function
a=20
print("Value of a inside the function: ",a)
print(id(a))
return
scope()
print("Value of outside the function: ",a)
print(id(a))
In [1]:
def fun():
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 17/104
2/9/22, 10:36 AM CS Lecture-1
x=100
print("Inside function x= ",x)
return
fun()
print("Outside the function x= ",x) # A local variable can not be accessed from outs
# as it is no longer exist after the function exit.
In [2]:
# A local variablle can not be accessed outside even if it is being
#returned by function as only it's value is returned
def fun():
x=500
print("Inside the function x= ",x)
return x
fun()
print("Outside the function x=",x)
RECURSION IN PYTHON:
Recursion is the process of defining something in terms of itself.
In Python, it’s also possible for a function to call itself! A function that calls itself is said to be
recursive, and the technique of employing a recursive function is called recursion.
It may seem peculiar for a function to call itself, but many types of programming problems are
best expressed recursively. When you bump up against such a problem, recursion is an
indispensable tool for you to have in your toolkit.
What is Recursion?
The word recursion comes from the Latin word recurrere, meaning to run or hasten back, return,
revert, or recur.
A recursive definition is one in which the defined term appears in the definition itself. Self-
referential situations often crop up in real life, even if they aren’t immediately recognizable as
such. For example, suppose you wanted to describe the set of people that make up your
ancestors. You could describe them this way:
In [1]:
# Recursive function for countdown.
def countdown(n):
print(n)
if n==0: # Recursion termination
return
else:
countdown(n-1) #Recursive call
In [ ]:
#Program to print the following Series:
#1, 2, 3, 6, 9, 18, 27, 54, ... upto n terms
In [ ]:
#Program to print the following Series:
#1, 2, 3, 6, 9, 18, 27, 54, ... upto n terms
print(b,c,end=',')
for i in range(3,n+1):
if i%2==0:
d=a+b+c
else:
d=b+c
print(d,end=',')
a=b
b=c
c=d
In [ ]:
#Program to print the following Series:
#2, 15, 41, 80, 132, 197, 275, 366, 470, 587
In [4]:
a = 2
b = 13
n =int(input("Enter a no. - "))
for i in range(1, n+1, 1):
print(a,end=',')
a = a + b*i
Enter a no. - 9
2,15,41,80,132,197,275,366,470,
In [3]:
#Program to add n natural number using recursion
def rec_add(n):
if n==1: #base condition
return 1
else:
return rec_add(n-1)+n #recursive condition
In [8]:
#Program to compute factorial of a given number using recursion
def fact(n):
if n==1: #base case
return 1
else:
return n*fact(n-1) #Recursive Case(Self Refrential Case)
Enter a number: 5
Factorial: 120
In [6]:
# A recursive function to calculate exponential (power) of a given numbe (x**y)
def exp(x,y):
if y==0: #Base Case
return 1
else:
return x*exp(x,y-1) #Recursive Case
In [ ]:
# W.A.P. to calculate sum of digits of a given number using recursion.
# W.A.P. to reverse a given number using recursion.
# W.A.P. to display n terms of fibonacci series using recursion.
In [3]:
#Program to calculate sum of digits of a given number using recursion.
def rec_digit(n):
if n==0:
return 0
else:
return n%10 + rec_digit(n//10)
In [3]:
# W.A.P. to reverse a given number using recursion.
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 21/104
2/9/22, 10:36 AM CS Lecture-1
def rev(n,r=0):
if n==0:
return r
else:
return rev(n//10,r*10+n%10)
In [1]:
# W.A.P. to display n terms of fibonacci series using recursion.
def fib(n):
if n==1: #base case
return 0
elif n==2: #base case
return 1
else:
return fib(n-1)+fib(n-2) #Recursive Case
def fib_series(n):
for i in range(1,n+1):
print(fib(i),end=',')
In [9]:
#Program to generate fibonacci Series using recursion.
def fibonacci(n):
if(n <= 2): #base case
return n
else:
return(fibonacci(n-1) + fibonacci(n-2)) #recursive case
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(1,n+1):
print(fibonacci(i),end=',')
FUNCTION AS AN OBJECT
Python is an object-oriented programming language. Unlike procedure-oriented programming,
where the main emphasis is on functions, object-oriented programming stresses on objects.
An object is simply a collection of data (variables) and methods (functions) that act on those data.
In [4]:
def fun(text):
return text + " students"
<class 'function'>
hello students
HIIIII students
NESTED FUNCTION:
FUNCTION DEFINED INSIDE THE BODY OF ANOTHER FUNCTION IS CALLED "NESTED
FUNCTION".
In [5]:
#Example of nested function
print(outer(10))
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4872/4165270793.py in <module>
7 return n # n can not be accessed as it is local to inner
8
----> 9 print(outer(10))
~\AppData\Local\Temp/ipykernel_4872/4165270793.py in outer(num)
5 n=n+1
6 return n
----> 7 return n # n can not be accessed as it is local to inner
8
9 print(outer(10))
In [6]:
#Example of nested function
return n
return
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_4872/3671796946.py in <module>
7 return
8
----> 9 print(inner(10)) #inner function can not be accessed from outside as it is l
ocal to other function
NON-LOCAL IN PYTHON:
Nonlocal variables are used in nested functions whose local scope is not defined. This means that
the variable can be neither in the local nor the global scope.
Note : If we change the value of a nonlocal variable, the changes appear in the local variable.
In [10]:
#Inner can be accessed from the body of outer function
In [11]:
#Understanding non-local variable
In [14]:
# Same name local variable will be created once we define a non-local vaiable
# Inside the inner function
def outer():
y=100 #Local for outer function
# y is non-local variable to inner
def inner():
y=200 # Once we define inside a function it become local
print("Value of y inside the inner function:",y)
return
inner()
print("Value of y inside the outer function:",y)
#non-local variable can not be modified directly in inner function
return
outer()
In [15]:
# To modify a non-local variable in inner function
# A non-local statement will be used
def outer():
y=444 #Local to outer function
# y is a non-local variable for inner
def inner():
nonlocal y
y=555 # once we define a variable inside a function it becomes local
print("VAlue of y inside the inner function: ",y)
return
print("Befor calling value of y inside the inner functon: ",y)
inner()# call of inner\
print("AFter calling value of y inside outer function: ",y)
# non-local ariable can not be modified directly in inner function
return
outer()
None
In [3]:
def greetings(): #outer function
def say_hi(): #inner function
return "Hiii How are you??"
msg=say_hi() #call of inner function inside the outer body
return msg
print(greetings()) #call of outer
In [4]:
#Accessing inner function from outside
In [5]:
#Accessing inner function from outside by returning it from outer function
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3964/2418066946.py in <module>
7
8 hi=greetings() #assisgning returned reference by outer function in some name
----> 9 print(say_hi()) #It is still a local resources
While normal functions are defined using the def keyword in Python, anonymous functions are
defined using the lambda keyword.
2.In the definition of the lambdas, the arguments don’t have parentheses around them.
3.Multi-argument functions (functions that take more than one argument) are expressed in
Python lambdas by listing arguments and separating them with a comma (,) but without
surrounding them with parentheses:
Python exposes higher-order functions as built-in functions or in the standard library. Examples
include map(), filter(), functools.reduce(), as well as key functions like sort(), sorted(), min(), and
max().
In [2]:
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 27/104
2/9/22, 10:36 AM CS Lecture-1
def add(x,y):
z=x+y
return z
print(add(5,3))
In [6]:
#Addition using anonymous/lambda function
In [7]:
#checking the type of defined lambda function
<class 'function'>
In [8]:
#calling the lambda function through its referenced variable
#s has the reference of defined lambda function..
#so s can be called like a normal function by passing parameters mentioned in lambda
#expression written in lambda function will be evaluated and it return the value.
print(s(7,5))
12
In [9]:
#Square of a number using lambda
lambda x:(x*x)
<function __main__.<lambda>(x)>
Out[9]:
In [10]:
#Square of a number using lambda
sq=lambda x:(x*x)
print(sq)
In [11]:
#Square of a number using lambda
sq=lambda x:(x*x)
print(sq())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9408/954540975.py in <module>
2
3 sq=lambda x:(x*x)
----> 4 print(sq())
In [15]:
#Square of a number using lambda
sq=lambda x:(x*x)
print(sq(x=8)) #Parameter passed as keyword argument.
print(sq(5)) #Parameter passed as positional argument.
64
25
In [1]:
# A lambda function to calculate simple interest
250.0
2500.0
In [3]:
#Lambda with default arguments:
500.0
1250.0
In [7]:
#Lambda function with user-defined function:
doubler=multiplier(2)
print(doubler(10))
print(doubler(5))
tripler=multiplier(3)
print(tripler(10))
20
10
30
In [8]:
x=10
y=15
z=x+y
if x>y:
print (z)
else:
print (x-y)
-5
In [ ]:
#Using "If-else" statement with lambda function.
#it's not advisable to use lambda for conditional statement.
#A conditional statement becomes very confusing when it's written like expression.
In [9]:
greater=lambda x,y: x if x>y else y
In [10]:
even_odd=lambda x:print("Even") if x%2==0 else print("Odd")
even_odd(12)
even_odd(7)
even_odd(9)
Even
Odd
Odd
In [11]:
#Lambda with non-keyword variable length arguments
var()
var(1)
var(1,2,3,4,5)
()
(1,)
(1, 2, 3, 4, 5)
In [14]:
#Lambda with keyword variable length arguments
kvar()
kvar(a=1,b=2,c=3,d=4,e=5)
{}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
As mentioned earlier, map(), filter() and reduce() are inbuilt functions of Python. These functions
enable the functional programming aspect of Python. In functional programming, the arguments
passed are the only factors that decide upon the output. These functions can take any other
function as a parameter and can be supplied to other functions as parameters as well.
MAP() FUNCTION:
The map() function is a type of higher-order function. As mentioned earlier, this function takes
another function as a parameter along with a sequence of iterables and returns an output after
applying the function to each iterable present in the sequence.
Syntax: map(function,iterables)
Here, the function defines an expression that is in turn applied to the iterables. The map function
can take user-defined functions as well as lambda functions as a parameter.
User-defined functions can be sent to the map() method. The user or programmer is the only one who can
change the parameters of these functions. For example look at the code mention below:
In [4]:
def cs(a):
return a*a
x=map(cs,(1,2,3,4,5,6,7,8,9))
print(x)
print(tuple(x))
output=map(lambda x:x+3,[1,2,3,4,5])
print(output)
print(list(output))
In [9]:
def doubler(x):
return x*2
li=[10,20,30,40,50]
new_list=map(doubler,li)
new_list=list(new_list)
print(new_list)
In [19]: keshav=[11,22,33,44,55]
do_li=list(map((lambda x:x*2),keshav))
print(do_li)
In [11]:
# map function with more than one iterables
#simple interest with map function
si_li=list(map((lambda p,r,t:p*r*t/100),pli,rli,tli))
print(si_li)
In [14]:
#Map function can also use built-in or library function as arguments
num=['10','20','30','40','50']
#a map function to convert each element of the above list into integer
#so each elements will be typecasted in integer by using int function
num_li=list(map(int,num))
print(num_li)
In [24]:
#Program to calculate length of a string using map function
#built-in function "len()" will be used in map
st_li=("amartya","kush","aslam","shivangi","diksha","kavya")
st_len=tuple(map(len,st_li))
print(st_len)
(7, 4, 5, 8, 6, 5)
FILTER FUNCTION:
1. The filter() function is used to create an output list consisting of values for which the function
returns true.
4. If None,then the function defaults to identity function which returns false if any elements are
false.
def bekar_class(x):
if x>=5:
return x
y = filter(bekar_class, (1,2,3,4,5,6,7,8))
print(y)
print(list(y))
#As you can see, y is the filter object and the list
#is a list of values that are true for the condition (x>=5).
In [27]:
y = filter(lambda x: (x>=5), (1,2,3,4,5,6,7,8))
print(list(y))
[5, 6, 7, 8]
In [2]:
#Filter function returns the elements of seq which produce True as a result
#for the condtion in function
seq=[True,False,True,True,False,False,None]
res=list(filter(lambda x:x,seq))
print(res)
In [4]:
#Filter out all the positive integers from a given list
cs=[-22,1,-34,45,67,-98,78,11,-65,65]
cs_obj=list(filter(lambda x:x>0,cs))
print("Positive Numbers are: ",cs_obj)
REDUCE() FUNCTION:
1. Python's reduce() implement a mathematical technique commonly known as "Folding" or
"Reduction". It is used to reduce a list of items to a single cumulative value.
3. The function applied to the first two items in an iteable and generate a partial result.
4. The partial result,together with the third item in the iterable to generate another partial
result and the process is repeated untill the iterable is exhausted and then return a single
cumulative value.
5. Reduce() function is available in "functools module". So before using it we must import in our
scope. "from functools import reduce"
In [10]:
#Example reduce() function:
morning=[2,4,5,6,7,8,1,10]
cs=reduce(lambda x,y:x+y,morning)
print("Sum of elements in list is: ",cs)
In [13]:
from functools import reduce
l=[10,20,30,40]
s=reduce(lambda x,y:x+y,l,1000) #third argument will be seed for the cumulative resul
print(s)
1100
In [14]:
#Sum of only even numbers using reduce in a given list
bolo=[1,2,3,4,5,6,7,8,9,10,11,12]
In [15]:
#To find the max value in a list using reduce
li2=[22,33,4,5,77,99,1,43]
print(mx)
99
In [21]:
from functools import reduce
66
In [4]:
from functools import reduce
cs=[1,2,3,4,5,6,7,8]
sum_lk=reduce(lambda x,y: x+y,list(filter(lambda x:x%2==0,list(map(int,cs)))))
print (sum_lk)
20
In [6]:
#filter all the prime numbers within a given range and compute its summation.
def prime(n):
if n<=1:
return False
for i in range(2,n):
if n%i==0:
return False
else:
return True
#input range
sum_cs=reduce(lambda x,y:x+y,prime_cs)
print("Sum of prime numbers is:",sum_cs)
In [11]:
#Find all the cubes of each element in a list which are divisible by 3
jordar=[10,20,30,40,50,60,70,80,90,100]
div_jordar=list(filter(lambda x: x%3==0,cube_jordar))
print("Divisible by 3: ",div_jordar)
Cubes are: [1000, 8000, 27000, 64000, 125000, 216000, 343000, 512000, 729000, 100000
0]
Divisible by 3: [27000, 216000, 729000]
[27000, 216000, 729000]
MATH MODULE:
In [1]:
import math
dir(math)
['__doc__',
Out[1]:
'__loader__',
'__name__',
'__package__',
'__spec__',
'acos',
'acosh',
'asin',
'asinh',
'atan',
'atan2',
'atanh',
'ceil',
'comb',
'copysign',
'cos',
'cosh',
'degrees',
'dist',
'e',
'erf',
'erfc',
'exp',
'expm1',
'fabs',
'factorial',
'floor',
'fmod',
'frexp',
'fsum',
'gamma',
'gcd',
'hypot',
'inf',
'isclose',
'isfinite',
'isinf',
'isnan',
'isqrt',
'lcm',
'ldexp',
'lgamma',
'log',
'log10',
'log1p',
'log2',
'modf',
'nan',
'nextafter',
'perm',
'pi',
'pow',
'prod',
'radians',
'remainder',
'sin',
'sinh',
'sqrt',
'tan',
'tanh',
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 37/104
2/9/22, 10:36 AM CS Lecture-1
'tau',
'trunc',
'ulp']
In [2]:
help(math)
NAME
math
DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.
FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.
acosh(x, /)
Return the inverse hyperbolic cosine of x.
asin(x, /)
Return the arc sine (measured in radians) of x.
asinh(x, /)
Return the inverse hyperbolic sine of x.
atan(x, /)
Return the arc tangent (measured in radians) of x.
atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.
atanh(x, /)
Return the inverse hyperbolic tangent of x.
ceil(x, /)
Return the ceiling of x as an Integral.
comb(n, k, /)
Number of ways to choose k items from n items without repetition and without
order.
copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 39/104
2/9/22, 10:36 AM CS Lecture-1
cos(x, /)
Return the cosine of x (measured in radians).
cosh(x, /)
Return the hyperbolic cosine of x.
degrees(x, /)
Convert angle x from radians to degrees.
dist(p, q, /)
Return the Euclidean distance between two points p and q.
erf(x, /)
Error function at x.
erfc(x, /)
Complementary error function at x.
exp(x, /)
Return e raised to the power of x.
expm1(x, /)
Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation
of exp(x)-1 for small x.
fabs(x, /)
Return the absolute value of the float x.
factorial(x, /)
Find x!.
floor(x, /)
Return the floor of x as an Integral.
fmod(x, y, /)
Return fmod(x, y), according to platform C.
x % y may differ.
frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).
fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.
gamma(x, /)
Gamma function at x.
gcd(*integers)
Greatest Common Divisor.
hypot(...)
hypot(*coordinates) -> value
rel_tol
maximum difference for being considered "close", relative to the
magnitude of the input values
abs_tol
maximum difference for being considered "close", regardless of the
magnitude of the input values
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.
isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.
isqrt(n, /)
Return the integer part of the square root of the input.
lcm(*integers)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 41/104
2/9/22, 10:36 AM CS Lecture-1
ldexp(x, i, /)
Return x * (2**i).
lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.
log(...)
log(x, [base=math.e])
Return the logarithm of x to the given base.
log10(x, /)
Return the base 10 logarithm of x.
log1p(x, /)
Return the natural logarithm of 1+x (base e).
log2(x, /)
Return the base 2 logarithm of x.
modf(x, /)
Return the fractional and integer parts of x.
nextafter(x, y, /)
Return the next floating-point value after x towards y.
perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with ord
er.
pow(x, y, /)
Return x**y (x to the power of y).
prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.
When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.
radians(x, /)
Convert angle x from degrees to radians.
remainder(x, y, /)
Difference between x and the closest integer multiple of y.
sin(x, /)
Return the sine of x (measured in radians).
sinh(x, /)
Return the hyperbolic sine of x.
sqrt(x, /)
Return the square root of x.
tan(x, /)
Return the tangent of x (measured in radians).
tanh(x, /)
Return the hyperbolic tangent of x.
trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.
ulp(x, /)
Return the value of the least significant bit of the float x.
DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586
FILE
(built-in)
In [3]:
print(math.ceil(2.5))
In [4]:
help(math.ceil)
ceil(x, /)
Return the ceiling of x as an Integral.
In [5]: print(math.factorial(2.5))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_8228/385641981.py in <module>
----> 1 print(math.factorial(2.5))
In [6]:
help(math.factorial)
factorial(x, /)
Find x!.
In [7]:
print(math.factorial(5))
120
In [8]:
print(math.floor(2.5))
In [9]:
print(math.floor(2.5))
print(math.floor(-2.5))
2
-3
In [10]:
r=5
print(math.pi)
area=math.pi*r*r
print(area)
3.141592653589793
78.53981633974483
In [11]:
help(math.pow)
pow(x, y, /)
Return x**y (x to the power of y).
In [12]:
print(math.pow(2,5))
32.0
STASTICS MODULE
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 44/104
2/9/22, 10:36 AM CS Lecture-1
In [13]:
import statistics as st
dir(st)
In [14]:
help(st)
NAME
statistics - Basic statistics module.
MODULE REFERENCE
https://docs.python.org/3.10/library/statistics.html
DESCRIPTION
This module provides functions for calculating statistics of data, including
averages, variance, and standard deviation.
Calculating averages
--------------------
================== ==================================================
Function Description
================== ==================================================
mean Arithmetic mean (average) of data.
fmean Fast, floating point arithmetic mean.
geometric_mean Geometric mean of data.
harmonic_mean Harmonic mean of data.
median Median (middle value) of data.
median_low Low median of data.
median_high High median of data.
median_grouped Median, or 50th percentile, of grouped data.
mode Mode (most common value) of data.
multimode List of modes (most common values of data).
quantiles Divide data into intervals with equal probability.
================== ==================================================
Calculate the median, or 50th percentile, of data grouped into class intervals
centred on the data values provided. E.g. if your data points are rounded to
the nearest whole number:
This should be interpreted in this way: you have two data points in the class
interval 1.5-2.5, three data points in the class interval 2.5-3.5, and one in
the class interval 3.5-4.5. The median of these data points is 2.8333...
================== =============================================
Function Description
================== =============================================
pvariance Population variance of data.
variance Sample variance of data.
pstdev Population standard deviation of data.
stdev Sample standard deviation of data.
================== =============================================
If you have previously calculated the mean, you can pass it as the optional
second argument to the four "spread" functions to avoid recalculating it:
================== ====================================================
Function Description
================== ====================================================
covariance Sample covariance for two variables.
correlation Pearson's correlation coefficient for two variables.
linear_regression Intercept and slope for simple linear regression.
================== ====================================================
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> covariance(x, y)
0.75
>>> correlation(x, y) #doctest: +ELLIPSIS
0.31622776601...
>>> linear_regression(x, y) #doctest:
LinearRegression(slope=0.1, intercept=1.5)
Exceptions
----------
CLASSES
builtins.ValueError(builtins.Exception)
StatisticsError
builtins.object
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 49/104
2/9/22, 10:36 AM CS Lecture-1
NormalDist
class NormalDist(builtins.object)
| NormalDist(mu=0.0, sigma=1.0)
|
| Normal distribution of a random variable
|
| Methods defined here:
|
| __add__(x1, x2)
| Add a constant or another NormalDist instance.
|
| If *other* is a constant, translate mu by the constant,
| leaving sigma unchanged.
|
| If *other* is a NormalDist, add both the means and the variances.
| Mathematically, this works only if the two distributions are
| independent or if they are jointly normally distributed.
|
| __eq__(x1, x2)
| Two NormalDist objects are equal if their mu and sigma are both equal.
|
| __hash__(self)
| NormalDist objects hash equal if their mu and sigma are both equal.
|
| __init__(self, mu=0.0, sigma=1.0)
| NormalDist where mu is the mean and sigma is the standard deviation.
|
| __mul__(x1, x2)
| Multiply both mu and sigma by a constant.
|
| Used for rescaling, perhaps to change measurement units.
| Sigma is scaled with the absolute value of the constant.
|
| __neg__(x1)
| Negates mu while keeping sigma the same.
|
| __pos__(x1)
| Return a copy of the instance.
|
| __radd__ = __add__(x1, x2)
|
| __repr__(self)
| Return repr(self).
|
| __rmul__ = __mul__(x1, x2)
|
| __rsub__(x1, x2)
| Subtract a NormalDist from a constant or another NormalDist.
|
| __sub__(x1, x2)
| Subtract a constant or another NormalDist instance.
|
| If *other* is a constant, translate by the constant mu,
| leaving sigma unchanged.
|
| If *other* is a NormalDist, subtract the means and add the variances.
| Mathematically, this works only if the two distributions are
| independent or if they are jointly normally distributed.
|
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 50/104
2/9/22, 10:36 AM CS Lecture-1
| __truediv__(x1, x2)
| Divide both mu and sigma by a constant.
|
| Used for rescaling, perhaps to change measurement units.
| Sigma is scaled with the absolute value of the constant.
|
| cdf(self, x)
| Cumulative distribution function. P(X <= x)
|
| inv_cdf(self, p)
| Inverse cumulative distribution function. x : P(X <= x) = p
|
| Finds the value of the random variable such that the probability of
| the variable being less than or equal to that value equals the given
| probability.
|
| This function is also called the percent point function or quantile
| function.
|
| overlap(self, other)
| Compute the overlapping coefficient (OVL) between two normal distribution
s.
|
| Measures the agreement between two normal probability distributions.
| Returns a value between 0.0 and 1.0 giving the overlapping area in
| the two underlying probability density functions.
|
| >>> N1 = NormalDist(2.4, 1.6)
| >>> N2 = NormalDist(3.2, 2.0)
| >>> N1.overlap(N2)
| 0.8035050657330205
|
| pdf(self, x)
| Probability density function. P(x <= X < x+dx) / dx
|
| quantiles(self, n=4)
| Divide into *n* continuous intervals with equal probability.
|
| Returns a list of (n - 1) cut points separating the intervals.
|
| Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
| Set *n* to 100 for percentiles which gives the 99 cuts points that
| separate the normal distribution in to 100 equal sized groups.
|
| samples(self, n, *, seed=None)
| Generate *n* samples for a given mean and standard deviation.
|
| zscore(self, x)
| Compute the Standard Score. (x - mean) / stdev
|
| Describes *x* in terms of the number of standard deviations
| above or below the mean of the normal distribution.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| from_samples(data) from builtins.type
| Make a normal distribution instance from sample data.
|
| ----------------------------------------------------------------------
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 51/104
2/9/22, 10:36 AM CS Lecture-1
| Readonly properties defined here:
|
| mean
| Arithmetic mean of the normal distribution.
|
| median
| Return the median of the normal distribution
|
| mode
| Return the mode of the normal distribution
|
| The mode is the value x where which the probability density
| function (pdf) takes its maximum value.
|
| stdev
| Standard deviation of the normal distribution.
|
| variance
| Square of the standard deviation.
class StatisticsError(builtins.ValueError)
| Method resolution order:
| StatisticsError
| builtins.ValueError
| builtins.Exception
| builtins.BaseException
| builtins.object
|
| Data descriptors defined here:
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.ValueError:
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| ----------------------------------------------------------------------
| Static methods inherited from builtins.ValueError:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.BaseException:
|
| __delattr__(self, name, /)
| Implement delattr(self, name).
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 52/104
2/9/22, 10:36 AM CS Lecture-1
| __setattr__(self, name, value, /)
| Implement setattr(self, name, value).
|
| __setstate__(...)
|
| __str__(self, /)
| Return str(self).
|
| with_traceback(...)
| Exception.with_traceback(tb) --
| set self.__traceback__ to tb and return self.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from builtins.BaseException:
|
| __cause__
| exception cause
|
| __context__
| exception context
|
| __dict__
|
| __suppress_context__
|
| __traceback__
|
| args
FUNCTIONS
correlation(x, y, /)
Pearson's correlation coefficient
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> correlation(x, x)
1.0
>>> correlation(x, y)
-1.0
covariance(x, y, /)
Covariance
Return the sample covariance of two inputs *x* and *y*. Covariance
is a measure of the joint variability of two inputs.
>>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> covariance(x, y)
0.75
>>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1]
>>> covariance(x, z)
-7.5
>>> covariance(z, x)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 53/104
2/9/22, 10:36 AM CS Lecture-1
-7.5
fmean(data)
Convert data to floats and compute the arithmetic mean.
This runs faster than the mean() function and it always returns a float.
If the input dataset is empty, it raises a StatisticsError.
geometric_mean(data)
Convert data to floats and compute the geometric mean.
harmonic_mean(data, weights=None)
Return the harmonic mean of data.
Suppose a car travels 40 km/hr for 5 km, and when traffic clears,
speeds-up to 60 km/hr for the remaining 30 km of the journey. What
is the average speed?
linear_regression(x, y, /)
Slope and intercept for simple linear regression.
where *slope* and *intercept* are the regression parameters that are
estimated, and noise represents the variability of the data that was
not explained by the linear regression (it is equal to the
difference between predicted and actual values of the dependent
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 54/104
2/9/22, 10:36 AM CS Lecture-1
variable).
>>> x = [1, 2, 3, 4, 5]
>>> noise = NormalDist().samples(5, seed=42)
>>> y = [3 * x[i] + 2 + noise[i] for i in range(5)]
>>> linear_regression(x, y) #doctest: +ELLIPSIS
LinearRegression(slope=3.09078914170..., intercept=1.75684970486...)
mean(data)
Return the sample arithmetic mean of data.
median(data)
Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
median_grouped(data, interval=1)
Return the 50th percentile (median) of grouped continuous data.
This function does not check whether the data points are at least
``interval`` apart.
median_high(data)
Return the high median of data.
When the number of data points is odd, the middle value is returned.
When it is even, the larger of the two middle values is returned.
median_low(data)
Return the low median of numeric data.
When the number of data points is odd, the middle value is returned.
When it is even, the smaller of the two middle values is returned.
mode(data)
Return the most common data point from discrete or nominal data.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
If there are multiple modes with same frequency, return the first one
encountered:
multimode(data)
Return a list of the most frequently occurring values.
Will return more than one result if there are multiple modes
or an empty list if *data* is empty.
>>> multimode('aabbbbbbbbcc')
['b']
>>> multimode('aabbbbccddddeeffffgg')
['b', 'd', 'f']
>>> multimode('')
[]
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 56/104
2/9/22, 10:36 AM CS Lecture-1
pstdev(data, mu=None)
Return the square root of the population variance.
pvariance(data, mu=None)
Return the population variance of ``data``.
Use this function to calculate the variance from the entire population.
To estimate the variance from a sample, the ``variance`` function is
usually a better choice.
Examples:
>>> data = [0.0, 0.25, 0.25, 1.25, 1.5, 1.75, 2.75, 3.25]
>>> pvariance(data)
1.25
If you have already calculated the mean of the data, you can pass it as
the optional second argument to avoid recalculating it:
>>> mu = mean(data)
>>> pvariance(data, mu)
1.25
Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles.
Set *n* to 100 for percentiles which gives the 99 cuts points that
separate *data* in to 100 equal sized groups.
variance(data, xbar=None)
Return the sample variance of data.
Examples:
If you have already calculated the mean of your data, you can pass it as
the optional second argument ``xbar`` to avoid recalculating it:
>>> m = mean(data)
>>> variance(data, m)
1.3720238095238095
This function does not check that ``xbar`` is actually the mean of
``data``. Giving arbitrary values for ``xbar`` may lead to invalid or
impossible results.
DATA
__all__ = ['NormalDist', 'StatisticsError', 'correlation', 'covariance...
FILE
c:\users\callage\appdata\local\programs\python\python310\lib\statistics.py
In [15]:
cs=[10,20,30,40,50]
print(st.mean(cs))
30
In [17]:
help(st.mode)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 58/104
2/9/22, 10:36 AM CS Lecture-1
mode(data)
Return the most common data point from discrete or nominal data.
``mode`` assumes discrete data, and returns a single value. This is the
standard treatment of the mode as commonly taught in schools:
If there are multiple modes with same frequency, return the first one
encountered:
In [18]:
st.mode([1,2,3,4,2,2,1,5,2,5])
2
Out[18]:
In [19]:
help (st.median)
median(data)
Return the median (middle value) of numeric data.
When the number of data points is odd, return the middle data point.
When the number of data points is even, the median is interpolated by
taking the average of the two middle values:
In [20]:
st.median([1,4,6,5,3,7,9])
5
Out[20]:
In [21]:
help (st.stdev)
stdev(data, xbar=None)
Return the square root of the sample variance.
RANDOM MODULE
In [22]:
import random as ra
dir(ra)
In [23]:
help(ra)
NAME
random - Random variable generators.
MODULE REFERENCE
https://docs.python.org/3.10/library/random.html
DESCRIPTION
bytes
-----
uniform bytes (values between 0 and 255)
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
pick weighted random sample
generate random permutation
CLASSES
_random.Random(builtins.object)
Random
SystemRandom
class Random(_random.Random)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 63/104
2/9/22, 10:36 AM CS Lecture-1
| Random(x=None)
|
| Random number generator base class used by bound module functions.
|
| Used to instantiate instances of Random to get generators that don't
| share state.
|
| Class Random can also be subclassed if you want to use a different basic
| generator of your own devising: in that case, override the following
| methods: random(), seed(), getstate(), and setstate().
| Optionally, implement a getrandbits() method so that randrange()
| can cover arbitrarily large ranges.
|
| Method resolution order:
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| __getstate__(self)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since random w
as
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 64/104
2/9/22, 10:36 AM CS Lecture-1
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| getstate(self)
| Return internal state; can be passed to setstate() later.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu, sigma)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randbytes(self, n)
| Generate n random bytes.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence or set.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 65/104
2/9/22, 10:36 AM CS Lecture-1
| selection in the sample.
|
| Repeated elements can be specified one at a time or with the optional
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| seed(self, a=None, version=2)
| Initialize internal state from a seed.
|
| The only supported seed types are None, int, float,
| str, bytes, and bytearray.
|
| None or no argument seeds from current time or from an operating
| system specific randomness source if available.
|
| If *a* is an int, all bits are used.
|
| For version 2 (the default), all of the bits are used if *a* is a str,
| bytes, or bytearray. For version 1 (provided for reproducing random
| sequences from older versions of Python), the algorithm for str and
| bytes generates a narrower range of seeds.
|
| setstate(self, state)
| Restore internal state from object returned by getstate().
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and
| kappa is the concentration parameter, which must be greater than or
| equal to zero. If kappa is equal to zero, this distribution reduces
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 66/104
2/9/22, 10:36 AM CS Lecture-1
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __init_subclass__(**kwargs) from builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Methods inherited from _random.Random:
|
| getrandbits(self, k, /)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| random(self, /)
| random() -> x in the interval [0, 1).
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
class SystemRandom(Random)
| SystemRandom(x=None)
|
| Alternate random number generator using sources provided
| by the operating system (such as /dev/urandom on Unix or
| CryptGenRandom on Windows).
|
| Not available on all systems (see os.urandom() for details).
|
| Method resolution order:
| SystemRandom
| Random
| _random.Random
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 67/104
2/9/22, 10:36 AM CS Lecture-1
| builtins.object
|
| Methods defined here:
|
| getrandbits(self, k)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| getstate = _notimplemented(self, *args, **kwds)
|
| randbytes(self, n)
| Generate n random bytes.
|
| random(self)
| Get the next random number in the range [0.0, 1.0).
|
| seed(self, *args, **kwds)
| Stub method. Not used for a system random number generator.
|
| setstate = _notimplemented(self, *args, **kwds)
|
| ----------------------------------------------------------------------
| Methods inherited from Random:
|
| __getstate__(self)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since random w
as
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| Exponential distribution.
|
| lambd is 1.0 divided by the desired mean. It should be
| nonzero. (The parameter would be called "lambda", but that is
| a reserved word in Python.) Returned values range from 0 to
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 68/104
2/9/22, 10:36 AM CS Lecture-1
| positive infinity if lambd is positive, and from negative
| infinity to 0 if lambd is negative.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha - 1) * math.exp(-x / beta)
| pdf(x) = --------------------------------------
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| lognormvariate(self, mu, sigma)
| Log normal distribution.
|
| If you take the natural logarithm of this distribution, you'll get a
| normal distribution with mean mu and standard deviation sigma.
| mu can have any value, and sigma must be greater than zero.
|
| normalvariate(self, mu, sigma)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence or set.
|
| Returns a new list containing elements from the population while
| leaving the original population unchanged. The resulting list is
| in selection order so that all sub-slices will also be valid random
| samples. This allows raffle winners (the sample) to be partitioned
| into grand prize and second place winners (the subslices).
|
| Members of the population need not be hashable or unique. If the
| population contains repeats, then each occurrence is a possible
| selection in the sample.
|
| Repeated elements can be specified one at a time or with the optional
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 69/104
2/9/22, 10:36 AM CS Lecture-1
| counts parameter. For example:
|
| sample(['red', 'blue'], counts=[4, 2], k=5)
|
| is equivalent to:
|
| sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)
|
| To choose a sample from a range of integers, use range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| mu is the mean angle, expressed in radians between 0 and 2*pi, and
| kappa is the concentration parameter, which must be greater than or
| equal to zero. If kappa is equal to zero, this distribution reduces
| to a uniform random angle over the range 0 to 2*pi.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ----------------------------------------------------------------------
| Class methods inherited from Random:
|
| __init_subclass__(**kwargs) from builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ----------------------------------------------------------------------
| Data descriptors inherited from Random:
|
| __dict__
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 70/104
2/9/22, 10:36 AM CS Lecture-1
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ----------------------------------------------------------------------
| Data and other attributes inherited from Random:
|
| VERSION = 3
|
| ----------------------------------------------------------------------
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
FUNCTIONS
betavariate(alpha, beta) method of Random instance
Beta distribution.
is equivalent to:
sample(range(10000000), 60)
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
http://en.wikipedia.org/wiki/Triangular_distribution
DATA
__all__ = ['Random', 'SystemRandom', 'betavariate', 'choice', 'choices...
FILE
c:\users\callage\appdata\local\programs\python\python310\lib\random.py
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 73/104
2/9/22, 10:36 AM CS Lecture-1
In [29]:
print(ra.random())
0.06902171704106841
In [30]:
help(ra.random)
In [33]:
help(ra.randint)
In [44]:
print(ra.randint(1,9))
In [45]:
help(ra.choice)
In [54]:
print(ra.choice([11,22,3,44,55,66]))
print(ra.choice("Computer Science"))
print(ra.choice(('a','b','c','d')))
66
t
a
In [55]:
help(ra.shuffle)
In [56]: mh=[12,22,33,44,55,66]
print(id(mh))
ra.shuffle(mh)
print(id(mh))
print(mh)
1905228688576
1905228688576
[55, 33, 44, 22, 66, 12]
OS MODULE
In [57]:
import os
dir(os)
In [58]:
help(os)
NAME
os - OS routines for NT or Posix depending on what system we're on.
MODULE REFERENCE
https://docs.python.org/3.10/library/os.html
DESCRIPTION
This exports:
- all functions from posix or nt, e.g. unlink, stat, etc.
- os.path is either posixpath or ntpath
- os.name is either 'posix' or 'nt'
- os.curdir is a string representing the current directory (always '.')
- os.pardir is a string representing the parent directory (always '..')
- os.sep is the (or a most common) pathname separator ('/' or '\\')
- os.extsep is the extension separator (always '.')
- os.altsep is the alternate pathname separator (None or '/')
- os.pathsep is the component separator used in $PATH etc
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
- os.defpath is the default search path for executables
- os.devnull is the file path of the null device ('/dev/null', etc.)
Programs that import and use 'os' stand a better chance of being
portable between different platforms. Of course, they must then
only use functions that are defined by all platforms (e.g., unlink
and opendir), and leave all pathname manipulation to os.path
(e.g., split and join).
CLASSES
builtins.Exception(builtins.BaseException)
builtins.OSError
builtins.object
nt.DirEntry
builtins.tuple(builtins.object)
nt.times_result
nt.uname_result
stat_result
statvfs_result
terminal_size
class DirEntry(builtins.object)
| Methods defined here:
|
| __fspath__(self, /)
| Returns the path for the entry.
|
| __repr__(self, /)
| Return repr(self).
|
| inode(self, /)
| Return inode of the entry; cached per entry.
|
| is_dir(self, /, *, follow_symlinks=True)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 79/104
2/9/22, 10:36 AM CS Lecture-1
| Return True if the entry is a directory; cached per entry.
|
| is_file(self, /, *, follow_symlinks=True)
| Return True if the entry is a file; cached per entry.
|
| is_symlink(self, /)
| Return True if the entry is a symbolic link; cached per entry.
|
| stat(self, /, *, follow_symlinks=True)
| Return stat_result object for the entry; cached per entry.
|
| ----------------------------------------------------------------------
| Class methods defined here:
|
| __class_getitem__(...) from builtins.type
| See PEP 585
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| name
| the entry's base filename, relative to scandir() "path" argument
|
| path
| the entry's full path name; equivalent to os.path.join(scandir_path, entr
y.name)
class stat_result(builtins.tuple)
| stat_result(iterable=(), /)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 81/104
2/9/22, 10:36 AM CS Lecture-1
|
| stat_result: Result from stat, fstat, or lstat.
|
| This object may be accessed either as a tuple of
| (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)
| or via the attributes st_mode, st_ino, st_dev, st_nlink, st_uid, and so on.
|
| Posix/windows: If your platform supports st_blksize, st_blocks, st_rdev,
| or st_flags, they are available as attributes only.
|
| See os.stat for more information.
|
| Method resolution order:
| stat_result
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| st_atime
| time of last access
|
| st_atime_ns
| time of last access in nanoseconds
|
| st_ctime
| time of last change
|
| st_ctime_ns
| time of last change in nanoseconds
|
| st_dev
| device
|
| st_file_attributes
| Windows file attribute bits
|
| st_gid
| group ID of owner
|
| st_ino
| inode
|
| st_mode
| protection bits
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 82/104
2/9/22, 10:36 AM CS Lecture-1
|
| st_mtime
| time of last modification
|
| st_mtime_ns
| time of last modification in nanoseconds
|
| st_nlink
| number of hard links
|
| st_reparse_tag
| Windows reparse tag
|
| st_size
| total size, in bytes
|
| st_uid
| user ID of owner
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __match_args__ = ('st_mode', 'st_ino', 'st_dev', 'st_nlink', 'st_uid',...
|
| n_fields = 18
|
| n_sequence_fields = 10
|
| n_unnamed_fields = 3
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 83/104
2/9/22, 10:36 AM CS Lecture-1
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...) from builtins.type
| See PEP 585
class statvfs_result(builtins.tuple)
| statvfs_result(iterable=(), /)
|
| statvfs_result: Result from statvfs or fstatvfs.
|
| This object may be accessed either as a tuple of
| (bsize, frsize, blocks, bfree, bavail, files, ffree, favail, flag, namema
x),
| or via the attributes f_bsize, f_frsize, f_blocks, f_bfree, and so on.
|
| See os.statvfs for more information.
|
| Method resolution order:
| statvfs_result
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 84/104
2/9/22, 10:36 AM CS Lecture-1
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| f_bavail
|
| f_bfree
|
| f_blocks
|
| f_bsize
|
| f_favail
|
| f_ffree
|
| f_files
|
| f_flag
|
| f_frsize
|
| f_fsid
|
| f_namemax
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __match_args__ = ('f_bsize', 'f_frsize', 'f_blocks', 'f_bfree', 'f_bav...
|
| n_fields = 11
|
| n_sequence_fields = 10
|
| n_unnamed_fields = 0
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 85/104
2/9/22, 10:36 AM CS Lecture-1
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...) from builtins.type
| See PEP 585
class terminal_size(builtins.tuple)
| terminal_size(iterable=(), /)
|
| A tuple of (columns, lines) for holding terminal window size
|
| Method resolution order:
| terminal_size
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __reduce__(...)
| Helper for pickle.
|
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 86/104
2/9/22, 10:36 AM CS Lecture-1
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| columns
| width of the terminal window in characters
|
| lines
| height of the terminal window in characters
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __match_args__ = ('columns', 'lines')
|
| n_fields = 2
|
| n_sequence_fields = 2
|
| n_unnamed_fields = 0
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 87/104
2/9/22, 10:36 AM CS Lecture-1
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...) from builtins.type
| See PEP 585
class times_result(builtins.tuple)
| times_result(iterable=(), /)
|
| times_result: Result from os.times().
|
| This object may be accessed either as a tuple of
| (user, system, children_user, children_system, elapsed),
| or via the attributes user, system, children_user, children_system,
| and elapsed.
|
| See os.times for more information.
|
| Method resolution order:
| times_result
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 88/104
2/9/22, 10:36 AM CS Lecture-1
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| children_system
| system time of children
|
| children_user
| user time of children
|
| elapsed
| elapsed time since an arbitrary point in the past
|
| system
| system time
|
| user
| user time
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __match_args__ = ('user', 'system', 'children_user', 'children_system'...
|
| n_fields = 5
|
| n_sequence_fields = 5
|
| n_unnamed_fields = 0
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 89/104
2/9/22, 10:36 AM CS Lecture-1
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...) from builtins.type
| See PEP 585
class uname_result(builtins.tuple)
| uname_result(iterable=(), /)
|
| uname_result: Result from os.uname().
|
| This object may be accessed either as a tuple of
| (sysname, nodename, release, version, machine),
| or via the attributes sysname, nodename, release, version, and machine.
|
| See os.uname for more information.
|
| Method resolution order:
| uname_result
| builtins.tuple
| builtins.object
|
| Methods defined here:
|
| __reduce__(...)
| Helper for pickle.
|
| __repr__(self, /)
| Return repr(self).
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 90/104
2/9/22, 10:36 AM CS Lecture-1
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| machine
| hardware identifier
|
| nodename
| name of machine on network (implementation-defined)
|
| release
| operating system release
|
| sysname
| operating system name
|
| version
| operating system version
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __match_args__ = ('sysname', 'nodename', 'release', 'version', 'machin...
|
| n_fields = 5
|
| n_sequence_fields = 5
|
| n_unnamed_fields = 0
|
| ----------------------------------------------------------------------
| Methods inherited from builtins.tuple:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 91/104
2/9/22, 10:36 AM CS Lecture-1
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ----------------------------------------------------------------------
| Class methods inherited from builtins.tuple:
|
| __class_getitem__(...) from builtins.type
| See PEP 585
FUNCTIONS
_exit(status)
Exit to the system with specified status, without normal exit processing.
abort()
Abort the interpreter immediately.
This function 'dumps core' or otherwise fails in the hardest way possible
on the hosting operating system. This function never returns.
path
Path to be tested; can be string, bytes, or a path-like object.
mode
Operating-system mode bitfield. Can be F_OK to test existence,
or the inclusive-OR of R_OK, W_OK, and X_OK.
dir_fd
If not None, it should be a file descriptor open to a directory,
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 92/104
2/9/22, 10:36 AM CS Lecture-1
Note that most operations will use the effective uid/gid, therefore this
routine can be used in a suid/sgid environment to test if the invoking user
has the specified access to the path.
chdir(path)
Change the current working directory to the specified path.
path
Path to be modified. May always be specified as a str, bytes, or a path-
like object.
On some platforms, path may also be specified as an open file descriptor.
If this functionality is unavailable, using it raises an exception.
mode
Operating-system mode bitfield.
dir_fd
If not None, it should be a file descriptor open to a directory,
and path should be relative; path will then be relative to that
directory.
follow_symlinks
If False, and the last element of the path is a symbolic link,
chmod will modify the symbolic link itself instead of the file
the link points to.
close(fd)
Close a file descriptor.
closerange(fd_low, fd_high, /)
Closes all file descriptors in [fd_low, fd_high), ignoring errors.
cpu_count()
Return the number of CPUs in the system; return None if indeterminable.
This number is not equivalent to the number of CPUs the current process can
use. The number of usable CPUs can be obtained with
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 93/104
2/9/22, 10:36 AM CS Lecture-1
``len(os.sched_getaffinity(0))``
device_encoding(fd)
Return a string describing the encoding of a terminal's file descriptor.
dup(fd, /)
Return a duplicate of a file descriptor.
execl(file, *args)
execl(file, *args)
Execute the executable file with argument list args, replacing the
current process.
execle(file, *args)
execle(file, *args, env)
execlp(file, *args)
execlp(file, *args)
execlpe(file, *args)
execlpe(file, *args, env)
execv(path, argv, /)
Execute an executable path with arguments, replacing current process.
path
Path of executable file.
argv
Tuple or list of strings.
path
Path of executable file.
argv
Tuple or list of strings.
env
Dictionary of strings mapping to strings.
execvp(file, args)
execvp(file, args)
fsdecode(filename)
Decode filename (an os.PathLike, bytes, or str) from the filesystem
encoding with 'surrogateescape' error handler, return str unchanged. On
Windows, use 'strict' error handler if the file system encoding is
'mbcs' (which is the default encoding).
fsencode(filename)
Encode filename (an os.PathLike, bytes, or str) to the filesystem
encoding with 'surrogateescape' error handler, return bytes unchanged.
On Windows, use 'strict' error handler if the file system encoding is
'mbcs' (which is the default encoding).
fspath(path)
Return the file system path representation of the object.
If the object is str or bytes, then allow it to pass through as-is. If the
object defines __fspath__(), then return the result of that method. All other
types raise a TypeError.
fstat(fd)
Perform a stat system call on the given file descriptor.
fsync(fd)
Force write of fd to disk.
ftruncate(fd, length, /)
Truncate a file, specified by file descriptor, to a specific length.
get_exec_path(env=None)
Returns the sequence of directories that will be searched for the
named executable (similar to a shell) when launching a process.
get_handle_inheritable(handle, /)
Get the close-on-exe flag of the specified file descriptor.
get_inheritable(fd, /)
Get the close-on-exe flag of the specified file descriptor.
get_terminal_size(...)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 95/104
2/9/22, 10:36 AM CS Lecture-1
getcwd()
Return a unicode string representing the current working directory.
getcwdb()
Return a bytes string representing the current working directory.
getenv(key, default=None)
Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default.
key, default and the result are str.
getlogin()
Return the actual login name.
getpid()
Return the current process id.
getppid()
Return the parent's process id.
If the parent process has already exited, Windows machines will still
return its id; others systems will return the id of the 'init' process (1).
isatty(fd, /)
Return True if the fd is connected to a terminal.
kill(pid, signal, /)
Kill a process with a signal.
listdir(path=None)
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 96/104
2/9/22, 10:36 AM CS Lecture-1
lstat(path, *, dir_fd=None)
Perform a stat system call on the given path, without following symbolic link
s.
Super-mkdir; create a leaf directory and all intermediate ones. Works like
mkdir, except that any intermediate path segment (not just the rightmost)
will be created if it does not exist. If the target directory already
exists, raise an OSError if exist_ok is False. Otherwise no exception is
raised. This is recursive.
pipe()
Create a pipe.
putenv(name, value, /)
Change or add an environment variable.
read(fd, length, /)
Read from a file descriptor. Returns a bytes object.
readlink(path, *, dir_fd=None)
Return a string representing the path to which the symbolic link points.
remove(path, *, dir_fd=None)
Remove a file (same as unlink()).
removedirs(name)
removedirs(name)
renames(old, new)
renames(old, new)
Note: this function can fail with the new directory structure made
if you lack permissions needed to unlink the leaf directory or
file.
rmdir(path, *, dir_fd=None)
Remove a directory.
scandir(path=None)
Return an iterator of DirEntry objects for given path.
set_handle_inheritable(handle, inheritable, /)
Set the inheritable flag of the specified handle.
set_inheritable(fd, inheritable, /)
Set the inheritable flag of the specified file descriptor.
mode
Mode of process creation.
path
Path of executable file.
argv
Tuple or list of strings.
mode
Mode of process creation.
path
Path of executable file.
argv
Tuple or list of strings.
env
Dictionary of strings mapping to strings.
startfile(...)
Start a file with its associated application.
path
Path to be examined; can be string, bytes, a path-like object or
open-file-descriptor int.
dir_fd
If not None, it should be a file descriptor open to a directory,
and path should be a relative string; path will then be relative to
that directory.
follow_symlinks
If False, and the last element of the path is a symbolic link,
stat will examine the symbolic link itself instead of the file
the link points to.
strerror(code, /)
Translate an error code to a message string.
system(command)
Execute the command in a subshell.
times()
Return a collection containing process timing information.
The object returned behaves like a named tuple with these fields:
(utime, stime, cutime, cstime, elapsed_time)
All fields are floating point numbers.
truncate(path, length)
Truncate a file, specified by path, to a specific length.
umask(mask, /)
Set the current numeric umask and return the previous umask.
unlink(path, *, dir_fd=None)
Remove a file (same as remove()).
unsetenv(name, /)
Delete an environment variable.
urandom(size, /)
Return a bytes object containing random bytes suitable for cryptographic use.
utime(...)
Set the access and modified time of path.
waitpid(pid, options, /)
Wait for completion of a given process.
waitstatus_to_exitcode(status)
Convert a wait status to an exit code.
On Unix:
For each directory in the directory tree rooted at top (including top
itself, but excluding '.' and '..'), yields a 3-tuple
When topdown is true, the caller can modify the dirnames list in-place
(e.g., via del or slice assignment), and walk will only recurse into the
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 102/104
2/9/22, 10:36 AM CS Lecture-1
subdirectories whose names remain in dirnames; this can be used to prune the
search, or to impose a specific order of visiting. Modifying dirnames when
topdown is false has no effect on the behavior of os.walk(), since the
directories in dirnames have already been generated by the time dirnames
itself is generated. No matter the value of topdown, the list of
subdirectories is retrieved before the tuples for the directory and its
subdirectories are generated.
Caution: if you pass a relative pathname for top, don't change the
current working directory between resumptions of walk. walk never
changes the current directory, and assumes that the client doesn't
either.
Example:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end="")
print(sum(getsize(join(root, name)) for name in files), end="")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
write(fd, data, /)
Write a bytes object to a file descriptor.
DATA
F_OK = 0
O_APPEND = 8
O_BINARY = 32768
O_CREAT = 256
O_EXCL = 1024
O_NOINHERIT = 128
O_RANDOM = 16
O_RDONLY = 0
O_RDWR = 2
O_SEQUENTIAL = 32
O_SHORT_LIVED = 4096
O_TEMPORARY = 64
O_TEXT = 16384
O_TRUNC = 512
O_WRONLY = 1
P_DETACH = 4
P_NOWAIT = 1
P_NOWAITO = 3
P_OVERLAY = 2
P_WAIT = 0
R_OK = 4
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 103/104
2/9/22, 10:36 AM CS Lecture-1
SEEK_CUR = 1
SEEK_END = 2
SEEK_SET = 0
TMP_MAX = 2147483647
W_OK = 2
X_OK = 1
__all__ = ['altsep', 'curdir', 'pardir', 'sep', 'pathsep', 'linesep', ...
altsep = '/'
curdir = '.'
defpath = r'.;C:\bin'
devnull = 'nul'
environ = environ({'ALLUSERSPROFILE': 'C:\\ProgramData', '...D': 'modu...
extsep = '.'
linesep = '\r\n'
name = 'nt'
pardir = '..'
pathsep = ';'
sep = r'\'
supports_bytes_environ = False
FILE
c:\users\callage\appdata\local\programs\python\python310\lib\os.py
In [1]:
import cspack
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7608/114026375.py in <module>
----> 1 import cspack