[go: up one dir, main page]

0% found this document useful (0 votes)
7 views6 pages

Function For MidTerm

The document outlines various programming functions for a mid-term exam, including calculations for factorial, Fibonacci sequence, prime number checking, GCD, sum of digits, matrix multiplication, binary to decimal conversion, combinations, finding a missing number in a list, counting vowels in a string, and linear search. Each function is accompanied by a solution in Python code with example usage and expected output. The document serves as a guide for implementing these algorithms and understanding their logic.

Uploaded by

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

Function For MidTerm

The document outlines various programming functions for a mid-term exam, including calculations for factorial, Fibonacci sequence, prime number checking, GCD, sum of digits, matrix multiplication, binary to decimal conversion, combinations, finding a missing number in a list, counting vowels in a string, and linear search. Each function is accompanied by a solution in Python code with example usage and expected output. The document serves as a guide for implementing these algorithms and understanding their logic.

Uploaded by

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

Functions for Mid-Term Exam

HMI-Batch 5
1. Factorial Calculation

Write a function to calculate the factorial of a number using recursion.

Solution

def factorial(n):

if n == 0 or n == 1:

return 1

return n * factorial(n - 1)

print(factorial(5)) # Output: 120

2. Fibonacci Sequence

Write a function that returns the n-th Fibonacci number using recursion.

Solution

def fibonacci(n):

if n == 0:

return 0

elif n == 1:

return 1

return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(6)) # Output: 8

3. Prime Number Checker

Write a function to check if a number is prime.

Solution

def is_prime(n):
if n < 2:

return False

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

return False

return True

print(is_prime(29)) # Output: True

print(is_prime(18)) # Output: False

4. Greatest Common Divisor (GCD)

Write a function to compute the GCD of two numbers using recursion (Euclidean Algorithm).

Solution

def gcd(a, b):

while b != 0:

temp = a % b # Store remainder

a=b # Update a to the value of b

b = temp # Update b to the remainder

return a

print(gcd(48, 18)) # Output: 6

5. Sum of Digits

Write a function that calculates the sum of the digits of a given number recursively.

Solution

def sum_of_digits(n):

total = 0

while n > 0:

total += n % 10 # Extract last digit


n //= 10 # Remove last digit

return total

print(sum_of_digits(1234)) # Output: 10

6. Matrix Multiplication

Write a function to perform matrix multiplication for two n x n matrices.

Solution

def matrix_multiply(A, B):

result = [[0] * len(B[0]) for _ in range(len(A))]

for i in range(len(A)):

for j in range(len(B[0])):

for k in range(len(B)):

result[i][j] += A[i][k] * B[k][j]

return result

A = [[1, 2], [3, 4]]

B = [[5, 6], [7, 8]]

print(matrix_multiply(A, B))

# Output: [[19, 22], [43, 50]]

7. Binary to Decimal Conversion

Write a function to convert a binary number (as a string) into decimal.

Solution

def binary_to_decimal(binary_str):

return int(binary_str, 2)

print(binary_to_decimal("1011")) # Output: 11
8. Compute nCr (Combinations Formula)

Write a function to compute combinations (nCr) for given n and r.

Solution

def factorial(n):

if n == 0 or n == 1:

return 1

return n * factorial(n - 1)

def combinations(n, r):

return factorial(n) // (factorial(r) * factorial(n - r))

print(combinations(5, 2)) # Output: 10

9. Finding the Missing Number in a List

Write a function to find the missing number in a list of n-1 numbers from 1 to n.

Solution

def find_missing_number(nums):

n = len(nums) + 1

expected_sum = n * (n + 1) // 2

actual_sum = sum(nums)

return expected_sum - actual_sum

print(find_missing_number([1, 2, 4, 5, 6])) # Output: 3

10. Count the Number of Vowels in a String

Write a function that counts the number of vowels in a given string.

Solution

def count_vowels(s):
count = 0

for char in s.lower():

if char in "aeiou":

count += 1

return count

print(count_vowels("Computer Science")) # Output: 6

11. Check if a number is prime

Write a function that Check if a number is prime .

Solution

def is_prime(n):

if n < 2:

return False

for i in range(2, int(n ** 0.5) + 1):

if n % i == 0:

return False

return True

12. Linear Search function


Write a function for linear serach (lst, target)
Lst is existing integer list and target is the serach number

Solution

def linearSearch(lst, target):


index=0
for value in enumerate(lst):
if value == target:
return index
index+=1
return -1 # If the target is not found

# Example usage:
nums = [10, 20, 30, 40, 50]
target = int(input("Enter the number to search for: "))
result = linearSearch(nums, target)

if result != -1:
print(f"The number {target} is at position {result}.")
else:
print(f"The number {target} is not in the list.")

You might also like