0% found this document useful (0 votes)
6 views57 pages

DS Lecture1 1

The document provides a collection of sample Python programs demonstrating various concepts such as swapping variables, finding square roots, linear search, and binary search. It includes code snippets for each concept along with explanations of algorithms and methods used. Additionally, it covers the implementation of a simple calculator and the Fibonacci series.

Uploaded by

Arif Kamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views57 pages

DS Lecture1 1

The document provides a collection of sample Python programs demonstrating various concepts such as swapping variables, finding square roots, linear search, and binary search. It includes code snippets for each concept along with explanations of algorithms and methods used. Additionally, it covers the implementation of a simple calculator and the Fibonacci series.

Uploaded by

Arif Kamal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Sample Programs in Python

Python Program to Swap Two Variables


r1 = input (“Enter the first variable”)
r2 = input (“Enter the second variable”)
mp = var1
r1 = var2
r2 = temp
int (“The value of the first variable after swapping is:”, var1)
int (“The value of the second variable after swapping is:”, var2)

Without Using Temporary Variable


r1 = input (“Enter the first variable”)
r2 = input (“Enter the second variable”)
r1, var2 = var2, var1

int (“First value variable after swapping is:”, var1)


int (“The value of second variable after swapping is:”, var2)
- Find the Square Root
umb = float(input('Enter a number: '))
umsqrt = numb ** 0.5
rint('square root of %0.3f is %0.3f'%(numb ,numsqrt))

- Square Root in Python Using Function


mport math #statement to generate the square root of 0
rint(math.sqrt(0))
statement to generate the square root of 4
rint(math.sqrt(4))
utput:0.02.0
ample 2:
mport math print ("math.sqrt(100) : ", math.sqrt(100))
rint ("math.sqrt(7) : ", math.sqrt(7))
rint ("math.sqrt(math.pi) : ", math.sqrt(math.pi))
utput:math.sqrt(100) : 10.0
- Square Root using Array
port numpy as geek
applying sqrt() method on integer numbers
ray1 = geek.sqrt([1, 4, 9, 16])
ray2 = geek.sqrt([6, 10, 18])
int("squareroot of an array1 : ", array1)
int("squareroot of an array2 : ", array2)

tput:the square root of an array1 : [ 1. 2. 3. 4.]

- Matrix Transpose using Nested Loop


= [[1, 3], [4,5], [7, 9]]
sult = [0, 0, 0], [0, 0, 0]]
r i in range (len (X)):
r j in range (len (X[0])):
sult [j][i] = X [i][j]
r r in result:
int (r)
cci series up to n
ib(n):
, b = 0, 1
hile a < n:
print(a, end=' ')
a, b = b, a+b
rint()
000)

5 8 13 21 34 55 89 144 233 377 610 987

dition of two numbers with user input.


