0% found this document useful (0 votes)
28 views10 pages

Assignment 1 Ge 6a CN

The document contains multiple programming questions and their corresponding Python solutions. It covers topics such as finding roots of quadratic equations, checking prime numbers, creating pyramids with characters, character type identification, string manipulation, and finding occurrences of substrings. Each question is followed by a well-structured code implementation.

Uploaded by

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

Assignment 1 Ge 6a CN

The document contains multiple programming questions and their corresponding Python solutions. It covers topics such as finding roots of quadratic equations, checking prime numbers, creating pyramids with characters, character type identification, string manipulation, and finding occurrences of substrings. Each question is followed by a well-structured code implementation.

Uploaded by

manshi04082003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

QUESTION-1

Write a program to find the roots of a quadratic equation

---------------------------------*********-------------------------------------

import math
def find_roots(a, b, c):
# Calculate the discriminant
D = b**2 - 4*a*c
if D > 0:
root1 = (-b + math.sqrt(D)) / (2*a)
root2 = (-b - math.sqrt(D)) / (2*a)
return (root1, root2)
elif D == 0:
root = -b / (2*a)
return (root,)
else:
real_part = -b / (2*a)
imaginary_part = math.sqrt(abs(D)) / (2*a)
return (real_part + imaginary_part*1j, real_part - imaginary_part*1j)

a = float(input("Enter the coefficient a: "))


b = float(input("Enter the coefficient b: "))
c = float(input("Enter the coefficient c: "))

roots = find_roots(a, b, c)

if len(roots) == 2:
print(f"The roots are real and distinct: {roots[0]} and {roots[1]}")
elif len(roots) == 1:
print(f"The root is real and repeated: {roots[0]}")
else:
print(f"The roots are complex: {roots[0]} and {roots[1]}")

----------------------------------*********-------------------------------------
----------------------------------*********-------------------------------------

QUESTION-2

Write a program to accept a number ‘n’ and


a. Check if ’n’ is prime
b. Generate all prime numbers till ‘n’
c. Generate first ‘n’ prime numbers This program may be done using
functions

---------------------------------*********---------------------------------------

def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

def primes_up_to_n(n):
primes = []
for i in range(2, n + 1):
if is_prime(i):
primes.append(i)
return primes
def first_n_primes(n):
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes

def main():
n = int(input("Enter a number n: "))

# a. Check if n is prime
if is_prime(n):
print(f"{n} is a prime number.")
else:
print(f"{n} is not a prime number.")

# b. Generate all primes till n


print(f"All prime numbers up to {n}: {primes_up_to_n(n)}")

# c. Generate first n primes


print(f"The first {n} prime numbers: {first_n_primes(n)}")

# Run the program


main()

---------------------------------*********-------------------------------------
---------------------------------*********-------------------------------------
QUESTION-3

Write a program to create a pyramid of the character ‘*’ and a reverse pyramid

---------------------------------*********-------------------------------------

def print_pyramid(n):
for i in range(1, n + 1):
# Printing spaces to center align the stars
print(' ' * (n - i) + '*' * (2 * i - 1))

def print_reverse_pyramid(n):
for i in range(n, 0, -1):
# Printing spaces to center align the stars
print(' ' * (n - i) + '*' * (2 * i - 1))

def main():
# Input the number of rows
n = int(input("Enter the number of rows: "))

print("\nPyramid of stars:")
print_pyramid(n)

print("\nReverse pyramid of stars:")


print_reverse_pyramid(n)

main()

---------------------------------*********-------------------------------------
---------------------------------*********-------------------------------------

QUESTION-4
Write a program that accepts a character and performs the following:
a. print whether the character is a letter or numeric digit or a special
character.
b. if the character is a letter, print whether the letter is uppercase or
lowercase
c. if the character is a numeric digit, prints its name in text (e.g., if input is 9,
output is NINE)

---------------------------------*********-------------------------------------

def check_character_type(ch):
if ch.isalpha():
return 'letter'
elif ch.isdigit
return 'digit'
else:
return 'special'

