0% found this document useful (0 votes)
9 views

14. Problem Solving Exercises

This document outlines a series of problem-solving exercises using Python for students at CMR University. It includes various programming tasks such as converting units, calculating areas, and implementing algorithms for mathematical operations. The exercises are designed to enhance students' understanding of Python programming and problem-solving skills.

Uploaded by

eshauppin1
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 views

14. Problem Solving Exercises

This document outlines a series of problem-solving exercises using Python for students at CMR University. It includes various programming tasks such as converting units, calculating areas, and implementing algorithms for mathematical operations. The exercises are designed to enhance students' understanding of Python programming and problem-solving skills.

Uploaded by

eshauppin1
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/ 16

CMR UNIVERSITY

School of Engineering and Technology


Department of Computer Science and Engineering
AY: 2024-2025 Batch: 2024 Section: J,K,N

Course Code/Name: 4CSPL1011/Problem Solving using Python

Problem Solving Exercises

1. Converting Miles to Kilometers:


miles = float(input("Enter distance in miles: "))
kilometers = miles * 1.60934
print(f"{miles} miles is equal to {kilometers} kilometers")
2. Convert Temperature from Celsius to Fahrenheit:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print(f"{celsius}°C is equal to {fahrenheit}°F")
3. Find the Distance Traveled by an Object:
speed = float(input("Enter speed (in meters/second): "))
time = float(input("Enter time (in seconds): "))
distance = speed * time
print(f"The object has traveled {distance} meters")
4. Swapping Values Stored in Two Variables:
x = input("Enter the first value: ")
y = input("Enter the second value: ")
x, y = y, x
print(f"After swapping: x = {x}, y = {y}")
5. Area of circle and Circumference
radius = float(input("Enter the radius of the circle: "))
pi = 3.14159
area = pi * radius * radius
circumference = 2 * pi * radius
print(f"Area of the circle: {area:.2f}")
print(f"Circumference of the circle: {circumference:.2f}")
6. Find the Sum of n Natural Numbers:
n = int(input("Enter a number: "))
sum_natural = n * (n + 1) // 2
print(f"The sum of first {n} natural numbers is {sum_natural}")
7. Find the Sum of Squares of n Natural Numbers:
n = int(input("Enter a number: "))
sum_squares = n * (n + 1) * (2 * n + 1) // 6
print(f"The sum of squares of first {n} natural numbers is {sum_squares}")
8. Print the Digit at Ones Place of a Given Number:
number = int(input("Enter a number: "))
ones_place = number % 10
print(f"The digit at ones place is {ones_place}")
9. Calculate the Square of a Number:
number = float(input("Enter a number: "))
square = number * number
print(f"The square of {number} is {square}")

10. Calculate the Simple Average of Two Numbers:


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
average = (num1 + num2) / 2
print(f"The average of {num1} and {num2} is {average}")

11. Find the Remainder of a Division:


dividend = float(input("Enter the dividend: "))
divisor = float(input("Enter the divisor: "))
remainder = dividend % divisor
print(f"The remainder when {dividend} is divided by {divisor} is {remainder}")
12. Convert Minutes into Hours and Minutes:
total_minutes = int(input("Enter time in minutes: "))
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{total_minutes} minutes is equal to {hours} hours and {minutes}
minutes")

13. Calculate the Perimeter of a Rectangle:


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
perimeter = 2 * (length + width)
print(f"The perimeter of the rectangle is {perimeter}")

14. Calculate the Product of Two Numbers:


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
product = num1 * num2
print(f"The product of {num1} and {num2} is {product}")

15. Find the Last Two Digits of a Given Number:


number = int(input("Enter a number: "))
last_two_digits = number % 100
print(f"The last two digits of {number} are {last_two_digits}")
16. Find the Simple Interest:
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period in years: "))
interest = (principal * rate * time) / 100
print(f"The simple interest is {interest}")
17. Convert Hours into Days, Hours, and Minutes:
hours = int(input("Enter time in hours: "))
days = hours // 24
remaining_hours = hours % 24
print(f"{hours} hours is equal to {days} days and{ remaining_hours} hours")
18. Find the Largest of Three Numbers:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c
print(f"The largest number is {largest}")
19. Check if Two Numbers are Equal:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num1 == num2:
print("Both numbers are equal")
else:
print("The numbers are not equal")

20. Check if a Number is Positive, Negative, or Zero:


number = float(input("Enter a number: "))
if number > 0:
print("The number is positive")
elif number < 0:
print("The number is negative")
else:
print("The number is zero")
21. Check Whether the Given Number is Odd or Even:
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")

22. Check if a Number is Divisible by Another:


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if num1 % num2 == 0:
print(f"{num1} is divisible by {num2}")
else:
print(f"{num1} is not divisible by {num2}")

23. Find the Total and Average of Marks Scored by a Student:


