0% found this document useful (0 votes)
13 views

dl lab-2

Deep learning lab manual

Uploaded by

Kavitha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

dl lab-2

Deep learning lab manual

Uploaded by

Kavitha
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT 3

PART A:
1. Comment with an eg on the use of local and global identifier name.(N/D22&23)
 The scope of a variable refers to the places that we can see or access a variable. If we define a variable
on the top of the script or module, the variable is called global variable. The variables that are defined
inside a class or function is called local variable.
Eg:
def my_local():
a=10
print(“This is local variable”)
Eg:
a=10
def my_global():
print(“This is global variable”)

2. Define fruitful function(N/D22&23)


A function that returns a value is called fruitful function.
Example:
Root=sqrt (25)

3. Compare return value and composition(A/M23)


Return Value:
Return gives back or replies to the caller of the function. The return statement causes our function to exit and
hand over back a value to its caller.
Eg:
def area(radius):
temp = math.pi * radius**2

return temp

Composition:
Calling one function from another is called composition.
Eg:
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)

result = area(radius)

return result
4. Define string immutability(A/M23)
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t mutate the
string but can change what value of the variable to a new string

5. Write purposes of pass statement(A/M22)


Using a pass statement is an explicit way of telling the interpreter to do nothing.
 It is used when a statement is required syntactically but you don’t want any code to execute.
 It is a null statement , nothing happens when it is executed.

6. What is linear search? (A/M22)


Linear search is one of the simplest searching algorithms. It works by checking each element of a list
sequentially until the desired element is found or the end of the list is reached. It's straightforward and
easy to implement, but it's not the most efficient for large datasets because its time complexity is O(n),
where n is the number of elements in the list.

7. Name the two types of iterative statements (J22)


• While loop
• Nested loop
• For loop

8. Define recursive function (J22)


A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion

9. What is len function? Give eg for how it is used on string (A/M24)


The function len returns the length of a list, which is equal to the number of elements.

len(list2) → 8
len(list3) → 4

10. How to split strings and what function is used to perform operation? (A/M24)
split() – returns a list of words in string
text = "Hello, world! Welcome to Python."
words = text.split()
print(words)
# Output: ['Hello,', 'world!', 'Welcome', 'to', 'Python.']
11. Why are string immutable? (N/D22)
Python strings are immutable. ‘a’ is not a string. It is a variable with string value. We can’t mutate the
string but can change what value of the variable to a new string

12. Write for a loop that prints no from 0 to 57 using range function in python (N/D23)
Program:
for number in range(58):
print(number)

PART B:
1. Write python program for finding square root of numbers without using inbuilt function
and explain (N/D22)8M
Newton-Raphson method:
Steps:
 Initial Guess: Start with an initial guess for the square root.
 Iterative Improvement: Improve the guess iteratively using the formula:
 new_guess=guess+nguess2\text{new\_guess} = \frac{\text{guess} + \frac{n}{\
text{guess}}}{2}
 Convergence Check: Repeat the steps until the guess converges to a stable value (i.e.,
the change between iterations is very small)
Program:
def newtonsqrt(n):
root=n/2
for i in range(10):
root=(root+n/root)/2
print(root)
n=eval(input("enter number to find Sqrt: "))
newtonsqrt(n)
OUTPUT: enter number to find Sqrt: 9 3.0

2. Write python program for linear and binary search and its implementation in
detail(N/D22).
Linear Search

Linear search is a simple search algorithm that checks each element of a list sequentially until the
desired element is found or the end of the list is reached. It's straightforward but not very efficient for
large datasets.

Implementation

def linear_search(arr, target):


for index, element in enumerate(arr):
if element == target:
return index
return -1

# Example usage
numbers = [10, 23, 45, 70, 11, 15]
target = 70
result = linear_search(numbers, target)

if result != -1:
print(f'Element found at index {result}')
else:
print('Element not found')

Binary Search
Binary search is a more efficient algorithm that works on sorted lists. It repeatedly divides the search
interval in half and compares the target with the middle element.

Implementation
def binary_search(arr, target):
left, right = 0, len(arr) - 1

while left <= right:


mid = left + (right - left) // 2

# Check if target is present at mid


if arr[mid] == target:
return mid
# If target is greater, ignore the left half
elif arr[mid] < target:
left = mid + 1
# If target is smaller, ignore the right half
else:
right = mid - 1
# Target is not present in the array
return -1

# Example usage
numbers = [10, 23, 45, 70, 11, 15]
numbers.sort() # Binary search requires a sorted array
target = 70
result = binary_search(numbers, target)

