0% found this document useful (0 votes)
3 views15 pages

Untitled Document

The document contains a series of Python code snippets that demonstrate various programming concepts, including calculations for compound interest, checking if a list is sorted, finding the GCD, and handling file operations. It also covers topics such as digital logic gates, palindrome checking, and exception handling. Each section provides user input prompts and outputs results based on the implemented logic.

Uploaded by

sucker9142
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)
3 views15 pages

Untitled Document

The document contains a series of Python code snippets that demonstrate various programming concepts, including calculations for compound interest, checking if a list is sorted, finding the GCD, and handling file operations. It also covers topics such as digital logic gates, palindrome checking, and exception handling. Each section provides user input prompts and outputs results based on the implemented logic.

Uploaded by

sucker9142
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/ 15

# 1.a.

Compound Interest

principal = float(input("Enter principal amount: "))[cite: 1]

rate = float(input("Enter annual interest rate (as a decimal): "))[cite: 1]

periods = float(input("Enter number of compounding periods: "))[cite: 1]

amount = principal * (1 + rate) ** periods [cite: 1]

compound_interest = amount - principal [cite: 1]

print("Compound Interest:", compound_interest)

# 1.b. is_sorted

list_input_str = input("Enter elements of the list separated by commas: ")

my_list_b = [int(x.strip()) for x in list_input_str.split(',')]

is_sorted_flag = True

for i in range(len(my_list_b) - 1):

if my_list_b[i] > my_list_b[i+1]:

is_sorted_flag = False

break

print(is_sorted_flag)

# 1.c. has_duplicates

list_input_str_c = input("Enter elements of the list separated by commas: ")

my_list_c = [x.strip() for x in list_input_str_c.split(',')]

has_duplicates_flag = False

seen_elements = set()

for item in my_list_c:

if item in seen_elements:

has_duplicates_flag = True

break

seen_elements.add(item)

print(has_duplicates_flag)
# 1.d. Character Type Checker

char_input = input("Enter a character: ")

if '0' <= char_input <= '9': [cite: 4]

print("Digit") [cite: 4]

elif 'a' <= char_input <= 'z': [cite: 4]

print("Lowercase character") [cite: 4]

elif 'A' <= char_input <= 'Z': [cite: 4]

print("Uppercase character") [cite: 4]

else: [cite: 4]

print("Special character") [cite: 4]

# 1.e. Distance between two points

import math

x1 = float(input("Enter x1: "))[cite: 5]

y1 = float(input("Enter y1: "))[cite: 5]

x2 = float(input("Enter x2: "))[cite: 5]

y2 = float(input("Enter y2: "))[cite: 5]

distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2) [cite: 5]

print("Distance:", distance)

# 1.f. GCD

a_gcd = int(input("Enter first number for GCD: "))[cite: 6]

b_gcd = int(input("Enter second number for GCD: "))[cite: 6]

while b_gcd: [cite: 6]

a_gcd, b_gcd = b_gcd, a_gcd % b_gcd [cite: 6]

print("GCD:", a_gcd)

# 1.g. Convert list and tuple to arrays (using numpy)


import numpy as np [cite: 7]

list_input_g = input("Enter elements of the list separated by commas: ") [cite: 7]

my_list_g = [int(x.strip()) for x in list_input_g.split(',')] [cite: 7]

tuple_input_g = input("Enter elements of the tuple separated by commas: ") [cite: 7]

my_tuple_g = tuple(int(x.strip()) for x in tuple_input_g.split(',')) [cite: 7]

list_array = np.array(my_list_g) [cite: 7]

tuple_array = np.array(my_tuple_g) [cite: 7]

print("List as array:", list_array) [cite: 7]

print("Tuple as array:", tuple_array) [cite: 7]

# 1.h. remove_duplicates

list_input_str_h = input("Enter elements of the list separated by commas: ")

my_list_h = [x.strip() for x in list_input_str_h.split(',')]

unique_list = []

seen_h = set()

