__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------==================================================================================="""
PART -1===================================================================================
Topics to be covered in today's class:
--> Pass by Value vs Pass by Reference
--> call by value vs call by reference
--> return keyword or return statement:
--> Scope of variables
1. Global variables
2. Local variables
--> Recursive function with example
--> Interview questions
"""
"""
Pass by Value vs Pass by Reference
call by value vs call by reference
All parameters (arguments) in the Python language are passed by reference.
It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −
"""
# # CALL BY VALUE
# numbers, strings and tuples are immutable data types,
# Even though values are same, for different variables they will be stored in same memory location
x = 40562 # Initialization
y = 40562
# print(id(x)) # will give memory location / address / reference
# print(id(y))
str_1= "kruthika"
str_2 = "kruthika"
# print(id(str_1))
# print(id(str_2))
tuple_1 = (1, 2, 3)
tuple_2 = (1, 2, 3)
# print(id(tuple_1))
# print(id(tuple_2))
# list is a mutable data type, they will be stored in different memory location
i = [1, 2, 3]
j = [1, 2, 3]
# print(id(i))
# print(id(j))
# nanditha = 340
# raahi = 340
# venkat = 340
# karthik = 340
# print(id(nanditha), id(raahi), id(venkat), id(karthik))
# Function definition is here
def change_me(mylist):
"""This changes a passed list into this function """
print("Values inside the function before change: ", mylist)
mylist = "Narendra" # This would assign new reference in mylist
print("Values inside the function after change: ", mylist)
# Now you can call change_me function
# mylist = [10, 20, 30] # global variable
# change_me(mylist)
# print("Values outside the function: ", mylist)
def change_me(mylist):
''' This changes a passed list into this function '''
print("Values inside the function before change: ", mylist)
mylist = "Narendra" # This would assign new reference in mylist
mylist = mylist.upper()
print("Values inside the function after change: ", mylist)
"""Now you can call change_me function"""
# mylist = [10, 20, 30] # global variable
# change_me(mylist) # Always calling function will be replaced with it's return value/values
# print("Values outside the function: ", mylist)
"""
The parameter mylist is local to the function changeme.
Changing mylist within the function does not affect mylist.
The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
"""
# 02 Call by reference
# Function definition is here
def change_me(mylist):
"This changes a passed list into this function"
print("Values inside the function before change: ", mylist)
mylist.insert(1, "nanditha")
# mylist.reverse()
print("Values inside the function after change: ", mylist)
# Now you can call changeme function
# mylist = [10, 20, 30] # memory created for the value not for the variable
# change_me(mylist) # Always calling function will be replaced with it's return value/values
# print("Values outside the function: ", mylist)
'''
Here, we are maintaining reference of the passed object and appending values in the same object.
Therefore, this would produce the following result −
Values inside the function before change: [10, 20, 30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
'''
"""
return keyword/Statement:
syntax:
return [expression/Value/values]
The statement return [expression/value] exits a function, optionally passing back an expression to the caller.
A return statement with no arguments is the same as "return None"
All the examples given below are not returning any value. You can return a value from a function as follows −
"""
"""
Scope of Variables
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 −
1. Global variables
2. Local variables
#Global vs. Local variables
Variables that are defined inside a function body have a local scope,
and those defined outside have a global scope.
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, x``the variables declared inside it are brought into scope.
Following is a simple example −
"""
# raahi = 200 # This is global variable.
# total = 100 # This is global variable.
# nanditha = 300 # This is global variable.
# nanditha = 400
# print(raahi, total,nanditha)
# Function definition is here
def sum(arg1, arg2):
# Add both the parameters and return them."
ganesh = 300 # local variable
nandhitha = 500 # local variable
total = arg1 + arg2 # Here total is local variable (new value assigned to it)
print ("Inside the function total value is : ", total)
return total
# Now you can call sum function
# sum(10, 20)
# total = sum(10, 20) # Always calling function will be replaced with it's return value/s
# print("Outside the function global total : ", total)
#============================================================================
# x = 10,20,30 # if user try to assign several values to the single variable, then values will be store in tuple
# print(x)
#
# x, y, z = 10, 20, 30
# print(y)
#============================================================================
def sum_mul(arg1, arg2, arg3):
"""
this function will perform addition and multiplication
:param arg1: have to provide maths marks
:param arg2: have to provide english
:param arg3:
:return: this program will return sum & multiplication values
"""
total = arg1 + arg2 + arg3
mul = arg1 * arg2 * arg3
div = mul/total # division operator always return float value
modulus = mul % div # gives remainder
print("Inside the function : ", total, mul, div,modulus)
return total, mul, div, modulus
# # # Now you can call sum function
# sum_mul(10, 20, 30)
# ganesh = sum_mul(10, 20, 30) # Always calling function will be replaced with it's return value/s
# print(ganesh)
# total, mul, div, modulus = sum_mul(2, 4, 6) # Always calling function will be replaced with it's return value/s
# print(total, mul, div, modulus)
#
# ganesh, jaya, mani, varun = sum_mul(12, 24, 6) # Always calling function will be replaced with it's return value/s
# print(ganesh, jaya, mani, varun)
"""
########### Recursive functions ########
A recursive function is a function that calls itself during its execution.
Syntax:
def func(): <--
|
| (recursive call)
|
func() ----
"""
"""
Recursive function Example 1 : Find the factorial of a number
4! = 4*3*2*1 = 24
5! = 5*4*3*2*1 = 120
6! = 6*5*4*3*2*1 = 720
"""
def calc_factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * calc_factorial(x-1))
# required_factorial_number = 4
# factorial_value = calc_factorial(required_factorial_number)
# print(factorial_value)
# required_factorial_number = int(input("Enter number for factorial: "))
# print(calc_factorial(required_factorial_number))
# print("The factorial of {0} is {1} ".format(required_factorial_number, calc_factorial(required_factorial_number)))
"""
Explanation of above example
In the above example, calc_factorial() is a recursive functions as it calls itself.
When we call this function with a positive integer, it will recursively call itself by decreasing the number.
Each function call multiples the number with the factorial of number 1 until the number is equal to one.
This recursive call can be explained in the following steps.
calc_factorial(4) # 1st call with 4
4 * calc_factorial(3) # 2nd call with 3
4 * 3 * calc_factorial(2) # 3rd call with 2
4 * 3 * 2 * calc_factorial(1) # 4th call with 1
4 * 3 * 2 * 1 # return from 4th call as number=1
24
"""
"""
Recursive function Example 2 : Program to print the fibonacci series upto n_terms
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5,8,
"""
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
# n_terms = int(input("Enter interger value: ")) # Ex: n_terms = 5
#
# # check if the number of terms is valid
# if n_terms <= 0:
# print("Invalid input provided! Please provide value more than 1")
# else:
# print("Fibonacci series:", end=" ")
# for i in range(n_terms): # range by default start with 0 range(5) == range(0,5) == [0, 1, 2, 3, 4]
# # print(recursive_fibonacci(i)) # Always calling function will be replaced with it's return value
# print(recursive_fibonacci(i), end=" ") # if tou want to print in single line
#
"""
console output:
Fibonacci series: 0 1 1 2 3 5 8
"""
import math
# print(math.factorial(5))
# Interview question :
# =================
def respective_data(x, *y, **z):
print(x, y, z)
# narendra(1,2,3,4,5,"Bhagyasree",x =11, y=12,z=13)
# output: TypeError: Narendra() got multiple values for argument 'x'
def cal(a, b, x):
c = a + b
d = a * b
x += 10
print(c, d, x)
return c, d, x
cal(2, 3, 4)
# raja, vinod, kavya = cal(2, 3, 4) # calling function will be replace with it's return values
# c, d, x = c, d, x # dummy
# print(raja, vinod, kavya)
# we can use different variables (identifiers) for capturing return values
# mounika, sunny, naziya = cal(2, 1.5, 5)
# print(mounika, sunny, naziya)
# we can capture retutn values in single variable (but it will store in tuple)
# jayanth_1 = cal(2, 1.5, 5)
# prin t(jayanth_1)===================================================================================
PART -2===================================================================================__author__ = "Narendra Boyina"
# -----------------------------------------------------------------------------
# Copyright (c) 2025 BR Technologies PVT LTD
# -----------------------------------------------------------------------------
"""
Topics to be covered in today's class:
--> what is Lambda function
--> map(), filter(), zip(), unzip()
--> enumerate concept with zip
--> Difference between sort() and sorted()
--> Sorting a List of Tuples using Lambda
--> Sorting a List of Dictionaries using Lambda
--> Practice programs
"""
"""
lambda function:
1) lambda function is called as "single line anonymous function" because it will not be declared in the standard manner
by using the "def" keyword.
2) You can use the lambda keyword to create small anonymous functions.
3) lambda function can take any number of arguments (input values) but return just one value in the form of an expression.
They cannot contain commands or multiple expressions.
x = ((a+b)*c/d)%e
Syntax: variable = lambda arg1 [arg2,arg3,.....argn]:expression
Note: variable works as a function name
"""
a = 10
b = 20
d = 2
def venkat(a, b, c):
d = a+b
e = d*c
f = e/2 # float vales
sujana = d+e+f
rindha = e-d
return d,e,f, sujana, rindha
# narendra, priyanka, ganesh, raahi, nanditha = venkat(2,4,2)
# print(narendra, priyanka, ganesh, raahi, nanditha)
varun = lambda a, b, d:((a+b)*d)/2
# print(varun(2, 4, 2))
Bharath = lambda arg1, arg2: arg1 + arg2
# print(Bharath) # it will give the memory location because you have not a passed any inputs
# # calling function
# print("Value of total : ", Bharath(10, 20))
# print("Value of total : ", Bharath(30, 40))
# print("Value of total : ", Bharath(60, 90))
calculation = lambda a, b: a**b
# print(calculation) # it will give the memory location because you have not apassed any inputs
#
# calling function
# print(calculation(2, 4))
# print(calculation(3,4))
# 2. Map Function
# =============
"""
map() :
map() will apply the same function to every element of iterable/sequence and
return a list of the results.
Syntax :
map(function_name, iterable, ...)
"""
# x = []
# for i in range(1, 16):
# z = i**i
# x.append(z)
# print(x)
# Ex : Create a list of squares for the first 5 numbers
def print_powers(x):
y = x**x
return y
# iterable = [1, 2, 3, 4, 5, 6, 7] # range(1, 8)
# iterable = range(1, 8)
# return_obj = map(print_powers, [1, 2, 3, 4, 5, 6, 7])
# print(return_obj)
# print(list(return_obj))
# print(list(map(print_powers, iterable)))
# iterable = range(1, 5)
# squares = map(lambda x: x**x, iterable)
# print(list(squares))
# squares = list(map(lambda x: x**x, iterable))
# squares = list(map(lambda x: x**x, range(1,6)))
# print(squares)
# squares = tuple(map(lambda x: x**x, range(1, 6)))
# print(squares)
# Note:- Need not necessarily use a lambda function print(list(map(square, iterable)))
# Filter Function:
# ================
""""
3. filter() :
The function filter(function_name, iterable) offers way, to filter out all the elements of a list,
for which the function returns True.
(or)
Filter items out of a sequence, returns filtered list
"""
# Ex: Print only the even numbers from 20 to 41
# def is_even(x):
# if x % 2 == 0: # remainder
# return x
# x = filter(is_even, range(20,41))
# print(list(x))
# print(list(filter(is_even, range(20,41))))
# or
# print(list(filter(lambda x :x%2==0, range(20, 41))))
# print(list(filter(lambda x :x%2==1, range(20, 41))))
# O / P: [20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]
# def div_5_and_7(x):
# if x % 5 == 0 and x%7 == 0: # remainder
# return x
#
#
# x = list(filter(div_5_and_7, range(20, 100)))
# print(x)
# print(list(filter(lambda x : x % 5 == 0 and x%7 == 0, range(20, 100))))
"""zip() function:
it will take multiple lists say list1, list2, etc and transform them into a single list of
tuples by taking the corresponding elements of the lists that are passed as parameters.
zip always creates the tuple in the order of iterables from left to right.
execute the below code in 2.7.x version it will give list of tuples.
"""
list_a = [1, 2, 3, 66, 88]
list_b = ['a', 'b', 'c']
# zipped_list = zip(list_a, list_b) # execute only in python 2.7.x version
# print(zipped_list) # it will print object (some memory location)
# print(list(zipped_list))
# or
# print(list(zip(list_a,list_b)))
"""If you take 2 tuples also zip() function will return 'list of tuples' """
tuple_1 = (1, 2, 3, 4)
tuple_2 = ('a', 'b', 'c', 'd', 'e')
# print(list(zip(tuple_1,tuple_2)))
# In Python3, zip methods returns a zip object instead of a list. This zip object is an iterator.
# Iterators are lazily evaluated.
# Iterators returns only element at a time. len function cannot be used with iterators. We can loop over the zip object
# or the iterator to get the actual list
list_a = [1, 2, 3, 4, 5]
list_b = ['a', 'b', 'c', 'd', 'e']
zipped_list = zip(list_a, list_b) # where zipped_list is an object
""" To see the values present in the zip object we have to pass zip object to list()"""
N = list(zipped_list) # [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]
# print(N)
# print(dict(N))
# B = list(zipped_list) # Output []... Output is empty list because by the above statement zip got exhausted.
# print(B)
""" simple way is directly pass zip_object to dict() instead of converting into list"""
# print(dict(zip(list_a, list_b)))
#
# # zip with more than 2 lists
list1 = ['A', 'B', 'C', 'd']
list2 = [10, 20, 30, 40]
list3 = ["Narendra", "Surendra", "Aruna"]
# x = list(zip(list1, list2,list3))
# print(x) # results in a list of tuples say [('A', 10, 'Narendra'), ('B', 20, 'Surendra'), ('C', 30, 'Aruna')])
# print(dict(x)) # error
"""whenever the given lists are of different lengths, zip stops generating tuples when the first list ends"""
# print(dict(zip(["Narendra", "Surendra", "Aruna"], [10, 20, 30, 40, 50])))
# print(dict(zip(("Narendra", "Surendra", "Aruna"), (10, 20, 30, 40, 50))))
"""
Unzip a list of tuples
To unzip a list of tuples we zip(*listP_of_tuples). Unzip creates separate list."""
zipper_list = [(1, 'a'), (2, 'b'), (3, 'c')]
x, y = zip(*zipper_list)
print(x) # (1, 2, 3)
print(y) # ('a', 'b', 'c')
# reverse apply of unzip
print(list(zip(x,y))) # [(1, 'a'), (2, 'b'), (3, 'c')]
#
# For loop on zip concept
# Python program that uses zip on list
""" use single for loop to iterate 2 lists at a time"""
data1 = ["blue", "red", "green", "white"]
data2 = ["sky", "sunset", "lawn", "pillow"]
# Zip the two lists and access pairs together.
# for x, y in zip(data1, data2):
# print(x, "====>",y)
""" use single for loop to iterate 3 lists at a time"""
data1 = ["blue", "red", "green", "white"]
data2 = ["sky", "sunset", "lawn", "pillow"]
data3 = ["kruthika", "kavya", "meera", "narendra"]
# print(list(zip(data1, data2)))
# Zip the two lists and access pairs together.
# for x, y, z in zip(data1, data2, data3):
# print(x, "====>",y, "===>",z)
# enumerate concept with zip
# Here is how to iterate over two lists and their indices using enumerate together with zip:
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']
# for i, (a, b) in enumerate(zip(alist, blist)):
# print(i+1, a, b)
"""The main difference between sort() and sorted() in Python lies in how you perform sorting on lists.
“sort()” modifies the original list in place, while “sorted()” creates a new sorted list.
"""
"""Sorting a List of Tuples using Lambda"""
# x = [1,5,2,7,3,9]
# x.sort()
# print(x)
# list1 = [('eggs', 5.25), ('honey', 9.70), ('carrots', 1.10), ('peaches', 2.45)]
# list1.sort(key = lambda x: x[1])
# print(list1)
# # ans:[('carrots', 1.1), ('peaches', 2.45), ('eggs', 5.25), ('honey', 9.7)]
"""Sorting a List of Dictionaries using Lambda"""
# import pprint
# list1 = [{'make':'Ford', 'model':'Focus', 'year':2013}, {'make':'Tesla', 'model':'X', 'year':1999}, {'make':'Mercedes', 'model':'C350E', 'year':2008}]
# list2 = sorted(list1, key = lambda x: x['year'])
# pprint.pprint(list2)
# # Ans : [{'make': 'Tesla', 'model': 'X', 'year': 1999},
# # {'make': 'Mercedes', 'model': 'C350E', 'year': 2008},
# # {'make': 'Ford', 'model': 'Focus', 'year': 2013}]
# Ex : Find the cube of a given number
################ Practice programs ######################
# cube = lambda x : x**3
# print(cube(2))
# print(cube(4))
# Note: like function we can reuse lambda function so many times (not like zip exhausted)
# input_string = input("")
# print("\n")
# input_list = input_string.split()
# for i in range(len(input_list)):
# input_list[i] = int(input_list[i])
# res = [ele for ele in range(max(input_list)+1) if ele not in input_list]
# print(res)
# print(ord("A"))
# print(chr(65))
def consecutive_str_validate(input_string):
l = len(input_string)
s = ''.join(sorted(input_string))
# print("*********",s)
for i in range(1, l):
if ord(s[i]) - ord(s[i - 1]) != 1:
return False
return True
# if __name__ == "__main__":
# input_string = "bcd"
# if consecutive_str_validate(input_string):
# print("true")
# else:
# print("false")
# input_string = "indusree"
# if consecutive_str_validate(input_string):
# print("true")
# else:
# print("false")
"""W.A.P to print missing numbers in a given list"""
def missing_num(lst):
missing_numbers=[]
flag=0
for n in range(1,lst[-1]+1):
if n not in lst:
# print(n," is missing")
missing_numbers.append(n)
flag+=1 # flag to count no of missing numbers
else:
continue
print(missing_numbers)
if(flag==0): # when flag is 0 print "no missing numbers"
print("Nothing is missing")
# lst=[1,2,4,5,8,10]
# lst=[1,2,3,4,5,6,7,8,9,10]
# missing_num(lst)Author: Boyina Narendra
Supporting Author: M. Meera Sindhu
Request: If you find this information useful, please provide your valuable comments
No comments:
Post a Comment