if result != -1:
print(f'Element found at index {result}')
else:
print('Element not found')
3. Explain string module (A/M23)
String modules:
 A module is a file containing Python definitions, functions, statements.
 Standard library of Python is extended as modules.
 To use these modules in a program, programmer needs to import the module.
 Once we import a module, we can reference or use to any of its functions or variables in our code.
 There is large number of standard modules also available in python.
 Standard modules can be imported the same way as we import our user-defined modules.
Syntax:
import module_name
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
print(string.capwords("happ KLMNOPQRSTUVWXYZ!"#$%&'()*+,-
y birthday")) ./:;<=>?@[\]^_`{|}~
print(string.hexdigits) Happy Birthday
print(string.octdigits) 0123456789abcdefABCDEF
01234567

Escape sequences in string


Escape Description example
Sequence
\n new line >>> print("hai \nhello")
hai
hello
\\ prints Backslash (\) >>> print("hai\\hello")
hai\hello
\' prints Single quote (') >>> print("'")
'
\" prints Double quote >>>print("\"")
(") "
\t prints tab sapace >>>print(“hai\thello”)
hai hello
\a ASCII Bell (BEL) >>>print(“\a”)

4. Write program for finding sum and array of numbers (A/M23)


Array:
Array is a collection of similar elements. Elements in the array can be accessed by index. Index
starts with 0. Array can be handled in python by module named array.
To create array have to import array module in the program.
Syntax :
import array
Syntax to create array:
Array_name = module_name.function_name(‘datatype’,[elements])
example:
a=array.array(‘i’,[1,2,3,4])
a- array name
array- module name i- integer datatype
Example
Program to find sum of Output
array elements

import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)

5. Write python program to perform search operation which sequentially checks each
element of list until a match is found or who the list is searched (A/M23)
PROGRAM
def linear_search(arr, target):
for index, element in enumerate(arr):
if element == target:
return index
return -1

# Example usage
numbers = [10, 23, 45, 70, 11, 15]
target = 70
result = linear_search(numbers, target)

if result != -1:
print(f'Element found at index {result}')
else:
print('Element not found')

6. Explain the string function and its types(A/M22)

• String functions are built-in methods in Python used to manipulate and process strings.
• These functions make it easier to work with string data by providing tools to perform various
operations.
• Here’s an overview of some common string functions and their types:
 Common String Functions:
 len()
o Description: Returns the length of the string.
o Usage: len("hello") returns 5.
 str()
o Description: Converts the specified value into a string.
o Usage: str(123) returns "123".
 lower()

 Description: Converts all characters in the string to lowercase.


 Usage: "HELLO".lower() returns "hello".
 upper()
 Description: Converts all characters in the string to uppercase.
 Usage: "hello".upper() returns "HELLO".
 capitalize()
 Description: Capitalizes the first character of the string.
 Usage: "hello".capitalize() returns "Hello".
 title()
 Description: Converts the first character of each word to uppercase.
 Usage: "hello world".title() returns "Hello World".
 find()
 Description: Returns the index of the first occurrence of the specified substring.
 Usage: "hello".find("e") returns 1.
 replace()
 Description: Replaces all occurrences of a specified substring with another.
 Usage: "hello world".replace("world", "Python") returns "hello Python".

 split()
 Description: Splits the string into a list of substrings based on a delimiter.
 Usage: "hello world".split(" ") returns ["hello", "world"].
 join()
 Description: Joins the elements of a list into a single string, separated by a specified delimiter.
 Usage: " ".join(["hello", "world"]) returns "hello world".
 count()
 Description: Returns the number of occurrences of a specified substring.
 Usage: "hello".count("l") returns 2.
 isalpha()
 Description: Checks if all characters in the string are alphabetic.
 Usage: "hello".isalpha() returns True.
 isdigit()
 Description: Checks if all characters in the string are digits.
 Usage: "123".isdigit() returns True.
 islower()
 Description: Checks if all characters in the string are lowercase.
 Usage: "hello".islower() returns True.
 isupper()
 Description: Checks if all characters in the string are uppercase.
 Usage: "HELLO".isupper() returns True.

7. Explain the difference between break and continue in python with eg (A/M22)

1.BREAK
 Break statements can alter the flow of a loop.
 It terminates the current
 loop and executes the remaining statement outside the loop.
 If the loop has else statement, that will also gets terminated and come out of the loop completely.
Syntax:
Break

Flowchart:

example Output
for i in "welcome": w
if(i=="c"): e
break l
print(i)

CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the loop.
Syntax: Continue

Flowchart

Example:
for i in "welcome": if(i=="c"):
continue print(i)
Output
we l ome

8. Explain the conditional branching with eg(J23)


Illustrate the different types of control flow statements with flowcharts (N/D23)

Conditional Statements

 Conditional if
 Alternative if… else
 Chained if…elif…else
 Nested if….else

Conditional (if):
conditional (if) is used to test a condition, if the condition is true the statements inside if will be executed.
syntax:

Flowchart

