100% found this document useful (2 votes)
2K views24 pages

Python Functions - Exercises: Mrs.S.Karthiga

The document contains Python functions and programs related to: 1) List processing functions like unique elements, max of numbers, sum and multiply of list elements. 2) String processing functions like reverse, count upper/lower cases. 3) Functions to check number range, prime numbers, local variables in function. 4) Programs for even numbers, perfect numbers, linear/binary search, sorting lists.

Uploaded by

Riya Ram
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
100% found this document useful (2 votes)
2K views24 pages

Python Functions - Exercises: Mrs.S.Karthiga

The document contains Python functions and programs related to: 1) List processing functions like unique elements, max of numbers, sum and multiply of list elements. 2) String processing functions like reverse, count upper/lower cases. 3) Functions to check number range, prime numbers, local variables in function. 4) Programs for even numbers, perfect numbers, linear/binary search, sorting lists.

Uploaded by

Riya Ram
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 24

Python Functions - Exercises

Mrs.S.Karthiga
function that takes a list and returns a new
list with unique elements of the first list.
def unique_list(l):
x = []
for a in l:
if a not in x:
x.append(a)
return x
print(unique_list([1,2,3,3,3,3,4,5]))

Output

[1,2,3,4,5]
function to find the Max of three
numbers.
def max_of_two( x, y ):
if x > y:
return x
return y
def max_of_three( x, y, z ):
return max_of_two( x, max_of_two( y, z ) )
print(max_of_three(3, 6, -5))
Output
function to sum all the numbers in a
list.
def sum(numbers):
total = 0
for x in numbers:
total += x
return total
print(sum((8, 2, 3, 0, 7)))

Output
20
function to multiply all the numbers
in a list.
def multiply(numbers):
total = 1
for x in numbers:
total *= x
return total
print(multiply((8, 2, 3, -1, 7)))

Output
-336
program to reverse a string.
def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[ index - 1 ]
index = index - 1
return rstr1
print(string_reverse('1234abcd'))

Output
dcba4321
function to calculate the number of upper case and lower
case letters.

def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
Output
d["UPPER_CASE"]+=1
elif c.islower(): Original String : The quick Brow
d["LOWER_CASE"]+=1 Fox
else:
No. of Upper case characters : 3
No. of Lower case Characters : 13
pass
print ("Original String : ", s)
print ("No. of Upper case characters : ", d["UPPER_CASE"])
print ("No. of Lower case Characters : ",
d["LOWER_CASE"])
string_test('The quick Brown Fox')
function to check whether a number
is in a given range.
def test_range(n):
if n in range(3,9):
print( " %s is in the range"%str(n))
else :
print("The number is outside the given range.")
test_range(5)

Output
5 is in the range
function that checks the number is prime or not?

def test_prime(n):
if (n==1):
return False
elif (n==2):
return True;
else:
for x in range(2,n):
if(n % x==0):
return False
return True
print(test_prime(9))

Output
False
program to detect the number of
local variables declared in a function.
def abc():
x=1
y=2
str1= "w3resource"
print("Python Exercises")

print(abc.__code__.co_nlocals)

Output
4
program to print the even numbers
from a given list.
def is_even_num(l):
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))

Output
[2, 4, 6, 8]
To check perfect number ?
def perfect_number(n):
sum = 0
for x in range(1, n):
if n % x == 0:
sum += x
return sum == n
print(perfect_number(6))

Output

True
Linear/Sequential Search
 A linear search (often called a sequential search) is
performed by inspecting each item in a list one by one
from one end to the other to find a match for what you
are searching for.

 A simple approach is to do linear search, i.e


 Start from the leftmost element of list and one by one
compare x with each element of the list.
 If x matches with an element, return True.
 If x doesn’t match with any of elements, return False.
Linear Search
Ex :-

def search(list,n):
for i in range(len(list)):
if list[i] == n:
Output
return True
return False Found

list = [1, 2, 'sachin', 4,'Geeks', 6]


n = 'Geeks'
if search(list, n):
print("Found")
else:
print("Not Found")
Binary Search

 Compare x with the middle element.


 If x matches with middle element, we return
the mid index.
 Else If x is greater than the mid element, then
x can only lie in right half subarray after the
mid element. So we recur for right half.
 Else (x is smaller) recur for the left half.
def binarySearch (arr, l, r, x):
if r >= l: arr = [ 2, 3, 4, 10, 40 ]
mid = l + (r - l)/2 x = 10
result = binarySearch(arr, 0, len(arr)-1, x)
if arr[mid] == x: if result != -1:
return mid print "Element is present at index % d" %
result
elif arr[mid] > x:
else:
return binarySearch(arr, l, print "Element is not present in array"
mid-1, x)
else:
return binarySearch(arr,
mid + 1, r, x)
Output
else:
return -1 Element is present
at index 3
Sorting list of Integers in ascending
numbers = [1, 3, 4, 2]

numbers.sort()

print(numbers)

[1,2,3,4]
Sorting list of Integers in descending

numbers = [1, 3, 4, 2]
numbers.sort(reverse = True)

print(numbers)

[4,3,2,1]
Sort Flatten list of list
test_list = [[3, 5], [7, 3, 9], [1, 12]]

print("The original list : " + str(test_list))

res = sorted([j for i in test_list for j in i])

print("The sorted and flattened list : " + str(res))

Output
The original list : [[3, 5], [7, 3, 9], [1, 12]]
The sorted and flattened list : [1, 3, 3, 5, 7, 9, 12]
Sort the values of first list using second list

Input : list1 = ["a", "b", "c", "d", "e", "f", "g", "h",
"i"]
list2 = [ 0, 1, 1, 0, 1, 2, 2, 0,
1]

Output :['a', 'd', 'h', 'b', 'c', 'e', 'i', 'f', 'g']
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for a, x in sorted(zipped_pairs)]
return z
x = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
print(sort_list(x, y))
x = ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k",
"s"]
y = [ 0, 1, 1, 0, 1, 2, 2, 0, 1]
print(sort_list(x, y))
from collections import Counter

ini_list = [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4]
print ("initial list", str(ini_list))
result = sorted(ini_list, key = ini_list.count, reverse = True)

print("final list", str(result))

Output
initial list [1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 5, 5, 5, 4, 4, 4, 4, 4, 4]
final list [4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 2, 2, 2, 5, 5, 5, 1, 1]

You might also like