for item in my_list_h:

if item not in seen_h:

unique_list.append(item)

seen_h.add(item)

print(unique_list)

# 1.i. Read and print person details

name = input("Enter name: ")[cite: 9]

address = input("Enter address: ")[cite: 9]

email = input("Enter email: ")[cite: 9]

phone = input("Enter phone number: ")[cite: 9]


print("\nPerson Details:") [cite: 9]

print("Name:", name) [cite: 9]

print("Address:", address) [cite: 9]

print("Email:", email) [cite: 9]

print("Phone Number:", phone) [cite: 9]

# 1.j. Capitalize first letter of each word

sentence_input_j = input("Enter a sentence: ") [cite: 10]

words_j = sentence_input_j.split() [cite: 10]

capitalized_words_j = [word.capitalize() for word in words_j] [cite: 10]

result_sentence_j = ' '.join(capitalized_words_j) [cite: 10]

print(result_sentence_j)

# 1.k. Find common values between two arrays (using numpy)

import numpy as np [cite: 11]

arr1_input_k = input("Enter elements of the first array separated by commas: ") [cite: 11]

arr1_k = np.array([int(x.strip()) for x in arr1_input_k.split(',')]) [cite: 11]

arr2_input_k = input("Enter elements of the second array separated by commas: ") [cite: 11]

arr2_k = np.array([int(x.strip()) for x in arr2_input_k.split(',')]) [cite: 11]

common_values_k = np.intersect1d(arr1_k, arr2_k) [cite: 11]

print("Common values:", common_values_k) [cite: 11]

# 1.l. Palindrome

string_input_l = input("Enter a string: ") [cite: 12]

if string_input_l == string_input_l[::-1]: [cite: 12]

print(True) [cite: 12]


else: [cite: 12]

print(False) [cite: 12]

# 2.a. Print triangle

rows_a = 5 [cite: 13]

for i_a in range(rows_a, 0, -1): [cite: 13]

print((str(i_a) + ' ') * (rows_a - i_a + 1)) [cite: 13]

# 2.b. Digital Logic Gates

a_logic = bool(int(input("Enter value for A (0 or 1): ")))[cite: 14]

b_logic = bool(int(input("Enter value for B (0 or 1): ")))[cite: 14]

print("AND:", a_logic and b_logic)[cite: 14]

print("OR:", a_logic or b_logic)[cite: 14]

print("NOT A:", not a_logic)[cite: 14]

print("NOT B:", not b_logic)[cite: 14]

print("EX-OR:", a_logic ^ b_logic)[cite: 14]

# 2.c. Word with most occurrences in a text file

file_name_c = input("Enter the filename for word count: ") [cite: 15]

try:

with open(file_name_c, 'r') as file_c: [cite: 15]

text_c = file_c.read().lower() [cite: 15]

words_c = text_c.split() [cite: 15]

word_counts_c = {} [cite: 15]

for word_c in words_c: [cite: 15]

word_c = word_c.strip('.,!?;:"\'') [cite: 15]

word_counts_c[word_c] = word_counts_c.get(word_c, 0) + 1 [cite: 15]


if word_counts_c: [cite: 15]

most_common_word_c = max(word_counts_c, key=word_counts_c.get) [cite: 15]

print("Word with most occurrences:", most_common_word_c) [cite: 15]

else: [cite: 15]

print("File is empty or contains no words.")

except FileNotFoundError:

print("File not found.")

# 2.d. Invert dictionary content

user_input_d = input("Enter dictionary items as key:value pairs, separated by commas (e.g., 'a:1,b:2'): ")
[cite: 16]

input_list_d = [item.strip().split(':') for item in user_input_d.split(',')] [cite: 16]

original_dict_d = {k.strip(): v.strip() for k, v in input_list_d} [cite: 16]

inverted_dict_d = {v: k for k, v in original_dict_d.items()} [cite: 16]

print("Inverted dictionary:", inverted_dict_d) [cite: 16]

