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

Computer Science Practice Assignement (3) Solution

The document provides examples of algorithms to solve various computational problems, including swapping numbers with and without a temporary variable, calculating dice rolls and their digit sums, rounding numbers and finding their sum, and calculating heart rate zones based on age and gender. It also includes sample inputs and outputs for problems involving discounts, converting dog ages to human years, deciding when to get gas based on tank level and mileage, and calculating BMI based on weight and height.

Uploaded by

Chantal Ramez
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)
18 views

Computer Science Practice Assignement (3) Solution

The document provides examples of algorithms to solve various computational problems, including swapping numbers with and without a temporary variable, calculating dice rolls and their digit sums, rounding numbers and finding their sum, and calculating heart rate zones based on age and gender. It also includes sample inputs and outputs for problems involving discounts, converting dog ages to human years, deciding when to get gas based on tank level and mileage, and calculating BMI based on weight and height.

Uploaded by

Chantal Ramez
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/ 9

German University in Cairo

Faculty of Media Engineering and Technology


Prof. Dr. Slim Abdennadher
Dr. Nada Sharaf
Dr. Mohammed Abd El Megeed

Introduction to Computer Science, Winter Semester 2020


Class Practice Assignment 3
Discussion: 07.11.2020 - 12.11.2020

Exercise 3-1 Swaping Numbers


Write an algorithm that takes as input two numbers and swaps the values of these numbers.

• Write the algorithm using a temporary variable

Solution:

x = eval(input())
y = eval(input())

tmp = x
x = y
y = tmp

print("The new value of x is ", x, " and the new value of y is ", y)

• Swap the two numbers without using a temporary variable. Is it always possible to swap any two
values of any types?

Solution:

x = eval(input())
y = eval(input())

y = y + x
x = y - x
y = y - x

print("The new value of x is ", x, " and the new value of y is ", y)

No, it is only possible when dealing with numbers.

Exercise 3-2 Dices


To be solved in Tutorial
Write an algorithm that generates two random numbers between 1 and 100 exclusive. if the sum
of the two random numbers’ digits are even, the program should display: You win , and displays
You lose! try again otherwise.

Solution:

1
import random

dice1 = random.randint(1,99)
dice2 = random.randint(1,99)
sum =0

if(dice1 <10):
sum +=dice1
else:
sum += dice1%10 + dice1//10

if(dice2 <10):
sum +=dice2
else:
sum += dice2%10 + dice2//10

if sum%2 ==0:
print("You win!")
else:
print("You lose! try again")

Exercise 3-3 The Sum of Rounded Numbers


To be discussed in Tutorial
Write an algorithm that given three integers displays the sum of their rounded values. We will round
an integer value to the next multiple of 10 if its rightmost digit is 5 or more, so 15 rounds up to 20.
Alternately, round down to the previous multiple of 10 if its rightmost digit is less than 5, so 122 rounds
down to 120. Here are some examples of evaluating the algorithm on representative input values:

16 17 12 -> 50
12 13 14 -> 30
6 4 4 -> 10

Solution:

a = eval(input())
b = eval(input())
c = eval(input())

aa = a % 10
bb = b % 10
cc = c % 10

if(aa >= 5):


a = (10 + a) - aa
else:
a = a - aa

if(bb >= 5):


b = (10 + b) - bb
else:
b = b - bb

2
if(cc >= 5):
c = (10 + c) - cc
else:
c = c - cc

sum = a + b + c
print(sum)

Exercise 3-4
To be discussed in Tutorial
Your task is to implement an algorithm that can calculate your maximum heart rate and your optimal
training pulse for fat-burning, endurance increase or cardiovascular system improvement. The Formula
for calculating the maximum heart rate (Pulse) depends on the age and the gender:

• For men: 220 - Age

• For women: 226 - Age

The training can be classified into the following zones:

• Health zone: This amounts to 50-60% of the maximum heart rate. Within this pulse range
particularly the cardiovascular system will be invigorated. This range is particularly suitable for
beginners.

• Fat burning zone: This amounts to 60-70% of the maximum heart rate. Within this pulse range,
most calories from fat are burned. Furthermore the cardiovascular system will be trained.
• Aerobic zone: This amounts to 70-80% of the maximum heart rate. Within this pulse range,
carbohydrates and fats are burned for power production in the muscle cells. This range requires
the cardiovascular system as well as the lung and the metabolism.
• Anaerobic zone: This amounts to 80-90% of the maximum heart rate. Within this pulse range,
the body cannot cover the oxygen demand any longer. This range is for the development of power
and muscle mass.
• Red zone: This amounts to 90-100% of the maximum heart rate. This pulse range should be
handled with caution. It is dangerous for beginners and can be harmful for the heart.

a) Write an algorithmthat given the age and the gender should display the different zones. For example,
your algorithm should display the following for a 45 years old man:

Health zone: Between 88 and 105


Fat-burning zone: to 122
Aerobic zone: to 140
Anaerobic zone: to 158
Maximum heart rate / Red zone: to 175

Solution:

age = eval(input())
gender = eval(input())
if(gender == "male"):
maxHeartRate = 220 - age
else:
maxHeartRate = 226 - age

healthZoneFrom = 50 * maxHeartRate / 100

3
healthZoneTo = 60 * maxHeartRate / 100
print("Health Zone: Between ", healthZoneFrom, " and ", healthZoneTo)

fatBurningZoneTo = 70 * maxHeartRate / 100


print("Fat-burning zone: to " , fatBurningZoneTo)

aerobicZoneTo = 80 * maxHeartRate / 100


print("Aerobic zone: to " , aerobicZoneTo)

anaerobicZoneTo = 90 * maxHeartRate / 100


print("Anaerobic zone: to " , anaerobicZoneTo)

print("Maximum heart rate / Red zone: to " , maxHeartRate)

b) Write an algorithm that given the age, the gender and the heart rate will display the corresponding
zone. For example, the algorithm should display for a 45 years old man and heart rate of 190, the
following message

Red Zone

Your algorithm should consist of only if then statements, i.e. you are not allowed to use any else
statements.

Solution:

age = eval(input())
gender = eval(input())
heartRate = eval(input())

if(gender == "male"):
maxHeartRate = 220 - age
if(gender == "female"):
maxHeartRate = 226 - age

healthZoneFrom = 50 * maxHeartRate / 100


healthZoneTo = 60 * maxHeartRate / 100
fatBurningZoneTo = 70 * maxHeartRate / 100
aerobicZoneTo = 80 * maxHeartRate / 100
anaerobicZoneTo = 90 * maxHeartRate / 100

if(heartRate >= healthZoneFrom and heartRate <= healthZoneTo):


print("Health Zone")

if(heartRate > healthZoneTo and heartRate <= fatBurningZoneTo):


print("Fat-burning zone")

if(heartRate > fatBurningZoneTo and heartRate <= aerobicZoneTo):


print("Aerobic zone")

if(heartRate > aerobicZoneTo and heartRate <= anaerobicZoneTo):


print("Anaerobic zone")

if(heartRate > anaerobicZoneTo):


print("Red zone")

4
Exercise 3-5 Discount
To be solved in Lab
A discount is made on a purchase as follows:

• if purchase ≤ 1000 L.E., there is no discount


• if purchase > 1000 L.E., the discount is 5%

Given the cost of the purchase, write an algorithm to calculate and print the money paid taking into
consideration the 10% sales taxes. The taxes are calculated on the amount after the discount.

Solution:

purchase = eval(input())
if(purchase <= 1000):
print(" There is no discount! ")
else:
discount = purchase * 0.05
purchase = purchase - discount

amount = purchase + purchase * 0.1


print(" The amount due is: ")
print(amount)

Exercise 3-6 Dog age


To be solved in Lab
For the first two years, a dog year is equal to 10.5 human years. After that, each dog year is equal to 4
human years. Write a Python program to calculate a dogâs age in dog years, given a dogâs age in human
years. Expected output should look like the following:

• Input a dog’s age in human years: 2 The dog’s age in dog years is 21
• Input a dog’s age in human years: 15 The dog’s age in dog years is 73
• Input a dog’s age in human years: -5 Age must be positive number.

Solution:

h_age = int(input("Input a dogâs age in human years: "))


if h_age < 0:
print("Age must be positive number.")
elif h_age <= 2:
d_age = h_age * 10.5
else:
d_age = 21 + (h_age - 2)*4
print("The dogâs age in dogâs years is", d_age)

Exercise 3-7 Gas Station


National Last Chance gas station sits on Cairo Alexandria route. There is no other gas station for 200
Miles. Write an algorithm to help drivers decide if they need gas or not. The user will enter:

• The capacity of the gas tank, in Gallons.


• The indication of the gas gauge in percent (full=100, three quarters=75 and so on).
• The miles per gallon of the car.

5
The following is a sample run of the algorithm:

Tank Capacity: 12
Gas Gauge Reading in percent: 50
Miles per Gallon: 30

Get Gas!

The algorithm should print out Get gas or Safe to proceed depending on if the car can cross the 200
miles with the gas remaining in the tank.

Solution:

t = eval(input()) # Tank Capacity


g = eval(input()) # Gage Reading Percent
m = eval(input()) # Miles per gallon
ng = (t * g) / 100 # Number of gallons in tank
nm = ng * m # Number of miles that can be made
if(nm >= 200):
print("Safe To Proceed")
else:
print("Get Gas !")

