Bonus Practice Problems(GMT To IST)

IST (Indian Standard Time) is 5 hours 30 minutes ahead of GMT(Greenwich Mean Time). Develop an algorithm and write the Python code to find day and IST, given day and time in GMT. For example, if day is Sunday and time in GMT is 23:05 then in IST is Monday (Next day) and time is 04:35. Check boundary conditions and print 'Invalid input' for wrong input. Write appropriate functions for accomplishing the task.
Use rstrip() to remove extra spaces while reading strings
Input Format
Day
Hours
minutes of time in GMT
Output Format
Day
Hours
minutes of time in IST
Boundary Condition:
All hour > 0 and <24
Minutes > 0 and < 60
Seconds > 0 and <60
Day is Sunday or Monday or Tuesday or Wednesday or Thursday or Friday or Saturday
Input:
Take the input serially as day,hours and minutes.
Processing Involved:
days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
day=input().rstrip()
hours_min=int(input())*60
minutes=int(input())
total=hours_min+minutes+330
if hours_min>0 and hours_min<24*60 and minutes>0 and minutes<60 and day in days:
    if total>=1440:
        for i in range(len(days)-1):
            if day==days[i]:
                print(days[i+1])
                break
        print(total//60-24)
        print(total%60)
    else:
        print(day)
        print(total//60)
        print(total%60)
else:
    print("Invalid input")

Output:
Display the time in IST

Program:
days=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
day=input().rstrip()
hours_min=int(input())*60
minutes=int(input())
total=hours_min+minutes+330
if hours_min>0 and hours_min<24*60 and minutes>0 and minutes<60 and day in days:
    if total>=1440:
        for i in range(len(days)-1):
            if day==days[i]:
                print(days[i+1])
                break
        print(total//60-24)
        print(total%60)
    else:
        print(day)
        print(total//60)
        print(total%60)
else:
    print("Invalid input")

Bonus Practice Problems(Cyclic Shift)

Given a set of elements, write an algorithm and the subsequent ‘C’ program to perform cyclic right shift of the array by 'm' places. For example, if the elements are 12, 13, 16, 7, 10 and m =2 then the resultant set will be 7, 10, 12, 13, 16.

Input Format

Number of elements in 'n'

element1

element2

...

elementn

value of 'm'



Output Format

Elements in the set after right shift by 'm' places
Input:
number of elements n
The n elements

Processing:
#include< stdio.h >
void main()
{
    int a[20],n,i,m,t,j;
    scanf("%d",&n);
    for(i=0;i < n;i++)
    scanf("%d",&a[i]);
    scanf("%d",&m);
    for(j=0;j < m;j++)
    {
        t=a[n-1]; 
        for(i=n-1;i > 0;i--)
        a[i]=a[i-1];
        a[0]=t;
    }
}

Output:
Elements in the set after right shift by 'm' places

Program:
#include< stdio.h >
void main()
{
    int a[20],n,i,m,t,j;
    scanf("%d",&n);
    for(i=0;i < n;i++)
    scanf("%d",&a[i]);
    scanf("%d",&m);
    for(j=0;j < m;j++)
    {
        t=a[n-1]; 
        for(i=n-1;i > 0;i--)
        a[i]=a[i-1];
        a[0]=t;
    }
    for(i=0;i < n;i++)
    printf("%d\n",a[i]);
}

Pseudocode:
Step1.get the number of elements 
Step2.get the n elements
Step3. get m
Step4. perform the cyclic shift using elementary operations
Step5. Display the updated array
Step6. End

Bonus Practice Problems(Amicable Numbers (Id-2337))

IF THE QUESTION HAS ANY ERRORS PLEASE WRITE IT AS A COMMENT BECAUSE I DID NOT HAVE THIS QUESTION FOR THE BONUS PPS AND COULD NOT TEST ALL THE TEST CASES AND HAVE ONLY CHECKED THE TEST CASES GIVEN IN THE QUESTION

CSE1701 Amicable Numbers (Id-2337)


Two numbers are said to be amicable if the sum of proper divisors of one number plus 1, is equal to the other number. All divisors of a number other than 1 and itself, are called proper divisors. For example, the numbers 220 and 284 are amicable as the sum of proper divisors of 220 (i.e.) 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110 is equal to 284 and sum of proper divisors of 284 (i.e.) 1, 2, 4, 71 and 142 is 220. Given two numbers, write an algorithm and the subsequent Python code to Print Yes if the given two numbers are amicable. Print ‘No’ if the given numbers are not amicable. Check for boundary conditions and print 'Invalid input' for wrong input. Write appropriate functions for accomplishing the task.

Input Format

First line contains the first number

Next line contains the second number

Output Format

Print either Yes or No

Input:
First line contains the first number

Next line contains the second number
Processing:
def prop_div_sum(n):
    total = 0
    for i in range(2,n):
        if n%i==0:
            total += i
    return total

n = int(input())
m = int(input())
if (prop_div_sum(n)+1) == m and (prop_div_sum(m)+1) == n:
    print('Yes')
else:
    print('No')
Output:
Print either Yes or No

Program:
def prop_div_sum(n):
    total = 0
    for i in range(2,n):
        if n%i==0:
            total += i
    return total

n = int(input())
m = int(input())
if (prop_div_sum(n)+1) == m or (prop_div_sum(m)+1) == n:
    print('Yes')
else:
    print('No')

Pseudocode:
Step1. Get the numbers 
Step2. Calculate the sum of the proper divisors for both the numbers
Step3. Check if the numbers are amicable based on the conditions
Step4. End

Bonus Practice Problems(Palindrome or symmetry)

 Palindrome or Symmetry (Id-2338)
Given a set of ‘n’ strings, write an algorithm and the subsequent Python code to check if the string is a Palindrome string  or Symmetry string.  A string is  said to be a palindrome string  if one half of the string is the reverse of the other half. If the length of string is odd then ignore middle character. For example, strings liril, abba are palindromes.
A string is said  to be a symmetry string if both the halves of the string are same. If the length of string is odd then ignore middle character. For example, strings khokho, abab are symmetr. If the string is palindrome then print ‘Palindrome’, if the string is a symmetry string then print ‘Symmetry’ if the string (aaa) has both property then print ‘Both property’ and print ‘No property’ otherwise. Write functions to check ‘Palindrome’ and ‘Symmetry’. Make the comparisons to be case insensitive.
Input for the problem
A number and that many number of strings
Processing involved
def palindrome(text):
    if text == (text.rstrip()[::-1]):
        return True
    else:
        return False

def symmetry(text):
    n = len(text)
    if n%2:
        for i in range(n//2):
            if text[i] != text[(n//2)+1+i]:
                return False
        return True
    else:
        for i in range(n//2):
            if text[i] != text[(n//2)+i]:
                return False
        return True

n = int(input())
for i in range(n):
    text = input().rstrip().lower()
    if palindrome(text) and symmetry(text):
        print('Both Property')
    elif palindrome(text):
        print('Palindrome')
    elif symmetry(text):
        print('Symmetry')
    else:
        print('No property')



Output for the problem
Whether string is Palindrome or Symmetric or both or none
Pseudocode
Step1:Enter the data
Step2:Split the string into two parts
Step3:Ignore the central Char if string has odd characters
Step4:If the the two halves are equal then print symmetric
Step5:If the first half anfd reverse of second half  are equal then print palindrome
Step6:If both are true then print both And if both  are false then none
Step7:End
Program:
from math import floor
def palindrome(text):
    if text == (text.rstrip()[::-1]):
        return True
    else:
        return False

def symmetry(text):
    n = len(text)
    if n%2:
        for i in range(n//2):
            if text[i] != text[(n//2)+1+i]:
                return False
        return True
    else:
        for i in range(n//2):
            if text[i] != text[(n//2)+i]:
                return False
        return True

n = int(input())
for i in range(n):
    text = input().rstrip().lower()
    if palindrome(text) and symmetry(text):
        print('Both property')
    elif palindrome(text):
        print('Palindrome')
    elif symmetry(text):
        print('Symmetry')
    else:

        print('No property')

Bonus Practice Problems(Pills Finish)

CSE1701 Pills Finish (Id-2333)

Funda has got flu. Her doctor prescribed her 'x' number of 20mg pills, and told her to take a pill every 'y' hours starting from ‘s’ a.m to ‘e’ p.m. Write an algorithm and a Python code to find out,  in how many days Funda will consume 'x' pills. For example, if 'x' is thirty, 'y' is four, ‘s’ is 9 am and ‘e’ is 10 pm then approximately the tablets will be consumed in 8 days. Use ceil function of math module to round the number of days. Time for start and finish of tablet can be read as an integer. Write appropriate functions for accomplishing the task.
Input Format
First line contains the value of 'x', number of pills
Next line contains the value of 'y', number of hours
Next line contains the value of ‘s’
Next line contains the value of ‘e’
Output Format
Approximate number of days to consume tablets, ceil the value got
Input for the problem
First line contains the value of 'x', number of pills
Next line contains the value of 'y', number of hours
Next line contains the value of ‘s’
Next line contains the value of ‘e’

Processing involved
from math import ceil
x,y = int(input()),int(input())
s,e = int(input()),int(input())
time = e-s + 12
pills_per_day = 0
for i in range(0,time,y):
    pills_per_day+=1
no_of_days = ceil(x/pills_per_day)

Output for the problem
Approximate number of days to consume tablets, ceil the value got

Pseudocode
Step1. Get the required data from the user
Step2. Calculate the number of hours available per day
Step3. Calculate the number of pills that can be taken in a day
Step4. Calculate the number of days required.
Step5. End

Program:
from math import ceil
x,y = int(input()),int(input())
s,e = int(input()),int(input())
time = e-s + 12
pills_per_day = 0
for i in range(0,time,y):
    pills_per_day+=1
no_of_days = ceil(x/pills_per_day)
print(no_of_days)


Bonus Practice Problem(second smallest number)

CSE1701 Second Smallest Number (Id-2342)
Given a set of elements, write an algorithm and the subsequent ‘C’ program to determine the second smallest element in it.
Input Format
Number of elements in 'n'
Element-1
Element-2
...
Element-n

Output Format
Second smallest element in the set
Input for the problem
Get the n elements

Processing involved
#include <stdio.h>
int main()
    int arr[20];
    int n;
    scanf("%d",&n);
    for(int i = 0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
    int i, first=32766, second=32766;
    for (i = 0; i < n ; i ++) 
    {     
        if (arr[i] < first)  
        {        
            second = first;  
            first = arr[i];    
        }     
        else if (arr[i] < second && arr[i] != first)
           second = arr[i];  
    }
    printf("%d",second);
    return 0;
}
Output for the problem
Second smallest element in the set
Pseudocode
Step1.Get the number of elements n and then get the elements
Step2. Find the smallest element
Step3. Find the second smallest element by finding the smallest number greater than the smallest number
Step4.Display the second smallest element
Step5.End

Program:
#include <stdio.h>
int main()
    int arr[20];
    int n;
    scanf("%d",&n);
    for(int i = 0;i<n;i++)
    {
        scanf("%d",&arr[i]);
    }
    int i, first=32766, second=32766;
    for (i = 0; i < n ; i ++) 
    {     
        if (arr[i] < first)  
        {        
            second = first;  
            first = arr[i];    
        }     
        else if (arr[i] < second && arr[i] != first) 
          second = arr[i];  
    }
    printf("%d",second);
    return 0;
}


Bonus Practice Problems(Triangular Pattern)

A triangular pattern with ‘n’ rows is formed with ‘i’ numbers in the i - th row, starting from the first row.  In a triangular pattern, The number of elements in the first row will be 1; the number of elemnts in the second row will be 2 ; and so on.
For example, if the value of ‘n’ is 3 and if the elements in each row are : First row has only one element , namely,  1 ; second  row has two elements, namely,  2, 1 ; The third rwo has three elements, namely, 1, 2, 3.
1
2 1
1 2 3
Path in a triangular pattern is described as the sequence of numbers, with one number taken from each row, starting from the first row till the last row.   For example, the paths in the pattern above are
1 – 2 – 1
1 – 2 – 2
1 – 2 – 3
1 – 1 - 1
1 – 1 – 2
1 – 1 - 3
Value of a Path is the sum of the numbers in that path. In the above illustration, Maximum value of  the paths in the  is ‘6’. Write an algorithm and the subsequent Python program to compute the maximum value among the paths in the triangular pattern.
Input Format
First line contains an integer ‘n’ which indicates the number of rows in the triangular patters
Next few lines contains the input for the triangular pattern
Output Format
Print the maximum value of the path in a triangular pattern
Input for the problem
The number of rows n
The triangular pattern
Processing involved
n = int(input())
maxi = []
pattern = []
for i in range(1,n+1):
    temp = []
    for j in range(1,i+1):
        temp.append(int(input()))
    pattern.append(temp)
for i in pattern:
    maxi.append(max(i))
Output for the problem
Print the maximum value of the path in a triangular pattern
Pseudocode
Step1.Get the number of rows n
Step2.Get the triangular pattern row by row and add all the maximum values to the maxi list
Step3. Print the sum of maxi list
Step4.End
Program:
n = int(input())
maxi = []
pattern = []
for i in range(1,n+1):
    temp = []
    for j in range(1,i+1):
        temp.append(int(input()))
    pattern.append(temp)
for i in pattern:
    maxi.append(max(i))

print(sum(maxi))

Bonus Practice Problem(When should we leave)

Your mother will take you to the doctor’s clinic for a check-up. She asks the time by which you have to book a taxi. Your mother has some works :  going to the dry-cleaners in the mall, have lunch in the restaurant, buy some dog food at the pet-shop, take money in the bank,  to be done on the way,
It takes 'x' minutes to drive to the mall and park the vehicle, and 'y' minutes to get the clothes dry cleaned, ‘z' minutes for lunch, 'a' minutes to get dog food, 'b' minutes to get money at the bank and 'c' minutes to drive to the doctor’s office from the mall.  Given the values for ‘x’, ‘y’, ‘z’, ‘a’ and ‘b’ and the time of appointment as 'h' hour 'm' minutes, write an algorithm and the subsequent Python code to determine when you should leave home. For example if x is 20, y is 10, z is 45, a is 10, b is 10, c is 20 and h is 14 and m is 0,  then you have to start from home by 12 hour 05 minutes.
Write appropriate functions for accomplishing the task.
Input Format
First line contains the value for ‘x’
Next line contains the value for ‘y’
Next line contains the value for ‘z’
Next line contains the value for ‘a’
Next line contains the value for ‘b’
Next line contains the value for ‘c’
Next line contains the value for ‘h’
Next line contains the value for ‘m’
Output Format
Print the start time from home in ‘hours’ and ‘minutes’ in 24 hour format.  Hours and minutes shall be separated by a space.
Input for the problem
First line contains the value for ‘x’
Next line contains the value for ‘y’
Next line contains the value for ‘z’
Next line contains the value for ‘a’
Next line contains the value for ‘b’
Next line contains the value for ‘c’
Next line contains the value for ‘h’
Next line contains the value for ‘m’
Processing involved 
data = []
for i in range(8):
    data.append(int(input().rstrip()))
hrs = 0
mini = 0
total_min = 0
for i in range(6):
    total_min += data[i]
hrs = total_min//60
mini = total_min%60
hrs = data[-2] - hrs
mini = data[-1] - mini
if mini < 0:
    mini = mini + 60
    hrs -= 1
print(hrs,mini)

Output for the problem
Print the start time from home in ‘hours’ and ‘minutes’ in 24 hour format.  Hours and minutes shall be separated by a space.
Pseudocode
Step1.Get the required data
Step2. Calculate the total time taken to do all the things
Step3. find the total time in hrs and minutes
Step4. Subtract the hrs and min from the appointment time
Step5.End
Program:
data = []
for i in range(8):
    data.append(int(input().rstrip()))
hrs = 0
mini = 0
total_min = 0
for i in range(6):
    total_min += data[i]
hrs = total_min//60
mini = total_min%60
hrs = data[-2] - hrs
mini = data[-1] - mini
if mini < 0:
    mini = mini + 60
    hrs -= 1

print(hrs,mini)

Student Data (Id-3146)

Given a file named student.txt which has  the information  of the students in a class such as Name, Roll number, Age, CGPA.
Write a pseudocode and the subsequent Python program to do the following operations.
a) Read the file and  print the contents of the file
b) Read the file and sort the contents (records) of the file  in an  increasing order of CGPA and print the content of the sorted file.
c) Read the file and print the record of the student with maximum age and minimum age.
d) Read the file and print the average CGPA of the class.
e) Read the file and print the name of the students whose CGPA is greater than the average CGPA of the class and whose age lies between average age of the class and the minimum age of the students in the class
Input Format
Read the name of the input file
Details of the students with the fields : Name, Rollnumber, Age, CGPA separated by a comma.

Input:
Read the name of the input file
Details of the students with the fields : Name, Rollnumber, Age, CGPA separated by a comma.
Processing:
name = input().rstrip()

def read_print():   
    grade = open(name)   
    for i in grade.readlines():       
        print(i,end='')
    print()
    grade.close()

def sort_file():
    stud_list = []
    grade = open(name)
    for i in grade.readlines():
        stud_list.append(i.rstrip().split(','))
    cgpa = {}
    for i in stud_list:
        cgpa.setdefault(eval(i[-1]),[])
        cgpa[eval(i[-1])].append(i)
    for i in cgpa.keys():
        cgpa[i].sort(key = lambda name:name[0])
    for i in reversed(sorted(cgpa.keys())):
        for j in cgpa[i]:
            print(','.join(j))
    stud_list.sort(key = lambda x:eval(x[-2]))
    max_age = []
    for i in range(len(stud_list)-1,-1,-1):               
        if stud_list[i][-2] == stud_list[-1][-2]:
            max_age.append(stud_list[i])
        else:
            break  
    max_age.sort(key = lambda x:x[0])
    min_age = []
    for i in range(len(stud_list)):
        if stud_list[i][-2] == stud_list[0][-2]:
            min_age.append(stud_list[i])
        else:
            break
    min_age.sort(key = lambda x:x[0])
    for i in max_age:
        print(','.join(i))
    for i in min_age:
        print(','.join(i))
    stud_list.sort(key = lambda x:eval(x[-1]),reverse = True)
    sum = 0
    age = 0
    for i in stud_list:
        age += eval(i[-2])
        sum += eval(i[-1])
    avg_grade = sum/len(stud_list)
    avg_age = age/len(stud_list)
    print(round(avg_grade,2))
    above_avg = []
    for i in stud_list:
        if float(i[-1]) > avg_grade and float(i[-2]) < avg_age:
            above_avg.append(i)
    above_avg.sort()
    for i in above_avg:
        print(i[0])
    grade.close()
   
read_print()

sort_file()

Output:
a) Print the contents of the file with each field of a records separated by a comma.
(b) Print the contents of file after sorting the records based on the CGPA, in the increasing order of the CGPA. If there are students with the same CGPA, Print in the order of their name.
(c) Print the details of the student with maximum age and Print the details of the student with minimum age. If there are more than one student with the maximum age (or minimum age), your program should print all  the student’s details in the increasing order of their name.
(d) Print the average CGPA of the class.
(e) Print the name of the student whose CGPA is greater than the average CGPA of the class and whose age lies between average age of the class and the minimum age of the students in the class
Program:
name = input().rstrip()

def read_print():   
    grade = open(name)   
    for i in grade.readlines():       
        print(i,end='')
    print()
    grade.close()

def sort_file():
    stud_list = []
    grade = open(name)
    for i in grade.readlines():
        stud_list.append(i.rstrip().split(','))
    cgpa = {}
    for i in stud_list:
        cgpa.setdefault(eval(i[-1]),[])
        cgpa[eval(i[-1])].append(i)
    for i in cgpa.keys():
        cgpa[i].sort(key = lambda name:name[0])
    for i in reversed(sorted(cgpa.keys())):
        for j in cgpa[i]:
            print(','.join(j))
    stud_list.sort(key = lambda x:eval(x[-2]))
    max_age = []
    for i in range(len(stud_list)-1,-1,-1):               
        if stud_list[i][-2] == stud_list[-1][-2]:
            max_age.append(stud_list[i])
        else:
            break  
    max_age.sort(key = lambda x:x[0])
    min_age = []
    for i in range(len(stud_list)):
        if stud_list[i][-2] == stud_list[0][-2]:
            min_age.append(stud_list[i])
        else:
            break
    min_age.sort(key = lambda x:x[0])
    for i in max_age:
        print(','.join(i))
    for i in min_age:
        print(','.join(i))
    stud_list.sort(key = lambda x:eval(x[-1]),reverse = True)
    sum = 0
    age = 0
    for i in stud_list:
        age += eval(i[-2])
        sum += eval(i[-1])
    avg_grade = sum/len(stud_list)
    avg_age = age/len(stud_list)
    print(round(avg_grade,2))
    above_avg = []
    for i in stud_list:
        if float(i[-1]) > avg_grade and float(i[-2]) < avg_age:
            above_avg.append(i)
    above_avg.sort()
    for i in above_avg:
        print(i[0])
    grade.close()
   
read_print()

sort_file()

Pseudocode:
Step1. Get the name of the file.
Step2. Display the contents of the file with each field of a records separated by a comma using read_print function
Step3. Display the contents of file after sorting the records based on the CGPA, in the increasing order of the CGPA. If there are students with the same CGPA, Print in the order of their name. This is done using sort_file function
Step4. Display the details of the student with maximum age and Print the details of the student with minimum age. If there are more than one student with the maximum age (or minimum age), your program should print all  the student’s details in the increasing order of their name. This is done using sort_file function
Step5.Display the average CGPA of the class
Step6. Display the name of the student whose CGPA is greater than the average CGPA of the class and whose age lies between average age of the class and the minimum age of the students in the class.This is done using sort_file function
Step7.End

Bonus Practice Problems(Deficient Number)

A number is said to be a deficient number if the sum of the proper divisors are less than that number. All divisors  of a number other than 1 and itself,   are called proper divisors. 8 is a deficient number since the sum of the proper divisors are 6 (proper divisors of 8 are 2 and 4) Examples of deficient numbers include 2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 19, 21, 22, and 23. Given a number, write an algorithm and the subsequent Python code to check whether the given number is deficient or not.
Input format
Number to be checked
Output Format
Print Deficient or Not deficient
Input:
Number to be checked

Processing:
n = int(input())
div = []
for i in range(2,n):
    if n%i==0:
        div.append(i)
if sum(div) < n:
    print('Deficient')
else:
    print('Not deficient')

Output:
Print Deficient or Not deficient

Program:
n = int(input())
div = []
for i in range(2,n):
    if n%i==0:
        div.append(i)
if sum(div) < n:
    print('Deficient')
else:
    print('Not deficient')


Pseuodocode:
Step1.Get the number
Step2. find the proper divisors of the numbers and then store these numbers in div list
Step3. check if the sum of all the elements in div is less than the number if yes the print deficient else print Not deficient

Step4.End

Inlab 9

A Student in a class is appreciated based on the following factors:
Number of 'S' grade in the subjects learnt >= 3
Percentage of Attendance >= 90
Participation in sports activity in a semester >= 2
Appreciation is given as follows:
(i) 'Excellent' if all three conditions are met
(ii)'Very Good' if conditions (i) and (ii) are met
(iii)'Good' if conditions (i) and (iii) are met
Given the Number of 'S' grades, Attendance and Participation in sports activity in a semester, write an algorithm and the subsequent 'C' program to output the appreciation for the student.
Input Format:
First line contains the number of 'S' grade
Next line contains the percentage of Attendance of the student
Next line contains the number participation in sports activity by the student in the current semester
Output Format:

Print the Appreciation for the student

Program:
#include<stdio.h>

void main()
{
int s_grade, attendance, sports;
scanf("%d%d%d", &s_grade, &attendance, &sports);
if (s_grade >= 3 && attendance >= 90 && sports >= 2)
printf("Excellent");
else if (s_grade >= 3 && attendance >= 90)
printf("Very good");
else if (s_grade >= 3 && sports >= 2)
printf("Good");
}

Algorithm:
Step1. get the number of s grades, attendance in the subjects and the number of sports activities that the person participated in.
Step2. if the inputs satisfy the all the criteria then display excellent.
Step3. if the inputs satisfy criteria i,ii then display very good.
Step4. if the inputs satisfy criteria i,iii then display good.
Step5. End

Bonus Practice Problems(GMT To IST)

IST (Indian Standard Time) is 5 hours 30 minutes ahead of GMT(Greenwich Mean Time). Develop an algorithm and write the Python code to find...