# 2.e. Define and print a matrix

rows_e = int(input("Enter the number of rows for the matrix: "))

cols_e = int(input("Enter the number of columns for the matrix: "))

matrix_e = []

print("Enter matrix elements row by row:")

for i_e in range(rows_e):

row_input_e = input(f"Enter elements for row {i_e+1} separated by spaces: ")

row_e = [int(x) for x in row_input_e.split()]

matrix_e.append(row_e)

print("\nMatrix:")

for row_print_e in matrix_e:

print(row_print_e)
# 3.a. Merge two file contents into a third file

file1_name_a = input("Enter the name of the first file to merge: ")

file2_name_a = input("Enter the name of the second file to merge: ")

output_file_name_a = input("Enter the name of the output file: ")

file1_content = ""

with open(file1_name_a, 'r') as file1_a: [cite: 18]

file1_content = file1_a.read() # [cite: 18]

file2_content = ""

with open(file2_name_a, 'r') as file2_a: # [cite: 18]

file2_content = file2_a.read() # [cite: 18]

with open(output_file_name_a, 'w') as outfile_a: # [cite: 18]

outfile_a.write(file1_content) # [cite: 18]

outfile_a.write(file2_content) # [cite: 18]

print(f"Contents of '{file1_name_a}' and '{file2_name_a}' merged into '{output_file_name_a}'.")

[cite: 18]

except FileNotFoundError:

print("One or both input files not found.")

# 3.b. Half Adder and Full Adder

A_adder = int(input("Enter A (0 or 1): ")) [cite: 19]

B_adder = int(input("Enter B (0 or 1): ")) [cite: 19]

# Half Adder

HA_Sum = A_adder ^ B_adder [cite: 19]

HA_Carry = A_adder & B_adder [cite: 19]

print("\nHalf Adder Output:") [cite: 19]

print("Sum:", HA_Sum) [cite: 19]

print("Carry:", HA_Carry) [cite: 19]


# Full Adder

Cin_adder = int(input("Enter Cin (0 or 1) for Full Adder: ")) [cite: 19]

FA_Sum1 = HA_Sum ^ Cin_adder

FA_Carry1 = HA_Sum & Cin_adder

FA_Sum = FA_Sum1

FA_Carry = HA_Carry | FA_Carry1

print("\nFull Adder Output:") [cite: 19]

print("Sum:", FA_Sum) [cite: 19]

print("Carry:", FA_Carry) [cite: 19]

# 3.c. Check for words in a file

file_name_c_check = input("Enter the filename to open: ") #

words_to_check_input_c = input("Enter words to check (comma-separated): ") #

words_to_check_c = [word.strip().lower() for word in words_to_check_input_c.split(',')] #

file_c_check_object = open(file_name_c_check, 'r') #

content_c_check = file_c_check_object.read().lower() #

file_c_check_object.close() #

found_words_c = [] #

for word_c_check in words_to_check_c: #

if word_c_check in content_c_check: #

found_words_c.append(word_c_check) #

if found_words_c: #

print("Found words:", ", ".join(found_words_c)) #

else: #

print("None of the specified words were found.") #


# 3.d. Method Resolution Order (MRO)

class A_mro:

def method(self):

print("Method from A")

class B_mro(A_mro):

def method(self):

print("Method from B")

class C_mro(A_mro):

def method(self):

print("Method from C")

class D_mro(B_mro, C_mro):

pass

d_instance_mro = D_mro()

d_instance_mro.method() [cite: 21]

print("MRO of D:", D_mro.__mro__) [cite: 21]

# 3.e. Exception Handling

try:

num1_e = int(input("Enter numerator: ")) [cite: 22]

num2_e = int(input("Enter denominator: ")) [cite: 22]

result_e = num1_e / num2_e [cite: 22]

print("Division result:", result_e) [cite: 22]

except ZeroDivisionError: [cite: 22]

print("Error: Cannot divide by zero.") [cite: 22]

except ValueError: [cite: 22]

print("Error: Invalid input. Please enter integers.") [cite: 22]

except IndexError: [cite: 22]

print("Error: Index out of bounds.") [cite: 22]


except FileNotFoundError: [cite: 22]

print("Error: File not found.") [cite: 22]

except TypeError: [cite: 22]

print("Error: Type mismatch.") [cite: 22]

except Exception as e: [cite: 22]

print("An unexpected error occurred:", e) [cite: 22]

# 4.a. Module concept (basic example, typically this would be separate files)

def circle_area(radius):

return 3.14159 * radius * radius

def rectangle_area(length, width):

return length * width

shape_type_a = input("Enter shape (circle/rectangle): ").lower() [cite: 23]

if shape_type_a == "circle": [cite: 23]

r_a = float(input("Enter radius: ")) [cite: 23]

print("Area of circle:", circle_area(r_a)) [cite: 23]

elif shape_type_a == "rectangle": [cite: 23]

l_a = float(input("Enter length: ")) [cite: 23]

w_a = float(input("Enter width: ")) [cite: 23]

print("Area of rectangle:", rectangle_area(l_a, w_a)) [cite: 23]

else: [cite: 23]

print("Unknown shape.")

# 4.b. Analyze file content

file_name_b_analyze = input("Enter the filename to analyze: ") [cite: 24]

file_b_analyze_object = open(file_name_b_analyze, 'r') #

content_b_analyze = file_b_analyze_object.read() #
file_b_analyze_object.close() #

num_words_b = len(content_b_analyze.split()) [cite: 24]

num_vowels_b = 0 [cite: 24]

for char_b in content_b_analyze.lower(): [cite: 24]

if char_b in 'aeiou': [cite: 24]

num_vowels_b += 1 [cite: 24]

num_blank_spaces_b = content_b_analyze.count(' ') [cite: 24]

num_lower_b = 0 [cite: 24]

for char_b in content_b_analyze: [cite: 24]

if 'a' <= char_b <= 'z': [cite: 24]

num_lower_b += 1 [cite: 24]

num_upper_b = 0 [cite: 24]

for char_b in content_b_analyze: [cite: 24]

if 'A' <= char_b <= 'Z': [cite: 24]

num_upper_b += 1 [cite: 24]

print("Number of words:", num_words_b) [cite: 24]

print("Number of vowels:", num_vowels_b) [cite: 24]

print("Number of blank spaces:", num_blank_spaces_b) [cite: 24]

print("Number of lowercase letters:", num_lower_b) [cite: 24]

print("Number of uppercase letters:", num_upper_b) [cite: 24]

# 4.c. Generate all binary strings of n-bit length (recursive helper function still used internally)

def generate_binary_strings_recursive(n, current_string=""): [cite: 25]

if n == 0: [cite: 25]

print(current_string) [cite: 25]

return [cite: 25]

generate_binary_strings_recursive(n - 1, current_string + "0") [cite: 25]

generate_binary_strings_recursive(n - 1, current_string + "1") [cite: 25]


n_bits_c = int(input("Enter the number of bits: ")) [cite: 25]

generate_binary_strings_recursive(n_bits_c)

# 4.d. Validate phone number and email-id

import re [cite: 26]

phone_number_d = input("Enter phone number: ") [cite: 26]

email_id_d = input("Enter email ID: ") [cite: 26]

phone_regex_d = r"^\+?(\d{1,3})?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}$" [cite: 26]

email_regex_d = r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$" [cite: 26]

if re.fullmatch(phone_regex_d, phone_number_d): [cite: 26]

print("Phone number: Valid") [cite: 26]

else: [cite: 26]

print("Phone number: Invalid") [cite: 26]

if re.fullmatch(email_regex_d, email_id_d): [cite: 26]

print("Email ID: Valid") [cite: 26]

else: [cite: 26]

print("Email ID: Invalid") [cite: 26]

# 5. Pyplot plots (Requires matplotlib library: pip install matplotlib)

