0% found this document useful (0 votes)
15 views37 pages

Arpit Negi Project

Uploaded by

Arpit Negi
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)
15 views37 pages

Arpit Negi Project

Uploaded by

Arpit Negi
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
You are on page 1/ 37

Question 1: Program that finds the two numbers with the

highest product from a list


a=eval(input("Enter list elements:"))
lst=list(a)
b=lst.sort()
print(lst)
product=lst[0]*lst[1]
print(product)
Question 2: Program to calculate nth term of Fibonacci series
n=int(input("Enter the total number of terms"))
a,b=0,1
c=[]
for i in range(n):
c.append(a)
a,b=b,a+b
print(c)
Question 3: Program to append two list together with only
unique values
a=eval(input("Enter list elements:"))
b=eval(input("Enter list elements:"))
c,d=list(a),list(b)
unique_list=[]
for i in c:
unique_list.append(i)
for i in d:
if i not in unique_list:
unique_list.append(i)
print(unique_list)

Output:
Question 4: Program to create mirror of string
a=input("Enter a string you want to mirror")
mirror=a[::-1]
m=a+' | '+mirror
print(m)

Output:
Question 5: Python function that takes a sentence and
returns the word frequencies in descending order
from collections import Counter

def word_frequencies(sentence):
a= ''.join(char.lower() if char.isalnum() or char.isspace()
else ' ' for char in sentence)
words = a.split()

word_count = Counter(words)
sorted_word_count = sorted(word_count.items(),
key=lambda x: x[1], reverse=True)

return sorted_word_count

sentence =input("Enter your sentence")


result = word_frequencies(sentence)

print("Word Frequencies:")
for word, frequency in result:
print(f"{word}: {frequency}")
Output:
Question 6: Python function to remove duplicates from a list
def remove_duplicates(lst):
unique_list = []
for item in lst:
if item not in unique_list:
unique_list.append(item)
return unique_list
input_list = eval(input("Enter a list"))
result = remove_duplicates(input_list)
print("Original List:", input_list)
print("List Without Duplicates:", result)

Output:
Question 7: Python program to solve a quadratic equation
import math

def solve_quadratic(a, b, c):


if a == 0:
return "This is not a quadratic equation."
D = b**2 - (4 * a * c)

if D > 0:
root1 = (-b + math.sqrt(D)) / (2 * a)
root2 = (-b - math.sqrt(D)) / (2 * a)
return f"Roots are real and distinct: {root1:.2f},
{root2:.2f}"
elif D == 0:
root = -b / (2 * a)
return f"Roots are real and equal: {root:.2f}"
else:
real_part = -b / (2 * a)
imaginary_part = math.sqrt(-D) / (2 * a)
return f"Roots are complex: {real_part:.2f} ±
{imaginary_part:.2f}i"

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


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

result = solve_quadratic(a, b, c)
print(result)

Output:
Question 8: Python Program to encrypt and decrypt by
certain number of characters
def encrypt(text, shift):
result = ""
for char in text:
if char.isalpha():
if char.islower():
new_char = chr((ord(char) - ord('a') + shift) % 26 +
ord('a'))
else:
new_char = chr((ord(char) - ord('A') + shift) % 26 +
ord('A'))
result += new_char
else:
result += char
return result

def decrypt(text, shift):


return encrypt(text, -shift)

plain_text = input("Enter the text to encrypt: ")


shift_value = int(input("Enter the shift value: "))
encrypted_text = encrypt(plain_text, shift_value)
print("Encrypted Text:", encrypted_text)

decrypted_text = decrypt(encrypted_text, shift_value)


print("Decrypted Text:", decrypted_text)

Output:
Question 9: Python program that checks if a number is prime
or not
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
num = int(input("Enter a number: "))
if is_prime(num):
print(f"{num} is a prime number.")
else:
print(f"{num} is not a prime number.")

Output:

Question 10: Simple password generator program in Python


import random
def generate_password(name, birth_year, favorite_color):
parts = [name[:3].capitalize(), favorite_color[-3:],
str(birth_year)[-2:],str(random.randint(10, 99))]
random.shuffle(parts)
password = ''.join(parts)
return password
name = input("Enter your name: ")
birth_year = int(input("Enter your birth year: "))
favorite_color = input("Enter your favorite color: ")

password = generate_password(name, birth_year,


favorite_color)
print("Generated Password:", password)

Output:

Question 11: Program that converts binary to decimal


def binary_to_decimal(binary):
decimal = 0
power = 0
for digit in binary[::-1]: # Reverse the binary string to
process from right to left
decimal += int(digit) * (2 ** power)
power += 1
return decimal
binary = input("Enter a binary number: ")
print("Decimal value:", binary_to_decimal(binary))

Output:

Question 12: To make a menu driven stack based program


class Stack:
def __init__(self):
self.stack = []

def push(self, item):


self.stack.append(item)
print(f"{item} pushed onto the stack.")

def pop(self):
if len(self.stack) > 0:
popped_item = self.stack.pop()
print(f"{popped_item} popped from the stack.")
else:
print("Stack is empty! Cannot pop.")

def peek(self):
if len(self.stack) > 0:
print(f"Top element is: {self.stack[-1]}")
else:
print("Stack is empty! No top element.")

def display(self):
if len(self.stack) > 0:
print("Stack elements are:", self.stack)
else:
print("Stack is empty!")

def main():
stack = Stack()
while True:
print("\nStack Menu:")
print("1. Push an element")
print("2. Pop an element")
print("3. Peek the top element")
print("4. Display all elements")
print("5. Exit")

