Skip to content

AdityaJha27/python-practical

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 

Repository files navigation

Python Practical Solutions

Q.1: Roots of a Quadratic Equation

Question: Write a program to find the roots of a quadratic equation.

import cmath

a, b, c = map(float, input("Enter coefficients a, b, c (space-separated): ").split())

d = (b**2) - (4*a*c) # discriminant

if d >= 0:
    r1 = (-b - d**0.5) / (2*a)
    r2 = (-b + d**0.5) / (2*a)
    print(f"Roots are: {r1} and {r2}")
else:
    r1 = (-b - cmath.sqrt(d)) / (2*a)
    r2 = (-b + cmath.sqrt(d)) / (2*a)
    print(f"Complex roots are: {r1} and {r2}")

Q.2: Prime Number Operations

Question: 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

def is_prime(n):
    # A number is prime if it's > 1 and not divisible by any number from 2 to its sqrt.
    return n > 1 and all(n % i != 0 for i in range(2, int(n**0.5) + 1))

n = int(input("Enter a number 'n': "))

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

# b. Generate all primes till 'n'
primes_till_n = [i for i in range(2, n + 1) if is_prime(i)]
print(f"Primes up to {n}: {primes_till_n}")

# c. Generate first 'n' primes
first_n_primes = []
num = 2
while len(first_n_primes) < n:
    if is_prime(num):
        first_n_primes.append(num)
    num += 1
print(f"First {n} primes: {first_n_primes}")

Q.3: Pyramid of Stars

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

rows = int(input("Enter number of rows: "))

print("--- Pyramid ---")
for i in range(1, rows + 1):
    print(f'{" " * (rows - i)}{"*" * (2 * i - 1)}')

print("\n--- Reverse Pyramid ---")
for i in range(rows, 0, -1):
    print(f'{" " * (rows - i)}{"*" * (2 * i - 1)}')

Q.4: Character Analysis

Question: Write a program that accepts a character and performs analysis on it.

char = input("Enter a single character: ")

if char.isalpha():
    print(f"'{char}' is a letter.")
    print("It's uppercase." if char.isupper() else "It's lowercase.")
elif char.isdigit():
    print(f"'{char}' is a digit.")
    names = ['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN', 'EIGHT', 'NINE']
    print(f"In text, it's {names[int(char)]}.")
else:
    print(f"'{char}' is a special character.")

Q.5: String Operations

Question: Perform various find/replace/remove operations on a string.

s = "programming is fun, programming is cool"
print(f"Original: '{s}'")

# a. Frequency of a character
print(f"Frequency of 'm': {s.count('m')}")

# b. Replace a character
print(f"Replacing 'm' with 'M': {s.replace('m', 'M')}")

# c. Remove first occurrence
print(f"Removing first 'o': {s.replace('o', '', 1)}")

# d. Remove all occurrences
print(f"Removing all 'o's: {s.replace('o', '')}")

Q.6: Swap First N Characters

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

def swap_prefix(s1, s2, n):
    return s2[:n] + s1[n:], s1[:n] + s2[n:]

s1, s2 = "apple", "orange"
n = 3
new_s1, new_s2 = swap_prefix(s1, s2, n)

print(f"Original: {s1}, {s2}")
print(f"Swapped:  {new_s1}, {new_s2}")

Q.7: Find All Substring Occurrences

Question: Return all indices of a substring in a string. Return -1 if not found.

def find_all(main_str, sub_str):
    indices = []
    start = 0
    while (start := main_str.find(sub_str, start)) != -1:
        indices.append(start)
        start += 1
    return indices or -1

print(find_all("abracadabra", "abra"))
print(find_all("hello world", "z"))

Q.8: Cubes of Even Integers in a List

Question: From a mixed list, create a list of cubes of only the even integers.

input_list = [1, 2, 'a', 4, 6, 7.5, 8]
print(f"Original list: {input_list}")

# The list comprehension is the most Pythonic way.
cubes = [x**3 for x in input_list if isinstance(x, int) and x % 2 == 0]
print(f"Cubes of even ints: {cubes}")

Q.9: File Operations

Question: Write a program to read a file and:

a. Print the total number of characters, words and lines.

b. Calculate the frequency of each character in the file.

c. Print the words in reverse order.

d. Copy even lines to ‘File1’ and odd lines to ‘File2’.

# Note: Before running, create a file named 'sample.txt'.
try:
    with open('sample.txt', 'r') as f:
        content = f.read()
        # To get lines correctly for part (d), read them separately
        f.seek(0) 
        lines = f.readlines()

    words = content.split()

    # a. Print stats
    print(f"a. Stats: {len(lines)} lines, {len(words)} words, {len(content)} chars.")

    # b. Calculate and show character frequency (using a dictionary)
    char_frequency = {char: content.count(char) for char in sorted(set(content))}
    print(f"b. Character frequency: {char_frequency}")

    # c. Print words reversed
    print(f"c. Words reversed: {' '.join(words[::-1])}")

    # d. Copy odd lines to File2 and even lines to File1
    with open('File1_even_lines.txt', 'w') as f_even, open('File2_odd_lines.txt', 'w') as f_odd:
        for i, line in enumerate(lines):
            # Line numbers (1, 2, 3...) correspond to index (0, 1, 2...)
            if (i + 1) % 2 == 0:
                f_even.write(line) # Even-numbered lines go to File1
            else:
                f_odd.write(line) # Odd-numbered lines go to File2
    print("d. Odd/Even lines written to their respective files.")

except FileNotFoundError:
    print("Error: 'sample.txt' not found. Please create it first.")

Q.10: Point Class

Question: Define a Point class with coordinates and a method to find the distance between two points.

import math

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
    
    def distance(self, other):
        return math.hypot(self.x - other.x, self.y - other.y)

p1 = Point(1, 2)
p2 = Point(4, 6)
print(f"Distance between {p1.x, p1.y} and {p2.x, p2.y} is {p1.distance(p2):.2f}")

Q.11: Dictionary of Cubes

Question: Print a dictionary where keys are 1-5 and values are their cubes.

# A dictionary comprehension is perfect for this.
cubes_dict = {x: x**3 for x in range(1, 6)}
print(cubes_dict)

Q.12: Tuple Operations

Question: Perform various operations on a given tuple t1.

t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)
t2 = (11, 13, 15)

# a. Half and half
mid = len(t1) // 2
print(f"Halves: {t1[:mid]} and {t1[mid:]}")

# b. Even numbers
print(f"Evens: {tuple(x for x in t1 if x % 2 == 0)}")

# c. Concatenate
print(f"Concatenated: {t1 + t2}")

# d. Max and min
print(f"Max: {max(t1)}, Min: {min(t1)}")

Q.13: Custom Exception for Name Validation

Question: Accept a name and raise an exception if it contains digits or special characters.

class InvalidNameError(Exception):
    pass

def validate_name(name):
    if not all(char.isalpha() or char.isspace() for char in name):
        raise InvalidNameError("Name can only contain letters and spaces.")
    print(f"'{name}' is a valid name.")

try:
    validate_name(input("Enter a name: "))
except InvalidNameError as e:
    print(f"Error: {e}")

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published