Sunday, March 24, 2024

BCA PART A 8. Implement Selection Sort

 



def selection_sort(arr):
    """
    Perform selection sort on the given list.
   
    Parameters:
        arr (list): The list to be sorted.
   
    Returns:
        list: Sorted list.
    """
    n = len(arr)
   
    for i in range(n-1):
        # Find the minimum element in the remaining unsorted list
        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]
   
    return arr

# Accepting input from the user
arr = input("Enter elements of the list separated by space: ").split()
arr = [int(x) for x in arr]  # converting input strings to integers

# Sorting the input list using selection sort
sorted_arr = selection_sort(arr)

# Displaying the sorted list
print("Sorted array:", sorted_arr)


Output :

Enter elements of the list separated by space: 3 5 7 9 2 4 6 Sorted array: [2, 3, 4, 5, 6, 7, 9]



BCA PART A 7. Explore string functions

 



# Define a sample string
sample_string = "Hello, World! This is a sample string."

# 1. Length of the string
print("1. Length of the string:", len(sample_string))

# 2. Convert the string to lowercase
print("2. Convert the string to lowercase:", sample_string.lower())

# 3. Convert the string to uppercase
print("3. Convert the string to uppercase:", sample_string.upper())

# 4. Count occurrences of a substring
substring = "is"
print("4. Count occurrences of '{}' in the string:".format(substring), sample_string.count(substring))

# 5. Check if the string starts with a specific prefix
prefix = "Hello"
print("5. Check if the string starts with '{}':".format(prefix), sample_string.startswith(prefix))

# 6. Check if the string ends with a specific suffix
suffix = "string."
print("6. Check if the string ends with '{}':".format(suffix), sample_string.endswith(suffix))

# 7. Find the index of a substring
substring = "World"
print("7. Find the index of '{}' in the string:".format(substring), sample_string.find(substring))

# 8. Replace occurrences of a substring with another substring
old_substring = "sample"
new_substring = "modified"
modified_string = sample_string.replace(old_substring, new_substring)
print("8. Replace occurrences of '{}' with '{}':".format(old_substring, new_substring), modified_string)

# 9. Split the string into a list of substrings based on a delimiter
delimiter = " "
split_string = sample_string.split(delimiter)
print("9. Split the string into substrings based on '{}':".format(delimiter), split_string)

# 10. Join a list of substrings into a single string using a delimiter
delimiter = "_"
joined_string = delimiter.join(split_string)
print("10. Join substrings into a single string using '{}':".format(delimiter), joined_string)


Output :

1. Length of the string: 382. Convert the string to lowercase: hello, world! this is a sample string.3. Convert the string to uppercase: HELLO, WORLD! THIS IS A SAMPLE STRING.4. Count occurrences of 'is' in the string: 25. Check if the string starts with 'Hello': True6. Check if the string ends with 'string.': True7. Find the index of 'World' in the string: 78. Replace occurrences of 'sample' with 'modified': Hello, World! This is a modified string.9. Split the string into substrings based on ' ': ['Hello,', 'World!', 'This', 'is', 'a', 'sample', 'string.']10. Join substrings into a single string using '_': Hello,_World!_This_is_a_sample_string.




BCA PART A 7. Create a calculator program

 


def add(x, y):
    """Addition function"""
    return x + y

def subtract(x, y):
    """Subtraction function"""
    return x - y

def multiply(x, y):
    """Multiplication function"""
    return x * y

def divide(x, y):
    """Division function"""
    if y == 0:
        return "Error! Division by zero."
    else:
        return x / y

print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")

while True:
    choice = input("Enter choice (1/2/3/4): ")

    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print("Result:", add(num1, num2))
        elif choice == '2':
            print("Result:", subtract(num1, num2))
        elif choice == '3':
            print("Result:", multiply(num1, num2))
        elif choice == '4':
            print("Result:", divide(num1, num2))
    else:
        print("Invalid input")

    next_calculation = input("Do you want to perform another calculation? (yes/no): ")
    if next_calculation.lower() != 'yes':
        break


Output :

Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter first number: 23
Enter second number: 67
Result: 90.0
Do you want to perform another calculation? (yes/no): yes
Enter choice (1/2/3/4): 

Output :

Select operation: 1. Add 2. Subtract 3. Multiply 4. Divide Enter choice (1/2/3/4): 5 Invalid input Do you want to perform another calculation? (yes/no): no













BCA PART A 6. Implement a sequential search

 



def sequential_search(arr, target):
    """
    Perform a sequential search to find the target in the given list.
   
    Parameters:
        arr (list): The list to search in.
        target: The element to search for.
       
    Returns:
        int: The index of the target if found, otherwise returns -1.
    """
    for i in range(len(arr)):
        if arr[i] == target:
            return i
    return -1

