Roll No.27

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Department of CSE, PES University

UE24CS151A-Python for Computational Problem Solving


Laboratory Week 4

Problem Statements

1. Write a Python program to Sum only even natural numbers up to n terms given by the
user. Use control flow tokens.

Solution
# Function to calculate sum of even natural numbers up to n terms
def sum_even_numbers(n):
total_sum = 0
count = 0 # To track how many even numbers have been added
number = 2 # Start from the first even number

while count < n:


if number % 2 == 0: # Check if the number is even
total_sum += number
count += 1 # Increment the count of even numbers
number += 1 # Move to the next number

return total_sum

# Taking user input

n_terms = int(input("Enter the number of terms: "))

# Output the sum of the first n even natural numbers

result = sum_even_numbers(n_terms)
print(f"The sum of the first {n_terms} even natural numbers is: {result}")

2. Write a Python program to find the factorial of a number using loops. Take input from the
user.

Solution
# Function to calculate factorial using a loop
def factorial(n):
result = 1
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

# Loop through numbers from 1 to n


for i in range(1, n + 1):
result *= i # Multiply the result by the current number
return result

# Taking user input


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

# Checking if the input is valid (factorial of negative numbers doesn't exist)


if number < 0:
print("Factorial does not exist for negative numbers.")
else:
# Calculating and printing the factorial
fact = factorial(number)
print(f"The factorial of {number} is: {fact}")

3. Create a Python program that counts down from 10 to 1 using a while loop. For each
number, if the number is odd, print "Odd: <number>", and if it is even, print "Even:
<number>". When it reaches 0, print "Blast off!".
Expected output:
Odd: 9
Even: 8
Odd: 7
Even: 6
Odd: 5
Even: 4
Odd: 3
Even: 2
Odd: 1
Blast off!
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

Solution
# Countdown function
def countdown():
number = 10

while number > 0:


if number % 2 == 0:
print(f"Even: {number}")
else:
print(f"Odd: {number}")
number -= 1 # Decrement the number by 1

print("Blast off!") # When countdown reaches 0

# Call the countdown function


countdown()

4. Write a Python program that takes a number from the user and prints its multiplication
table (from 1 to 10) using a for loop.

Solution

# Function to print multiplication table


def multiplication_table(n):
print(f"Multiplication Table for {n}:")
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")

# Taking user input


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

# Call the function to print the multiplication table


multiplication_table(number)
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

5. Create a Python program that prints the numbers from 1 to 30. For multiples of 3, print
"Fizz" instead of the number, and for multiples of 5, print "Buzz". For numbers that are
multiples of both 3 and 5, print "FizzBuzz".
Expected output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

Solution

# Function to print Fizz, Buzz, and FizzBuzz


def fizz_buzz():
for i in range(1, 31):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)

# Call the function


fizz_buzz()
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

6. Write a Python program that takes a number as input and checks whether the number is
prime or not. A prime number is a number greater than 1 that has no divisors other than
1 and itself.

Solution

# Function to check if a number is prime


def is_prime(n):
if n <= 1:
return False # Numbers less than or equal to 1 are not prime
for i in range(2, int(n ** 0.5) + 1): # Loop from 2 to the square root of n
if n % i == 0: # If n is divisible by any number other than 1 and itself
return False
return True

# Taking user input


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

# Checking and printing whether the number is prime


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

7. Write a Python program to print a right-angled triangle of numbers where each row
contains the number repeated multiple times. The number of rows is provided by the
user.
For input 5
1
22
333
4444
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

55555

Solution

# Function to print right-angled triangle of numbers


def print_triangle(rows):
for i in range(1, rows + 1):
# Print the number 'i', repeated 'i' times
print(str(i) * i)

# Taking user input for the number of rows


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

# Call the function to print the triangle


print_triangle(num_rows)

8. Write a Python program to find the sum of the digits of a given number. For eg. , for input
123, the output should be 6 (1 + 2 + 3 = 6).

Solution

# Function to calculate the sum of the digits


def sum_of_digits(n):
total_sum = 0
while n > 0:
digit = n % 10 # Get the last digit of the number
total_sum += digit # Add the digit to the total sum
n = n // 10 # Remove the last digit from the number
return total_sum

# Taking user input


number = int(input("Enter a number: "))
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

# Call the function and print the sum of the digits


result = sum_of_digits(number)
print(f"The sum of the digits of {number} is: {result}")

9. John is using a computer in which arithmetic operations (+, -, *, /, **) are not working. But
as his assignments deadline are near he is looking for alternative methods. Help him out
in solving the below questions using other operators.
a. To calculate the power of 2 up to n terms.
Eg. 2 , 2 , …… ,2
0 1 (n-1)