num_subjects = int(input("Enter the number of subjects: "))
mark1 = int(input("Enter mark for subject 1: "))
if num_subjects > 1:
mark2 = int(input("Enter mark for subject 2: "))
if num_subjects > 2:
mark3 = int(input("Enter mark for subject 3: "))
if num_subjects > 3:
mark4 = int(input("Enter mark for subject 4: "))
if num_subjects > 4:
mark5 = int(input("Enter mark for subject 5: "))
if num_subjects == 1:
total_marks = mark1
elif num_subjects == 2:

total_marks = mark1 + mark2


elif num_subjects == 3:
total_marks = mark1 + mark2 + mark3
elif num_subjects == 4:
total_marks = mark1 + mark2 + mark3 + mark4
elif num_subjects == 5:
total_marks = mark1 + mark2 + mark3 + mark4 + mark5
average_marks = total_marks / num_subjects
print(f"Total Marks: {total_marks}")
print(f"Average Marks: {average_marks:.2f}")

24. Program to Print the Sum of Odd and Even Numbers


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_sum = 0
odd_sum = 0
for num in numbers:
if num % 2 == 0:
even_sum += num
else:
odd_sum += num

print(f"Sum of even numbers: {even_sum}")


print(f"Sum of odd numbers: {odd_sum}")

25. Program to Circulate the Values of N Variables


def circulate_values(values):
last_value = values.pop() # Remove the last value
values.insert(0, last_value) # Insert it at the beginning
return values
values = [1, 2, 3, 4, 5]
print("Original list:", values)
print("After circulation:", circulate_values(values))

26. Program to Find the Sum of Values in a List


numbers = [10, 20, 30, 40, 50]
total_sum = sum(numbers)
print(f"Sum of values in the list: {total_sum}")
27. Program to Find Minimum and Maximum in a List
numbers = [5, 10, 20, 1, 50, 30]
min_value = min(numbers)
max_value = max(numbers)
print(f"Minimum value: {min_value}")
print(f"Maximum value: {max_value}")

28. Program for GCD (Greatest Common Divisor)


import math
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
gcd = math.gcd(a, b)
print(f"GCD of {a} and {b} is {gcd}")

29. Program to Find Sum of Odd and Even Numbers (Using Range)
n = int(input("Enter the limit: "))
odd_sum = sum(i for i in range(1, n + 1) if i % 2 != 0)
even_sum = sum(i for i in range(1, n + 1) if i % 2 == 0)
print(f"Sum of odd numbers: {odd_sum}")
print(f"Sum of even numbers: {even_sum}")

30. Program to Check if a Number is Prime or Not


def is_prime(num):
if num < 2:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
number = int(input("Enter a number: "))
if is_prime(number):
print(f"{number} is a prime number.")
else:
print(f"{number} is not a prime number.")
31. Program to Check if a String is a Palindrome
def is_palindrome(text):
return text == text[::-1]
text = input("Enter a string: ")
if is_palindrome(text):
print(f"{text} is a palindrome.")
else:
print(f"{text} is not a palindrome.")

32. Program to Find Compound Interest


Formula:
CI=P×(1+r100)t−P\text{CI} = P \times (1 + \frac{r}{100})^t - PCI=P×(1+100r)t−P

def compound_interest(principal, rate, time):


amount = principal * (1 + rate / 100) ** time
return amount - principal

p = float(input("Enter principal amount: "))


r = float(input("Enter rate of interest: "))

t = float(input("Enter time in years: "))


ci = compound_interest(p, r, t)
print(f"Compound Interest: {ci:.2f}")

33. Program to Insert a Number in a Sorted List


def insert_sorted(lst, num):
lst.append(num)
lst.sort()
return lst

# Example usage
sorted_list = [1, 3, 5, 7, 9]
number = int(input("Enter the number to insert: "))
result = insert_sorted(sorted_list, number)
print("List after inserting:", result)
34. Program to Guess an Integer Number in a Range
import random
def guess_number():
number_to_guess = random.randint(1, 100)
attempts = 0

while True:
guess = int(input("Guess a number between 1 and 100: "))
attempts += 1

if guess < number_to_guess:


print("Too low! Try again.")
elif guess > number_to_guess:
print("Too high! Try again.")
else:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break

guess_number()

35. Program for Towers of Hanoi Using Function


def towers_of_hanoi(n, source, target, auxiliary):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
towers_of_hanoi(n - 1, source, auxiliary, target)
print(f"Move disk {n} from {source} to {target}")
towers_of_hanoi(n - 1, auxiliary, target, source)