Exercise 3-8 BMI


Write an algorithm that determines whether you are underweight, fit, or overweight given your weight
and height based on your BMI calculation.
The BMI is calculated using the weight divided by height squared, where weight is in kg and height is in
meters.

• If BMI ≤ 18.5, you are underweight


• If BMI > 18.5 and BMI ≤ 25, you are fit
• If BMI > 25, you are overweight

Solution:

• weight, height = eval(input("Please enter weight")),eval(input("Please enter height"))

BMI = weight/(height**2)

if(BMI <= 18.5):


print("You are underweight")
elif(BMI <= 25):
print("You are fit")
else:
print("You are overweight")

• weight, height = eval(input("Please enter weight")),eval(input("Please enter height"))

BMI = weight/(height**2)

if(BMI <= 18.5):

6
print("You are underweight")
else:
if(BMI <= 25):
print("You are fit")
else:
print("You are overweight")

Exercise 3-9 Triangle


To be solved in Lab
Write an algorithm that determines whether A, B, and C can form the sides of a triangle. Note A, B
and C can form the sides of a triangle if each side is less than the sum of the two other sides, i.e.:
A < B + C, B < A + C and C < A + B .
If A, B, and C forms a triangle, calculate its area using the formula:
p
Area = S(S − A)(S − B)(S − C) , where S = (A + B + C)/2

Solution:


import math
A,B,C = eval(input()), eval(input()), eval(input())

if(A < B + C): # first if


if(B < C+ A): #second if
if(C < A + B): #third if
S = ((A + B+ C) / 2)
Area = (math.sqrt(S * (S - A) * ( S - B) * (S - C)))
print(" This is a triangle with the Area: ")
print(Area)
else: #else of 3rd if
print("This cannot be a triangle!")

else: #else of 2nd if


print("This cannot be a triangle!")

else: #else of 1st if


print("This cannot be a triangle!")


import math
A, B, C = eval(input()), eval(input()), eval(input())
triangle = 0
if(A < B + C):
if(B < C+ A):
if(C < A + B):
triangle = 1

if(triangle == 0):
print("This cannot be a triangle!")
else:
S = ((A + B+ C) / 2)
Area = (math.sqrt(S * (S - A) * ( S - B) * (S - C)))
print(" This is a triangle with the Area: ")
print(Area)

7

import math
A, B, C = eval(input()), eval(input()), eval(input())

if(A < B + C and B < C+ A and C < A + B):


S = ((A + B+ C) / 2)
Area = (math.sqrt(S * (S - A) * ( S - B) * (S - C)))
print(" This is a triangle with the Area: ")
print(Area)
else:
print("This cannot be a triangle!")

Exercise 3-10 Letter Grades


Students marks in a class are graded on the following policy:

• A: 85-100
• B: 74-85
• C: 60-74

• D: 50-60
• F: <50

Keeping in mind that a student cannot score more than 105 marks, nor less than 0 marks.
Write an algorithm that reads each student’s marks, print either a grade or an error message.

Solution:

• Mark = eval(input())
if(Mark < 0):
print("invalid mark, less than 0")
else:
if(Mark >105):
print("invalid mark, greater than 105")
else:
if(Mark <50):
print("grade is F")
else:
if(Mark <60):
print("grade is D")
else:
if(Mark <74):
print("grade is C")
else:
if(Mark <85):
print("grade is B")
else:
print("grade is A")

• Mark = eval(input())
if(Mark < 0):
print("invalid mark, less than 0")
elif(Mark >100):
print("invalid mark, greater than 105")

8
elif(Mark <50):
print("grade is F")
elif(Mark <60):
print("grade is D")
elif(Mark <74):
print("grade is C")
elif(Mark <85):
print("grade is B")
else:
print("grade is A")

Exercise 3-11 Student School


To be solved in Tutorial
The following algorithm prints out whether a current student is in elementary (1st - 5th), middle (6th -
8th), or high school (9th - 12th).

grade = eval(input())
if(grade <= 5):
print("this student is in elementary school")
elif(grade <= 8):
print("this student is in middle school")
elif(grade <= 12):
print("this student is in high school")

The algorithm above uses nested if-statements.

a) Write an equivalent algorithm that will print the same messages as the algorithm above without
using any nested if-statements.

Solution:

grade = eval(input())
if(grade <= 5):
print("this student is in elementary school")

if(grade <= 8 and grade > 5):


print("this student is in middle school")

if(grade <= 12 and grade > 8):


print("this student is in high school")

b) Discuss the drawback of your algorithm? Hint: Compare the efficiency of both algorithms.

Solution:
The first algorithm is more efficient than the second one since in the second algorithms all conditions
should be checked. In the first algorithm the number of conditions that should be checked depend
on the input.

You might also like