input("Enter first no. :"))
input("Enter second no. :"))
(num1+num2)
ng the user input values
rst number is :",num1)
cond number is :",num2)
ng addition of user input
dition is : ",addition)
- Find the Largest Among Three Numbers:
Find largest number among the three input numbers
change the values of num1, num2 and num3
for a different resultnum1 = 10num2 = 14num3 = 12
uncomment following lines to take three numbers
om user
um1 = float(input("Enter first number: "))
um2 = float(input("Enter second number: "))
um3 = float(input("Enter third number: "))
(num1 >= num2) and (num1 >= num3):
rgest = num1elif (num2 >= num1) and (num2 >= num3)
rgest = num2else:
rgest = num3print("The largest number is", largest
- Simple Calculator by Using Functions
add(a, z):
rn a + z
is function takes two numbers and subtracts them.
subtract(a, z):
rn a – z
is function takes two numbers and multiplies them.
multiply(a, z):
rn a * z
is function takes two numbers and divides them.
divide(a, z):
rn a / z
t("Select operation.")
t("1.Addition")
t("2.Subtraction")
t("3.Multiplication")
t("4.Division")
e True:
hile True:
Take input from the user
hoice = input("Enter choice(1/2/3/4): ")
Check to see if your choice is one of the four
ptions if choice in ('1', '2', '3', '4'):
umb1 = float(input("Enter first number: "))
umb2 = float(input("Enter second number: "))
f choice == '1':
rint(numb1, "+", numb2, "=", add(numb1, numb2))
elif choice == '2':
rint(numb1, "-", numb2, "=", subtract(numb1, numb2))
elif choice == '3':
rint(numb1, "*", numb2, "=", multiply(numb1, numb2))
elif choice == '4':
rint(numb1, "/", numb2, "=", divide(numb1, numb2))
break
lse:
rint("Invalid Input")
utput:
elect operation.
.Add
.Subtract
.Multiply
.DivideEnter

hoice(1/2/3/4): 3

nter first number: 80


nter second number: 3480 * 34 = 2720.0
What is linear search in Python?
Linear search is the most basic type of search that is performed. It is also called the sequential
search. In this search, we check each element in the given list one by one until a match is found.
This method is often used in our daily life like when we check grocery items, we do so in a linear
search manner.
Technically in Python, This search method compares each and every element with the particular
value that we are searching for. If both are matched, the element is found, and the algorithm
returns the key’s index position.
Algorithm of linear search:
Before writing any code of the program, we must know its algorithm. So let’s understand the
algorithm of this program.
1.Input a list of numbers.
2.Input the item to be searched.
3.Compare that element with each and every element of the list one by one.
4.If the match is found, then return True.
5.If the match is not found in the whole list, then return False.
#Method 1: Linear search Using range()
list1 = [16, 2, 7, 5, 12, 54, 21, 9, 64, 12]
print('List has the items: ', list1)
Item = int(input('Enter a number to search for: '))
found = False
for i in range(len(list1)):
if list1[i] == Item:
found = True

print(Item, ' was found in the list at index ', i)

break
if found == False:
print(Item, ' was not found in the list!')

#Output
List has the items: [16, 2, 7, 5, 12, 54, 21, 9, 64, 12]
Enter a number to search for: 7
7 was found in the list at index 2
#Method 2: Linear search using def().
def linear(x,y): for i in x:

if i ==y:
return true return false
x = [12, 37, 45, 89, 1, 2, 34, 48, 9]

linear(x,2)

linear(x,9) linear(x,5)
#Output
True
True
False
Linear Search in Python:
Python is one of the most popular and powerful languages. It takes
a few lines to execute the code, which makes it much user-friendly
language. In this tutorial, we will learn the linear search in Python.
Searching is a technique to find the particular element is present
or not in the given list.
There are two types of searching:
1. Linear Search
2. Binary Search
What is a Linear Search?
Linear search is a method of finding elements within a list. It is also called a
sequential search. It is the simplest searching algorithm because it searches the
desired element in a sequential manner.
It compares each and every element with the value that we are searching for. If
both are matched, the element is found, and the algorithm returns the key's index
Program in Python:
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1

list1 = [1 ,3, 5, 4, 7, 9]
key = 7

n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Program in Python (User inputted number):
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1

list1 = [1 ,3, 5, 4, 7, 9]
key = int(input('Enter a number to search for: '))

n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Concept of Binary Search:
In the binary search algorithm, we can find the element position using the following methods.
We have a sorted list of elements, and we are looking for the index position of 45.
[12, 24, 32, 39, 45, 50, 54]

So, we are setting two pointers in our list. One pointer is used to denote the smaller value called low and the second pointer is
used to denote the highest value called high.
Next, we calculate the value of the middle element in the array.
mid = (low+high)/2
Here, the low is 0 and the high is 7.
mid = (0+7)/2
mid = 3 (Integer)
Now, we will compare the searched element to the mid index value. In this case, 32 is not equal to 45. So we need to do further
comparison to find the element.
If the number we are searching equal to the mid. Then return mid otherwise move to the further comparison.
The number to be search is greater than the middle number, we compare the n with the middle element of the elements on the
right side of mid and set low to low = mid + 1.
Repeat until the number that we are searching for is found.
Implement a Binary Search in Python:
First, we implement a binary search with the iterative method. We will repeat a set of statements and
iterate every item of the list. We will find the middle value until the search is complete.
# Iterative Binary Search Function method Python Implementation # It returns index of n in given list1 if present, # e
lse returns -1

1. def binary_search(list1, n):


2. low = 0
3. high = len(list1) - 1
4. mid = 0
5. while low <= high:
6. # for get integer result
7. mid = (high + low) // 2
8. # Check if n is present at mid
9. if list1[mid] < n:
10. low = mid + 1
11. # If n is greater, compare to the right of mid
12. elif list1[mid] > n:
13. high = mid - 1
Implement a Binary Search in Python:
14. # If n is smaller, compared to the left of mid
15. else:
16. return mid
17. # element was not present in the list, return -1
18. return -1
19. # Initial list1
20. list1 = [12, 24, 32, 39, 45, 50, 54]
21. n = 45
22. # Function call
23. result = binary_search(list1, n)
24. if result != -1:
25. print("Element is present at index", str(result))
26. else:
27. print("Element is not present in list1")
Binary Search
Binary search in python uses a divide-and-conquer strategy to significantly speed up searching in sorted data as
opposed to linear search, which examines each element one at a time.
Binary search in C only works on sorted data sets. The collection must be arranged in ascending or descending order.
This sorting enables the divide-and-conquer approach.
The key steps are:
1. Find midpoint index of the entire dataset.
2. Compare element at midpoint against target value.
3. If equal, return index of match.
4. If less, repeat search on left half.
5. If greater, repeat search on right half.
This recursive halving of search space enables tremendous efficiency gains.
We have a sorted array arr[] = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91} and we want to search for the value 23.