def digit_to_text(digit):
digit_names = {
'0': 'ZERO', '1': 'ONE', '2': 'TWO', '3': 'THREE',
'4': 'FOUR', '5': 'FIVE', '6': 'SIX', '7': 'SEVEN',
'8': 'EIGHT', '9': 'NINE'
}
return digit_names.get(digit, 'Invalid') # Return corresponding text for digit

def main():
ch = input("Enter a character: ")

char_type = check_character_type(ch)
# a. Check and print whether it's a letter, digit, or special character
if char_type == 'letter':
print(f"The character '{ch}' is a letter.")

# b. If it's a letter, check if it's uppercase or lowercase


if ch.isupper():
print(f"The letter '{ch}' is uppercase.")
else:
print(f"The letter '{ch}' is lowercase.")
elif char_type == 'digit':
print(f"The character '{ch}' is a digit.")

# c. If it's a digit, print its name in text


print(f"The digit '{ch}' is {digit_to_text(ch)}.")
else:
print(f"The character '{ch}' is a special character.")

main()

---------------------------------*********-------------------------------------
---------------------------------*********-------------------------------------

QUESTION-5

5. Write a program to perform the following operations on a string


a. Find the frequency of a character in a string.
b. Replace a character by another character in a string.
c. Remove the first occurrence of a character from a string.
d. Remove all occurrences of a character from a string.

---------------------------------*********-------------------------------------
def find_frequency(string, char):
return string.count(char)

def replace_character(string, old_char, new_char):


return string.replace(old_char, new_char)

def remove_first_occurrence(string, char):


return string.replace(char, '', 1)

def remove_all_occurrences(string, char):


return string.replace(char, '')

def main():
string = input("Enter a string: ")

char = input("Enter the character to find frequency: ")


freq = find_frequency(string, char)
print(f"Frequency of '{char}' in the string: {freq}")

old_char = input("Enter the character to replace: ")


new_char = input("Enter the new character: ")
modified_string = replace_character(string, old_char, new_char)
print(f"String after replacing '{old_char}' with '{new_char}':
{modified_string}")

remove_char = input("Enter the character to remove (first occurrence): ")


modified_string_c = remove_first_occurrence(string, remove_char)
print(f"String after removing the first occurrence of '{remove_char}':
{modified_string_c}")

remove_all_char = input("Enter the character to remove all occurrences: ")


modified_string_d = remove_all_occurrences(string, remove_all_char)
print(f"String after removing all occurrences of '{remove_all_char}':
{modified_string_d}")

main()

---------------------------------*********-------------------------------------
---------------------------------*********-------------------------------------

QUESTION-6

Write a program to swap the first n characters of two strings.

---------------------------------*********-------------------------------------

def swap_first_n_chars(str1, str2, n):

if n > len(str1) or n > len(str2):


print("Error: n is greater than the length of one of the strings.")
return None, None

new_str1 = str2[:n] + str1[n:]


new_str2 = str1[:n] + str2[n:]

return new_str1, new_str2

def main():
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")
n = int(input("Enter the number of characters to swap: "))

swapped_str1, swapped_str2 = swap_first_n_chars(str1, str2, n)


if swapped_str1 is not None and swapped_str2 is not None:
print(f"String 1 after swapping: {swapped_str1}")
print(f"String 2 after swapping: {swapped_str2}")

main()

---------------------------------*********-------------------------------------
---------------------------------*********-------------------------------------

QUESTION-7

Write a function that accepts two strings and returns the indices of all the
occurrences of the second string in the first string as a list. If the second string is
not present in the first string then it should return -1.

---------------------------------*********-------------------------------------

def find_occurrences(str1, str2):

indices = []
start = 0

while True:
index = str1.find(str2, start)

if index == -1:
break

indices.append(index)

start = index + 1
if not indices:
return -1

return indices

def main():
str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")

result = find_occurrences(str1, str2)

if result == -1:
print(f"The second string '{str2}' is not present in the first string.")
else:
print(f"The indices of occurrences of '{str2}' in '{str1}' are: {result}")

ujkmain()

---------------------------------*********-------------------------------------
---------------------------------*********-------------------------------------

You might also like