# Example usage
num_disks = int(input("Enter the number of disks: "))
towers_of_hanoi(num_disks, 'A', 'C', 'B')
36. Program to Calculate the Square Root of a Number (Newton's Method)
def newton_sqrt(number, tolerance=1e-10):
estimate = number / 2.0
while True:
new_estimate = (estimate + number / estimate) / 2
if abs(new_estimate - estimate) < tolerance:
return new_estimate
estimate = new_estimate

# Example usage
num = float(input("Enter a number to find its square root: "))
result = newton_sqrt(num)
print(f"The square root of {num} is approximately {result:.6f}")

37. Word Count Program (Read File)


def word_count(filename):
with open(filename, 'r') as file:
text = file.read()
words = text.split()
print(f"Word Count: {len(words)}")

# Example usage
word_count('sample.txt')

38. Copy File Program

def copy_file(source, destination):


with open(source, 'r') as src:
content = src.read()
with open(destination, 'w') as dest:
dest.write(content)
print("File copied successfully.")

# Example usage
copy_file('source.txt', 'destination.txt')

39. File Pointer Manipulation using seek()


with open('sample.txt', 'r') as file:
file.seek(5) # Move file pointer to the 5th byte
print(file.read())

40. Color Game in Python Using Tkinter


import tkinter
import random

colors = ['Red', 'Blue', 'Green', 'Pink', 'Black', 'Yellow', 'Orange', 'White', 'Purple', 'Brown']
score = 0
time_left = 30

def start_game(event):
if time_left == 30:
countdown()
next_color()

def next_color():
global score, time_left
if time_left > 0:
color_entry.focus_set()
if color_entry.get().lower() == colors[1].lower():
score += 1
color_entry.delete(0, tkinter.END)
random.shuffle(colors)
color_label.config(fg=str(colors[1]), text=str(colors[0]))
score_label.config(text="Score: " + str(score))

def countdown():
global time_left
if time_left > 0:
time_left -= 1
time_label.config(text="Time left: " + str(time_left))
time_label.after(1000, countdown)

root = tkinter.Tk()
root.title("Color Game")
root.geometry("400x200")

instructions = tkinter.Label(root, text="Type the color of the words!", font=('Helvetica',


12))
instructions.pack()
score_label = tkinter.Label(root, text="Press Enter to start", font=('Helvetica', 12))
score_label.pack()
time_label = tkinter.Label(root, text="Time left: " + str(time_left), font=('Helvetica', 12))
time_label.pack()
color_label = tkinter.Label(root, font=('Helvetica', 60))
color_label.pack()
color_entry = tkinter.Entry(root)
root.bind('<Return>', start_game)
color_entry.pack()
color_entry.focus_set()
root.mainloop()

41. Age Calculator Application using Tkinter


from tkinter import *
from datetime import date

def calculate_age():
birth_year = int(entry_year.get())
current_year = date.today().year
age = current_year - birth_year
label_result.config(text=f"Your Age is: {age} years")

root = Tk()
root.title("Age Calculator")
Label(root, text="Enter Birth Year:").pack()
entry_year = Entry(root)
entry_year.pack()

Button(root, text="Calculate Age", command=calculate_age).pack()


label_result = Label(root, text="")
label_result.pack()

root.mainloop()

42. Snake Game Project in Python using Tkinter

import turtle
import time
import random

delay = 0.1
score = 0
high_score = 0

# Set up the screen


window = turtle.Screen()
window.title("Snake Game")
window.bgcolor("green")
window.setup(width=600, height=600)
window.tracer(0)

# Snake head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("black")
head.penup()
head.goto(0, 0)
head.direction = "stop"

# Food
food = turtle.Turtle()
food.speed(0)
food.shape("circle")
food.color("red")
food.penup()
food.goto(0, 100)

# Snake body segments


segments = []

# Functions to control snake movement


def go_up():
if head.direction != "down":
head.direction = "up"

def go_down():
if head.direction != "up":
head.direction = "down"

def go_left():
if head.direction != "right":
head.direction = "left"

def go_right():
if head.direction != "left":
head.direction = "right"

def move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 20)
if head.direction == "down":
y = head.ycor()
head.sety(y - 20)
if head.direction == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)

# Keyboard bindings
window.listen()
window.onkeypress(go_up, "w")
window.onkeypress(go_down, "s")
window.onkeypress(go_left, "a")
window.onkeypress(go_right, "d")

# Main game loop


while True:
window.update()
move()
time.sleep(delay)

window.mainloop()

43. Creating Classes and Accessing Data Members

class Person:
def init (self, name, age):
self.name = name
self.age = age

def display(self):
print(f"Name: {self.name}, Age: {self.age}")

# Example usage
person1 = Person("Alice", 30)
person1.display()

44. Class Method to Create a Person Object by Birth Year


class Person:
def init (self, name, birth_year):
self.name = name
self.birth_year = birth_year

@classmethod
def from_birth_year(cls, name, birth_year):
return cls(name, birth_year)

# Example usage
person1 = Person.from_birth_year("Alice", 1993)
print(f"Name: {person1.name}, Birth Year: {person1.birth_year}")

45. Using call Method in a Class


class Calculator:
def call (self, a, b):
return a + b

# Example usage
calc = Calculator()
print(calc(10, 20)) # Output: 30

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