The steps are:

1. Set lower index to 0 and the upper index to n-1.

2. Here, n is the number of elements in the array, which is 10. So lower = 0 and upper = 9 (10-1 = 9)
3. Calculate the mid index as mid = (lower + upper) / 2. In this case, mid = (0 + 9) / 2 = 4.
4. Compare the value at arr[mid] with the target value 23. Here arr[mid] is arr[4], which is 16.
5. Since 16 is less than 23, the target is greater than the mid element. So set lower = mid +
This eliminates the left half of the array.
6. Recalculate mid index with new lower and upper bounds. mid = (lower + upper) / 2 = (5+ 9) / 2 = 7
7. Check if arr[mid] (which is 38) equals target. It does not. Since 38 > 23, set upper = mid - 1
This eliminates the right half.
8. Recalculate mid as (lower + upper) / 2 = (5 + 6) / 2 = 5
9. Check arr[mid] (which is 23) against the target 23. It matches!
10. Return the index mid.
Concept of Binary Search
In the binary search algorithm, we can find the element position using the following methods:
1. Recursive Method
2. Iterative Method
The divide-and-conquer approach technique is followed by the recursive method. In this method, a function is called again and
again until it finds an element in the list.
We have a sorted list of elements, and we are looking for the index position of 45. [12, 24, 32, 39, 45, 50, 54]
So, we are setting two pointers in our list. One pointer is used to denote the smaller value called low, and the second pointer is
used to denote the highest value called high.
Next, we calculate the value of the middle element in the array.
Now, we will compare the searched element to the mid-index value. In this case, 32 is not equal to 45. So we need to do further
comparisons to find the element.
If the number we are searching for is equal to the mid, then return the mid; otherwise, move to the next comparison.
The number to be searched is greater than the middle number, so we compare the n with the middle element of the elements on
the right side of mid and set low to low = mid + 1.
Otherwise, compare the n with the middle element of the elements on the left side of mid, and set high to high = mid—1.
# Iterative Binary Search Function method Python Implementation
# It returns index of n in given list1 if present, # else returns -1