Program to provide bonus mark if the category is output


sports
m=eval(input(“enter ur mark out of 100”)) enter ur mark out of 100
c=input(“enter ur categery G/S”) 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90
Alternative (if-else):
In the alternative the condition must be true or false. In this else statement can be combined with if
statement. The else statement contains the block of code that executes when the condition is false. If the
condition is true statements inside the if get executed otherwise else part gets executed. The alternatives are
called branches, because they are branches in the flow of execution.
syntax:
Flowchart:

Example

Odd or even number Output


n=eval(input("enter a number")) if(n enter a number4
%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")

Chained conditionals (if-elif-else)

 The elif is short for else if.


 This is used to check more than one condition.

 If the condition1 is False, it checks the condition2 of the elif block. If all the conditions are False, then the
else part is executed.

 Among the several if...elif...else part, only one part is executed according to the condition.

 The if block can have only one else block. But it can have multiple elif blocks.
o The way to express a computation like that is a chained conditional.
lOMoARcPSD|22814775

Syntax:

Flowchart

Example

student mark system Output


mark=eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
lOMoARcPSD|22814775

Nested conditionals
One conditional can also be nested within another. Any number of condition can
be nested inside one another. In this, if the condition is true it checks another if
condition1. If both the conditions are true statement1 get executed otherwise
statement2 get execute. if the condition is false statement3 gets executed
Syntax:

Flowchart

Example

a = 10
b = 20
c = 30
if a >= b:
if a >= c:
greatest = a
else:
greatest = c
lOMoARcPSD|22814775

else:
if b >= c:
greatest = b
else:
greatest = c

print(f'The greatest number is {greatest}')

9. Write python program for finding sum of 1st n natural odd no and print
the result using function (J22)
def sum_of_odd_numbers(n):
# Initialize the sum to 0
total_sum = 0

# Iterate through the first n odd numbers


for i in range(n):
# Calculate the ith odd number
odd_number = 2 * i + 1
# Add it to the total sum
total_sum += odd_number

return total_sum

# Example usage
n = 5 # Change this value to the desired number of terms
result = sum_of_odd_numbers(n)
print(f'The sum of the first {n} natural odd numbers is {result}')
Output: The sum of the first 5 natural odd numbers is 25

10. Explain call by value and reference in python (A/M24)

Call by Value
 Definition: When a function is called, a copy of the argument's value is passed to the
function.
 Implication: Changes made to the parameter inside the function do not affect the
original argument.
Call by Reference
 Definition: When a function is called, a reference to the actual argument (not a copy)
is passed to the function.
 Implication: Changes made to the parameter inside the function affect the original
argument.

 Mutable Objects (e.g., lists, dictionaries): If you pass a mutable object, the function
can modify the original object because the reference to the object is passed.
lOMoARcPSD|22814775

 Immutable Objects (e.g., integers, strings, tuples): If you pass an immutable object,
the function cannot modify the original object itself, but it can reassign the reference
to a new object.

11. How to perform a user input in python? Explain with eg (A/M24)

12. Explain function prototypes(A/M24)


Function Prototypes:
 Function without arguments and without return type
 Function with arguments and without return type
 Function without arguments and with return type
 Function with arguments and with return type
lOMoARcPSD|22814775

i) Function without arguments and without return type


o In this type no argument is passed through the function call and no
output is return to main function
o The sub function will read the input values perform the operation and
print the result in the same block
ii) Function with arguments and without return type
o Arguments are passed through the function call but output is not return to the
main function
iii) Function without arguments and with return type
o In this type no argument is passed through the function call but output is
return to the main function.
iv) Function with arguments and with return type
o In this type arguments are passed through the function call and output is
return to the main function

Without Return Type


Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enter b")) print(c)
c=a+b a=int(input("enter a"))
print(c) b=int(input("enter b"))
add() add(a,b)

OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
With return type
Without argument With argument
def add(): def add(a,b):
a=int(input("enter a")) c=a+b
b=int(input("enterb")) return
c=a+b c
return c a=int(input("enter a"))
c=add() b=int(input("enter b"))
c=add(a,b)
print(c)
print(c)
OUTPUT: OUTPUT:
enter a5 enter a5
enter b 10 enter b 10
15 15
lOMoARcPSD|22814775

13.Write python program to check whether entered string is palindrome or


not (A/M24)
Program:
def is_palindrome(string):
# Remove spaces and convert to lowercase for a case-insensitive comparison
cleaned_string = string.replace(" ", "").lower()

# Check if the cleaned string is equal to its reverse


return cleaned_string == cleaned_string[::-1]

# Example usage
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print(f'"{input_string}" is a palindrome.')
else:
print(f'"{input_string}" is not a palindrome.')
Output:
Enter a string: Racecar
"Racecar" is a palindrome.

You might also like