try:
choice = int(input("Enter your choice (1-5): "))
except ValueError:
print("Invalid input! Please enter an integer (1-5).")
continue

if choice == 1:
item = input("Enter an element to push: ")
stack.push(item)
elif choice == 2:
stack.pop()
elif choice == 3:
stack.peek()
elif choice == 4:
stack.display()
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice! Please enter a valid option (1-
5).")

if __name__ == "__main__":
main()

Output:
Question 13: Python program to write a list of strings to a
text file, then read the contents of the text file and display
them
def write(filename, lines):
with open(filename, "w") as file:
for line in lines:
file.write(line + "\n")

def read(filename):
with open(filename, "r") as file:
contents = file.readlines()
for line in contents:
print(line.strip())
filename = "ArpitWord.txt"
string_list = input("Enter what you want to write (separate by
space): ")
write(filename, string_list)

print("Contents of the file:")


read(filename)
Output:
Question 14: WAP in Python, using functions to create and
read a binary file “LAPTOP.DAT” containing the records of the
following type, [ModelNo, RAM, HDD, Details]. Write a
search function in which the user should enter the model
number to display the details of the laptop where ModelNo,
RAM, HDD are integers, and Details is a string.

import pickle
def create_file():
with open("LAPTOP.DAT", "ab") as file:
while True:
try:
model_no = int(input("Enter Model Number: "))
ram = int(input("Enter RAM (in GB): "))
hdd = int(input("Enter HDD size (in GB): "))
details = input("Enter Details: ")
record = { "ModelNo": model_no,
"RAM": ram,
"HDD": hdd,
"Details": details }

pickle.dump(record, file)
more = input("Do you want to add another record? (yes/no):
").strip().lower()
if more != "yes":
break
except ValueError:
print("Invalid input. Please enter valid data.")

def search_model(model_no):
try:
with open("LAPTOP.DAT", "rb") as file:
found = False
while True:
try:
record = pickle.load(file)
if record["ModelNo"] == model_no:
print(f"Laptop Found:\nModel Number:
{record['ModelNo']}\nRAM: {record['RAM']} GB\nHDD:
{record['HDD']} GB\nDetails: {record['Details']}")
found = True
break
except EOFError:
break
if not found:
print("Laptop with the specified model number not
found.")
except FileNotFoundError:
print("The file LAPTOP.DAT does not exist. Please create
it first.")

def main():
while True:
print("\nMenu:")
print("1. Create or Add Records")
print("2. Search for a Laptop by Model Number")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ").strip()

if choice == "1":
create_file()
elif choice == "2":
try:
model_no = int(input("Enter the Model Number to
search: "))
search_model(model_no)
except ValueError:
print("Invalid input. Please enter a valid model
number.")
elif choice == "3":
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")

if __name__ == "__main__":
main()

Output:
Question 15:
Write program in python in Python to create a text file, and
then read this file to print all the words that contain the
character a' in this file and also write these lines to another
text file.

def create_and_write_file():
with open("input.txt", "w") as file:
print("Enter the content for the file (type 'STOP' to
finish):")
while True:
line = input()
if line.strip().upper() == "STOP":
break
file.write(line + "\n")
print("Content added to 'input.txt':")
with open("input.txt", "r") as file:
print(file.read())

def read_and_filter_words():
try:
with open("input.txt", "r") as file:
lines = file.readlines()

words_with_a = [word for line in lines for word in


line.split() if 'a' in word or 'A' in word]

# Write these words to another file


with open("output.txt", "w") as output_file:
output_file.write("Words containing 'a' or 'A':\n")
output_file.write("\n".join(words_with_a))

print("Words containing 'a' or 'A':")


print("\n".join(words_with_a))

except FileNotFoundError:
print("The file 'input.txt' does not exist. Please create it
first.")

def main():
"""Main function to provide a menu for the user."""
while True:
print("\nMenu:")
print("1. Create and Write to File")
print("2. Read File and Filter Words")
print("3. Exit")

choice = input("Enter your choice (1/2/3): ").strip()

if choice == "1":
create_and_write_file()
elif choice == "2":
read_and_filter_words()
elif choice == "3":
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")

if __name__ == "__main__":
main()

Output
Question 16 Write a function called addDict(dict1, dict2)
which computes the union of two dictionaries. It should
return a new dictionary, with all the items in both its
arguments (assumed to be dictionaries). If the same key
appears in both arguments, feel free to pick a value from
either.

def create_and_write_file():
with open("input.txt", "w") as file:
print("Enter the content for the file (type 'STOP' to
finish):")
while True:
line = input()
if line.strip().upper() == "STOP":
break
file.write(line + "\n")
print("Content added to 'input.txt':")
with open("input.txt", "r") as file:
print(file.read())

def addDict(dict1, dict2):


union={}
for key, value in dict1.items():
union[key]= value
for key, value in dict2.items():
union[key]= value
return union

def main():
while True:
print("\nMenu:")
print("1. Create and Write to File")
print("2. Add Two Dictionaries")
print("3. Exit")

choice = input("Enter your choice (1/2/3/4): ").strip()

if choice == "1":
create_and_write_file()
elif choice == "2":
dict1 = eval(input("Enter first dictionary: "))
dict2 = eval(input("Enter second dictionary: "))
union = addDict(dict1, dict2)
print("Resulting Dictionary:", union)
elif choice == "3":
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please select a valid option.")

if __name__ == "__main__":
main()

Output:
MYSQL QUERIES
Creating and inserting values in table
Using Select Command and Viewing Table
Using “Update” and “Alter” Command
Using “Grouped By” and “Having Clause”

Creating Table using Constraints


Using MAX, MIN and AVG command in
Destination Table

You might also like