# Accepting input from the user
arr = input("Enter elements of the list separated by space: ").split()
arr = [int(x) for x in arr]  # converting input strings to integers

target = int(input("Enter the element to search for: "))

# Performing sequential search
result = sequential_search(arr, target)

# Displaying the result
if result != -1:
    print(f"Target {target} found at index {result}.")
else:
    print(f"Target {target} not found in the list.")

Output :

Enter elements of the list separated by space: 1 3 45 6 8 90 Enter the element to search for: 3 Target 3 found at index 1.


Output 2:

Enter elements of the list separated by space: 3 5 7 89 -1 0 34 Enter the element to search for: 8 Target 8 not found in the list.






Monday, March 11, 2024

BCA PART A 5. Check if a given number is a Prime Number or not

 def is_prime(number):

# Check if the number is less than 2 (not a prime number)
if number < 2:
return False
# Check for factors from 2 to the square root of the number
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True

# Get input from the user
num = int(input("Enter a number to check if it's prime: "))

# Call the function to check if the number is prime
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Output 1:
Enter a number to check if it's prime: 121 121 is not a prime number.

Output 2:
Enter a number to check if it's prime: 17 17 is a prime number.

Explanation :

Function Definition:

This line defines a function named is_prime that takes a parameter number. The function will return True if the number is prime and False otherwise.

Check for Numbers Less than 2:

This block of code checks if the input number is less than 2. If so, it immediately returns False since prime numbers are defined as greater than 1.

Check for Factors:

This loop checks for factors of the number from 2 up to the square root of the number. If any factor is found, the function returns False since the number is not prime.

Return True for Prime Numbers:

If the loop completes without finding any factors, the function returns True, indicating that the number is prime.

User Input:

This line prompts the user to enter a number for prime checking.

Function Call and Output:

This block of code calls the is_prime function with the user-provided number and prints the result based on whether the number is prime or not.


BCA PART A 4. Display Multiplication Tables

 def multiplication_table(number, limit):

# Display the multiplication table for the given number up to the specified limit
print(f"Multiplication Table for {number} up to {limit}:")

for i in range(1, limit + 1):
result = number * i
print(f"{number} * {i} = {result}")

# Get input from the user
number = int(input("Enter the number for the multiplication table: "))
limit = int(input("Enter the limit for the multiplication table: "))

# Call the function to display the multiplication table
multiplication_table(number, limit)

Output :
Enter the number for the multiplication table: 5 Enter the limit for the multiplication table: 5 Multiplication Table for 5 up to 5: 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25

Explaination:

Function Definition:

This line defines a function named multiplication_table that takes two parameters: number (the base number for the multiplication table) and limit (the maximum value up to which the table will be displayed).

Display Header:

This line prints a header indicating that the multiplication table is for the specified number and will be displayed up to the specified limit.

Multiplication Table Loop:

This loop iterates from 1 to limit (inclusive) and calculates the result of multiplying the number by the loop variable i. It then prints each multiplication equation in the format "number * i = result".

User Input:

These lines prompt the user to enter the number for which they want to see the multiplication table and the limit up to which the table should be displayed. The inputs are converted to integers using int().

Function Call:

This line calls the multiplication_table function with the user-provided values of number and limit. The function then displays the multiplication table accordingly.

When you run this program, it will prompt you to enter a number and a limit. After entering the values, the program will display the multiplication table for the specified number up to the given limit.

BCA PART A 3. Find the sum of n natural numbers

 def sum_of_natural_numbers(n):

# Ensure that n is a positive integer
if n <= 0 or not isinstance(n, int):
print("Please enter a positive integer.")
return
# Calculate the sum using the formula: sum = n * (n + 1) / 2
sum_natural_numbers = n * (n + 1) // 2
print(f"The sum of the first {n} natural numbers is: {sum_natural_numbers}")

# Get input from the user
n = int(input("Enter a positive integer (n): "))

# Call the function to find the sum of n natural numbers
sum_of_natural_numbers(n)

Function Definition:

This line defines a function named sum_of_natural_numbers that takes a parameter n. This function will calculate the sum of the first n natural numbers.

Input Validation:

This block of code checks if the input n is a positive integer. If n is not a positive integer or not an integer at all, it prints an error message and exits the function using return.

Sum Calculation:

This line calculates the sum of the first n natural numbers using the formula sum = n * (n + 1) / 2. The // operator is used for integer division to ensure that the result is an integer.

Output:

This line prints the result, indicating the sum of the first n natural numbers.

User Input:

This line prompts the user to enter a positive integer value for n using the input function. The input is then converted to an integer using int().

Function Call:

This line calls the sum_of_natural_numbers function with the user-provided value of n. The function performs the necessary calculations and prints the result.