0% found this document useful (0 votes)
9 views11 pages

Anshpdf

Uploaded by

03abhi09
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)
9 views11 pages

Anshpdf

Uploaded by

03abhi09
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/ 11

Assignment 3

Ansh Kumar Pachauri


2023UEE1306
Q 1.
(a)
Code:
for i in range(1,6):
for j in range(i):
print(i,end=" ")
print()
Output:

(b)
Code:
a = 5
b = 6
c = 7
s = (a+b+c)/2
area = math.sqrt(s*(s-a)*(s-b)*(s-c))
print(area)
Output:

Q 2.
(a)
Code:
n = int(input("Enter number of terms you want to print : "))
a = 0
b = 1
for i in range(0,n):
print(a,end = " ")
a,b = b,a+b
Output:

(b)
Code:
def is_armstrong(number):
digits = str(number)
num_digits = len(digits)
armstrong_sum = sum(int(digit) ** num_digits for digit in digits)
return armstrong_sum == number

def find_armstrong_numbers(N1, N2):


armstrong_numbers = []
for num in range(N1, N2 + 1):
if is_armstrong(num):
armstrong_numbers.append(num)
return armstrong_numbers
N1 = 100
N2 = 1000
result = find_armstrong_numbers(N1, N2)
print(f"Armstrong numbers between {N1} and {N2}: {result}")
Output:

(c)
Code:
n1 = int(input("Enter 1st no."))
n2 = int(input("Enter 2nd no."))
def is_prime(n):
for i in range(2,n):
if(n % i == 0):
return False
return True
for i in range(n1,n2+1):
if(is_prime(i)):
print(i,end=" ")
Output:

Q3
(a)
Code:
n = int(input("Enter number"))
print((n*(n+1))/2)
Output:

(b)
Code:
a = int(input("Enter first no. :"))
b = int(input("Enter second no. :"))
product = a*b
print("product = ",product)
if(product > 1000):
print("sum = ",a+b)
Output:

Q4
(a)
Code:
n = int(input("enter year"))
leap = False
if(n%100 == 0):
if(n%400 == 0):
leap = True
else:
if(n%4 == 0):
leap = True

print(leap)
Output:

(b)
Code:
sub = "ansh"
s = "4anshanshans3"
i = 0
count = 0
while(i < len(s)-len(sub)):
if(s[i:i+len(sub)] == sub):
count += 1
i+=1
print(count)
Output:

Q5
(a)
Code:
def fact(n):
# base case
if(n == 0 or n == 1):
return 1
return n*fact(n-1)
print(fact(5))

(b)
dict = {
"Ansh" : 19,
"Ritika" : 18,
"Ayushi" : 19,
"Dev" : 18
}
for key in dict:
if(dict[key] > 18):
print(key)

Output:

Q6
(a)
Code:
def count_words(filename):
with open(filename, 'r') as file:
text = file.read()
words = text.split()
count = len(words)
print(count)

filename = "ex.txt"
count_words(filename)
Output:

File:
Life is like a pendulum and psychologically speaking the toughest part is to figure out the balance point between
letting things go and holding on to them.
(b)
def calculate_average(input_file, output_file):
total_score = 0
student_count = 0
with open(input_file, 'r') as infile:
for line in infile:
parts = line.split()
if len(parts) == 2:
name, score = parts
try:
score = float(score)
total_score += score
student_count += 1
except ValueError:
print(f"Invalid score for student: {name}")

if student_count > 0:
average_score = total_score / student_count
else:
average_score = 0

with open(output_file, 'w') as outfile:


outfile.write(f"Average Score: {average_score:.2f}\n")

print(f"Average score calculated and written to '{output_file}'.")

input_file = "students.txt"
output_file = "average_score.txt"
calculate_average(input_file, output_file)
Output:
Students.txt:
Ansh 85
Ritika 100
Sarthak 80
Vatsal 90
Dev 95

Output.txt:
Average Score: 90.00

(c)
Code:
def read_file(filename):
try:
with open(filename, 'r') as file:
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")

filename = "non_existent_file.txt"
read_file(filename)
OUTPUT:

Q 7.
(a)
Code:
class Student:
def __init__(self, name, percentage):
self.name = name
self.percentage = percentage

def update_percentage(self, new_percentage):


self.percentage = new_percentage
print(f"Updated {self.name}'s percentage to {self.percentage}%.")

def has_passed(self):
if self.percentage >= 50:
return True
else:
return False

def display(self):
status = "Passed" if self.has_passed() else "Failed"
print(f"Student: {self.name}, Percentage: {self.percentage}%, Status:
{status}")
student1 = Student("Ansh", 72)
student1.display()

student2 = Student("Random", 45)


student2.display()

student2.update_percentage(55)
student2.display()
Output :

(b)
def calculate_compound_interest(principal, rate, times_compounded, years):
rate = rate / 100
amount = principal * math.pow((1 + rate / times_compounded), times_compounded
* years)
compound_interest = amount - principal
return amount, compound_interest

P = 1000 # Principal amount in dollars


R = 5 # Annual interest rate in percentage
N = 4 # Compounded quarterly
T = 5 # Time in years

final_amount, interest = calculate_compound_interest(P, R, N, T)

print(f"Final Amount: ${final_amount:.2f}")


print(f"Compound Interest Earned: ${interest:.2f}")
Output:
Q8
(a)
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 500)


y = np.sin(x)

plt.figure(figsize=(10, 5))
plt.plot(x, y, label='Sine Wave', color='blue', linewidth=2)

plt.title('Sine Wave Plot')


plt.xlabel('x (radians)')
plt.ylabel('sin(x)')
plt.grid(True)
plt.axhline(0, color='black', linewidth=0.5)
plt.axvline(0, color='black', linewidth=0.5)
plt.legend()

plt.show()

Output:

(b)
import random

def guessing_game():
secret_number = random.randint(1, 10)
attempts = 0

print("Welcome to the Guessing Game!")


print("I have selected a number between 1 and 10. Can you guess it?")
while True:
guess = input("Enter your guess (1-10): ")
attempts += 1
if not guess.isdigit():
print("Invalid input! Please enter a number between 1 and 10.")
continue
guess = int(guess)
if guess == secret_number:
print(f"Congratulations! You guessed the correct number {secret_number} in
{attempts} attempts.")
break
elif guess < secret_number:
print("Too low! Try again.")
else:
print("Too high! Try again.")

guessing_game()

Output:

Q 9.
Code:
def merge_sorted_lists(list1, list2):
merged_list = []
i, j = 0, 0
while i < len(list1) and j < len(list2):
if list1[i] < list2[j]:
merged_list.append(list1[i])
i += 1
else:
merged_list.append(list2[j])
j += 1
while i < len(list1):
merged_list.append(list1[i])
i += 1
while j < len(list2):
merged_list.append(list2[j])
j += 1

return merged_list
list1 = [1, 3, 5]
list2 = [2, 4, 6]
result = merge_sorted_lists(list1, list2)
print(result)
Output:

Q 10.
Code:
def flatten(nested_list):
flat_list = []
def flatten_helper(sublist):
for item in sublist:
if isinstance(item, list):
flatten_helper(item)
else:
flat_list.append(item)

flatten_helper(nested_list)
return flat_list
nested_list = [1, [2, [3, 4], 5], 6]
result = flatten(nested_list)
print(result)
Output:

You might also like