Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

[Type here]

5) Write a Python function to calculate the factorial of a number. [use


recursive approach]
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)

# Example usage:
number = 5
print("Factorial of", number, "is", factorial(number))
Output

6) Write a function which can search for an entry in a list. Also show the entry
count in the list.
def search_and_count(lst, entry):
count = lst.count(entry)
return count

# Example usage:
my_list = [1, 2, 3, 4, 2, 5, 2]
entry_to_search = 2
count = search_and_count(my_list, entry_to_search)
print("Number of occurrences of", entry_to_search, "in the list:", count)
[Type here]

Output

7) Develop code in python for sorting a list using selection sort approach. In
selection sort you find the minimum value first and place it at the end of the
list.
def selection_sort(arr):
n = len(arr)
for i in range(n):
# Find the index of the minimum element in the remaining unsorted array
min_idx = i
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j

# Swap the found minimum element with the first element


arr[i], arr[min_idx] = arr[min_idx], arr[i]

# Example usage:
my_list = [64, 25, 12, 22, 11]
print("Original list:", my_list)
selection_sort(my_list)
print("Sorted list:", my_list)
Output

You might also like