b. Check whether a given number is even or odd.


Hint - express the given num in the binary number system for analysis
and check the least significant bit. (use pen and paper to analyze )

Eg. 5 => 101


10 => 1010

c. Multiple a given number by 33.


Hint - (n * 2 + n)
5

- (33 = 2 + 2 )
5 0

Try using “bitwise or” and “bitwise shifts” operators instead of addition and
multiplication operators.

Solution

# Function to calculate powers of 2 up to n terms


def powers_of_two(n):
result = []
for i in range(n):
result.append(1 << i) # Bitwise left shift to calculate 2^i
return result

# Taking user input


n = int(input("Enter the number of terms for powers of 2: "))

# Call the function and print the result


powers = powers_of_two(n)
print(f"Powers of 2 up to {n} terms: {powers}")
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

# Function to check if a number is even or odd using LSB


def check_even_odd(n):
if n & 1 == 0: # Check the least significant bit using bitwise AND
return "Even"
else:
return "Odd"

# Taking user input


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

# Call the function and print the result


result = check_even_odd(number)
print(f"{number} is {result}.")

# Function to multiply a number by 33 using bitwise shifts


def multiply_by_33(n):
return (n << 5) + n # Equivalent to n * 32 + n

# Taking user input


number = int(input("Enter a number to multiply by 33: "))

# Call the function and print the result


result = multiply_by_33(number)
print(f"{number} multiplied by 33 is: {result}")

10. Imagine you are a student calculating your final semester grade. You have 5 subjects,
and each subject has a score between 1 and 100. Write a Python program that:
● Takes the score of each subject using a for loop.
● Calculates the average score.
● Assigns a grade based on the following scale:
o 90 and above: Grade A
o 80-89: Grade B
o 70-79: Grade C
o 60-69: Grade D
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

o Below 60: Grade F

Prints the average score and the corresponding grade.

# Function to calculate average and assign a grade


def calculate_grade():
total_score = 0
num_subjects = 5

# Taking scores for 5 subjects using a loop


for i in range(1, num_subjects + 1):
score = int(input(f"Enter the score for subject {i}: "))
total_score += score

# Calculate the average score


average_score = total_score / num_subjects

# Assigning a grade based on the average score


if average_score >= 90:
grade = 'A'
elif 80 <= average_score < 90:
grade = 'B'
elif 70 <= average_score < 80:
grade = 'C'
elif 60 <= average_score < 70:
grade = 'D'
else:
grade = 'F'

# Print the average and grade


print(f"\nAverage Score: {average_score:.2f}")
print(f"Your Grade: {grade}")

# Call the function to calculate the grade


calculate_grade
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

Extra Questions

1. Two persons A and B are conducting a Chemical experiment. In which A is user element
D and E in ratio of 2:1 and B uses the ratio of 4:3, calculate the mass of the compound if
each generates a 1 mole gram of substance given that the mass of D is 1 unit(amu) and
E is 5 units(amu). Take the values from the user.
Hint - Consider using split() method on the input string
eg-
"1:2".split(":") # [‘1’,’2’]
a,b = "1:2".split(":") # a <- '1' ; b <- ‘2
a,b = int(a), int(b) # type casting char/string to integers

Solution

# Function to calculate the mass of the compounds


def calculate_compound_mass():
# Get user inputs for ratios
ratio_A = input("Enter the ratio for A (D:E) in the format 'x:y': ")
ratio_B = input("Enter the ratio for B (D:E) in the format 'x:y': ")

# Split the ratios


ratio_A_D, ratio_A_E = map(int, ratio_A.split(":"))
ratio_B_D, ratio_B_E = map(int, ratio_B.split(":"))

# Given masses
mass_D = 1 # amu
mass_E = 5 # amu

# Calculate total mass of compound for A


# Let x be the common factor for A
total_mass_A = (ratio_A_D * mass_D + ratio_A_E * mass_E)

# Calculate total mass of compound for B


# Let y be the common factor for B
total_mass_B = (ratio_B_D * mass_D + ratio_B_E * mass_E)

return total_mass_A, total_mass_B


Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

# Run the function and get results


mass_A, mass_B = calculate_compound_mass()
print(f"Total mass of compound for A: {mass_A} units")
print(f"Total mass of compound for B: {mass_B} units")

2. You are asked to color quarter of a circle withreed, one third of the remaining with blue
and rest in yellow, find the area covered by each color and perimeter of each color
(include inner boundaries also ). Take radius as input.

Solution
import math

def calculate_colors_area_perimeter(radius):
# Area of the quarter circle
area_quarter_circle = (1/4) * math.pi * radius**2

# Area covered by each color