import matplotlib.pyplot as plt [cite: 27]

print("Choose plot type:") [cite: 27]

print("a. Line graph") [cite: 27]

print("b. Line graph with markers") [cite: 27]

print("c. Scatter plot") [cite: 28]


print("d. Bar chart") [cite: 28]

print("e. Histogram") [cite: 28]

print("f. Pie chart") [cite: 28]

choice_plot = input("Enter your choice (a-f): ").lower() [cite: 27]

if choice_plot in ['a', 'b', 'c']: [cite: 27, 28]

x_values_str_plot = input("Enter x values (comma-separated): ") [cite: 27]

y_values_str_plot = input("Enter y values (comma-separated): ") [cite: 27]

x_plot = [float(val.strip()) for val in x_values_str_plot.split(',')] [cite: 27]

y_plot = [float(val.strip()) for val in y_values_str_plot.split(',')] [cite: 27]

plt.figure(figsize=(8, 6)) [cite: 27]

if choice_plot == 'a': [cite: 27]

plt.plot(x_plot, y_plot) [cite: 27]

plt.title('Line Graph') [cite: 27]

plt.xlabel('X-axis') [cite: 27]

plt.ylabel('Y-axis') [cite: 27]

elif choice_plot == 'b': [cite: 27]

plt.plot(x_plot, y_plot, marker='o') [cite: 27]

plt.title('Line Graph with Markers') [cite: 27]

plt.xlabel('X-axis') [cite: 27]

plt.ylabel('Y-axis') [cite: 27]

elif choice_plot == 'c': [cite: 28]

plt.scatter(x_plot, y_plot) [cite: 28]

plt.title('Scatter Plot') [cite: 28]

plt.xlabel('X-axis') [cite: 28]

plt.ylabel('Y-axis') [cite: 28]

plt.grid(True) [cite: 27]


plt.show() [cite: 27]

elif choice_plot == 'd': [cite: 28]

categories_str_plot = input("Enter categories (comma-separated): ") [cite: 28]

values_str_plot = input("Enter values (comma-separated): ") [cite: 28]

categories_plot = [val.strip() for val in categories_str_plot.split(',')] [cite: 28]

values_plot = [float(val.strip()) for val in values_str_plot.split(',')] [cite: 28]

plt.figure(figsize=(8, 6)) [cite: 28]

plt.bar(categories_plot, values_plot) [cite: 28]

plt.title('Bar Chart') [cite: 28]

plt.xlabel('Categories') [cite: 28]

plt.ylabel('Values') [cite: 28]

plt.show() [cite: 28]

elif choice_plot == 'e': [cite: 28]

data_str_plot = input("Enter data for histogram (comma-separated): ") [cite: 28]

data_plot = [float(val.strip()) for val in data_str_plot.split(',')] [cite: 28]

plt.figure(figsize=(8, 6)) [cite: 28]

plt.hist(data_plot, bins=5, edgecolor='black') [cite: 28]

plt.title('Histogram') [cite: 28]

plt.xlabel('Value') [cite: 28]

plt.ylabel('Frequency') [cite: 28]

plt.show() [cite: 28]

elif choice_plot == 'f': [cite: 28]

sizes_str_plot = input("Enter sizes for pie chart (comma-separated): ") [cite: 28]

labels_str_plot = input("Enter labels for pie chart (comma-separated): ") [cite: 28]
sizes_plot = [float(val.strip()) for val in sizes_str_plot.split(',')] [cite: 28]

labels_plot = [val.strip() for val in labels_str_plot.split(',')] [cite: 28]

plt.figure(figsize=(8, 8)) [cite: 28]

plt.pie(sizes_plot, labels=labels_plot, autopct='%1.1f%%', startangle=90) [cite: 28]

plt.title('Pie Chart') [cite: 28]

plt.axis('equal') [cite: 28]

plt.show() [cite: 28]

else: [cite: 27]

print("Invalid choice.") [cite: 27]

You might also like