def binary_search (list1, n): low = 0

high = len(list1) - 1 mid = 0

while low <= high:

# for get integer result mid = (high + low) // 2

# Check if n is present at mid if list1[mid] < n:


low = mid + 1

# If n is greater, compare to the right of mid elif list1[mid] > n:


high = mid – 1
# If n is smaller, compared to the left of mid else:
return mid

# element was not present in the list, return -1 return -1


# Initial list1
list1 = [12, 24, 32, 39, 45, 50, 54]
# Iterative Binary Search Function method Python Implementation
# It returns index of n in given list1 if present, # else returns -1

# function call result = binary_search(list1, n)


if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in list1")

OUT PUT
Element is present at index 4
Explanation:
In the above program - We have created a function called binary_search() function which takes two arguments
— a list to sorted and a number to be searched.

We have declared two variables to store the lowest and highest values in the list.
The low is assigned initial value to 0, high to len (list1) — 1 and mid as 0.

Next, we have declared the while loop with the condition that the lowest is equal and smaller than the highest
The while loop will iterate if the number has not been found yet.

In the while loop, we find the mid value and compare the index value to the number we are searching for.
If the value of the mid-index is smaller than n, we increase the mid value by 1 and assign it to The search moves to
the left side.
Otherwise, decrease the mid value and assign it to the high. The search moves to the right side. If the n is equal to
the mid value then return mid.
This will happen until the low is equal and smaller than the high.
If we reach at the end of the function, then the element is not present in the list. We return -1 to the calling
function.
Recursive Binary Search:
The recursion method can be used in the binary search. In this, we will define recursive function
that keeps calling itself until it meets the condition.

Python Program
Python program for recursive binary search

# Returns index position of n in list1 if present, otherwise -1 def binary_search (list1, low, high, n):

# Check base case for the recursive function if low <= high:
mid = (low + high) // 2

# If element is available at the middle itself then return the its index if list1[mid] == n:
return mid
# If the element is smaller than mid value, then search moves
# left sublist1
elif list1[mid] > n:
return binary_search(list1, low, mid - 1, n)

# Else the search moves to the right sublist1 else:

return binary_search(list1, mid + 1, high, n) else:


# Element is not available in the list1 return -1

# Test list1ay
list1 = [12, 24, 32, 39, 45, 50, 54]
n = 32
# Function call
res = binary_search(list1, 0, len(list1)-1, n) if res != -1:
print("Element is present at index", str(res))
else:
print("Element is not present in list1")

Output:
Element is present at index 2
Explanation
The above program is similar to the previous program. We declared a recursive function and its base condition. The
condition is the lowest value is smaller or equal to the highest value.
1. We calculate the middle number as in the last program.
2. We have used the if statement to proceed with the binary search.
3. If the middle value equal to the number that we are looking for, the middle value is returned.
4. If the middle value is less than the value, we are looking then our recursive function
5. binary_search() again and increase the mid value by one and assign to low.
6. If the middle value is greater than the value we are looking then our recursive function
7. binary_search() again and decrease the mid value by one and assign it to low.

In the last part, we wrote our main program. It is the same as the previous program, but the only difference is that
we have passed two parameters in the binary_search() function.
This is because we can’t assign the initial values to the low, high and mid in the recursive function. Every
time the recursive is called the value will be reset for those variables. That will give the wrong result.
Python implementation
import math

def binarySearch(lst, key):

low = 0
end = len(lst) -1
while low <= end:
mid = math.floor((low + end)/2)
if key == lst[mid]:
return f 'key {key} = lst[{mid}]'

elif

key < lst[mid]: end = mid - 1


else:
low = mid + 1
return f'{key} is not in this list'

You might also like