area_red = area_quarter_circle / 4
area_blue = (1/3) * (area_quarter_circle - area_red)
area_yellow = area_quarter_circle - area_red - area_blue

# Perimeter calculations
perimeter_red = (1/4) * (2 * math.pi * radius) + 2 * radius
perimeter_blue = radius / 3 # Straight boundary of blue
perimeter_yellow = radius / 3 # Straight boundary of yellow

return {
'area_red': area_red,
'area_blue': area_blue,
'area_yellow': area_yellow,
'perimeter_red': perimeter_red,
'perimeter_blue': perimeter_blue,
'perimeter_yellow': perimeter_yellow,
}
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

# Take radius input from the user


radius = float(input("Enter the radius of the circle: "))
results = calculate_colors_area_perimeter(radius)

# Print the results


print(f"Area covered by Red: {results['area_red']:.2f} square units")
print(f"Area covered by Blue: {results['area_blue']:.2f} square units")
print(f"Area covered by Yellow: {results['area_yellow']:.2f} square units")
print(f"Perimeter of Red: {results['perimeter_red']:.2f} units")
print(f"Perimeter of Blue: {results['perimeter_blue']:.2f} units")
print(f"Perimeter of Yellow: {results['perimeter_yellow']:.2f} units")

3. You’re planning a vacation to a different country, but their weather forecasts are in
Celsius, and you’re more familiar with Fahrenheit. Write a Python program to help you
convert temperatures from Celsius to Fahrenheit so you can pack accordingly for your
trip! (use the formula: F = C * 9/5 + 32)

Solution

def celsius_to_fahrenheit(celsius):
"""Convert Celsius to Fahrenheit."""
fahrenheit = celsius * (9/5) + 32
return fahrenheit

def main():
# Prompt user for temperature in Celsius
try:
celsius = float(input("Enter the temperature in Celsius: "))
fahrenheit = celsius_to_fahrenheit(celsius)
print(f"{celsius}°C is equivalent to {fahrenheit:.2f}°F")
except ValueError:
print("Please enter a valid number.")

# Run the program


if __name__ == "__main__":
main()
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

4. You’re baking a cake, but the recipe you’re following is for 12 servings, and you need to
make enough for a different number of people. Write a Python program that takes the
number of servings you want to make and adjusts the ingredients accordingly. If the
recipe calls for 2 cups of sugar for 12 servings, calculate how many cups of sugar you'll
need for the number of servings entered by the user.

Solution

def adjust_ingredients(desired_servings, original_servings=12, sugar_per_recipe=2):


"Adjust the amount of sugar needed based on the desired number of servings."
# Calculate the amount of sugar needed for the desired servings
sugar_needed = (desired_servings / original_servings) * sugar_per_recipe
return sugar_needed

def main():
# Prompt user for the number of servings they want to make
try:
desired_servings = int(input("Enter the number of servings you want to make: "))

# Call the function to adjust the ingredients


sugar_needed = adjust_ingredients(desired_servings)

print(f"For {desired_servings} servings, you'll need {sugar_needed:.2f} cups of sugar.")


except ValueError:
print("Please enter a valid number.")

# Run the program


if __name__ == "__main__":
main()
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

5. You're throwing a pizza party for your friends, and you want to make sure everyone gets
an equal number of slices. Write a Python program that takes the number of pizzas,
slices per pizza, and the number of people attending the party as input, and calculates
how many slices each person gets. Also, calculate how many slices will be left over.

Solution
def calculate_slices(pizzas, slices_per_pizza, attendees):
"""Calculate the number of slices each person gets and the leftover slices."""
total_slices = pizzas * slices_per_pizza
slices_per_person = total_slices // attendees # Integer division for slices per person
leftover_slices = total_slices % attendees # Modulus for leftover slices
return slices_per_person, leftover_slices

def main():
try:
# Input for the number of pizzas, slices per pizza, and number of attendees
pizzas = int(input("Enter the number of pizzas: "))
slices_per_pizza = int(input("Enter the number of slices per pizza: "))
attendees = int(input("Enter the number of people attending: "))

# Ensure there are people to serve


if attendees <= 0:
print("The number of attendees must be greater than zero.")
return

# Calculate the number of slices


slices_per_person, leftover_slices = calculate_slices(pizzas, slices_per_pizza,
attendees)

# Display results
print(f"Each person gets {slices_per_person} slices of pizza.")
print(f"There will be {leftover_slices} leftover slices.")

except ValueError:
print("Please enter valid numbers.")

# Run the program


if __name__ == "__main__":
main()
Department of CSE, PES University
UE24CS151A-Python for Computational Problem Solving
Laboratory Week 4

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy