├── LICENSE ├── README.md ├── gu-ito-1-1.py ├── gu-ito-1-10.py ├── gu-ito-1-11.py ├── gu-ito-1-12.py ├── gu-ito-1-13.py ├── gu-ito-1-14.py ├── gu-ito-1-15.py ├── gu-ito-1-2.py ├── gu-ito-1-3.py ├── gu-ito-1-4.py ├── gu-ito-1-5.py ├── gu-ito-1-6.py ├── gu-ito-1-7.py ├── gu-ito-1-8.py ├── gu-ito-1-9.py ├── gu-ito-1.py ├── gu-ito-10.py ├── gu-ito-11.py ├── gu-ito-2-1.py ├── gu-ito-2-10.py ├── gu-ito-2-11.py ├── gu-ito-2-12.py ├── gu-ito-2-13.py ├── gu-ito-2-14.py ├── gu-ito-2-15.py ├── gu-ito-2-16.py ├── gu-ito-2-17.py ├── gu-ito-2-18.py ├── gu-ito-2-19.py ├── gu-ito-2-2.py ├── gu-ito-2-3.py ├── gu-ito-2-4.py ├── gu-ito-2-5.py ├── gu-ito-2-6.py ├── gu-ito-2-7.py ├── gu-ito-2-8.py ├── gu-ito-2-9.py ├── gu-ito-2.py ├── gu-ito-3-1.py ├── gu-ito-3-10.py ├── gu-ito-3-11.py ├── gu-ito-3-12.py ├── gu-ito-3-13.py ├── gu-ito-3-14.py ├── gu-ito-3-15.py ├── gu-ito-3-16.py ├── gu-ito-3-17.py ├── gu-ito-3-18.py ├── gu-ito-3-19.py ├── gu-ito-3-2.py ├── gu-ito-3-20.py ├── gu-ito-3-3.py ├── gu-ito-3-4.py ├── gu-ito-3-5.py ├── gu-ito-3-6.py ├── gu-ito-3-7.py ├── gu-ito-3-8.py ├── gu-ito-3-9.py ├── gu-ito-3.py ├── gu-ito-4.py ├── gu-ito-5.py ├── gu-ito-6.py ├── gu-ito-7.py ├── gu-ito-8.py └── gu-ito-9.py /LICENSE: -------------------------------------------------------------------------------- 1 | --- 2 | 3 | Mozilla Public License Version 2.0 4 | ================================== 5 | 6 | 1. Definitions 7 | -------------- 8 | 9 | 1.1. "Contributor" 10 | means each individual or legal entity that creates, contributes to 11 | the creation of, or owns Covered Software. 12 | 13 | 1.2. "Contributor Version" 14 | means the combination of the Contributions of others (if any) used 15 | by a Contributor and that particular Contributor's Contribution. 16 | 17 | 1.3. "Contribution" 18 | means Covered Software of a particular Contributor. 19 | 20 | 1.4. "Covered Software" 21 | means Source Code Form to which the initial Contributor has attached 22 | the notice in Exhibit A, the Executable Form of such Source Code 23 | Form, and Modifications of such Source Code Form, in each case 24 | including portions thereof. 25 | 26 | 1.5. "Incompatible With Secondary Licenses" 27 | means 28 | 29 | (a) that the initial Contributor has attached the notice described 30 | in Exhibit B to the Covered Software; or 31 | 32 | (b) that the Covered Software was made available under the terms of 33 | version 1.1 or earlier of the License, but not also under the 34 | terms of a Secondary License. 35 | 36 | 1.6. "Executable Form" 37 | means any form of the work other than Source Code Form. 38 | 39 | 1.7. "Larger Work" 40 | means a work that combines Covered Software with other material, in 41 | a separate file or files, that is not Covered Software. 42 | 43 | 1.8. "License" 44 | means this document. 45 | 46 | 1.9. "Licensable" 47 | means having the right to grant, to the maximum extent possible, 48 | whether at the time of the initial grant or subsequently, any and 49 | all of the rights conveyed by this License. 50 | 51 | 1.10. "Modifications" 52 | means any of the following: 53 | 54 | (a) any file in Source Code Form that results from an addition to, 55 | deletion from, or modification of the contents of Covered 56 | Software; or 57 | 58 | (b) any new file in Source Code Form that contains any Covered 59 | Software. 60 | 61 | 1.11. "Patent Claims" of a Contributor 62 | means any patent claim(s), including without limitation, method, 63 | process, and apparatus claims, in any patent Licensable by such 64 | Contributor that would be infringed, but for the grant of the 65 | License, by the making, using, selling, offering for sale, having 66 | made, import, or transfer of either its Contributions or its 67 | Contributor Version. 68 | 69 | 1.12. "Secondary License" 70 | means either the GNU General Public License, Version 2.0, the GNU 71 | Lesser General Public License, Version 2.1, the GNU Affero General 72 | Public License, Version 3.0, or any later versions of those 73 | licenses. 74 | 75 | 1.13. "Source Code Form" 76 | means the form of the work preferred for making modifications. 77 | 78 | 1.14. "You" (or "Your") 79 | means an individual or a legal entity exercising rights under this 80 | License. For legal entities, "You" includes any entity that 81 | controls, is controlled by, or is under common control with You. For 82 | purposes of this definition, "control" means (a) the power, direct 83 | or indirect, to cause the direction or management of such entity, 84 | whether by contract or otherwise, or (b) ownership of more than 85 | fifty percent (50%) of the outstanding shares or beneficial 86 | ownership of such entity. 87 | 88 | 1.15. "Owner" 89 | means Aditya Sah, the individual or legal entity that owns the Covered Software and holds the ultimate authority to grant permissions for any tasks involving the Covered Software. 90 | 91 | 2. License Grants and Conditions 92 | -------------------------------- 93 | 94 | 2.1. Grants 95 | 96 | Each Contributor hereby grants You a world-wide, royalty-free, 97 | non-exclusive license: 98 | 99 | (a) under intellectual property rights (other than patent or trademark) 100 | Licensable by such Contributor to use, reproduce, make available, 101 | modify, display, perform, distribute, and otherwise exploit its 102 | Contributions, either on an unmodified basis, with Modifications, or 103 | as part of a Larger Work, subject to obtaining prior written permission from the Owner, Aditya Sah; and 104 | 105 | (b) under Patent Claims of such Contributor to make, use, sell, offer 106 | for sale, have made, import, and otherwise transfer either its 107 | Contributions or its Contributor Version, subject to obtaining prior written permission from the Owner, Aditya Sah. 108 | 109 | 2.2. Effective Date 110 | 111 | The licenses granted in Section 2.1 with respect to any Contribution 112 | become effective for each Contribution on the date the Contributor first 113 | distributes such Contribution. 114 | 115 | 2.3. Limitations on Grant Scope 116 | 117 | The licenses granted in this Section 2 are the only rights granted under 118 | this License. No additional rights or licenses will be implied from the 119 | distribution or licensing of Covered Software under this License. 120 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 121 | Contributor: 122 | 123 | (a) for any code that a Contributor has removed from Covered Software; 124 | or 125 | 126 | (b) for infringements caused by: (i) Your and any other third party's 127 | modifications of Covered Software, or (ii) the combination of its 128 | Contributions with other software (except as part of its Contributor 129 | Version); or 130 | 131 | (c) under Patent Claims infringed by Covered Software in the absence of 132 | its Contributions. 133 | 134 | This License does not grant any rights in the trademarks, service marks, 135 | or logos of any Contributor (except as may be necessary to comply with 136 | the notice requirements in Section 3.4). 137 | 138 | 2.4. Subsequent Licenses 139 | 140 | No Contributor makes additional grants as a result of Your choice to 141 | distribute the Covered Software under a subsequent version of this 142 | License (see Section 10.2) or under the terms of a Secondary License (if 143 | permitted under the terms of Section 3.3). 144 | 145 | 2.5. Representation 146 | 147 | Each Contributor represents that the Contributor believes its 148 | Contributions are its original creation(s) or it has sufficient rights 149 | to grant the rights to its Contributions conveyed by this License. 150 | 151 | 2.6. Fair Use 152 | 153 | This License is not intended to limit any rights You have under 154 | applicable copyright doctrines of fair use, fair dealing, or other 155 | equivalents. 156 | 157 | 2.7. Conditions 158 | 159 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 160 | in Section 2.1. 161 | 162 | 3. Responsibilities 163 | ------------------- 164 | 165 | 3.1. Distribution of Source Form 166 | 167 | All distribution of Covered Software in Source Code Form, including any 168 | Modifications that You create or to which You contribute, must be under 169 | the terms of this License. You must inform recipients that the Source 170 | Code Form of the Covered Software is governed by the terms of this 171 | License, and how they can obtain a copy of this License. You may not 172 | attempt to alter or restrict the recipients' rights in the Source Code 173 | Form. 174 | 175 | 3.2. Distribution of Executable Form 176 | 177 | If You distribute Covered Software in Executable Form then: 178 | 179 | (a) such Covered Software must also be made available in Source Code 180 | Form, as described in Section 3.1, and You must inform recipients of 181 | the Executable Form how they can obtain a copy of such Source Code 182 | Form by reasonable means in a timely manner, at a charge no more 183 | than the cost of distribution to the recipient; and 184 | 185 | (b) You may distribute such Executable Form under the terms of this 186 | License, or sublicense it under different terms, provided that the 187 | license for the Executable Form does not attempt to limit or alter 188 | the recipients' rights in the Source Code Form under this License. 189 | 190 | 3.3. Distribution of a Larger Work 191 | 192 | You may create and distribute a Larger Work under terms of Your choice, 193 | provided that You also comply with the requirements of this License for 194 | the Covered Software. If the Larger Work is a combination of Covered 195 | Software with a work governed by one or more Secondary Licenses, and the 196 | Covered Software is not Incompatible With Secondary Licenses, this 197 | License permits You to additionally distribute such Covered Software 198 | under the terms of such Secondary License(s), so that the recipient of 199 | the Larger Work may, at their option, further distribute the Covered 200 | Software under the terms of either this License or such Secondary 201 | License(s). 202 | 203 | 3.4. Notices 204 | 205 | You may not remove or alter the substance of any license notices 206 | (including copyright notices, patent notices, disclaimers of warranty, 207 | or limitations of liability) contained within the Source Code Form of 208 | the Covered Software, except that You may alter any license notices to 209 | the extent required to remedy known factual inaccuracies. 210 | 211 | 3.5. Application of Additional Terms 212 | 213 | You may choose to offer, and to charge a fee for, warranty, support, 214 | indemnity or liability obligations to one or more recipients of Covered 215 | Software. However, You may do so only on Your own behalf, and not on 216 | behalf of any Contributor. You must make it absolutely clear that any 217 | such warranty, support, indemnity, or liability obligation is offered by 218 | You alone, and You hereby agree to indemnify every Contributor for any 219 | liability incurred by such Contributor as a result of warranty, support, 220 | indemnity or liability terms You offer. You may include additional 221 | disclaimers of warranty and limitations of liability specific to any 222 | jurisdiction. 223 | 224 | 4. Inability to Comply Due to Statute or Regulation 225 | --------------------------------------------------- 226 | 227 | If it is impossible for You to comply with any of the terms of this 228 | License with respect to some or all of the Covered Software due to 229 | statute, judicial order, or regulation then You must: 230 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GUVI-Codekata 2 | This repository contains the solution for the questions present on codekata platform on guvi.in. 3 | This repository contains the solution of GU- Introduction to OOPS Coded as gu-ito-...py 4 | This repository contains the solution of GU- Introduction to OOPS Unit 1 coded as gu-ito-1-...py 5 | This repository contains the solution of GU- Introduction to OOPS Unit 2 coded as gu-ito-2-...py 6 | This repository contains the solution of GU- Introduction to OOPS Unit 3 coded as gu-ito-3-...py 7 | -------------------------------------------------------------------------------- /gu-ito-1-1.py: -------------------------------------------------------------------------------- 1 | #this file contains the solution to the problem of gu introduction to oops unit 1 - question 1. 2 | '''Mani finds himself in a queue of( n) people but is uncertain about his exact position. However, he's confident that there are at least( a) people in front of him and at most( b) people behind him. Mani seeks to determine the number of different positions he could occupy in the queue. 3 | 4 | Input: 5 | 6 | The input consists of a single line containing three integers:( n),( a), and( b) (( 0≤a,bself.y: 36 | return 1 37 | years=0 38 | while self.x<=self.y: 39 | self.x*=3 40 | self.y*=2 41 | years+=1 42 | return years 43 | 44 | #..... YOUR CODE ENDS HERE ..... 45 | 46 | if __name__ == "__main__": 47 | x, y = map(int, input().split()) 48 | calculation = Calculation(x, y) 49 | result = calculation.find_iteration() 50 | if result is not None: 51 | print(result) -------------------------------------------------------------------------------- /gu-ito-1-11.py: -------------------------------------------------------------------------------- 1 | '''A group of friends is planning a road trip to visit multiple destinations. Each friend owns a car, and they need to ensure that the total fuel consumption of their vehicles matches the distance they plan to travel. The distance to each destination is represented by a list of integers, where positive values indicate the distance in kilometers they need to travel, and negative values indicate the distance they need to backtrack. 2 | 3 | The friends can adjust the fuel levels of their cars by adding or subtracting fuel, with each adjustment costing one coin. They want to minimize the total cost of adjusting their fuel levels to match the total distance they plan to travel. 4 | 5 | What is the minimum cost the group will have to pay to ensure that the total fuel consumption of their vehicles equals the total distance they plan to travel? 6 | 7 | Input: 8 | 9 | The first line contains a single integer n (1 ≤ n ≤ 10^5) — the number of destinations the group plans to visit. 10 | The second line contains n integers a1, a2, ..., an (-10^9 ≤ ai ≤ 10^9) — representing the distances to each destination. Positive values indicate the distance they need to travel, and negative values indicate the distance they need to backtrack. 11 | Output: 12 | 13 | Output a single number — the minimal number of coins you need to pay to make the product equal to 1. 14 | 15 | Sample input: 16 | 17 | 4 18 | 0 0 0 0 19 | 20 | Sample output: 21 | 22 | 4''' 23 | 24 | 25 | 26 | class NumberProcessor: 27 | def __init__(self, l): 28 | self.l = l 29 | self.s = 0 30 | self.odd = 0 31 | self.nz = 0 32 | 33 | def process_numbers(self): 34 | #..... YOUR CODE STARTS HERE ..... 35 | 36 | for i in range(len(self.l)): 37 | if int(self.l[i])<0: 38 | self.odd+=1 39 | self.s+=abs(-1-int(self.l[i])) 40 | elif int(self.l[i])>0: 41 | self.s+=(int(self.l[i])-1) 42 | else: 43 | 44 | self.nz+=1 45 | 46 | if self.odd%2!=0: 47 | if '0' in self.l: 48 | return self.s+1*self.za 49 | else: 50 | return self.s+2 51 | else: 52 | if '0' in self.l: 53 | return self.s+1*self.nz 54 | else: 55 | return self.s 56 | #..... YOUR CODE ENDS HERE ..... 57 | 58 | 59 | if __name__ == "__main__": 60 | n = int(input()) 61 | l = str(input()).split(" ") 62 | 63 | number_processor = NumberProcessor(l) 64 | result = number_processor.process_numbers() 65 | print(result) 66 | -------------------------------------------------------------------------------- /gu-ito-1-12.py: -------------------------------------------------------------------------------- 1 | '''The Felicity Committee assigns a power value to each superhero, and the Avengers aim to maximize their team's average power through strategic operations. 2 | 3 | Initially, the Avengers have n superheroes with powers a1, a2, ..., an. In each operation, they can either remove a superhero (if there are at least two) or increase a superhero's power by 1. 4 | 5 | They are allowed a maximum of m operations, with each superhero limited to k power increases. Can you assist the Avengers in maximizing their team's average power 6 | 7 | Input: 8 | 9 | The first line contains three integers n, k and m (1≤n≤105, 1≤k≤105, 1≤m≤107) — the number of superheroes, the maximum number of times you can increase power of a particular superhero, and the total maximum number of operations. 10 | 11 | The second line contains n integers a1,a2,…,an (1≤ai≤106) — the initial powers of the superheroes in the cast of avengers. 12 | 13 | Output: 14 | 15 | Output a single number — the maximum final average power. 16 | 17 | Your answer is considered correct if its absolute or relative error does not exceed 10−6. 18 | 19 | Formally, let your answer be a, and the jury's answer be b. Your answer is accepted if and only if |a−b|max(1,|b|)≤10−6. 20 | 21 | Sample input: 22 | 23 | 2 4 6 24 | 4 7 25 | 26 | Sample output: 27 | 28 | 11.0''' 29 | 30 | n, k, m = map(int, input().split()) 31 | a = list(map(int, input().split())) 32 | 33 | #..... YOUR CODE STARTS HERE ..... 34 | 35 | a.sort() 36 | ans=sum(a) 37 | r=0 38 | for i in range(n): 39 | if i<=m: 40 | r=int(max(r,(ans+min(k*(n-i),m-i))/(n-i))) 41 | ans-=a[i] 42 | 43 | print(r) 44 | 45 | #..... YOUR CODE ENDS HERE ..... -------------------------------------------------------------------------------- /gu-ito-1-13.py: -------------------------------------------------------------------------------- 1 | '''Sanjay is a student who hates maths. But he was a good programmer. There was a sum in second chapter which was given to him as a homework.Help him to finish his homework. You are given with a number n. You have to find the sum of numbers from 1 to n and subtract all the 2nd values from the sum. Help him to finish the exercise in the second chapter. Write a program to finish the maths homework. 2 | 3 | Input: 4 | 5 | The first line contains an integer t, the total number of testcases. 6 | The next t lines contain an integer n. 7 | Input Constraints: 8 | 1<=t<=100 9 | 1<=n<=10^9 10 | 11 | Output: 12 | 13 | Print t lines of integer values 14 | 15 | Sample input: 16 | 17 | 2 18 | 4 19 | 1000000000 20 | 21 | Sample output: 22 | 23 | -4 24 | 499999998352516354 25 | 26 | ''' 27 | 28 | 29 | 30 | import math 31 | 32 | class NumberCalculator: 33 | #..... YOUR CODE STARTS HERE ..... 34 | 35 | def __init__(self): 36 | pass 37 | 38 | def calculate_result(self,n): 39 | return n*(n+1)//2 - 2*(2**(int(math.log2(n))+1)-1) 40 | 41 | #..... YOUR CODE ENDS HERE ..... 42 | 43 | if __name__ == "__main__": 44 | number_calculator = NumberCalculator() 45 | test_cases = int(input()) 46 | 47 | for i in range(test_cases): 48 | n = int(input()) 49 | result = number_calculator.calculate_result(n) 50 | print(result) 51 | -------------------------------------------------------------------------------- /gu-ito-1-14.py: -------------------------------------------------------------------------------- 1 | class FactorFinder: 2 | def __init__(self, n): 3 | self.n = n 4 | 5 | def find_factors(self): 6 | def backtrack(remaining, start, path, result): 7 | #..... YOUR CODE STARTS HERE ..... 8 | 9 | if remaining == 1: 10 | if len(path) > 1: 11 | result.append(path[ : ]) 12 | else: 13 | result.append([1, path[0]]) 14 | return 15 | for i in range(start, remaining + 1): 16 | if remaining % i ==0: 17 | path.append(i) 18 | backtrack(remaining // i,i,path,result) 19 | path.pop() 20 | result = [] 21 | backtrack(self.n,2,[],result) 22 | return result 23 | 24 | #..... YOUR CODE ENDS HERE ..... 25 | 26 | result = [] 27 | backtrack(self.n, 2, [], result) 28 | return result 29 | 30 | if __name__ == '__main__': 31 | n = int(input()) 32 | factor_finder = FactorFinder(n) 33 | print(factor_finder.find_factors()) -------------------------------------------------------------------------------- /gu-ito-1-15.py: -------------------------------------------------------------------------------- 1 | '''Mani, renowned for his cryptographic prowess, has developed a novel encryption technique for transmitting positive integers securely to his acquaintances. In his method, Mani selects three secret integers — a, b, and c — from a specified range determined by lower and upper bounds, denoted as l and r. Subsequently, he employs the formula m = n * a + b - c to generate the encrypted value of the integer n. 2 | 3 | However, an adversary has managed to intercept the parameters l, r, and m, posing a challenge to decrypt the original values of a, b, and c. The task at hand is to decipher any valid combination of a, b, and c that adheres to the following criteria: 4 | 5 | The values of a, b, and c must be integers. 6 | They must fall within the inclusive range [l, r]. 7 | There exists at least one positive integer n such that n * a + b - c equals the intercepted value m. 8 | The input comprises multiple test cases, each presenting the intercepted values of l, r, and m. It is assured that at least one feasible solution exists, and any valid combination of a, b, and c may be outputted if multiple solutions are available. 9 | Sample input: 10 | 11 | 20 12 | 10 12 43 13 | 25 49 1 14 | 5 7 39 15 | 8 9 44 16 | 16 17 50 17 | 30 40 975 18 | 601 801 1000 19 | 100 102 909 20 | 599 799 1000 21 | 503 997 9 22 | 194 383 5 23 | 90000 100000 709999 24 | 75000 100000 124999 25 | 375000 499999 625001 26 | 375000 500000 624999 27 | 300000 400000 499999 28 | 250000 500000 1 29 | 70000 80000 2272770257 30 | 70000 80000 9999953344 31 | 90000 100000 9999955820 32 | 33 | Sample output: 34 | 35 | 11 11 12 36 | 25 25 49 37 | 5 6 7 38 | 9 8 9 39 | 17 16 17 40 | 35 35 40 41 | 800 801 601 42 | 101 102 102 43 | 599 601 799 44 | 503 503 997 45 | 194 194 383 46 | 100000 100000 90001 47 | 99999 100000 75000 48 | 375000 375000 499999 49 | 499999 500000 375000 50 | 399999 400000 300000 51 | 250000 250001 500000 52 | 70007 73002 80000 53 | 70009 80000 72198 54 | 90003 92499 100000''' 55 | 56 | 57 | import sys 58 | 59 | def get_ints(): 60 | return map(int, sys.stdin.readline().split()) 61 | 62 | for _ in range(int(input())): 63 | lst = list(get_ints()) 64 | 65 | #..... YOUR CODE STARTS HERE ..... 66 | 67 | 68 | l,r,m=lst[0],lst[1],lst[2] 69 | for i in range(l,r+1): 70 | x1=m%i 71 | x2=i-(m%i) 72 | if i<=m and x1<=(r-l): 73 | a=i 74 | b=r 75 | c=r-x1 76 | i=r+2 77 | break 78 | elif x2<=(r-l): 79 | a=i 80 | b=r-x2 81 | c=r 82 | i=r+2 83 | break 84 | print(a,end=" ") 85 | print(b,end=" ") 86 | print(c) 87 | 88 | #..... YOUR CODE ENDS HERE ..... -------------------------------------------------------------------------------- /gu-ito-1-2.py: -------------------------------------------------------------------------------- 1 | '''Lucas, a university student, is working on a project where he needs to process a set of student records. He is given a list of students where each record contains the student's name and marks in three subjects: Math, Physics, Biology. Each subject's mark is within the range 0-100. He needs to return the name of the student with the highest average score. 2 | 3 | If there is more than one student who has the highest average score, Lucas needs to return the first student in the list. 4 | 5 | Input: 6 | 7 | The first line contains an integer 'n' (1 <= n <= 1000) - representing the number of students. 8 | The 'n' following lines each contain a string and three space-separated integers. 9 | Output: 10 | 11 | Print the name of the student who has the highest average score. 12 | Sample Input: 13 | 14 | 5 15 | John 85 90 82 16 | Alice 90 91 92 17 | Bob 80 79 81 18 | Lucas 88 90 92 19 | Maria 90 91 90 20 | Sample Output: 21 | 22 | Alice 23 | Note: The five students' average scores are as follows: 24 | 25 | John's average is 85.67 26 | Alice's average is 91 27 | Bob's average is 80 28 | Lucas's average is 90 29 | Maria's average is 90.33 30 | Alice has the highest average score and showcases the best performance among all students. 31 | 32 | ''' 33 | class Student: 34 | def __init__(self, name, scores): 35 | self._name = name # protected attribute 36 | self.__scores = scores # private attribute 37 | 38 | def calculate_average(self): 39 | return sum(self.__scores) / len(self.__scores) 40 | 41 | def get_name(self): # public method to access protected attribute 42 | return self._name 43 | 44 | 45 | class TopStudentFinder: 46 | def __init__(self): 47 | self.max_avg = -1.0 48 | self.top_student = "" 49 | 50 | def find_top_student(self, students): 51 | 52 | 53 | for student in students: 54 | avg_score=student.calculate_average() 55 | if avg_score>self.max_avg: 56 | self.max_avg=avg_score 57 | self.top_student=student.get_name() 58 | 59 | 60 | 61 | 62 | 63 | def get_top_student(self): 64 | return self.top_student 65 | 66 | 67 | if __name__ == "__main__": 68 | n = int(input()) 69 | students_data = [] 70 | 71 | for _ in range(n): 72 | student_info = input().split() 73 | name = student_info[0] 74 | scores = list(map(int, student_info[1:])) 75 | students_data.append(Student(name, scores)) 76 | 77 | 78 | 79 | top_student_finder=TopStudentFinder() 80 | top_student_finder.find_top_student(students_data) 81 | top_student=top_student_finder.get_top_student() 82 | print(top_student) 83 | 84 | -------------------------------------------------------------------------------- /gu-ito-1-3.py: -------------------------------------------------------------------------------- 1 | '''Many years ago, the country of Berland was inhabited by a small population of( n) individuals, each with their own savings. The government aimed to increase the number of wealthy individuals by implementing a series of reforms. 2 | 3 | Each reform involved the government selecting a subset of individuals, collecting all their savings, and then redistributing the total equally among the selected individuals. The ultimate goal was to ensure that each individual had at least( x) burles to be considered wealthy. 4 | 5 | Given the initial savings of each individual and the minimum wealth threshold( x), your task is to calculate the maximum possible number of wealthy individuals after the reforms, if any were implemented. 6 | 7 | Input: 8 | 9 | The first line contains a single integer( T) where, ( 1 <= T <= 1000) — the number of test cases. 10 | For each test case, there are two lines: - The second line contains two integers( n) and( x) where, (1 <= n <= 10^5, 1 <= x <= 10^9) — representing the number of individuals and the minimum wealth threshold. - The third line contains( n) integers( a1, a2,...., an) where, ( 1 <= ai <= 10^9) — the initial savings of each individual. 11 | Output: 12 | 13 | Print( T) integers, one per test case, representing the maximum possible number of wealthy individuals after the reforms. 14 | Constraints: 15 | 16 | The total sum of( n) across all test cases does not exceed( 10^5). 17 | Sample input: 18 | 19 | 1 20 | 1 2 21 | 13 22 | 23 | Sample output: 24 | 25 | 1''' 26 | 27 | class TestCase: 28 | def __init__(self, n, x, a): 29 | self.n = n 30 | self.x = x 31 | self.a = a 32 | 33 | def calculate_qualified_elements(self): 34 | a_sorted = sorted(self.a, reverse=True) 35 | p, q = 0, 0 36 | 37 | 38 | for savings in a_sorted: 39 | p+=savings 40 | if p >= self.x*(q+1): 41 | q+=1 42 | else: 43 | break 44 | 45 | 46 | return q 47 | 48 | 49 | def process_test_cases(): 50 | test_cases = int(input()) 51 | results = [] 52 | 53 | for _ in range(test_cases): 54 | n, x = map(int, input().split()) 55 | a = list(map(int, input().split())) 56 | 57 | 58 | case=TestCase(n,x,a) 59 | results.append(case.calculate_qualified_elements()) 60 | 61 | 62 | 63 | return results 64 | 65 | 66 | if __name__ == "__main__": 67 | results = process_test_cases() 68 | for result in results: 69 | print(result) 70 | -------------------------------------------------------------------------------- /gu-ito-1-4.py: -------------------------------------------------------------------------------- 1 | '''Vishakan, a dedicated reader, has a limited time to indulge in his favorite activity: reading books in the library. Each book has its own unique charm, but Vishakan needs to optimize his time to read as many books as possible within his available time. 2 | 3 | Input: 4 | 5 | The first line contains two integers,(n) and (t) where, (1 <= n <= 10^5) and (1 <= t <= 10^9), denoting the number of books in the library and the total free minutes Vishakan has. 6 | The second line contains( n) space-separated integers (a1, a2,...., an) where (1 <= ai <= 10^4), representing the time required to read each book. 7 | Output: 8 | 9 | Print a single integer, the maximum number of books Vishakan can read within his available time. 10 | Constraints: 11 | 12 | Vishakan has a maximum of( 10^9) minutes to spend in the library. 13 | Each book takes between 1 and 10,000 minutes to read. 14 | Sample input: 15 | 16 | 3 3 17 | 2 2 3 18 | 19 | Sample output: 20 | 21 | 1 22 | 23 | ''' 24 | 25 | import sys 26 | from collections import deque, defaultdict 27 | 28 | I = sys.stdin.readline 29 | 30 | def ii(): 31 | return int(I().strip()) 32 | 33 | def li(): 34 | return list(map(int, I().strip().split())) 35 | 36 | def mi(): 37 | return map(int, I().strip().split()) 38 | 39 | def main(): 40 | n, k = mi() 41 | arr = li() 42 | 43 | #..... YOUR CODE STARTS HERE ..... 44 | 45 | arr.sort() 46 | books_read=0 47 | total_time=0 48 | for time in arr: 49 | if total_time+time<=k: 50 | total_time+=time 51 | books_read+=1 52 | else: 53 | break 54 | print(books_read) 55 | 56 | #..... YOUR CODE ENDS HERE ..... 57 | 58 | if __name__ == '__main__': 59 | main() -------------------------------------------------------------------------------- /gu-ito-1-5.py: -------------------------------------------------------------------------------- 1 | '''On Earth, each plane has a special affinity for another plane. Given a group of n planes, numbered from 1 to n, where plane i likes plane fi, we aim to determine if any love triangle exists. 2 | 3 | Input: 4 | 5 | The first line contains a single integer n (2 ≤ n ≤ 5000) — representing the number of planes. 6 | 7 | The second line contains n integers f1, f2, ..., fn (1 ≤ fi ≤ n, fi ≠ i), indicating that the i-th plane is fond of plane fi. 8 | 9 | Output: 10 | 11 | Output "YES" if there exists a love triangle among the planes. Otherwise, output "NO". 12 | 13 | Sample input: 14 | 15 | 5 16 | 5 5 5 5 1 17 | 18 | Sample output: 19 | 20 | NO''' 21 | 22 | 23 | class CycleChecker: 24 | def __init__(self, f): 25 | self.f = f 26 | self.n = len(f) 27 | 28 | def check_cycle(self): 29 | 30 | for i in range(self.n): 31 | a=i+1 32 | b=self.f[a-1] 33 | c=self.f[b-1] 34 | if self.f[c-1]==a: 35 | return "YES" 36 | else: 37 | return "NO" 38 | 39 | 40 | 41 | if __name__ == "__main__": 42 | n = int(input()) 43 | f = list(map(int, input().split())) 44 | 45 | 46 | 47 | cycle_checker=CycleChecker(f) 48 | result=cycle_checker.check_cycle() 49 | print(result) 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /gu-ito-1-6.py: -------------------------------------------------------------------------------- 1 | '''You have been given an array ( a ) containing ( n ) positive integers. 2 | 3 | Your task is to find the minimum number of moves required to transform the array such that each element is divisible by ( k ) (given). 4 | 5 | During each move, you can either increase ( x ) by 1 or choose one element ( ai ) from ( a ) and increase it by ( x ) (then increase ( x ) by 1). However, you can only perform the first operation once for each ( i ) from 1 to ( n ). 6 | 7 | Let's solve ( t ) independent test cases. 8 | 9 | Input: 10 | 11 | The first line contains ( t ) (the number of test cases). 12 | For each test case: - The first line contains ( n ) and ( k ) (length of ( a ) and required divisor). - The second line contains ( n ) integers ( a1, a2, ..., an ). 13 | Output: 14 | 15 | For each test case, print the minimum number of moves required. 16 | Constraints: 17 | 18 | ( 1 <= t <= 2 times 10^4 ) 19 | ( 1 <= n <= 2 times 10^5 ) 20 | ( 1 <= k <= 10^9 ) 21 | ( 1 <= ai <= 10^9 ) 22 | Sample input: 23 | 24 | 5 25 | 4 3 26 | 1 2 1 3 27 | 10 6 28 | 8 7 1 8 3 7 5 10 8 9 29 | 5 10 30 | 20 100 50 20 100500 31 | 10 25 32 | 24 24 24 24 24 24 24 24 24 24 33 | 8 8 34 | 1 2 3 4 5 6 7 8 35 | 36 | Sample output: 37 | 38 | 6 39 | 18 40 | 0 41 | 227 42 | 8''' 43 | 44 | 45 | class RemainderCalculator: 46 | def __init__(self, n, k, a): 47 | self.n = n 48 | self.k = k 49 | self.a = a 50 | 51 | def calculate_remainders(self): 52 | rem = {} 53 | #..... YOUR CODE STARTS HERE ..... 54 | 55 | for num in self.a: 56 | remainder=num%self.k 57 | if remainder!=0: 58 | rem[remainder]=rem.get(remainder,0)+1 59 | 60 | #..... YOUR CODE ENDS HERE ..... 61 | 62 | return rem 63 | 64 | def find_maximum_result(self, rem): 65 | #..... YOUR CODE STARTS HERE ..... 66 | 67 | result=0 68 | for r, count in rem.items(): 69 | moves=(self.k*(count-1))+(self.k-r)+1 70 | result=max(result,moves) 71 | return result 72 | #..... YOUR CODE ENDS HERE ..... 73 | 74 | 75 | if __name__ == "__main__": 76 | from sys import stdin, stdout, setrecursionlimit 77 | 78 | setrecursionlimit(10**6) 79 | 80 | t = int(stdin.readline()) 81 | for _ in range(t): 82 | n, k = map(int, stdin.readline().split()) 83 | a = list(map(int, stdin.readline().split())) 84 | 85 | #..... YOUR CODE STARTS HERE ..... 86 | 87 | calc=RemainderCalculator(n,k,a) 88 | remainders=calc.calculate_remainders() 89 | result=calc.find_maximum_result(remainders) 90 | stdout.write(str(result)+"\n") 91 | 92 | #..... YOUR CODE ENDS HERE ..... 93 | -------------------------------------------------------------------------------- /gu-ito-1-7.py: -------------------------------------------------------------------------------- 1 | '''Richard Hendricks, Gilfoyle, and Dinesh, the brilliant minds behind Pied Piper, are on a mission to optimize their messaging platform's data compression algorithm. They aim to represent "Yes" and "No" messages more efficiently by converting them into a different base that requires fewer characters, thus reducing the overall message size. 2 | 3 | Richard explains that they currently represent "Yes" messages as 1 and "No" messages as 0 in their messaging platform. However, he believes they can further compress this representation by changing the base to a more efficient one, achieving a four-fold decrease in the number of characters needed to represent the messages. 4 | 5 | Gilfoyle immediately jumps in, suggesting a strategy to change the base of the representation to achieve their goal. With his expertise in cryptography and data compression, Gilfoyle proposes a solution to map the binary representation onto a different base that requires only one-fourth of the characters needed in the existing base. 6 | 7 | Help Gilfoyle defend his case and determine the optimal base for representing "Yes" and "No" messages to achieve a four-fold decrease in the number of characters required. 8 | 9 | Input: 10 | 11 | A single line containing a string made up of 0's and 1's representing "Yes" and "No" messages. 12 | Input Constraints: 1 ≤ N ≤ 57, where N is the number of characters (0's and 1's) in the string. 13 | 14 | Output: 15 | 16 | Single line denoting the value of the binary string in a base that uses four times fewer characters than the existing base. 17 | 18 | Sample input: 19 | 20 | 10110111000010010011011001010111111000111010010010000 21 | 22 | Sample output: 23 | 24 | 16e126cafc7490''' 25 | 26 | 27 | a = input() 28 | 29 | def base(b): 30 | basesn=hex(int(b,2))[2:] 31 | return basesn 32 | 33 | print(base(a)) 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /gu-ito-1-8.py: -------------------------------------------------------------------------------- 1 | '''Sanjay is a Stock Exchange Specialist. Any stocks that he buys, he has a capacity of for such greater price. He has created a algorithm to find the profit that can be obtained by trading certain stocks. 2 | 3 | The machines will be generating a string, the string will be made up of integers from 0 to 9. Now each integer in this string will be a coded value of the profit. You have to multiply a digit N, with n-1,n-2,...till n-i>=1. Each digit in the string will be giving a profit of the particular amount thus obtained. Now summing up all the profits, it should be equal to the entire string considered as a integer input. 4 | 5 | If they are equal, then the prediction was right, so print Right, if else print Wrong. 6 | 7 | Input: 8 | 9 | One single string input N, where N is the prediction by Victor 10 | 11 | Input Constraints : 1<=length of N<=10^5 12 | 13 | Output: 14 | 15 | "Right" if the prediction is right and "Wrong" if the prediction is wrong 16 | 17 | Sample input: 18 | 19 | 40583 20 | 21 | Sample output: 22 | 23 | Wrong''' 24 | 25 | 26 | 27 | class NumberChecker: 28 | def __init__(self, n): 29 | self.n = n 30 | self.sum = 0 31 | self.temp = n 32 | 33 | def check_factorial_sum(self): 34 | while self.n: 35 | #..... YOUR CODE STARTS HERE ..... 36 | 37 | digit=int(self.n%10) 38 | factorial=1 39 | for i in range(1,digit+1): 40 | factorial*=i 41 | self.sum+=factorial 42 | self.n//=10 43 | 44 | #..... YOUR CODE ENDS HERE ..... 45 | 46 | if self.sum == self.temp: 47 | return "Right" 48 | else: 49 | return "Wrong" 50 | 51 | 52 | if __name__ == "__main__": 53 | n = int(input()) 54 | number_checker = NumberChecker(n) 55 | result = number_checker.check_factorial_sum() 56 | print(result) 57 | -------------------------------------------------------------------------------- /gu-ito-1-9.py: -------------------------------------------------------------------------------- 1 | '''Gordon the wizard possesses an extraordinary collection of magical stones. Each stone has a unique weight ranging from 1 to n. 2 | 3 | Gordon's peculiar ability allows him to fuse two stones together, resulting in a new stone with a weight equal to the sum of the weights of the two original stones. However, the two original stones vanish after fusion. 4 | 5 | Gordon's ultimate goal is to maximize the number of stones that have the same weight. While it's not mandatory to make all stones uniform in weight, he desires to have as many stones of equal weight as possible. 6 | 7 | Given the number of stones in Gordon's collection, determine how many stones of equal weight he can create using his magical fusion process. 8 | 9 | Input: 10 | 11 | The input consists of multiple test cases. The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of test cases. 12 | 13 | The following t lines each contain a single integer n (1 ≤ n ≤ 10^9), representing the number of stones in Gordon's collection. 14 | 15 | Output: 16 | 17 | For each test case, print a single integer, the maximum number of stones with equal weight that Gordon can create. 18 | 19 | Sample input: 20 | 21 | 1 22 | 10 23 | 24 | Sample output: 25 | 26 | 5''' 27 | 28 | 29 | class StoneCalculator: 30 | def __init__(self, t): 31 | self.t = t 32 | 33 | def calculate_max_stones(self, n): 34 | #..... YOUR CODE STARTS HERE ..... 35 | 36 | return n//2 37 | 38 | #..... YOUR CODE ENDS HERE ..... 39 | if __name__ == "__main__": 40 | t = int(input()) 41 | stone_calculator = StoneCalculator(t) 42 | 43 | for i in range(t): 44 | n = int(input()) 45 | result = stone_calculator.calculate_max_stones(n) 46 | print(result) 47 | -------------------------------------------------------------------------------- /gu-ito-1.py: -------------------------------------------------------------------------------- 1 | '''You are required to write a program that calculates and prints the perimeter of a triangle given its three sides a, b, and c units. Implement a class named 'Triangle' without any parameter in its constructor. 2 | 3 | Input: 4 | 5 | The input consists of three lines. Each line contains an integer representing one side of the triangle. 6 | 7 | Output: 8 | 9 | Output the perimeter of the triangle. 10 | 11 | Sample Input: 12 | 13 | 3 14 | 4 15 | 5 16 | 17 | Sample Output: 18 | 19 | 12''' 20 | 21 | 22 | class Triangle: 23 | def __init__(self): 24 | pass 25 | 26 | 27 | 28 | 29 | a=int(input()) 30 | b=int(input()) 31 | c=int(input()) 32 | print(a+b+c) 33 | 34 | 35 | def main(): 36 | triangle = Triangle() 37 | 38 | # Input for the sides of the triangle 39 | a = int(input()) 40 | b = int(input()) 41 | c = int(input()) 42 | 43 | # Calculate and print the perimeter of the triangle 44 | print(triangle.perimeter(a, b, c)) 45 | 46 | if __name__ == "__main__": 47 | main() 48 | -------------------------------------------------------------------------------- /gu-ito-10.py: -------------------------------------------------------------------------------- 1 | '''You're required to write a program to calculate and print the area and perimeter of two rectangles given their sides. Implement a class named 'Rectangle' with methods named 'Area' and 'Perimeter', which return the area and perimeter, respectively. The length and breadth of the rectangles are passed as parameters to its constructor. 2 | 3 | Input: 4 | 5 | The input consists of two lines. Each line contains two integers representing the sides of the rectangles in the format (a, b) for the first rectangle and (c, d) for the second rectangle. 6 | 7 | Output: 8 | 9 | Output the area and perimeter of both rectangles separated by spaces in the format 10 | Area1 Perimeter1 11 | Area2 Perimeter2. 12 | 13 | Sample Input: 14 | 15 | 3 4 16 | 4 5 17 | 18 | Sample Output: 19 | 20 | 12 14 21 | 20 18''' 22 | 23 | 24 | class Rectangle: 25 | def __init__(self, length, breadth): 26 | self.length = length 27 | self.breadth = breadth 28 | 29 | #..... YOUR CODE STARTS HERE ..... 30 | 31 | def Area(self): 32 | return self.length*self.breadth 33 | def Perimeter(self): 34 | return 2*(self.length+self.breadth) 35 | #..... YOUR CODE ENDS HERE ..... 36 | 37 | def main(): 38 | # Input for rectangle 1 39 | a, b = map(int, input().split()) 40 | rectangle1 = Rectangle(a, b) 41 | 42 | # Input for rectangle 2 43 | c, d = map(int, input().split()) 44 | rectangle2 = Rectangle(c, d) 45 | 46 | # Calculate and print area and perimeter for both rectangles 47 | print(rectangle1.Area(), rectangle1.Perimeter()) 48 | print(rectangle2.Area(), rectangle2.Perimeter()) 49 | 50 | if __name__ == "__main__": 51 | main() 52 | 53 | -------------------------------------------------------------------------------- /gu-ito-11.py: -------------------------------------------------------------------------------- 1 | '''You are required to implement a notification system for banks that notifies customers through SMS, Email, and monthly e-statement. The system consists of an interface Notification with three methods: 2 | 3 | notificationBySms() 4 | notificationByEmail() 5 | notificationByCourier() 6 | Implement two classes, Icici and Hdfc, which implement the Notification interface. Additionally, create a BankFactory class with two methods: 7 | 8 | public Icici getIcici() (returns an object for Icici) 9 | public Hdfc getHdfc() (returns an object for Hdfc) 10 | The main class should get input from the user and display the appropriate notification based on the bank and notification type selected. 11 | 12 | Input: 13 | 14 | The first integer corresponds to the name of the bank, and the next integer corresponds to the type of notification. If there is no valid input, display 'Invalid input'. 15 | 16 | Output: 17 | 18 | Output the notification message based on the bank and notification type selected. 19 | 20 | Sample Input: 21 | 22 | 1 1 23 | 24 | Sample Output: 25 | 26 | ICICI - Notification By SMS''' 27 | 28 | 29 | 30 | # Notification interface 31 | class Notification: 32 | def notificationBySms(self): 33 | pass 34 | 35 | def notificationByEmail(self): 36 | pass 37 | 38 | def notificationByCourier(self): 39 | pass 40 | 41 | # Icici class implementing Notification interface 42 | class Icici(Notification): 43 | #..... YOUR CODE STARTS HERE ..... 44 | 45 | def notificationBySms(self): 46 | return "ICICI - Notification By SMS" 47 | 48 | def notificationByEmail(self): 49 | return "ICIcI - Notification By Email" 50 | 51 | def notificationByCourier(self): 52 | return "ICICI - Notification By Courier" 53 | #..... YOUR CODE ENDS HERE ..... 54 | 55 | # Hdfc class implementing Notification interface 56 | class Hdfc(Notification): 57 | #..... YOUR CODE STARTS HERE ..... 58 | 59 | def notificationBySms(self): 60 | return "HDFC - Notification By SMS" 61 | 62 | def notificationByEmail(self): 63 | return "HDFC - Notification By Email" 64 | 65 | def notificationByCourier(self): 66 | return "HDFC - Notification By Courier" 67 | 68 | 69 | #..... YOUR CODE ENDS HERE ..... 70 | 71 | # BankFactory class 72 | class BankFactory: 73 | def getIcici(self): 74 | return Icici() 75 | 76 | def getHdfc(self): 77 | return Hdfc() 78 | 79 | def main(): 80 | bank, notification = map(int, input().split()) 81 | bank_factory = BankFactory() 82 | 83 | if bank == 1: 84 | bank_obj = bank_factory.getIcici() 85 | elif bank == 2: 86 | bank_obj = bank_factory.getHdfc() 87 | else: 88 | print("Invalid input") 89 | return 90 | 91 | if notification == 1: 92 | print(bank_obj.notificationBySms()) 93 | elif notification == 2: 94 | print(bank_obj.notificationByEmail()) 95 | elif notification == 3: 96 | print(bank_obj.notificationByCourier()) 97 | else: 98 | print("Invalid input") 99 | 100 | if __name__ == "__main__": 101 | main() 102 | -------------------------------------------------------------------------------- /gu-ito-2-1.py: -------------------------------------------------------------------------------- 1 | '''In a college, there are two types of students: Undergraduate and Graduate. Both types of students have a method get_fee() that returns the tuition fee. However, the tuition fee is calculated differently for Undergraduate and Graduate students. For Undergraduate students, the tuition fee is a fixed amount of $5000. For Graduate students, the tuition fee is the number of credits taken times $50. 2 | 3 | Please write a Python program that defines classes for Undergraduate and Graduate students, both inheriting from a common Student class. The Student class should have the get_fee() method, which should be overridden in the Undergraduate and Graduate classes. 4 | 5 | Sample Input: 6 | 7 | 60 8 | 9 | Sample Output: 10 | 11 | 5000 12 | 3000 13 | 14 | Explanation: 15 | 16 | The Undergraduate class overrides the get_fee() method and returns a fixed amount of $5000. The Graduate class also overrides the get_fee() method and returns the number of credits taken times $50. In the sample input, the Graduate student has taken 60 credits, so the fee is 60 * $50 = $3000. 17 | 18 | Constraints: 19 | 20 | The number of credits for a Graduate student is a positive integer.''' 21 | 22 | 23 | 24 | class Student: 25 | #..... YOUR CODE STARTS HERE ..... 26 | 27 | def get_fee(self): 28 | return 0 29 | 30 | #..... YOUR CODE ENDS HERE ..... 31 | 32 | class Undergraduate(Student): 33 | def get_fee(self): 34 | #..... YOUR CODE STARTS HERE ..... 35 | 36 | return 5000 37 | 38 | #..... YOUR CODE ENDS HERE ..... 39 | 40 | class Graduate(Student): 41 | def __init__(self, credits): 42 | #..... YOUR CODE STARTS HERE ..... 43 | 44 | self.credits=credits 45 | 46 | #..... YOUR CODE ENDS HERE ..... 47 | 48 | def get_fee(self): 49 | #..... YOUR CODE STARTS HERE ..... 50 | 51 | return self.credits*50 52 | 53 | #..... YOUR CODE ENDS HERE ..... 54 | 55 | credits = int(input()) 56 | 57 | undergraduate = Undergraduate() 58 | graduate = Graduate(credits) 59 | 60 | programs = [undergraduate, graduate] 61 | for program in programs: 62 | print(program.get_fee()) -------------------------------------------------------------------------------- /gu-ito-2-10.py: -------------------------------------------------------------------------------- 1 | '''In the sample output, each line represents the details of an electronic device: 2 | 3 | The first line is the details of a mobile. It's a Samsung Galaxy S21 with a price of $799.99 and a screen size of 6.2 inches. 4 | The second line is the details of a laptop. It's a Dell XPS 13 with a price of $999.99 and a screen resolution of 1920 x 1080. 5 | These details are printed by calling the print_details() method of each device object. The method is defined in each class and prints the details specific to that device. 6 | 7 | This is an example of hierarchical inheritance, where the Mobile and Laptop classes inherit from a common base class (ElectronicDevice). The base class defines properties and methods common to all electronic devices (like name and price), while the derived classes add properties and methods specific to mobiles and laptops (like screen_size and screen_resolution). 8 | 9 | Constraints: 10 | 11 | The name of the mobile or laptop is a string and can contain any printable ASCII characters. 12 | The price of the mobile or laptop is a float and can be any positive number. 13 | The screen size of the mobile is a string and can contain any printable ASCII characters. 14 | The screen resolution of the laptop is a string and can contain any printable ASCII characters. 15 | ''' 16 | 17 | class ElectronicDevice: 18 | def __init__(self, name, price): 19 | #..... YOUR CODE STARTS HERE ..... 20 | self.name=name 21 | self.price=price 22 | 23 | 24 | #..... YOUR CODE ENDS HERE ..... 25 | 26 | class Mobile(ElectronicDevice): 27 | def __init__(self, name, price, screen_size): 28 | #..... YOUR CODE STARTS HERE ..... 29 | super().__init__(name,price) 30 | self.screen_size=screen_size 31 | 32 | 33 | #..... YOUR CODE ENDS HERE ..... 34 | 35 | def print_details(self): 36 | #..... YOUR CODE STARTS HERE ..... 37 | return(f"Mobile: {self.name}, Price: ${self.price}, Screen Size: {self.screen_size}" ) 38 | 39 | 40 | #..... YOUR CODE ENDS HERE ..... 41 | 42 | class Laptop(ElectronicDevice): 43 | def __init__(self, name, price, screen_resolution): 44 | #..... YOUR CODE STARTS HERE ..... 45 | super().__init__(name,price) 46 | self.screen_resolution=screen_resolution 47 | 48 | 49 | #..... YOUR CODE ENDS HERE ..... 50 | 51 | def print_details(self): 52 | #..... YOUR CODE STARTS HERE ..... 53 | return(f"Laptop: {self.name}, Price: ${self.price}, Screen Resolution: {self.screen_resolution}") 54 | 55 | 56 | #..... YOUR CODE ENDS HERE ..... 57 | 58 | # Get sample input from the user 59 | mobile_input = input().split(", ") 60 | laptop_input = input().split(", ") 61 | 62 | # Create objects 63 | mobile = Mobile(*mobile_input) 64 | laptop = Laptop(*laptop_input) 65 | 66 | # Print details 67 | print(mobile.print_details()) 68 | print(laptop.print_details()) -------------------------------------------------------------------------------- /gu-ito-2-11.py: -------------------------------------------------------------------------------- 1 | '''Design a Python program that uses single level inheritance to model a school. The school has two types of people: students and teachers. Both students and teachers have a name and an age. However, a student also has a department, while a teacher has a subject they teach. 2 | 3 | Create classes to represent both a student and a teacher, and use inheritance to avoid code duplication. Write a method in each class to print the details of the student or teacher. 4 | 5 | Sample Input: 6 | 7 | Ravi Kumar, 20, Computer Science 8 | Dr. Srinivasan, 45, Data Structures and Algorithms 9 | 10 | Sample Output: 11 | 12 | Student: Ravi Kumar, Age: 20, Department: Computer Science 13 | Teacher: Dr. Srinivasan, Age: 45, Subject: Data Structures and Algorithms 14 | 15 | Explanation: 16 | 17 | In the sample output, each line represents the details of a person in the school: 18 | 19 | The first line is the details of a student. It's Ravi Kumar who is 20 years old and studying Computer Science. 20 | The second line is the details of a teacher. It's Dr. Srinivasan who is 45 years old and teaches Data Structures and Algorithms. 21 | These details are printed by calling the print_details() method of each person object. The method is defined in each class and prints the details specific to that person. 22 | 23 | This is an example of single level inheritance, where the Student and Teacher classes inherit from a common base class (Person). The base class defines properties and methods common to all people (like name and age), while the derived classes add properties and methods specific to students and teachers (like grade and subject). 24 | 25 | Constraints: 26 | 27 | The name of the student or teacher is a string and can contain any printable ASCII characters. 28 | The age of the student or teacher is an integer and can be any positive integer. 29 | The department of the student is a string and can contain any printable ASCII characters. 30 | The subject of the teacher is a string and can contain any printable ASCII characters.''' 31 | 32 | 33 | 34 | class Person: 35 | def __init__(self, name, age): 36 | self.name = name 37 | self.age = age 38 | 39 | def print_details(self): 40 | pass 41 | 42 | 43 | class Student(Person): 44 | def __init__(self, name, age, department): 45 | #..... YOUR CODE STARTS HERE ..... 46 | self.name=name 47 | self.age=age 48 | self.department=department 49 | 50 | 51 | #..... YOUR CODE ENDS HERE ..... 52 | 53 | def print_details(self): 54 | #..... YOUR CODE STARTS HERE ..... 55 | print(f"Student: {self.name}, Age: {self.age}, Department: {self.department}") 56 | 57 | 58 | #..... YOUR CODE ENDS HERE ..... 59 | 60 | 61 | class Teacher(Person): 62 | def __init__(self, name, age, subject): 63 | #..... YOUR CODE STARTS HERE ..... 64 | self.name=name 65 | self.age=age 66 | self.subject=subject 67 | 68 | 69 | #..... YOUR CODE ENDS HERE ..... 70 | 71 | def print_details(self): 72 | #..... YOUR CODE STARTS HERE ..... 73 | print(f"Teacher: {self.name}, Age: {self.age}, Subject: {self.subject}") 74 | 75 | 76 | #..... YOUR CODE ENDS HERE ..... 77 | 78 | 79 | def main(): 80 | # Sample Input 81 | student_info = input().split(", ") 82 | teacher_info = input().split(", ") 83 | 84 | # Create objects 85 | student = Student(*student_info) 86 | teacher = Teacher(*teacher_info) 87 | 88 | # Print details 89 | student.print_details() 90 | teacher.print_details() 91 | 92 | 93 | if __name__ == "__main__": 94 | main() -------------------------------------------------------------------------------- /gu-ito-2-12.py: -------------------------------------------------------------------------------- 1 | '''Consider an e-commerce application that uses a class hierarchy to represent different types of products. We have a base class Product and two subclasses Book and Electronics. Both Book and Electronics classes override a method get_details() from the Product class. Now, we have a new product type EBook that is both a Book and an Electronics. The EBook class inherits from both Book and Electronics. 2 | 3 | Write a Python function mro_sequence(cls) that takes a class cls as input and returns the Method Resolution Order (MRO) for that class as a list of class names. 4 | 5 | Sample Input: 6 | 7 | EBook 8 | 9 | Sample Output: 10 | 11 | ['EBook', 'Book', 'Electronics', 'Product', 'object'] 12 | 13 | Explanation: 14 | 15 | In Python, the Method Resolution Order (MRO) is the order in which the base classes are searched when executing a method. Python uses an algorithm called C3 Linearization, or just C3, to compute this order. In the given example, the MRO for class EBook is EBook -> Book -> Electronics -> Product -> object. 16 | 17 | Constraints: 18 | 19 | The input class cls is a valid Python class. 20 | The class hierarchy can have multiple levels of inheritance but does not contain any circular inheritance. 21 | ''' 22 | 23 | 24 | 25 | class Product: 26 | def get_details(self): 27 | pass 28 | 29 | class Book(Product): 30 | def get_details(self): 31 | pass 32 | 33 | class Electronics(Product): 34 | def get_details(self): 35 | pass 36 | 37 | class EBook(Book, Electronics): 38 | pass 39 | 40 | class Apparel(Product): 41 | pass 42 | 43 | class SmartWatch(Apparel, Electronics): 44 | pass 45 | 46 | class Furniture(Product): 47 | pass 48 | 49 | class SmartFurniture(Furniture, Electronics): 50 | pass 51 | 52 | class Organic(Product): 53 | pass 54 | 55 | class Grocery(Product): 56 | pass 57 | 58 | class OrganicGrocery(Grocery, Organic): 59 | pass 60 | 61 | def mro_sequence(cls): 62 | #..... YOUR CODE STARTS HERE ..... 63 | return [c.__name__ for c in cls.mro()] 64 | 65 | 66 | #..... YOUR CODE ENDS HERE ..... 67 | 68 | class_name = input() 69 | 70 | cls = globals()[class_name] 71 | 72 | # Print the MRO sequence 73 | print(mro_sequence(cls)) -------------------------------------------------------------------------------- /gu-ito-2-13.py: -------------------------------------------------------------------------------- 1 | '''Consider an election scenario where we have different roles such as Citizen, Politician, and PublicServant. Both Politician and PublicServant are subclasses of Citizen. Now, we have a new role Mayor who is both a Politician and a PublicServant. The Mayor class inherits from both Politician and PublicServant. 2 | 3 | Each of these classes has a method role_duties() that describes the duties of the role. However, when a Mayor object calls this method, which method should it execute? This is known as the Diamond Problem. 4 | 5 | Write a Python function mro_sequence(cls) that takes a class cls as input and returns the Method Resolution Order (MRO) for that class as a list of class names. 6 | 7 | Sample Input: 8 | 9 | Mayor 10 | 11 | Sample Output: 12 | 13 | ['Mayor', 'Politician', 'PublicServant', 'Citizen', 'object'] 14 | 15 | Explanation: 16 | 17 | In Python, the Method Resolution Order (MRO) is the order in which the base classes are searched when executing a method. Python uses an algorithm called C3 Linearization, or just C3, to compute this order. In the given example, the MRO for class Mayor is Mayor -> Politician -> PublicServant -> Citizen -> object. This means that if a Mayor object calls the role_duties() method, it will first look for this method in the Mayor class. If it doesn't find it there, it will look in the Politician class, then in the PublicServant class, and finally in the Citizen class. 18 | 19 | Constraints: 20 | 21 | The input class cls is a valid Python class. 22 | The class hierarchy can have multiple levels of inheritance but does not contain any circular inheritance. 23 | ''' 24 | 25 | 26 | class Citizen: 27 | def role_duties(self): 28 | return "Citizen duties" 29 | 30 | class Politician(Citizen): 31 | def role_duties(self): 32 | return "Politician duties" 33 | 34 | class PublicServant(Citizen): 35 | def role_duties(self): 36 | return "Public servant duties" 37 | 38 | class Mayor(Politician, PublicServant): 39 | def role_duties(self): 40 | return "Mayor duties" 41 | 42 | class Voter(Citizen): 43 | def role_duties(self): 44 | return "Voter duties" 45 | 46 | class Candidate(Citizen): 47 | def role_duties(self): 48 | return "Candidate duties" 49 | 50 | class ElectedOfficial(Voter, Candidate): 51 | def role_duties(self): 52 | return "Elected official duties" 53 | 54 | 55 | class Activist(Citizen): 56 | def role_duties(self): 57 | return "Activist duties" 58 | 59 | class ActivistPolitician(Activist, Politician): 60 | def role_duties(self): 61 | return "Activist politician duties" 62 | 63 | class Worker(Citizen): 64 | def role_duties(self): 65 | return "Worker duties" 66 | 67 | class WorkingPolitician(Worker, Politician): 68 | def role_duties(self): 69 | return "Working politician duties" 70 | 71 | def mro_sequence(cls): 72 | #..... YOUR CODE STARTS HERE ..... 73 | return [c.__name__ for c in cls.mro()] 74 | 75 | 76 | #..... YOUR CODE ENDS HERE ..... 77 | 78 | class_name = input() 79 | 80 | cls = globals()[class_name] 81 | 82 | # Print the MRO sequence 83 | print(mro_sequence(cls)) -------------------------------------------------------------------------------- /gu-ito-2-14.py: -------------------------------------------------------------------------------- 1 | '''Design a Python program that uses multilevel inheritance to model the administrative divisions of Tamil Nadu. Tamil Nadu is divided into districts, and each district is divided into cities. All divisions have a name and a population. However, a district also has a number of cities, and Tamil Nadu has a number of districts. 2 | 3 | Create classes to represent Tamil Nadu, a district, and a city, and use multilevel inheritance to avoid code duplication. Write a method in each class to print the details of the division. 4 | 5 | Sample Input: 6 | 7 | Coimbatore, 1064000 8 | Coimbatore District, 3472578, 2 9 | Tamil Nadu, 77841267, 38 10 | 11 | Sample Output: 12 | 13 | City: Coimbatore, Population: 1064000 14 | District: Coimbatore District, Population: 3472578, Number of Cities: 2 15 | State: Tamil Nadu, Population: 77841267, Number of Districts: 38 16 | 17 | Explanation: 18 | 19 | Multilevel inheritance is used to model the hierarchical relationship between a state, its districts, and the cities within those districts. 20 | 21 | The City class is the base level in this hierarchy. It has properties like name and population. 22 | The District class inherits from the City class, making it the next level in the hierarchy. It has all the properties of a City, plus an additional property: the number of cities. When we create a District object and call its print_details() method, it prints the details specific to that district, including the number of cities. 23 | The TamilNadu class inherits from the District class, making it the top level in the hierarchy. It has all the properties of a District, plus an additional property: the number of districts. When we create a TamilNadu object and call its print_details() method, it prints the details specific to the state, including the number of districts. 24 | This is an example of multilevel inheritance, where a derived class inherits from a base class, which in turn inherits from another base class. In this case, TamilNadu is a derived class that inherits from District, which is a derived class that inherits from City. 25 | 26 | Constraints: 27 | 28 | The name of the city, district, or state is a string and can contain any printable ASCII characters. 29 | The population of the city, district, or state is an integer and can be any positive integer. 30 | The number of cities in a district is an integer and can be any positive integer. 31 | The number of districts in Tamil Nadu is an integer and can be any positive integer. 32 | ''' 33 | 34 | 35 | class City(): 36 | def __init__(self, name, population): 37 | #..... YOUR CODE STARTS HERE ..... 38 | self.name=name 39 | self.population=population 40 | 41 | 42 | #..... YOUR CODE ENDS HERE ..... 43 | 44 | def print_details(self): 45 | #..... YOUR CODE STARTS HERE ..... 46 | print(f"City: {self.name}, Population: {self.population}") 47 | 48 | 49 | #..... YOUR CODE ENDS HERE ..... 50 | 51 | 52 | class District(City): 53 | def __init__(self, name, population, num_cities): 54 | #..... YOUR CODE STARTS HERE ..... 55 | super().__init__(name,population) 56 | self.num_cities=num_cities 57 | 58 | 59 | #..... YOUR CODE ENDS HERE ..... 60 | 61 | def print_details(self): 62 | #..... YOUR CODE STARTS HERE ..... 63 | print(f"District: {self.name}, Population: {self.population}, Number of Cities: {self.num_cities}") 64 | 65 | 66 | #..... YOUR CODE ENDS HERE ..... 67 | 68 | 69 | class TamilNadu(District): 70 | def __init__(self, name, population, num_districts): 71 | #..... YOUR CODE STARTS HERE ..... 72 | self.name=name 73 | self.population=population 74 | self.num_districts=num_districts 75 | 76 | 77 | #..... YOUR CODE ENDS HERE ..... 78 | 79 | def print_details(self): 80 | #..... YOUR CODE STARTS HERE ..... 81 | print(f"State: {self.name}, Population: {self.population}, Number of Districts: {self.num_districts}") 82 | 83 | 84 | #..... YOUR CODE ENDS HERE ..... 85 | 86 | def clean_input(value): 87 | return str(value.strip()) 88 | 89 | def main(): 90 | city_name, city_population = map(clean_input, input().strip().split(",")) 91 | city = City(city_name, int(city_population)) 92 | 93 | district_name, district_population, num_cities = map(clean_input, input().strip().split(",")) 94 | district = District(district_name, int(district_population), int(num_cities)) 95 | 96 | state_name, state_population, num_districts = map(clean_input, input().strip().split(",")) 97 | state = TamilNadu(state_name, int(state_population), int(num_districts)) 98 | 99 | city.print_details() 100 | district.print_details() 101 | state.print_details() 102 | 103 | 104 | if __name__ == "__main__": 105 | main() -------------------------------------------------------------------------------- /gu-ito-2-15.py: -------------------------------------------------------------------------------- 1 | '''Design a Python program for a bookstore that uses classes and inheritance. The bookstore sells two types of items: books and magazines. Both books and magazines have a title and a price. However, a book also has an author, while a magazine has an issue number. Create classes to represent both items and use inheritance to avoid code duplication. 2 | 3 | Write a method in each class to print the details of the book or magazine. Also, write a method in each class to change the price of the book or magazine. 4 | 5 | Sample Input: 6 | 7 | The Great Gatsby, F. Scott Fitzgerald, 15.99 8 | Time, 5.99, 23 9 | 12.99 10 | 4.99 11 | 12 | Sample Output: 13 | 14 | Book: The Great Gatsby by F. Scott Fitzgerald, priced at $15.99 15 | Magazine: Time, Issue No. 23, priced at $5.99 16 | Book: The Great Gatsby by F. Scott Fitzgerald, priced at $12.99 17 | Magazine: Time, Issue No. 23, priced at $4.99 18 | 19 | Explanation: 20 | 21 | In the sample output, each line represents the details of an item in the bookstore: 22 | 23 | The first line is the details of a book. It's "The Great Gatsby" by F. Scott Fitzgerald, priced at $15.99. 24 | The second line is the details of a magazine. It's "Time", Issue No. 23, priced at $5.99. 25 | The third line is the updated details of the book after changing the price. The price of "The Great Gatsby" has been updated to $12.99. 26 | The fourth line is the updated details of the magazine after changing the price. The price of "Time", Issue No. 23, has been updated to $4.99. 27 | These details are printed by calling the print_details() method of each item object. The method is defined in each class and prints the details specific to that item. 28 | 29 | This is an example of single level inheritance, where the Book and Magazine classes inherit from a common base class (Item). The base class defines properties and methods common to all items (like name and price), while the derived classes add properties and methods specific to books and magazines (like author and issue number). 30 | 31 | The change_price() method in each class demonstrates the concept of reusability in object-oriented programming. Instead of writing separate functions to change the price of a book and a magazine, we write a single method in the base class (Item) that both Book and Magazine inherit. This allows us to change the price of any item, regardless of whether it's a book or a magazine. 32 | 33 | Constraints: 34 | 35 | The title of the book or magazine is a string and can contain any printable ASCII characters. 36 | The author of the book is a string and can contain any printable ASCII characters. 37 | The issue number of the magazine is an integer and can be any positive integer. 38 | The price of the book or magazine is a float and can be any positive number. 39 | ''' 40 | 41 | class Item: 42 | def __init__(self, title, price): 43 | #..... YOUR CODE STARTS HERE ..... 44 | self.title=title 45 | self.price=price 46 | 47 | 48 | #..... YOUR CODE ENDS HERE ..... 49 | 50 | def change_price(self, new_price): 51 | #..... YOUR CODE STARTS HERE ..... 52 | self.new_price=new_price 53 | self.price=self.new_price 54 | 55 | 56 | #..... YOUR CODE ENDS HERE ..... 57 | 58 | def print_details(self): 59 | #..... YOUR CODE STARTS HERE ..... 60 | print(f"Item: {self.title}, priced at ${self.price}") 61 | 62 | 63 | #..... YOUR CODE ENDS HERE ..... 64 | 65 | 66 | class Book(Item): 67 | def __init__(self, title, author, price): 68 | #..... YOUR CODE STARTS HERE ..... 69 | super().__init__(title,price) 70 | self.author=author 71 | 72 | 73 | #..... YOUR CODE ENDS HERE ..... 74 | 75 | def print_details(self): 76 | #..... YOUR CODE STARTS HERE ..... 77 | print(f"Book: {self.title} by {self.author}, priced at ${self.price}") 78 | 79 | 80 | #..... YOUR CODE ENDS HERE ..... 81 | 82 | 83 | class Magazine(Item): 84 | def __init__(self, title, price, issue): 85 | #..... YOUR CODE STARTS HERE ..... 86 | super().__init__(title,price) 87 | self.issue=issue 88 | 89 | 90 | #..... YOUR CODE ENDS HERE ..... 91 | 92 | def print_details(self): 93 | #..... YOUR CODE STARTS HERE ..... 94 | print(f"Magazine: {self.title}, Issue No. {self.issue}, priced at ${self.price}") 95 | 96 | 97 | #..... YOUR CODE ENDS HERE ..... 98 | 99 | 100 | def clean_input(ip): 101 | return str(ip.strip()) 102 | 103 | book_title, book_author, book_price = map(clean_input, input().strip().split(",")) 104 | mz_title, mz_price, mz_issue = map(clean_input, input().strip().split(",")) 105 | 106 | book1 = Book(book_title, book_author, book_price) 107 | magazine1 = Magazine(mz_title, mz_price, mz_issue) 108 | 109 | # Printing initial details 110 | book1.print_details() 111 | magazine1.print_details() 112 | 113 | # Changing prices 114 | book1.change_price(input()) 115 | magazine1.change_price(input()) 116 | 117 | # Printing updated details 118 | book1.print_details() 119 | magazine1.print_details() -------------------------------------------------------------------------------- /gu-ito-2-16.py: -------------------------------------------------------------------------------- 1 | '''Design a Python program for an e-commerce platform that sells products. Each product on the platform has a name, price, and seller. There are two types of products: new and used. Used products have an additional attribute: condition. 2 | 3 | Create classes to represent a Product, NewProduct, and UsedProduct. Use inheritance and the super() function to avoid code duplication. Write a method in each class to print the details of the product. 4 | 5 | Sample Input: 6 | 7 | Laptop, 1200.99, ElectronicsHub 8 | Smartphone, 450.50, TechResell, Good 9 | 10 | Sample Output: 11 | 12 | New Product: Laptop, Price: $1200.99, Seller: ElectronicsHub 13 | Used Product: Smartphone, Price: $450.50, Seller: TechResell, Condition: Good 14 | 15 | Explanation: 16 | 17 | In the sample output, each line represents the details of a product: 18 | 19 | The first line is the details of a new product. It's a Laptop with a price of $1200.99 sold by ElectronicsHub. 20 | The second line is the details of a used product. It's a Smartphone with a price of $450.50 sold by TechResell and its condition is Good. 21 | These details are printed by calling the print_details() method of each product object. The method is defined in each class and prints the details specific to that product. 22 | 23 | This is an example of single level inheritance, where the NewProduct and UsedProduct classes inherit from a common base class (Product). The base class defines properties and methods common to all products (like name, price, and seller), while the derived classes add properties and methods specific to new and used products. The super() function is used to call a method in the parent class from the child class. 24 | 25 | Constraints: 26 | 27 | The name of the product and the seller is a string and can contain any printable ASCII characters. 28 | The price of the product is a float and can be any positive number. 29 | The condition of the used product is a string and can contain any printable ASCII characters.''' 30 | 31 | 32 | 33 | class Product: 34 | def __init__(self, name, price, seller): 35 | #..... YOUR CODE STARTS HERE ..... 36 | self.name=name 37 | self.price=price 38 | self.seller=seller 39 | 40 | 41 | #..... YOUR CODE ENDS HERE ..... 42 | 43 | def print_details(self): 44 | #..... YOUR CODE STARTS HERE ..... 45 | pass 46 | 47 | 48 | #..... YOUR CODE ENDS HERE ..... 49 | 50 | class NewProduct(Product): 51 | def print_details(self): 52 | #..... YOUR CODE STARTS HERE ..... 53 | return(f"New Product: {self.name}, Price: ${self.price}, Seller: {self.seller}") 54 | 55 | 56 | #..... YOUR CODE ENDS HERE ..... 57 | 58 | class UsedProduct(Product): 59 | def __init__(self, name, price, seller, condition): 60 | #..... YOUR CODE STARTS HERE ..... 61 | super().__init__(name,price,seller) 62 | self.condition=condition 63 | 64 | 65 | #..... YOUR CODE ENDS HERE ..... 66 | 67 | def print_details(self): 68 | #..... YOUR CODE STARTS HERE ..... 69 | return(f"Used Product: {self.name}, Price: ${self.price}, Seller: {self.seller}, Condition: {self.condition}") 70 | 71 | 72 | #..... YOUR CODE ENDS HERE ..... 73 | 74 | # Get input from the user 75 | product1_info = input().split(", ") 76 | product2_info = input().split(", ") 77 | 78 | # Create product objects 79 | product1 = NewProduct(*product1_info) 80 | if len(product2_info) == 4: 81 | product2 = UsedProduct(*product2_info) 82 | else: 83 | product2 = None 84 | 85 | # Print details 86 | print(product1.print_details()) 87 | if product2: 88 | print(product2.print_details()) -------------------------------------------------------------------------------- /gu-ito-2-17.py: -------------------------------------------------------------------------------- 1 | '''You are developing a Python program for managing various shapes in a geometry application. The program should support different types of shapes, such as circles, rectangles, and triangles. Each shape has its own unique attributes and methods. 2 | 3 | Write a Python script that demonstrates method overloading in the context of different shape classes. Your program should accomplish the following tasks: 4 | 5 | Define a base class called Shape. 6 | Implement different subclasses for various shapes, such as Circle, Rectangle, and Triangle. 7 | Each shape class should have methods to calculate its area and perimeter. 8 | Demonstrate method overloading by implementing different versions of the area and perimeter methods for each shape class. 9 | Ensure the following operations can be performed: 10 | 11 | Calculate the area and perimeter of a circle. 12 | Calculate the area and perimeter of a rectangle. 13 | Calculate the area and perimeter of a triangle. 14 | Your program should continuously prompt the user for shape inputs until the "quit" command is entered. 15 | 16 | Provide appropriate error handling for invalid inputs. Display a message in the following format for invalid inputs: "Invalid input. Please enter a valid shape (circle/rectangle/triangle)." 17 | 18 | Sample Input: 19 | 20 | circle 21 | 5 22 | rectangle 23 | 4 6 24 | triangle 25 | 3 4 5 26 | quit 27 | 28 | Sample Output: 29 | 30 | Area of the circle: 78.54 31 | Perimeter of the circle: 31.42 32 | Area of the rectangle: 24.0 33 | Perimeter of the rectangle: 20.0 34 | Area of the triangle: 6.0 35 | Perimeter of the triangle: 12.0 36 | Quitting the program. 37 | 38 | Explanation: 39 | 40 | The user selects a shape and provides the necessary dimensions. 41 | The program calculates the area and perimeter based on the provided inputs and shape type. 42 | The process continues until the user enters "quit." If the user enters an invalid shape, an appropriate error message is displayed. 43 | ''' 44 | 45 | 46 | 47 | import math 48 | 49 | class Shape: 50 | #..... YOUR CODE STARTS HERE ..... 51 | def area(self): 52 | pass 53 | 54 | def perimeter(self): 55 | pass 56 | 57 | 58 | #..... YOUR CODE ENDS HERE ..... 59 | 60 | class Circle(Shape): 61 | #..... YOUR CODE STARTS HERE ..... 62 | 63 | def area(self,radius): 64 | self.radius=radius 65 | return math.pi*self.radius*self.radius 66 | 67 | def perimeter(self,radius): 68 | self.radius=radius 69 | return (2*math.pi*self.radius) 70 | 71 | 72 | #..... YOUR CODE ENDS HERE ..... 73 | 74 | class Rectangle(Shape): 75 | #..... YOUR CODE STARTS HERE ..... 76 | 77 | def area(self,lenght,breath): 78 | self.lenght=lenght 79 | self.breath=breath 80 | return self.lenght*self.breath 81 | 82 | def perimeter(self,lenght,breath): 83 | self.lenght=lenght 84 | self.breath=breath 85 | return (2*(self.lenght+self.breath)) 86 | 87 | 88 | 89 | #..... YOUR CODE ENDS HERE ..... 90 | 91 | class Triangle(Shape): 92 | #..... YOUR CODE STARTS HERE ..... 93 | def perimeter(self,a,b,c): 94 | self.a=a 95 | self.b=b 96 | self.c=c 97 | return self.a+self.b+self.c 98 | 99 | def area(self,a,b,c): 100 | self.a=a 101 | self.b=b 102 | self.c=c 103 | s= (self.a+self.b+self.c)/2 104 | return (math.sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))) 105 | 106 | 107 | #..... YOUR CODE ENDS HERE ..... 108 | 109 | def main(): 110 | shape_classes = {'circle': Circle(), 'rectangle': Rectangle(), 'triangle': Triangle()} 111 | while True: 112 | shape = input().lower() 113 | if shape == 'quit': 114 | print("Quitting the program.") 115 | break 116 | elif shape not in shape_classes: 117 | print("Invalid input. Please enter a valid shape (circle/rectangle/triangle).") 118 | continue 119 | 120 | dimensions = list(map(float, input().split())) 121 | print("Area of the {}: {:.2f}".format(shape, shape_classes[shape].area(*dimensions))) 122 | print("Perimeter of the {}: {:.2f}".format(shape, shape_classes[shape].perimeter(*dimensions))) 123 | 124 | if __name__ == "__main__": 125 | main() -------------------------------------------------------------------------------- /gu-ito-2-18.py: -------------------------------------------------------------------------------- 1 | '''You are tasked with creating a Python program to manage the borrowing of resources from a library. The library offers both books and DVDs. Write a Python script that allows users to borrow items from the library. Faculty members can only borrow DVDs, while students can borrow both books and DVDs. 2 | 3 | Here are the operations the program should support: 4 | 5 | Allow a user to borrow an item from the library. 6 | Display a message indicating whether the borrowing was successful or not, based on the user's status and the type of item they are trying to borrow. 7 | Quit the program. 8 | Ensure the following message formats: 9 | 10 | For borrowing a book: Book "{book_title}" successfully borrowed by {self.name}. 11 | For borrowing a DVD by a faculty member: DVD "{title}" successfully borrowed by {self.name}. 12 | For informing a faculty member that they can only borrow DVDs: Faculty members can only borrow DVDs. 13 | Please enter the following details for borrowing: 14 | 15 | Name of the borrower 16 | Status of the borrower (faculty/student) 17 | Title of the item to borrow 18 | Sample Input: 19 | 20 | Alice 21 | faculty 22 | The Great Gatsby 23 | quit 24 | 25 | Sample Output: 26 | 27 | Faculty members can only borrow DVDs. 28 | Quitting the program. 29 | 30 | Explanation: 31 | 32 | Alice, a faculty member, attempts to borrow "The Great Gatsby", which is a book. However, the program informs her that faculty members can only borrow DVDs. Then, the program quits as Alice does not attempt any further operations. Please ensure to include "DVD" in the title if you want to borrow a DVD, as shown in the sample input. 33 | 34 | ''' 35 | 36 | 37 | 38 | 39 | class User: 40 | def __init__(self, name, user_type): 41 | #..... YOUR CODE STARTS HERE ..... 42 | self.name=name 43 | self.user_type=user_type 44 | 45 | 46 | #..... YOUR CODE ENDS HERE ..... 47 | 48 | def borrow_book(self, book_title): 49 | #..... YOUR CODE STARTS HERE ..... 50 | self.book_title=book_title 51 | return f'Book \"{self.book_title}\" successfully borrowed by {self.name}.' 52 | 53 | #..... YOUR CODE ENDS HERE ..... 54 | 55 | class Faculty(User): 56 | def __init__(self, name): 57 | #..... YOUR CODE STARTS HERE ..... 58 | self.name=name 59 | 60 | 61 | #..... YOUR CODE ENDS HERE ..... 62 | 63 | def borrow_book(self, title): 64 | #..... YOUR CODE STARTS HERE ..... 65 | self.title=title 66 | return f'DVD \"{self.title}\" successfully borrowed by {self.name}.' 67 | 68 | #..... YOUR CODE ENDS HERE ..... 69 | 70 | def main(): 71 | while True: 72 | name = input() 73 | user_type = input().lower() 74 | if user_type == "faculty": 75 | user = Faculty(name) 76 | else: 77 | user = User(name, user_type) 78 | 79 | item_title = input() 80 | if user_type == "faculty": 81 | if "DVD" in item_title: 82 | print(user.borrow_book(item_title)) 83 | else: 84 | print("Faculty members can only borrow DVDs.") 85 | else: 86 | print(user.borrow_book(item_title)) 87 | 88 | choice = input().lower() 89 | if choice != "yes": 90 | print("Quitting the program.") 91 | break 92 | 93 | if __name__ == "__main__": 94 | main() -------------------------------------------------------------------------------- /gu-ito-2-19.py: -------------------------------------------------------------------------------- 1 | '''You're developing a Python program for a virtual pet simulation game. The game features various types of pets, each with its own unique abilities and needs. You need to implement a system to manage different types of pets and their actions. The program should support pets such as cats, dogs, and birds. 2 | 3 | Write a Python script that demonstrates method overloading in the context of different pet classes. Your program should accomplish the following tasks: 4 | 5 | Define a base class called Pet. 6 | Implement different subclasses for various types of pets, such as Cat, Dog, and Bird. 7 | Each pet class should have methods to perform actions such as eating, sleeping, and making sounds. 8 | Demonstrate method overloading by implementing different versions of the eat(), sleep(), and make_sound() methods for each pet class. 9 | Additionally, integrate some unique behaviors for each type of pet: 10 | 11 | Cats should be able to purr when making a sound. 12 | Dogs should be able to wag their tails when making a sound. 13 | Birds should be able to chirp when making a sound. 14 | Ensure the following operations can be performed: 15 | 16 | Feed a pet and display a message indicating it's eating. 17 | Put a pet to sleep and display a message indicating it's sleeping. 18 | Prompt a pet to make a sound and display the appropriate message based on its type. 19 | Your program should continuously prompt the user for pet actions until the "quit" command is entered. 20 | 21 | Provide appropriate error handling for invalid inputs. Display a message in the following format for invalid inputs: "Invalid input. Please enter a valid action (feed/sleep/make_sound/quit)." 22 | 23 | Sample Input: 24 | 25 | cat 26 | eat 27 | dog 28 | make_sound 29 | bird 30 | sleep 31 | quit 32 | 33 | Sample Output: 34 | 35 | Cat is eating. 36 | Dog is wagging its tail. 37 | Bird is sleeping. 38 | Quitting the program. 39 | 40 | Explanation: 41 | 42 | The user selects a pet and an action to perform. 43 | The program executes the action based on the selected pet type and displays an appropriate message. 44 | The process continues until the user enters "quit." If the user enters an invalid action, an appropriate error message is displayed.''' 45 | 46 | 47 | 48 | class Pet: 49 | #..... YOUR CODE STARTS HERE ..... 50 | 51 | def eat(self): 52 | pass 53 | def sleep(self): 54 | pass 55 | def make_sound(self): 56 | pass 57 | 58 | #..... YOUR CODE ENDS HERE ..... 59 | 60 | 61 | class Cat(Pet): 62 | #..... YOUR CODE STARTS HERE ..... 63 | def eat(self): 64 | print("Cat is eating.") 65 | def sleep(self): 66 | print("Cat is sleeping.") 67 | def make_sound(self): 68 | print("Cat is purring.") 69 | 70 | 71 | #..... YOUR CODE ENDS HERE ..... 72 | 73 | class Dog(Pet): 74 | #..... YOUR CODE STARTS HERE ..... 75 | def eat(self): 76 | print("Dog is eating.") 77 | def sleep(self): 78 | print("Dog is sleeping.") 79 | def make_sound(self): 80 | print("Dog is wagging its tail.") 81 | 82 | 83 | #..... YOUR CODE ENDS HERE ..... 84 | 85 | class Bird(Pet): 86 | #..... YOUR CODE STARTS HERE ..... 87 | def eat(self): 88 | print("Bird is eating.") 89 | def sleep(self): 90 | print("Bird is sleeping.") 91 | def make_sound(self): 92 | print("Bird is chirping.") 93 | 94 | 95 | #..... YOUR CODE ENDS HERE ..... 96 | 97 | def main(): 98 | while True: 99 | pet_type = input("").lower() 100 | if pet_type == 'quit': 101 | print("Quitting the program.") 102 | break 103 | elif pet_type not in ['cat', 'dog', 'bird']: 104 | print("Invalid input. Please enter a valid pet type (cat/dog/bird).") 105 | continue 106 | 107 | pet_action = input("").lower() 108 | if pet_action == 'quit': 109 | print("Quitting the program.") 110 | break 111 | elif pet_action not in ['eat', 'sleep', 'make_sound']: 112 | print("Invalid input. Please enter a valid action (eat/sleep/make_sound/quit).") 113 | continue 114 | 115 | if pet_type == 'cat': 116 | cat = Cat() 117 | if pet_action == 'eat': 118 | cat.eat() # Output: "Cat is eating." 119 | elif pet_action == 'sleep': 120 | cat.sleep() # Output: "Cat is sleeping." 121 | elif pet_action == 'make_sound': 122 | cat.make_sound() # Output: "Cat is purring." 123 | elif pet_type == 'dog': 124 | dog = Dog() 125 | if pet_action == 'eat': 126 | dog.eat() # Output: "Dog is eating." 127 | elif pet_action == 'sleep': 128 | dog.sleep() # Output: "Dog is sleeping." 129 | elif pet_action == 'make_sound': 130 | dog.make_sound() # Output: "Dog is wagging its tail." 131 | elif pet_type == 'bird': 132 | bird = Bird() 133 | if pet_action == 'eat': 134 | bird.eat() # Output: "Bird is eating." 135 | elif pet_action == 'sleep': 136 | bird.sleep() # Output: "Bird is sleeping." 137 | elif pet_action == 'make_sound': 138 | bird.make_sound() # Output: "Bird is chirping." 139 | 140 | if __name__ == "__main__": 141 | main() -------------------------------------------------------------------------------- /gu-ito-2-2.py: -------------------------------------------------------------------------------- 1 | '''In a B.Tech course, there are several subjects, each with a different method of evaluation. Some subjects have lab work, some have project work, and some have only theory exams. Define an interface Subject with the methods has_lab(), has_project(), and get_theory_marks(). Then, define three classes LabSubject, ProjectSubject, and TheorySubject that implement this interface according to the following rules: 2 | 3 | LabSubject returns True for has_lab(), False for has_project(), and a fixed score of 70 for get_theory_marks(). 4 | ProjectSubject returns False for has_lab(), True for has_project(), and a fixed score of 80 for get_theory_marks(). 5 | TheorySubject returns False for both has_lab() and has_project(), and a fixed score of 90 for get_theory_marks(). 6 | Sample Input: 7 | 8 | LabSubject().has_lab() 9 | ProjectSubject().has_project() 10 | TheorySubject().get_theory_marks() 11 | 12 | Sample Output: 13 | 14 | True 15 | True 16 | 90 17 | 18 | Explanation: 19 | 20 | The LabSubject class returns True for has_lab(), indicating that the subject has lab work. The ProjectSubject class returns True for has_project(), indicating that the subject has project work. The TheorySubject class returns 90 for get_theory_marks(), indicating that the theory marks for the subject are 90.''' 21 | 22 | 23 | 24 | 25 | from abc import ABC, abstractmethod 26 | 27 | class Subject(ABC): 28 | #..... YOUR CODE STARTS HERE ..... 29 | 30 | @abstractmethod 31 | def has_lab(self): 32 | pass 33 | @abstractmethod 34 | def has_project(self): 35 | pass 36 | @abstractmethod 37 | def get_theory_marks(self): 38 | pass 39 | 40 | #..... YOUR CODE ENDS HERE ..... 41 | 42 | class LabSubject(Subject): 43 | def has_lab(self): 44 | #..... YOUR CODE STARTS HERE ..... 45 | 46 | return True 47 | 48 | #..... YOUR CODE ENDS HERE ..... 49 | 50 | def has_project(self): 51 | #..... YOUR CODE STARTS HERE ..... 52 | 53 | return False 54 | 55 | #..... YOUR CODE ENDS HERE ..... 56 | 57 | def get_theory_marks(self): 58 | #..... YOUR CODE STARTS HERE ..... 59 | 60 | return 70 61 | 62 | #..... YOUR CODE ENDS HERE ..... 63 | 64 | class ProjectSubject(Subject): 65 | def has_lab(self): 66 | #..... YOUR CODE STARTS HERE ..... 67 | 68 | return False 69 | 70 | #..... YOUR CODE ENDS HERE ..... 71 | 72 | def has_project(self): 73 | #..... YOUR CODE STARTS HERE ..... 74 | 75 | return True 76 | 77 | #..... YOUR CODE ENDS HERE ..... 78 | 79 | def get_theory_marks(self): 80 | #..... YOUR CODE STARTS HERE ..... 81 | 82 | return 80 83 | 84 | #..... YOUR CODE ENDS HERE ..... 85 | 86 | class TheorySubject(Subject): 87 | def has_lab(self): 88 | #..... YOUR CODE STARTS HERE ..... 89 | 90 | return False 91 | 92 | #..... YOUR CODE ENDS HERE ..... 93 | 94 | def has_project(self): 95 | #..... YOUR CODE STARTS HERE ..... 96 | 97 | return False 98 | 99 | #..... YOUR CODE ENDS HERE ..... 100 | 101 | def get_theory_marks(self): 102 | #..... YOUR CODE STARTS HERE ..... 103 | 104 | return 90 105 | 106 | #..... YOUR CODE ENDS HERE ..... 107 | 108 | def call_func(cls, func): 109 | value = None 110 | 111 | if (func == "has_lab()"): 112 | value = cls.has_lab() 113 | 114 | elif(func == "has_project()"): 115 | value = cls.has_project() 116 | 117 | elif(func == "get_theory_marks()"): 118 | value = cls.get_theory_marks() 119 | 120 | return value 121 | 122 | # Getting input from the user 123 | lab_class, lab_func = input().strip().split(".") 124 | project_class, project_func = input().strip().split(".") 125 | theory_class, theory_func = input().strip().split(".") 126 | 127 | if (lab_class == 'LabSubject()'): 128 | lab = LabSubject() 129 | print(call_func(lab, lab_func)) 130 | 131 | if(project_class == "ProjectSubject()"): 132 | project = ProjectSubject() 133 | print(call_func(project, project_func)) 134 | 135 | if(theory_class == "TheorySubject()"): 136 | theory = TheorySubject() 137 | print(call_func(theory, theory_func)) -------------------------------------------------------------------------------- /gu-ito-2-3.py: -------------------------------------------------------------------------------- 1 | '''In a school, there are several types of staff members: Teachers, Janitors, and Administrators. All staff members have a method get_salary() that returns their monthly salary. However, the salary is calculated differently for each type of staff member. For Teachers, the salary is a fixed amount of $3000. For Janitors, the salary is a fixed amount of $2000. For Administrators, the salary is a fixed amount of $4000. 2 | 3 | Write a Python program that defines an abstract class StaffMember with the abstract method get_salary(). Then, define three classes Teacher, Janitor, and Administrator that inherit from the StaffMember class and implement the get_salary() method. 4 | 5 | Sample Input: 6 | 7 | Teacher().get_salary() 8 | Janitor().get_salary() 9 | Administrator().get_salary() 10 | 11 | Sample Output: 12 | 13 | 3000 14 | 2000 15 | 4000 16 | 17 | Explanation: 18 | 19 | In this sample, the Teacher class returns a salary of $3000, the Janitor class returns a salary of $2000, and the Administrator class returns a salary of $4000. This demonstrates how each class correctly implements the get_salary() method from the StaffMember abstract base class.''' 20 | 21 | 22 | 23 | from abc import ABC, abstractmethod 24 | 25 | class StaffMember(ABC): 26 | @abstractmethod 27 | def get_salary(self): 28 | pass 29 | 30 | #..... YOUR CODE STARTS HERE ..... 31 | 32 | class Teacher(StaffMember): 33 | def get_salary(self): 34 | return 3000 35 | 36 | class Janitor(StaffMember): 37 | def get_salary(self): 38 | return 2000 39 | 40 | class Administrator(StaffMember): 41 | def get_salary(self): 42 | return 4000 43 | #..... YOUR CODE ENDS HERE ..... 44 | 45 | def call_func(cls, func): 46 | value = None 47 | cls_obj = None 48 | 49 | if (cls == "Teacher()"): 50 | cls_obj = Teacher() 51 | 52 | elif(cls == "Janitor()"): 53 | cls_obj = Janitor() 54 | 55 | elif(cls == "Administrator()"): 56 | cls_obj = Administrator() 57 | 58 | if (func == "get_salary()"): 59 | value = cls_obj.get_salary() 60 | 61 | return value 62 | 63 | for _ in range(3): 64 | cls, func = input().strip().split(".") 65 | print(call_func(cls, func)) -------------------------------------------------------------------------------- /gu-ito-2-4.py: -------------------------------------------------------------------------------- 1 | '''In a sports team, each player has a name and a number of goals scored. The number of goals scored should always be a non-negative integer. If a negative value or a non-integer value is assigned to the number of goals, it should be automatically set to 0. 2 | 3 | Please write a Python class Player that has name and goals as attributes. Use the property decorator to ensure that goals is always a non-negative integer. 4 | 5 | Sample Input 1: 6 | 7 | John, 5 8 | 10 9 | 10 | Sample Output 1: 11 | 12 | John 13 | 5 14 | 10 15 | 16 | Sample Input 2: 17 | 18 | John, 10 19 | -5 20 | 21 | Sample Output 2: 22 | 23 | John 24 | 10 25 | 0 26 | 27 | Explanation: 28 | 29 | In the sample input, a Player object is created with the name "John" and 5 goals. The goals property is then updated to 10, -5, and "hello". When the goals property is set to a negative value or a non-integer value, the goals.setter method automatically sets goals to 0. This is why the output is 5, 10, 0, 0. This demonstrates how the property decorator can be used to control the values of an attribute.''' 30 | 31 | 32 | 33 | 34 | class Player: 35 | def __init__(self, name, goals=0): 36 | #..... YOUR CODE STARTS HERE ..... 37 | self._name=name 38 | self._goals=0 39 | self.goals = goals 40 | 41 | @property 42 | def goals(self): 43 | return self._goals 44 | 45 | #..... YOUR CODE ENDS HERE ..... 46 | 47 | #..... YOUR CODE STARTS HERE ..... 48 | @goals.setter 49 | def goals(self, value): 50 | try: 51 | value = int(value) 52 | if value < 0: 53 | self._goals=0 54 | else: 55 | self._goals=value 56 | 57 | except ValueError: 58 | self._goals=0 59 | 60 | 61 | @property 62 | def name(self): 63 | return self._name 64 | 65 | 66 | #..... YOUR CODE ENDS HERE ..... 67 | 68 | def clean_input(value): 69 | return str(value.strip()) 70 | 71 | name, goal = map(clean_input, input().strip().split(",")) 72 | next_goal = input() 73 | 74 | player = Player(name, goal) 75 | print(name) 76 | print(player.goals) 77 | player.goals =next_goal 78 | print(player.goals) -------------------------------------------------------------------------------- /gu-ito-2-5.py: -------------------------------------------------------------------------------- 1 | '''You are developing a book management system for a bookstore. The system has a function get_book_details(isbn: str) -> dict that takes an ISBN number as input and returns a dictionary with book details. The dictionary contains the following keys: 'title', 'author', 'price', and 'quantity'. 2 | 3 | The bookstore has the following books: 4 | 5 | "Python Programming" by John Doe, ISBN: "1234567890", Price: 500, Quantity: 10 6 | "Data Structures and Algorithms" by Jane Doe, ISBN: "9876543210", Price: 600, Quantity: 5 7 | "Machine Learning" by Sam Smith, ISBN: "1111111111", Price: 700, Quantity: 2 8 | However, not all books are available in the store at all times. If a book is not available, the function should raise a ValueError with a message "Book not found". 9 | 10 | Write a Python function handle_book_request(isbn: str) -> str that calls get_book_details(isbn: str) -> dict and handles any ValueError that might be raised. The function should return a string message about the status of the request. 11 | 12 | If the book is found, the function should return a message in the following format: "Book found: {title} by {author}. Price: {price}, Quantity: {quantity}". If the book is not found, it should return the message "Book not found". 13 | 14 | Constraints: 15 | 16 | ISBN is a string of length 10 or 13. 17 | The title, author are strings and price, quantity are integers. 18 | You can't install any external libraries. 19 | Sample Input: 20 | 21 | 1234567890 22 | 23 | Sample Output: 24 | 25 | Book found: Python Programming by John Doe. Price: 500, Quantity: 10 26 | 27 | Explanation: 28 | 29 | In the sample output, that message is returned when the book is found in the bookstore. The details of the book, including the title, author, price, and quantity, are displayed in the message. This is done by catching the book details returned by the get_book_details function in a try block. 30 | 31 | A message, "Book not found", is returned If the book is not found in the bookstore. This happens when the get_book_details function raises a ValueError. In the except block, this error is caught and the error message is returned. This demonstrates how error handling works in Python - when an error occurs, instead of the program crashing, the error is caught and handled gracefully. In this case, a meaningful message is returned to the user. This is a key aspect of robust software design.''' 32 | 33 | 34 | def get_book_details(isbn): 35 | books = { 36 | "1234567890": {"title": "Python Programming", "author": "John Doe", "price": 500, "quantity": 10}, 37 | "9876543210": {"title": "Data Structures and Algorithms", "author": "Jane Doe", "price": 600, "quantity": 5}, 38 | "1111111111": {"title": "Machine Learning", "author": "Sam Smith", "price": 700, "quantity": 2}, 39 | } 40 | if isbn in books: 41 | return books[isbn] 42 | else: 43 | raise ValueError("Book not found") 44 | 45 | def handle_book_request(isbn): 46 | #..... YOUR CODE STARTS HERE ..... 47 | try: 48 | book = get_book_details(isbn) 49 | return f"Book found: {book['title']} by {book['author']}. Price: {book['price']}, Quantity: {book['quantity']}" 50 | except ValueError: 51 | return "Book not found" 52 | 53 | #..... YOUR CODE ENDS HERE ..... 54 | 55 | isbn = input() 56 | response = handle_book_request(isbn) 57 | print(response) -------------------------------------------------------------------------------- /gu-ito-2-6.py: -------------------------------------------------------------------------------- 1 | '''You are developing a product management system for an e-commerce platform. The system has a function get_product_details(product_id: str) -> dict that takes a product ID as input and returns a dictionary with product details. The dictionary contains the following keys: 'name', 'category', 'price', and 'stock'. 2 | 3 | The e-commerce platform has the following products: 4 | 5 | "Wireless Mouse", Product ID: "123456", Category: "Electronics", Price: 500, Stock: 10 6 | "Running Shoes", Product ID: "789012", Category: "Sports", Price: 600, Stock: 5 7 | "Coffee Maker", Product ID: "345678", Category: "Home Appliances", Price: 700, Stock: 2 8 | However, not all products are available on the platform at all times. If a product is not available, the function should raise an Exception with a message "Product not found". 9 | 10 | Write a Python function handle_product_request(product_id: str) -> str that calls get_product_details(product_id: str) -> dict and handles any Exception that might be raised. The function should return a string message about the status of the request. 11 | 12 | If the product is found, the function should return a message in the following format: "Product found: {name}, Category: {category}, Price: {price}, Stock: {stock}". If the product is not found, it should return the message "Product not found". 13 | 14 | Constraints: 15 | 16 | Product ID is a string of length 6. 17 | The name, category are strings and price, stock are integers. 18 | You can't install any external libraries. 19 | Sample Input: 20 | 21 | 901234 22 | 23 | Sample Output: 24 | 25 | Request handled 26 | Product not found 27 | 28 | Explanation: 29 | 30 | "Product not found": This message is returned when the product with the ID "901234" is not found on the platform. In this case, the get_product_details function raises an Exception with the message "Product not found". This exception is caught in the handle_product_request function and the error message is returned. This demonstrates how exception handling works in Python - when an exception occurs, instead of the program crashing, the exception is caught and handled gracefully. In this case, a meaningful message is returned to the user. 31 | In all cases, the finally block is executed after the try and except blocks, indicating that the product request has been processed (Request handled), regardless of whether an exception was raised or not. This is a key aspect of robust software design and demonstrates the use of the finally keyword in Python exception handling.''' 32 | 33 | 34 | 35 | def get_product_details(product_id): 36 | products = { 37 | "123456": {"name": "Wireless Mouse", "category": "Electronics", "price": 500, "stock": 10}, 38 | "789012": {"name": "Running Shoes", "category": "Sports", "price": 600, "stock": 5}, 39 | "345678": {"name": "Coffee Maker", "category": "Home Appliances", "price": 700, "stock": 2}, 40 | } 41 | if product_id in products: 42 | return products[product_id] 43 | else: 44 | raise Exception("Product not found") 45 | 46 | def handle_product_request(product_id): 47 | #..... YOUR CODE STARTS HERE ..... 48 | print ("Request handled") 49 | try: 50 | product = get_product_details(product_id) 51 | return f"Product found: {product['name']}, Category: {product['category']}, Price: {product['price']}, Stock: {product['stock']}" 52 | except: 53 | return "Product not found" 54 | 55 | 56 | 57 | #..... YOUR CODE ENDS HERE ..... 58 | 59 | # Get input from the user 60 | user_input = input() 61 | 62 | # Call the handle_product_request function with user input 63 | result = handle_product_request(user_input) 64 | print(result) 65 | -------------------------------------------------------------------------------- /gu-ito-2-7.py: -------------------------------------------------------------------------------- 1 | '''You are developing a simple calculator in Python. The calculator has a function calculate(operation: str, num1: float, num2: float) -> float that takes an operation and two numbers as input and returns the result of the operation. The operation can be one of the following: 'add', 'subtract', 'multiply', 'divide'. 2 | 3 | However, not all operations are valid. If an invalid operation is passed, the function should raise a ValueError with a message "Invalid operation". 4 | 5 | Also, if the operation is 'divide' and the second number is 0, the function should raise a ZeroDivisionError with a message "Cannot divide by zero". 6 | 7 | Write a Python function handle_calculation(operation: str, num1: float, num2: float) -> str that calls calculate(operation: str, num1: float, num2: float) -> float and handles any ValueError or ZeroDivisionError that might be raised. The function should return a string message about the status of the calculation. 8 | 9 | Constraints: 10 | 11 | num1 and num2 are floats. 12 | You can't install any external libraries. 13 | Sample Input: 14 | 15 | add, 1.0, 2.0 16 | 17 | Sample Output: 18 | 19 | Result: 3.0 20 | 21 | Explanation: 22 | 23 | The result of the operation is displayed in the message.''' 24 | 25 | 26 | def calculate(operation, num1, num2): 27 | if operation == 'add': 28 | return num1 + num2 29 | elif operation == 'subtract': 30 | return num1 - num2 31 | elif operation == 'multiply': 32 | return num1 * num2 33 | elif operation == 'divide': 34 | if num2 == 0: 35 | raise ZeroDivisionError("Cannot divide by zero") 36 | return num1 / num2 37 | else: 38 | raise ValueError("Invalid operation") 39 | 40 | def handle_calculation(operation, num1, num2): 41 | #..... YOUR CODE STARTS HERE ..... 42 | try: 43 | ans = calculate(operation, num1, num2) 44 | return f"Result: {ans}" 45 | except ZeroDivisionError: 46 | print("Cannot divide by zero") 47 | except ValueError: 48 | print("Invalid operation") 49 | 50 | 51 | 52 | #..... YOUR CODE ENDS HERE ..... 53 | 54 | def main(): 55 | inputs = input() 56 | operation, num1, num2 = map(str.strip, inputs.split(",")) 57 | num1 = float(num1) 58 | num2 = float(num2) 59 | 60 | message = handle_calculation(operation, num1, num2) 61 | print(message) 62 | 63 | if __name__ == "__main__": 64 | main() -------------------------------------------------------------------------------- /gu-ito-2-8.py: -------------------------------------------------------------------------------- 1 | '''You are developing a stock management system for a market. The system has a function get_stock(item: str) -> int that takes an item name as input and returns the quantity of that item in stock. 2 | 3 | The market has the following items in stock: 4 | 5 | "Apples" - 50 6 | "Oranges" - 30 7 | "Grapes" - 0 8 | However, not all items are available in the market at all times. If an item is not available, the function should raise a custom exception ItemNotFoundError with a message "Item not found". 9 | 10 | Write a Python function handle_stock_request(item: str) -> str that calls get_stock(item: str) -> int and handles any ItemNotFoundError that might be raised. The function should return a string message about the status of the request. 11 | 12 | If the item is found and the stock is greater than 0, the function should return a message in the following format: "Stock for {item}: {stock}". If the item is not found or the stock is 0, it should return the message "Item not found". 13 | 14 | Constraints: 15 | 16 | Item is a string. 17 | You can't install any external libraries. 18 | Sample Input: 19 | 20 | Apples 21 | 22 | Sample Output: 23 | 24 | Stock for Apples: 50 25 | 26 | Explanation: 27 | 28 | In the sample outputs, the message is returned when the item is found in the market and the stock is greater than 0. The stock quantity of the item is displayed in the message. This is done by catching the stock quantity returned by the get_stock function in a try block.''' 29 | 30 | 31 | 32 | 33 | class ItemNotFoundError(Exception): 34 | pass 35 | 36 | def get_stock(item): 37 | stock = { 38 | "Apples": 50, 39 | "Oranges": 30, 40 | "Grapes": 0, 41 | } 42 | if item in stock: 43 | return stock[item] 44 | else: 45 | raise ItemNotFoundError("Item not found") 46 | 47 | def handle_stock_request(item): 48 | #..... YOUR CODE STARTS HERE ..... 49 | try: 50 | stock = get_stock(item) 51 | return f"Stock for {item}: {stock}" 52 | except ItemNotFoundError: 53 | return "Item not found" 54 | 55 | 56 | 57 | #..... YOUR CODE ENDS HERE ..... 58 | 59 | user_input = input() 60 | 61 | print(handle_stock_request(user_input)) -------------------------------------------------------------------------------- /gu-ito-2-9.py: -------------------------------------------------------------------------------- 1 | '''Design a Python program that uses multiple inheritance to model an e-commerce platform. The platform sells two types of products: physical products and digital products. Both types of products have a name and a price. However, a physical product also has a shipping weight, while a digital product has a file size. 2 | 3 | Create classes to represent both types of products and use multiple inheritance to create a third class that represents a product that is both physical and digital (for example, a video game that can be purchased as a physical disc or downloaded digitally). 4 | 5 | Write a method in each class to print the details of the product. 6 | 7 | Sample Input: 8 | 9 | Book, 9.99, 1.0 10 | Ebook, 6.99, 2 11 | Video Game, 59.99, 0.2, 25 12 | 13 | Sample Output: 14 | 15 | Physical Product: Book, Price: $9.99, Shipping Weight: 1.0 kg 16 | Digital Product: Ebook, Price: $6.99, File Size: 2 MB 17 | Hybrid Product: Video Game, Price: $59.99, Shipping Weight: 0.2 kg, File Size: 25 GB 18 | 19 | Explanation: 20 | 21 | In the sample output, each line represents the details of a product: 22 | 23 | The first line is the details of a physical product. It’s a book with a price of $9.99 and a shipping weight of 1.0 kg. 24 | The second line is the details of a digital product. It’s an Ebook with a price of $6.99 and a file size of 2 MB. 25 | The third line is the details of a hybrid product. It’s a video game with a price of $59.99, a shipping weight of 0.2 kg, and a file size of 25 GB. 26 | These details are printed by calling the print_details() method of each product object. The method is defined in each class and prints the details specific to that class. For the HybridProduct class, which inherits from both PhysicalProduct and DigitalProduct, the print_details() method prints the details of both the physical and digital aspects of the product. 27 | 28 | ''' 29 | 30 | class Product: 31 | def __init__(self, name, price): 32 | #..... YOUR CODE STARTS HERE ..... 33 | self.name= name 34 | self.price= price 35 | 36 | 37 | #..... YOUR CODE ENDS HERE ..... 38 | 39 | class PhysicalProduct(Product): 40 | def __init__(self, name, price, weight): 41 | #..... YOUR CODE STARTS HERE ..... 42 | 43 | self.weight= weight 44 | super().__init__(name,price) 45 | 46 | 47 | #..... YOUR CODE ENDS HERE ..... 48 | 49 | def print_details(self): 50 | #..... YOUR CODE STARTS HERE ..... 51 | print(f"Physical Product: {self.name}, Price: ${self.price}, Shipping Weight: {self.weight} kg") 52 | 53 | 54 | #..... YOUR CODE ENDS HERE ..... 55 | 56 | class DigitalProduct(Product): 57 | def __init__(self, name, price, file_size): 58 | #..... YOUR CODE STARTS HERE ..... 59 | self.name=name 60 | self.price=price 61 | self.file_size= file_size 62 | 63 | 64 | #..... YOUR CODE ENDS HERE ..... 65 | 66 | def print_details(self): 67 | #..... YOUR CODE STARTS HERE ..... 68 | print(f"Digital Product: {self.name}, Price: ${self.price}, File Size: {self.file_size} MB") 69 | 70 | 71 | #..... YOUR CODE ENDS HERE ..... 72 | 73 | class HybridProduct(PhysicalProduct, DigitalProduct): 74 | def __init__(self, name, price, weight, file_size): 75 | #..... YOUR CODE STARTS HERE ..... 76 | self.name=name 77 | self.price=price 78 | self.weight= weight 79 | self.file_size= file_size 80 | 81 | 82 | #..... YOUR CODE ENDS HERE ..... 83 | 84 | def print_details(self): 85 | #..... YOUR CODE STARTS HERE ..... 86 | print(f"Hybrid Product: {self.name}, Price: ${self.price}, Shipping Weight: {self.weight} kg, File Size: {self.file_size} GB") 87 | 88 | 89 | #..... YOUR CODE ENDS HERE ..... 90 | 91 | 92 | def clean_input(value): 93 | return str(value.strip()) 94 | 95 | 96 | if __name__ == '__main__': 97 | pp_name, pp_price, shipping_weight = map(clean_input, input().strip().split(',')) 98 | physical_product = PhysicalProduct(pp_name, pp_price, shipping_weight) 99 | 100 | dp_name, dp_price, file_size = map(clean_input, input().strip().split(',')) 101 | digital_product = DigitalProduct(dp_name, dp_price, file_size) 102 | 103 | hp_name, hp_price, hp_shipping_weight, hp_file_size = map(clean_input, input().strip().split(',')) 104 | hybrid_product = HybridProduct(hp_name, hp_price, hp_shipping_weight, hp_file_size) 105 | 106 | physical_product.print_details() 107 | digital_product.print_details() 108 | hybrid_product.print_details() -------------------------------------------------------------------------------- /gu-ito-2.py: -------------------------------------------------------------------------------- 1 | class Banks: 2 | def calculateCreditScore(self): 3 | pass 4 | 5 | class RBI(Banks): 6 | CREDIT = 0.10 7 | 8 | def __init__(self, accountNumber, creditScore, holderName): 9 | self.__accountNumber = accountNumber 10 | self.__creditScore = creditScore 11 | self.__holderName = holderName 12 | 13 | def calculateCreditScore(self, amount): 14 | #..... YOUR CODE STARTS HERE ..... 15 | credit_gained = amount * self.CREDIT 16 | self.__creditScore += credit_gained 17 | return credit_gained 18 | 19 | 20 | #..... YOUR CODE ENDS HERE ..... 21 | 22 | def display(self): 23 | print("Bank type: RBI") 24 | print("Account Number:", self.__accountNumber) 25 | print("Credit score:", "{:.2f}".format(self.__creditScore)) 26 | 27 | class ICICI(RBI): 28 | def __init__(self, accountNumber, creditScore, holderName): 29 | super().__init__(accountNumber, creditScore, holderName) 30 | 31 | def calculateCreditScore(self, amount): 32 | #..... YOUR CODE STARTS HERE ..... 33 | 34 | credit_gained = super().calculateCreditScore(amount) 35 | print("Hi,", self._RBI__holderName, "You have gained {:.2f} credit score for the payment of {:.1f} Your Total Credit Score is {:.2f}".format(credit_gained, amount, self._RBI__creditScore)) 36 | 37 | #..... YOUR CODE ENDS HERE ..... 38 | 39 | class HDFC(RBI): 40 | def __init__(self, accountNumber, creditScore, holderName): 41 | super().__init__(accountNumber, creditScore, holderName) 42 | 43 | def calculateCreditScore(self, amount): 44 | #..... YOUR CODE STARTS HERE ..... 45 | 46 | credit_gained = super().calculateCreditScore(amount) 47 | print("Hi,", self._RBI__holderName, "You have gained {:.2f} credit score for the payment of {:.1f} Your Total Credit Score is {:.2f}".format(credit_gained, amount, self._RBI__creditScore)) 48 | 49 | #..... YOUR CODE ENDS HERE ..... 50 | 51 | class Main: 52 | def __init__(self): 53 | input_data = input().split() 54 | bank = int(input_data[0]) 55 | holderName = input_data[1] 56 | accountNumber = input_data[2] 57 | previousCreditScore = float(input_data[3]) 58 | amount = float(input_data[4]) 59 | 60 | if bank == 1: 61 | icici = ICICI(accountNumber, previousCreditScore, holderName) 62 | icici.calculateCreditScore(amount) 63 | elif bank == 2: 64 | hdfc = HDFC(accountNumber, previousCreditScore, holderName) 65 | hdfc.calculateCreditScore(amount) 66 | else: 67 | print("Invalid bank selection") 68 | 69 | # Main program execution 70 | if __name__ == "__main__": 71 | Main() -------------------------------------------------------------------------------- /gu-ito-3-1.py: -------------------------------------------------------------------------------- 1 | '''You are a college professor and you have the scores of your students in a list. You want to find out which students have passed the course. A student passes the course if they score 60 or more. Write a Python function passed_students(scores) that takes a list of scores and returns a list of scores that are 60 or more. Use the filter function to filter out the passing scores. 2 | 3 | Input: 4 | 5 | scores: a list of integers representing the scores of the students. 6 | Output: 7 | 8 | The function should return a list of integers representing the scores of the students who have passed. 9 | Sample Input: 10 | 11 | [55, 60, 65, 70, 75, 80, 85, 90, 95, 100] 12 | 13 | Sample Output: 14 | 15 | [60, 65, 70, 75, 80, 85, 90, 95, 100] 16 | 17 | Explanation: 18 | 19 | The filter function applies a function to every item in the scores list and returns a new list with the items for which the function returns True. In this case, the function is a lambda function that checks if a score is 60 or more. This demonstrates how the filter function can be used to filter items in a list based on a condition. In the context of grading students in a college, this can be useful to find out which students have passed the course based on their scores. 20 | 21 | ''' 22 | 23 | 24 | import json 25 | from io import StringIO 26 | 27 | def passed_students(scores): 28 | #..... YOUR CODE STARTS HERE ..... 29 | 30 | return list(filter(lambda x: x >= 60, scores)) 31 | 32 | #..... YOUR CODE ENDS HERE ..... 33 | 34 | if __name__ == "__main__": 35 | scores = json.load(StringIO(input().strip())) 36 | passed_students = passed_students(scores) 37 | 38 | print(passed_students) 39 | -------------------------------------------------------------------------------- /gu-ito-3-10.py: -------------------------------------------------------------------------------- 1 | '''You are managing a bank's software system. Every time a customer makes a transaction, the transaction amount is recorded. You want to create a function that calculates the square root of the transaction amount. Write a Python function transaction_sqrt(transaction_amount) that takes a transaction amount and returns the square root of the transaction amount. Use the sqrt function from the built-in Python math module to calculate the square root. 2 | 3 | Input: 4 | 5 | transaction_amount: a float representing the transaction amount. 6 | Output: 7 | 8 | The function should return a float representing the square root of the transaction amount. 9 | Sample Input: 10 | 11 | 100.0 12 | 13 | Sample Output: 14 | 15 | 10.0 16 | 17 | Explanation : 18 | 19 | The sqrt function from the math module calculates the square root of a number. In the context of managing a bank's software system, this can be useful to perform various calculations related to the transaction amount.''' 20 | 21 | 22 | from math import sqrt 23 | 24 | def transaction_sqrt(transaction_amount): 25 | #..... YOUR CODE STARTS HERE ..... 26 | 27 | return sqrt(transaction_amount) 28 | 29 | #..... YOUR CODE ENDS HERE ..... 30 | 31 | transaction_amount = float(input()) 32 | result = transaction_sqrt(transaction_amount) 33 | print(result) -------------------------------------------------------------------------------- /gu-ito-3-11.py: -------------------------------------------------------------------------------- 1 | '''You are managing a bank's software system. You want to calculate the monthly interest for a given principal amount, rate of interest, and time period. Write a Python function calculate_interest(principal, rate, time) to calculate and return the monthly interest. 2 | 3 | Input: 4 | 5 | principal: a float representing the principal amount. 6 | rate: a float representing the annual rate of interest in percentage. 7 | time: an integer representing the time period in months. 8 | Output: 9 | 10 | The function should return a float representing the monthly interest. 11 | Sample Input: 12 | 13 | 1000.0, 5, 12 14 | 15 | Sample Output: 16 | 17 | 50.0 18 | 19 | Explanation: 20 | 21 | The calculate_interest function takes three parameters: principal, rate, and time, representing the principal amount, annual rate of interest (in percentage), and time period (in months) respectively. Inside the function, it first converts the annual rate to a monthly rate by dividing it by 100 and then by 12 (since there are 12 months in a year). 22 | Then, it calculates the monthly interest by multiplying the principal amount with the monthly rate and the time period.''' 23 | 24 | 25 | 26 | def calculate_interest(principal, rate, time): 27 | #..... YOUR CODE STARTS HERE ..... 28 | 29 | monthly_rate = rate / (100 * 12) # Convert annual rate to monthly rate 30 | monthly_interest = principal * monthly_rate * time 31 | return monthly_interest 32 | 33 | #..... YOUR CODE ENDS HERE ..... 34 | 35 | 36 | if __name__ == "__main__": 37 | principal, rate, time = list(map(float, input().strip().split(','))) 38 | 39 | # Calculate and print monthly interest 40 | print(calculate_interest(principal, rate, time)) -------------------------------------------------------------------------------- /gu-ito-3-12.py: -------------------------------------------------------------------------------- 1 | '''You are working on a Python project that involves performing complex mathematical operations. For this project, you need to calculate the square root of a list of transaction amounts. So write a Python function calculate_sqrt(transaction_amounts) that takes a list of transaction amounts and returns a list of their square roots. 2 | 3 | Sample Input: 4 | 5 | [100.0, 200.0, 300.0, 400.0] 6 | 7 | Sample Output: 8 | 9 | [10.0, 14.142135623730951, 17.320508075688775, 20.0] 10 | 11 | Explanation: 12 | 13 | The calculate_sqrt function uses the sqrt function from the math module to calculate the square root of each transaction amount. The square root of a number is a value that, when multiplied by itself, gives the original number. In this case, we're calculating the square root of each transaction amount in the list.''' 14 | 15 | 16 | 17 | import math 18 | 19 | def calculate_sqrt(transaction_amounts): 20 | #..... YOUR CODE STARTS HERE ..... 21 | 22 | return [math.sqrt(amount) for amount in transaction_amounts] 23 | 24 | #..... YOUR CODE ENDS HERE ..... 25 | 26 | if __name__ == "__main__": 27 | transaction_amounts = eval(input().strip()) 28 | print(calculate_sqrt(transaction_amounts)) -------------------------------------------------------------------------------- /gu-ito-3-13.py: -------------------------------------------------------------------------------- 1 | '''You are a college professor and you have the scores of your students in a list. You want to grade the students based on their scores. Write a Python function grade_students(scores) that takes a list of scores and returns a list of grades. Use the map function to apply the grading scheme to all scores. 2 | 3 | The grading scheme is as follows: 4 | 5 | Score >= 90: 'A' 6 | 80 <= Score < 90: 'B' 7 | 70 <= Score < 80: 'C' 8 | 60 <= Score < 70: 'D' 9 | Score < 60: 'F' 10 | Input: 11 | 12 | scores: a list of integers representing the scores of the students. 13 | Output: 14 | 15 | The function should return a list of strings representing the grades of the students. 16 | Sample Input: 17 | 18 | [95,55] 19 | 20 | Sample Output: 21 | 22 | ['A','F'] 23 | 24 | Explanation: 25 | 26 | The map function applies the get_grade function to every item in the scores list. The get_grade function takes a score and returns a grade based on the grading scheme. This demonstrates how the map function can be used to apply a function to every item in a list. In the context of grading students in a college, this can be useful to grade all students based on their scores.''' 27 | 28 | 29 | 30 | import json 31 | from io import StringIO 32 | 33 | def grade_students(scores): 34 | def get_grade(score): 35 | #..... YOUR CODE STARTS HERE ..... 36 | 37 | if score >= 90: 38 | return 'A' 39 | elif 80 <= score < 90: 40 | return 'B' 41 | elif 70 <= score < 80: 42 | return 'C' 43 | elif 60 <= score < 70: 44 | return 'D' 45 | else: 46 | return 'F' 47 | 48 | #..... YOUR CODE ENDS HERE ..... 49 | 50 | return list(map(get_grade, scores)) 51 | 52 | if __name__ == "__main__": 53 | scores = json.load(StringIO(input().strip())) 54 | grades = grade_students(scores) 55 | 56 | print(grades) -------------------------------------------------------------------------------- /gu-ito-3-14.py: -------------------------------------------------------------------------------- 1 | '''In an e-commerce application, you have a list of n products. Each product has a unique ID and a price. You need to implement a generator function get_products_in_budget(budget, products) that yields products one by one, sorted by price, until the total price of yielded products exceeds the budget. 2 | 3 | Input: 4 | 5 | budget: an integer representing the total budget. 6 | products: a list of tuples. Each tuple contains two elements - the first element is the product ID (a string), and the second element is the product price (an integer). 7 | Output: 8 | 9 | The function should yield tuples. Each tuple contains two elements - the first element is the product ID (a string), and the second element is the product price (an integer). 10 | Constraints: 11 | 12 | 1 <= n <= 10^5 13 | 1 <= budget <= 10^9 14 | 1 <= price <= 10^6 15 | Sample Input: 16 | 17 | 100 18 | [("p1", 30), ("p2", 50), ("p3", 40), ("p4", 60)] 19 | 20 | Sample Output: 21 | 22 | ('p1', 30) 23 | ('p3', 40) 24 | 25 | Explanation: 26 | 27 | The generator function get_products_in_budget yields products one by one, sorted by price, until the total price of yielded products exceeds the budget. In this case, the products "p1" and "p3" are yielded, with total price 30+40=70, which is the maximum possible total price not exceeding the budget of 100. 28 | 29 | This question highlights the importance and performance benefits of generators. Generators allow us to generate as we go along, instead of holding everything in memory. In the context of an e-commerce application, this can be particularly useful when dealing with a large number of products, as it allows us to efficiently process each product one at a time, reducing memory usage.''' 30 | 31 | 32 | 33 | 34 | import re 35 | 36 | def get_products_in_budget(budget, products): 37 | #..... YOUR CODE STARTS HERE ..... 38 | 39 | products.sort(key=lambda x: x[1]) 40 | 41 | total_price = 0 42 | 43 | # Yield products one by one until total price exceeds budget 44 | for product_id, price in products: 45 | if total_price + price <= budget: 46 | yield product_id, price 47 | total_price += price 48 | else: 49 | break 50 | 51 | #..... YOUR CODE ENDS HERE ..... 52 | 53 | def replace_non_alphanumeric(text, replacement=''): 54 | return re.sub(r'[^a-zA-Z0-9,]', replacement, text) 55 | 56 | def clean_input(value): 57 | value = replace_non_alphanumeric(value).split(',') 58 | 59 | id, price = list(map(lambda x: x.strip(), value)) 60 | 61 | return (id, int(price)) 62 | 63 | if __name__ == "__main__": 64 | budget = int(input()) 65 | products = input() 66 | 67 | products = list(map(clean_input, products.strip().replace('[', '').replace(']', '').split('),'))) 68 | 69 | for product in get_products_in_budget(budget, products): 70 | print(product) -------------------------------------------------------------------------------- /gu-ito-3-15.py: -------------------------------------------------------------------------------- 1 | '''You are organizing a marriage function and you have a list of tasks to be done. Each task has a time duration. You want to keep track of how long each task takes. Write a Python decorator time_it that takes a function and prints the time taken by that function. Use this decorator to decorate the function do_task(task), which simulates doing the task by sleeping for the duration of the task. 2 | 3 | The output of the do_task function should be in the format: f"{task[0]} took {round(end - start, 2)} seconds" 4 | 5 | Input: 6 | 7 | task: a tuple. The first element is the task name (a string), and the second element is the task duration in seconds (an integer). 8 | Output: 9 | 10 | The function should print the task name and the time taken by the task in the format: f"{task[0]} took {round(end - start, 2)} seconds" 11 | Sample Input: 12 | 13 | Decorating the hall, 2 14 | 15 | Sample Output: 16 | 17 | Decorating the hall took 2.0 seconds 18 | 19 | Explanation: 20 | 21 | The decorator time_it is used to measure the time taken by the function do_task. The do_task function simulates doing a task by sleeping for the duration of the task. The decorator prints the task name and the time taken by the task. This demonstrates how decorators can be used to modify the behavior of a function, in this case, by adding timing functionality. In the context of organizing a marriage function, this can be useful to keep track of how long each task takes.''' 22 | 23 | 24 | 25 | 26 | import time 27 | 28 | def time_it(func): 29 | #..... YOUR CODE STARTS HERE ..... 30 | 31 | def wrapper(task): 32 | start_time = time.time() 33 | result = func(task) 34 | end_time = time.time() 35 | duration = end_time - start_time 36 | print(f"{task[0]} took {round(duration, 2)} seconds") 37 | return result 38 | return wrapper 39 | 40 | #..... YOUR CODE ENDS HERE ..... 41 | 42 | @time_it 43 | def do_task(task): 44 | #..... YOUR CODE STARTS HERE ..... 45 | 46 | task_name, task_duration = task 47 | time.sleep(task_duration) 48 | 49 | #..... YOUR CODE ENDS HERE ..... 50 | 51 | 52 | if __name__ == "__main__": 53 | task_name, duration = list(map(lambda x: x.strip(), input().strip().split(','))) 54 | task = [task_name, int(duration)] 55 | 56 | do_task(task) -------------------------------------------------------------------------------- /gu-ito-3-16.py: -------------------------------------------------------------------------------- 1 | '''You are organizing a marriage function and you have a list of tasks to be done. Each task has a time duration. You want to keep track of the total time taken by all tasks. Write a Python class MarriageFunction with a class method do_task that simulates doing a task and keeps track of the total time taken by all tasks. 2 | 3 | Input: 4 | 5 | task: a tuple. The first element is the task name (a string), and the second element is the task duration in seconds (an integer). 6 | Output: 7 | 8 | The function should print the task name and the time taken by the task in the format: f"{task[0]} took {round(end - start, 2)} seconds 9 | Sample Input: 10 | 11 | [("Decorating the hall", 2)] 12 | 13 | Sample Output: 14 | 15 | Decorating the hall took 2.0 seconds 16 | 17 | Explanation: 18 | 19 | The class MarriageFunction has a class method do_task which simulates doing a task by sleeping for the duration of the task. The method adds the time taken by the task to the total_duration class variable and prints the task name and the time taken by the task. This demonstrates how class variables can be used to keep track of state across multiple method calls. In the context of organizing a marriage function, this can be useful to keep track of how long all tasks take in total.''' 20 | 21 | 22 | 23 | 24 | import time 25 | import re 26 | 27 | class MarriageFunction: 28 | total_duration = 0 29 | 30 | @classmethod 31 | def do_task(cls, task): 32 | #..... YOUR CODE STARTS HERE ..... 33 | 34 | start_time = time.time() 35 | time.sleep(task[1]) 36 | end_time = time.time() 37 | duration = end_time - start_time 38 | cls.total_duration += duration 39 | print(f"{task[0]} took {round(duration, 2)} seconds") 40 | 41 | #..... YOUR CODE ENDS HERE ..... 42 | 43 | def replace_non_alphanumeric(text, replacement=''): 44 | return re.sub(r'[^a-zA-Z0-9, ]', replacement, text) 45 | 46 | def clean_input(value): 47 | value = replace_non_alphanumeric(value).split(',') 48 | 49 | id, price = list(map(lambda x: x.strip(), value)) 50 | 51 | return (id, int(price)) 52 | 53 | if __name__ == "__main__": 54 | tasks = input() 55 | 56 | tasks = list(map(clean_input, tasks.strip().replace('[', '').replace(']', '').split('),'))) 57 | 58 | for task in tasks: 59 | MarriageFunction.do_task(task) -------------------------------------------------------------------------------- /gu-ito-3-17.py: -------------------------------------------------------------------------------- 1 | '''You are developing a student management system for a B.Tech program. The system has a function get_student_grade(student_id: str) -> str that takes a student ID as input and returns the grade of that student. 2 | 3 | The program has the following students enrolled: 4 | 5 | Student ID: "BT202101", Grade: "A" 6 | Student ID: "BT202102", Grade: "B" 7 | However, not all students are enrolled in the program at all times. If a student is not enrolled, the function should raise a StudentNotFoundError with a message "Student not found". 8 | 9 | Write a Python function proxy_get_student_grade(student_id: str) -> str that acts as a proxy to the get_student_grade(student_id: str) -> str function. The proxy function should handle any StudentNotFoundError that might be raised and return a default grade 'N/A' if the student is not found. 10 | 11 | Constraints: 12 | 13 | Student ID is a string. 14 | You can't install any external libraries. 15 | Sample Input: 16 | 17 | BT202101 18 | 19 | Sample Output: 20 | 21 | A 22 | 23 | Explanation: 24 | 25 | In the sample outputs, the first grade is returned when the student is found in the program. The grade of the student is displayed in the output. This is done by catching the grade returned by the get_student_grade function in a try block. 26 | 27 | This demonstrates how proxy functions work in Python - a proxy function acts as an interface to another function and can add additional behavior (like error handling) without changing the original function’s code. In this case, the proxy function adds error handling to the get_student_grade function, allowing it to return a default grade when a student is not found. This is a key aspect of robust software design. 28 | 29 | In Python, functions are first-class objects, which means they can be passed around and used as arguments just like any other object (string, int, float, list, etc.). Higher-order functions are a kind of function that takes one or more functions as arguments, returns a function, or both. This property allows us to create proxy functions like proxy_get_student_grade.''' 30 | 31 | 32 | 33 | class StudentNotFoundError(Exception): 34 | pass 35 | 36 | def get_student_grade(student_id): 37 | 38 | students = { 39 | "BT202101": "A", 40 | "BT202102": "B", 41 | } 42 | if student_id in students: 43 | return students[student_id] 44 | else: 45 | raise StudentNotFoundError("Student not found") 46 | 47 | def proxy_get_student_grade(student_id): 48 | #..... YOUR CODE STARTS HERE ..... 49 | 50 | try: 51 | return get_student_grade(student_id) 52 | except StudentNotFoundError: 53 | return 'N/A' 54 | 55 | #..... YOUR CODE ENDS HERE ..... 56 | 57 | student_id = input() 58 | 59 | print(proxy_get_student_grade(student_id)) 60 | 61 | -------------------------------------------------------------------------------- /gu-ito-3-18.py: -------------------------------------------------------------------------------- 1 | '''You are developing a calculator in Python. The calculator has four operations: add, subtract, multiply, and divide. Each operation is a function that takes two numbers and returns the result of the operation. 2 | 3 | Write a Python function calculate(operation: Callable[[float, float], float], num1: float, num2: float) -> float that takes an operation function and two numbers as input and returns the result of the operation. The operation function is a higher-order function that can be any of the four operation functions. 4 | 5 | Constraints: 6 | 7 | num1 and num2 are floats. 8 | You can't install any external libraries. 9 | Sample Input: 10 | 11 | add, 1.0, 2.0 12 | 13 | Sample Output: 14 | 15 | 3.0 16 | 17 | Explanation: 18 | 19 | In the sample outputs, each number is the result of a calculation performed by the calculate function. The calculate function is a higher-order function, which means it accepts other functions as arguments and/or returns a function as its result. In this case, calculate accepts an operation function as an argument and applies it to the two number arguments. 20 | 21 | The operation functions (add, divide) are defined using lambda functions, which are small anonymous functions defined with the lambda keyword in Python. They can take any number of arguments but can only have one expression. In this case, each lambda function takes two arguments and returns the result of a specific arithmetic operation. 22 | 23 | This demonstrates the power and flexibility of higher-order functions and lambda functions in Python. They allow us to write more modular and concise code by treating functions as first-class objects, meaning that functions can be passed around and used as arguments or return values, just like any other objects (strings, numbers, lists, etc.).''' 24 | 25 | 26 | 27 | from typing import Callable 28 | 29 | def calculate(operation: Callable[[float, float], float], num1: float, num2: float) -> float: 30 | #..... YOUR CODE STARTS HERE ..... 31 | 32 | return operation(num1, num2) 33 | 34 | #..... YOUR CODE ENDS HERE ..... 35 | 36 | def clean_input(value): 37 | return str(value.strip()) 38 | 39 | add = lambda x, y: x + y 40 | subtract = lambda x, y: x - y 41 | multiply = lambda x, y: x * y 42 | divide = lambda x, y: x / y if y != 0 else None 43 | 44 | 45 | operation, num1, num2 = map(clean_input, input().strip().split(',')) 46 | 47 | func = None 48 | 49 | if (operation == 'add'): 50 | func = add 51 | 52 | elif (operation == 'subtract'): 53 | func = subtract 54 | 55 | elif (operation == 'multiply'): 56 | func = multiply 57 | 58 | elif (operation == 'divide'): 59 | func = divide 60 | 61 | print(calculate(func, float(num1), float(num2))) 62 | -------------------------------------------------------------------------------- /gu-ito-3-19.py: -------------------------------------------------------------------------------- 1 | '''You are developing a student management system for a B.Tech program. The system has a list of students, where each student is represented as a dictionary with the following keys: 'id', 'name', 'course', and 'grade'. 2 | 3 | Write a Python function iterate_students(students: List[Dict[str, Union[str, int]]]) -> None that takes a list of students as input and prints each student's details using an iterator. The details should be printed in the following format: "Student ID: {id}, Name: {name}, Course: {course}, Grade: {grade}". 4 | 5 | Constraints: 6 | 7 | The id, name, course are strings and grade is an integer. 8 | You can't install any external libraries. 9 | Sample Input: 10 | 11 | [ {"id": "BT202101", "name": "John Doe", "course": "Computer Science", "grade": "A"}, {"id": "BT202102", "name": "Jane Doe", "course": "Electrical Engineering", "grade": "B"}, ] 12 | 13 | Sample Output: 14 | 15 | Student ID: BT202101, Name: John Doe, Course: Computer Science, Grade: A 16 | Student ID: BT202102, Name: Jane Doe, Course: Electrical Engineering, Grade: B 17 | 18 | Explanation: 19 | 20 | In the sample output, each line is the result of iterating over the list of students and printing each student’s details. This is done using a for loop, which in Python, creates an iterator for the list and iterates over it. 21 | 22 | Iterators in Python are objects that can be iterated (or looped) over. An object is called iterable if we can get an iterator from it. Most built-in containers in Python like: list, tuple, string, etc. are iterables. The iter() function (which in turn calls the iter() method) returns an iterator from them. 23 | 24 | In this case, the list of students is an iterable and the for loop creates an iterator that iterates over each student in the list. For each student, the student’s details are printed to the console. This demonstrates the use of iterators in Python to efficiently loop over an iterable object.''' 25 | 26 | 27 | 28 | import sys 29 | import json 30 | from io import StringIO 31 | 32 | def iterate_students(students): 33 | #..... YOUR CODE STARTS HERE ..... 34 | 35 | for student in students: 36 | print(f"Student ID: {student['id']}, Name: {student['name']}, Course: {student['course']}, Grade: {student['grade']}") 37 | 38 | #..... YOUR CODE ENDS HERE ..... 39 | 40 | def clean_input(value): 41 | value = value.strip() 42 | if (len(value)): 43 | if ('}' not in value): 44 | value += '}' 45 | 46 | if ('{' in value and '}' in value): 47 | return json.load(StringIO(value)) 48 | return False 49 | 50 | if __name__ == "__main__": 51 | students_list = "" 52 | 53 | for line in sys.stdin: 54 | line = line.strip() 55 | students_list += line 56 | 57 | students_list = list(map(clean_input, students_list.replace('[', '').replace(']', '').split('},'))) 58 | students_list = list(filter(lambda student: isinstance(student, dict), students_list)) 59 | 60 | iterate_students(students_list) -------------------------------------------------------------------------------- /gu-ito-3-2.py: -------------------------------------------------------------------------------- 1 | '''You are a college professor and you have two lists: one with the names of your students and another with their corresponding scores. You want to associate each student with their score. Write a Python function associate_students(names, scores) that takes a list of names and a list of scores and returns a list of tuples where each tuple contains a name and the corresponding score. Use the zip function to associate the names with the scores. 2 | 3 | Input: 4 | 5 | names: a list of strings representing the names of the students. 6 | scores: a list of integers representing the scores of the students. 7 | Output: 8 | 9 | The function should return a list of tuples where each tuple contains a name and the corresponding score. 10 | Sample Input: 11 | 12 | ['Alice', 'Bob', 'Charlie', 'Dave'], [85, 90, 78, 92] 13 | 14 | Sample Output: 15 | 16 | [('Alice', 85), ('Bob', 90), ('Charlie', 78), ('Dave', 92)] 17 | 18 | Explanation: 19 | 20 | The zip function takes two or more iterable objects (like lists or strings), aggregates them in a tuple, and returns it. In this case, it takes a name from the names list and a score from the scores list and puts them together in a tuple. This demonstrates how the zip function can be used to combine two lists into a list of tuples. In the context of grading students in a college, this can be useful to associate each student with their score.''' 21 | 22 | 23 | 24 | import re 25 | 26 | def associate_students(names, scores): 27 | #..... YOUR CODE STARTS HERE ..... 28 | 29 | return list(zip(names, scores)) 30 | 31 | #..... YOUR CODE ENDS HERE ..... 32 | 33 | def clean_input(value): 34 | value = value.strip() 35 | return re.sub(r'[^A-Z0-9a-z,]', '', value).split(',') 36 | 37 | if __name__ == "__main__": 38 | names, scores = list(map(clean_input, input().strip().split('],'))) 39 | scores = list(map(int, scores)) 40 | print(associate_students(names, scores)) -------------------------------------------------------------------------------- /gu-ito-3-20.py: -------------------------------------------------------------------------------- 1 | '''You are implementing a simple calculator. Write a Python class Calculator with static methods add, subtract, multiply, and divide that perform the respective operations. 2 | 3 | Input: 4 | 5 | num1: a float, the first number. 6 | num2: a float, the second number. 7 | Output: 8 | 9 | The function should return the result of the operation. 10 | Sample Input: 11 | 12 | Calculator.add(5, 3) 13 | 14 | Sample Output: 15 | 16 | 8 17 | 18 | Explanation: 19 | 20 | The class Calculator has static methods add, subtract, multiply, and divide which perform the respective operations. Static methods, marked with the @staticmethod decorator, don't take a self or cls parameter. This means you can't modify object state or class state within a static method. However, they're useful when you need to perform a utility function that doesn't modify the state of the object or class, like in this case where we're performing simple mathematical operations.''' 21 | 22 | 23 | 24 | 25 | class Calculator: 26 | @staticmethod 27 | def add(num1, num2): 28 | #..... YOUR CODE STARTS HERE ..... 29 | 30 | return num1+num2 31 | 32 | #..... YOUR CODE ENDS HERE ..... 33 | 34 | @staticmethod 35 | def subtract(num1, num2): 36 | #..... YOUR CODE STARTS HERE ..... 37 | 38 | return num1-num2 39 | 40 | #..... YOUR CODE ENDS HERE ..... 41 | 42 | @staticmethod 43 | def multiply(num1, num2): 44 | #..... YOUR CODE STARTS HERE ..... 45 | 46 | return num1*num2 47 | 48 | #..... YOUR CODE ENDS HERE ..... 49 | 50 | @staticmethod 51 | def divide(num1, num2): 52 | #..... YOUR CODE STARTS HERE ..... 53 | 54 | return num1/num2 55 | 56 | #..... YOUR CODE ENDS HERE ..... 57 | 58 | def call_func(func, args): 59 | value = None 60 | num1, num2 = args 61 | 62 | if (func == "add"): 63 | value = Calculator.add(num1, num2) 64 | 65 | elif (func == "subtract"): 66 | value = Calculator.subtract(num1, num2) 67 | 68 | elif (func == "multiply"): 69 | value = Calculator.multiply(num1, num2) 70 | 71 | elif (func == "divide"): 72 | value = Calculator.divide(num1, num2) 73 | 74 | return value 75 | 76 | 77 | if __name__ == "__main__": 78 | func_call = list(map(lambda x: str(x.strip()), input().strip().split('.'))) 79 | class_name, func = func_call 80 | 81 | if (class_name == 'Calculator'): 82 | parans_pos = func.index('(') 83 | 84 | name = func[:parans_pos].strip() 85 | args = tuple(map(lambda x: int(x.strip()), func[parans_pos+1: len(func)-1].strip().split(','))) 86 | 87 | print(call_func(name, args)) -------------------------------------------------------------------------------- /gu-ito-3-3.py: -------------------------------------------------------------------------------- 1 | '''You are a college professor and you have the scores of your students in a list. You want to find the total score of all students. Write a Python function total_score(scores) that takes a list of scores and returns the total score. Use the reduce function to calculate the total score. 2 | 3 | Input: 4 | 5 | scores: a list of integers representing the scores of the students. 6 | Output: 7 | 8 | The function should return an integer representing the total score of all students. 9 | Sample Input: 10 | 11 | [85, 90, 78, 92] 12 | 13 | Sample Output: 14 | 15 | 345 16 | 17 | Explanation: 18 | 19 | The reduce function applies a function of two arguments cumulatively to the items of an iterable, from left to right, so as to reduce the iterable to a single output. In this case, it takes two scores at a time and adds them, continuing this process until all scores have been added together. This demonstrates how the reduce function can be used to reduce a list to a single result. In the context of grading students in a college, this can be useful to calculate the total score of all students. 20 | 21 | ''' 22 | 23 | 24 | import json 25 | from io import StringIO 26 | from functools import reduce 27 | 28 | def total_score(scores): 29 | #..... YOUR CODE STARTS HERE ..... 30 | 31 | return reduce(lambda x, y: x + y, scores) 32 | 33 | #..... YOUR CODE ENDS HERE ..... 34 | 35 | def clean_input(value): 36 | return json.load(StringIO(value)) 37 | 38 | if __name__ == "__main__": 39 | scores = clean_input(input().strip()) 40 | 41 | print(total_score(scores)) -------------------------------------------------------------------------------- /gu-ito-3-4.py: -------------------------------------------------------------------------------- 1 | '''You are given a string that represents a list of movies and their release years. The format of the string is " ()". Write a Python function get_movies(data) that takes this string and returns a list of tuples where each tuple contains the movie title and the release year. Use regular expressions to parse the data. 2 | 3 | Input: 4 | 5 | data: a string representing a list of movies and their release years. 6 | Output: 7 | 8 | The function should return a list of tuples where each tuple contains a movie title and the release year. 9 | Sample Input: 10 | 11 | The Shawshank Redemption (1994), The Godfather (1972), The Dark Knight (2008) 12 | 13 | Sample Output: 14 | 15 | [('The Shawshank Redemption', '1994'), ('The Godfather', '1972'), ('The Dark Knight', '2008')] 16 | 17 | Explanation: 18 | 19 | The re.findall function applies the regular expression pattern to the data string and returns a list of tuples where each tuple contains the movie title and the release year.''' 20 | 21 | 22 | import re 23 | 24 | def get_movies(data): 25 | #..... YOUR CODE STARTS HERE ..... 26 | 27 | # Define the regular expression pattern 28 | pattern = r'([\w\s]+) \((\d{4})\)' 29 | 30 | # Find all matches using the pattern 31 | matches = re.findall(pattern, data) 32 | 33 | # Create a list of tuples from the matches 34 | movies = [(title.strip(), year) for title, year in matches] 35 | 36 | return movies 37 | 38 | #..... YOUR CODE ENDS HERE ..... 39 | 40 | if __name__ == "__main__": 41 | data = input().strip() 42 | print(get_movies(data)) -------------------------------------------------------------------------------- /gu-ito-3-5.py: -------------------------------------------------------------------------------- 1 | '''You are managing an e-commerce website and you have a list of products. Each product is represented as a dictionary with two keys: 'name' and 'price'. You want to create a list of all products that cost more than $50. Write a Python function expensive_products(products) that takes a list of products and returns a list of the names of products that cost more than $50. Use a list comprehension to create the list. 2 | 3 | Input: 4 | 5 | products: a list of dictionaries. Each dictionary represents a product and has two keys: 'name' (a string) and 'price' (a float). 6 | Output: 7 | 8 | The function should return a list of strings representing the names of products that cost more than $50. 9 | Sample Input: 10 | 11 | [{'name': 'Product 1', 'price': 49.99}, {'name': 'Product 2', 'price': 50.01}, {'name': 'Product 3', 'price': 50.00}] 12 | 13 | Sample Output: 14 | 15 | ['Product 2'] 16 | 17 | Explanation: 18 | 19 | The list comprehension generates a new list containing the names of all products that cost more than $50. It does this by iterating over each product in the products list and checking if the product's price is greater than $50. If it is, the product's name is added to the new list. This demonstrates how list comprehensions can be used to create new lists based on existing lists in Python. In the context of managing an e-commerce website, this can be useful to quickly find all products that meet a certain price criterion.''' 20 | 21 | 22 | 23 | import json 24 | from io import StringIO 25 | import re 26 | 27 | def expensive_products(products): 28 | #..... YOUR CODE STARTS HERE ..... 29 | 30 | return [product['name'] for product in products if product['price'] > 50] 31 | 32 | #..... YOUR CODE ENDS HERE ..... 33 | 34 | def convert_to_list_of_dicts(data): 35 | data_without_brackets = re.sub(r'[\[\]]', '', data).split('},') 36 | 37 | lst = [] 38 | 39 | data = [d + '}' if '}' not in d else d for d in data_without_brackets] 40 | 41 | for d in data: 42 | if ('{' in d and '}' in d): 43 | d = d.strip().replace("'", '"') 44 | lst.append(json.load(StringIO(d))) 45 | 46 | return lst 47 | 48 | if __name__ == "__main__": 49 | products = convert_to_list_of_dicts(input().strip()) 50 | print(expensive_products(products)) -------------------------------------------------------------------------------- /gu-ito-3-6.py: -------------------------------------------------------------------------------- 1 | '''You are managing an e-commerce website and you have a list of products. Each product is represented as a dictionary with two keys: 'name' and 'category'. You want to create a list of all products that belong to the category 'Electronics'. Write a Python function electronics_products(products) that takes a list of products and returns a list of tuples where each tuple contains the product name and the category. Use a tuple comprehension to create the list. 2 | 3 | Input: 4 | 5 | products: a list of dictionaries. Each dictionary represents a product and has two keys: 'name' (a string) and 'category' (a string). 6 | Output: 7 | 8 | The function should return a list of tuples where each tuple contains a product name and the category. 9 | Sample Input: 10 | 11 | [{'name': 'Product 1', 'category': 'Books'}, {'name': 'Product 2', 'category': 'Electronics'}, {'name': 'Product 3', 'category': 'Electronics'}] 12 | 13 | Sample Output: 14 | 15 | [('Product 2', 'Electronics'), ('Product 3', 'Electronics')] 16 | 17 | Explanation: 18 | 19 | The tuple comprehension generates a new list containing tuples of the names and categories of all products that belong to the 'Electronics' category. It does this by iterating over each product in the products list and checking if the product's category is 'Electronics'. If it is, a tuple containing the product's name and category is added to the new list. This demonstrates how tuple comprehensions can be used to create new lists based on existing lists in Python. In the context of managing an e-commerce website, this can be useful to quickly find all products that belong to a certain category.''' 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | import json 29 | from io import StringIO 30 | import re 31 | 32 | def electronics_products(products): 33 | #..... YOUR CODE STARTS HERE ..... 34 | 35 | return [(product['name'], product['category']) for product in products if product['category'] == 'Electronics'] 36 | 37 | #..... YOUR CODE ENDS HERE ..... 38 | 39 | def convert_to_list_of_dicts(data): 40 | data_without_brackets = re.sub(r'[\[\]]', '', data).split('},') 41 | 42 | lst = [] 43 | 44 | data = [d + '}' if '}' not in d else d for d in data_without_brackets] 45 | 46 | for d in data: 47 | if ('{' in d and '}' in d): 48 | d = d.strip().replace("'", '"') 49 | lst.append(json.load(StringIO(d))) 50 | 51 | return lst 52 | 53 | if __name__ == "__main__": 54 | products = convert_to_list_of_dicts(input().strip()) 55 | print(electronics_products(products)) -------------------------------------------------------------------------------- /gu-ito-3-7.py: -------------------------------------------------------------------------------- 1 | '''You are managing an e-commerce website and you have a list of products. Each product is represented as a dictionary with three keys: 'name', 'category', and 'brand'. You want to create a set of all unique brands present in your product list. Write a Python function unique_brands(products) that takes a list of products and returns a set of unique brands. Use a set comprehension to create the set. 2 | 3 | Input: 4 | 5 | products: a list of dictionaries. Each dictionary represents a product and has three keys: 'name' (a string), 'category' (a string), and 'brand' (a string). 6 | Output: 7 | 8 | The function should return a set of unique brands. 9 | Sample Input: 10 | 11 | [{'name': 'Product 1', 'category': 'Books', 'brand': 'Brand A'}, {'name': 'Product 2', 'category': 'Electronics', 'brand': 'Brand B'}, {'name': 'Product 3', 'category': 'Electronics', 'brand': 'Brand B'}] 12 | 13 | Sample Output: 14 | 15 | ['Brand A', 'Brand B'] 16 | 17 | Explanation: 18 | 19 | The set comprehension generates a new set containing unique brands of all products. It does this by iterating over each product in the products list and adding the product's brand to the new set. Since sets in Python only contain unique elements, any duplicate brands are automatically removed. This demonstrates how set comprehensions can be used to create new sets based on existing lists in Python. In the context of managing an e-commerce website, this can be useful to quickly find all unique product brands.",''' 20 | 21 | import json 22 | from io import StringIO 23 | import re 24 | 25 | def unique_brands(products): 26 | #..... YOUR CODE STARTS HERE ..... 27 | 28 | return sorted({product['brand'] for product in products}) 29 | 30 | #..... YOUR CODE ENDS HERE ..... 31 | 32 | def convert_to_list_of_dicts(data): 33 | data_without_brackets = re.sub(r'[\[\]]', '', data).split('},') 34 | 35 | lst = [] 36 | 37 | data = [d + '}' if '}' not in d else d for d in data_without_brackets] 38 | 39 | for d in data: 40 | if ('{' in d and '}' in d): 41 | d = d.strip().replace("'", '"') 42 | lst.append(json.load(StringIO(d))) 43 | 44 | return lst 45 | 46 | if __name__ == "__main__": 47 | products = convert_to_list_of_dicts(input().strip()) 48 | print(sorted(unique_brands(products))) -------------------------------------------------------------------------------- /gu-ito-3-8.py: -------------------------------------------------------------------------------- 1 | '''You are managing an e-commerce website and you have a list of products. Each product is represented as a dictionary with three keys: 'name', 'category', and 'stock'. The 'stock' key represents the number of units of the product available in your inventory. You want to create a dictionary where the keys are the product names and the values are the stock count. Write a Python function product_stock(products) that takes a list of products and returns a dictionary of product names and their stock count. Use a dictionary comprehension to create the dictionary. 2 | 3 | Input: 4 | 5 | products: a list of dictionaries. Each dictionary represents a product and has three keys: 'name' (a string), 'category' (a string), and 'stock' (an integer). 6 | Output: 7 | 8 | The function should return a dictionary where the keys are product names and the values are their stock count. 9 | Sample Input: 10 | 11 | [{'name': 'Product 1', 'category': 'Books', 'stock': 20}, {'name': 'Product 2', 'category': 'Electronics', 'stock': 15}, {'name': 'Product 3', 'category': 'Electronics', 'stock': 30}] 12 | 13 | Sample Output: 14 | 15 | {'Product 1': 20, 'Product 2': 15, 'Product 3': 30} 16 | 17 | Explanation: 18 | 19 | The dictionary comprehension generates a new dictionary containing product names as keys and their stock count as values. It does this by iterating over each product in the products list and adding an entry to the new dictionary where the key is the product's name and the value is the product's stock count. This demonstrates how dictionary comprehensions can be used to create new dictionaries based on existing lists in Python. In the context of managing an e-commerce website, this can be useful to quickly find the stock count of a product given its name.''' 20 | 21 | 22 | 23 | def product_stock(products): 24 | #..... YOUR CODE STARTS HERE ..... 25 | 26 | return {product['name']: product['stock'] for product in products} 27 | 28 | #..... YOUR CODE ENDS HERE ..... 29 | 30 | products_input = eval(input()) 31 | 32 | result = product_stock(products_input) 33 | print(result) -------------------------------------------------------------------------------- /gu-ito-3-9.py: -------------------------------------------------------------------------------- 1 | '''You are managing an e-commerce website and you have a list of products. Each product is represented as a dictionary with three keys: 'name', 'category', and 'price'. You want to calculate the total price of all products in a specific category. Write a Python function total_price(products, category) that takes a list of products and a category, and returns the total price of all products in that category. Use the sum function from the built-in Python math module to calculate the total price. 2 | 3 | Input: 4 | 5 | products: a list of dictionaries. Each dictionary represents a product and has three keys: 'name' (a string), 'category' (a string), and 'price' (a float). 6 | category: a string representing the category of products for which the total price should be calculated. 7 | Output: 8 | 9 | The function should return a float representing the total price of all products in the specified category. 10 | Sample Input: 11 | 12 | [{'name': 'Product 1', 'category': 'Books', 'price': 19.99}, {'name': 'Product 2', 'category': 'Electronics', 'price': 299.99}, {'name': 'Product 3', 'category': 'Electronics', 'price': 499.99}], 'Electronics' 13 | 14 | Sample Output: 15 | 16 | 799.98 17 | 18 | Explanation: 19 | 20 | The generator expression generates a sequence of prices for all products in the specified category. It does this by iterating over each product in the products list and checking if the product's category matches the specified category. If it does, the product's price is added to the sequence. The fsum function from the math module then calculates the sum of this sequence, which is the total price of all products in the specified category. This demonstrates how modules and packages can be used in Python to provide additional functionality, such as mathematical operations. In the context of managing an e-commerce website, this can be useful to quickly calculate the total price of all products in a certain category.''' 21 | 22 | 23 | import json 24 | from io import StringIO 25 | import re 26 | from math import fsum 27 | 28 | def total_price(products, category): 29 | #..... YOUR CODE STARTS HERE ..... 30 | 31 | return fsum(product['price'] for product in products if product['category'] == category) 32 | 33 | #..... YOUR CODE ENDS HERE ..... 34 | 35 | def convert_to_list_of_dicts(data): 36 | data_without_brackets = re.sub(r'[\[\]]', '', data).split('},') 37 | 38 | lst = [] 39 | 40 | data = [d + '}' if '}' not in d else d for d in data_without_brackets] 41 | 42 | for d in data: 43 | if ('{' in d and '}' in d): 44 | d = d.strip().replace("'", '"') 45 | lst.append(json.load(StringIO(d))) 46 | 47 | return lst 48 | 49 | if __name__ == "__main__": 50 | ip = input().strip().replace("],", ']') 51 | products, category = ip.split("") 52 | products = convert_to_list_of_dicts(products) 53 | category = category.replace("'", '').strip() 54 | 55 | print(total_price(products, category)) -------------------------------------------------------------------------------- /gu-ito-3.py: -------------------------------------------------------------------------------- 1 | '''In a scenario where banks need to perform confidential fund or message transfers, each bank may utilize its encryption and decryption techniques. The Reserve Bank provides an interface with method names, leaving the implementation details to the individual banks. 2 | 3 | Create an interface BankTransfers. 4 | Add two methods with the following prototypes: 5 | public String encrypt(String a); 6 | public String decrypt(String a); 7 | Create a class ICICI which implements the BankTransfers interface and implements a simple encryption technique. 8 | Create a class HDFC which implements the BankTransfers interface and implements a simple encryption technique. 9 | Encryption techniques used by both banks: 10 | ICICI: Add 1 to the ASCII value of each character and insert the number '1' after every character. 11 | HDFC: Add 1 to the ASCII value of characters at even indices and subtract 1 from the ASCII value of characters at odd indices. Spaces are not encrypted. 12 | The reverse of both techniques will decrypt the message (i.e., original text). 13 | 14 | Input: 15 | 16 | Bank Type and the message. 17 | 18 | Output: 19 | 20 | Output the encrypted input. 21 | 22 | Sample Input: 23 | 24 | 1 welcome all 25 | 26 | Sample Output: 27 | 28 | x1f1m1d1p1n1f1!1b1m1m1''' 29 | 30 | 31 | # Interface for Bank Transfers 32 | class BankTransfers: 33 | def encrypt(self, a): 34 | pass 35 | 36 | def decrypt(self, a): 37 | pass 38 | 39 | # ICICI class implementing BankTransfers interface 40 | class ICICI(BankTransfers): 41 | #..... YOUR CODE STARTS HERE ..... 42 | 43 | def encrypt(self,a): 44 | encrypted_message="" 45 | for char in a: 46 | encrypted_message+=chr(ord(char)+1)+"1" 47 | return encrypted_message 48 | def decrypt(self,a): 49 | decrypted_message="" 50 | for i in range(0,len(a),2): 51 | decrypted_message+=chr(ord(a[i])-1) 52 | return decrypted_message 53 | #..... YOUR CODE ENDS HERE ..... 54 | 55 | # HDFC class implementing BankTransfers interface 56 | class HDFC(BankTransfers): 57 | #..... YOUR CODE STARTS HERE ..... 58 | 59 | def encrypt(self,a): 60 | encrypted_message="" 61 | for i, char in enumerate(a): 62 | if char!=' ': 63 | if i%2==0: 64 | encrypted_message+=chr(ord(char)+1) 65 | else: 66 | encrypted_message+=chr(ord(char)-1) 67 | else: 68 | encrypted_message+=char 69 | return encrypted_message 70 | def decrypt(self,a): 71 | decrypted_message="" 72 | for i, char in enumerate(a): 73 | if char!= ' ': 74 | if i%2==0: 75 | decrypted_message+=chr(ord(char)-1) 76 | else: 77 | decrypted_message+=chr(ord(char)+1) 78 | else: 79 | decrypted_message+=char 80 | return decrypted_message 81 | 82 | #..... YOUR CODE ENDS HERE ..... 83 | 84 | # Main function 85 | def main(): 86 | bank_type, message = input("").split(maxsplit=1) 87 | bank_type = int(bank_type) 88 | 89 | if bank_type == 1: 90 | bank = ICICI() 91 | elif bank_type == 2: 92 | bank = HDFC() 93 | else: 94 | print("Invalid bank type") 95 | return 96 | 97 | encrypted_message = bank.encrypt(message) 98 | print(encrypted_message) 99 | 100 | # Call the main function 101 | if __name__ == "__main__": 102 | main() 103 | -------------------------------------------------------------------------------- /gu-ito-4.py: -------------------------------------------------------------------------------- 1 | '''You need to implement a Matrix class with methods to perform various operations on matrices. The class should have methods for the following: 2 | 3 | Get the number of rows. 4 | Get the number of columns. 5 | Set the elements of the matrix at a given position (i, j). 6 | Multiply two matrices. 7 | Input: 8 | 9 | The input consists of the following: 10 | 11 | Number of rows for the first matrix (mat1). 12 | Number of columns for the first matrix (mat1). 13 | Values of each element of the first matrix (mat1) in row-major order. 14 | Number of rows for the second matrix (mat2). 15 | Number of columns for the second matrix (mat2). 16 | Values of each element of the second matrix (mat2) in row-major order. 17 | Output: 18 | 19 | After inputting both matrices, print each resultant element of the matrix multiplication in a loop. 20 | 21 | Sample Input: 22 | 23 | 2 24 | 2 25 | 2 2 2 2 26 | 2 27 | 2 28 | 2 2 2 2 29 | 30 | Sample Output: 31 | 32 | 8 8 8 8''' 33 | 34 | 35 | 36 | 37 | class Matrix: 38 | #..... YOUR CODE STARTS HERE ..... 39 | 40 | def __init__(self,rows,cols): 41 | self.rows=rows 42 | self.cols=cols 43 | self.matrix=[[0 for _ in range(cols)]for _ in range(rows)] 44 | 45 | def get_rows(self): 46 | return self.rows 47 | def get_cols(self): 48 | return self.cols 49 | 50 | def set_element(self,i,j,value): 51 | self.matrix[i][j]=value 52 | 53 | def multiply(self,other): 54 | if self.cols !=other.rows: 55 | print("Invalid") 56 | return None 57 | 58 | result= Matrix(self.rows,other.cols) 59 | 60 | for i in range(self.rows): 61 | for j in range(other.cols): 62 | for k in range(self.cols): 63 | result.matrix[i][j]+= self.matrix[i][k] * other.matrix[k][j] 64 | return result 65 | 66 | #..... YOUR CODE ENDS HERE ..... 67 | 68 | def main(): 69 | mat1_rows = int(input()) 70 | mat1_cols = int(input()) 71 | mat1_values = list(map(int, input().split())) 72 | 73 | mat2_rows = int(input()) 74 | mat2_cols = int(input()) 75 | mat2_values = list(map(int, input().split())) 76 | 77 | if mat1_cols != mat2_rows: 78 | print("Invalid") 79 | return 80 | 81 | mat1 = Matrix(mat1_rows, mat1_cols) 82 | mat2 = Matrix(mat2_rows, mat2_cols) 83 | 84 | # Set values for matrix 1 85 | index = 0 86 | for i in range(mat1_rows): 87 | for j in range(mat1_cols): 88 | mat1.set_element(i, j, mat1_values[index]) 89 | index += 1 90 | 91 | # Set values for matrix 2 92 | index = 0 93 | for i in range(mat2_rows): 94 | for j in range(mat2_cols): 95 | mat2.set_element(i, j, mat2_values[index]) 96 | index += 1 97 | 98 | # Multiply matrices 99 | result = mat1.multiply(mat2) 100 | 101 | if result: 102 | for i in range(result.get_rows()): 103 | for j in range(result.get_cols()): 104 | if j+1 == result.get_cols() and i+1 == result.get_rows(): 105 | print(result.matrix[i][j], end="") 106 | else: 107 | print(result.matrix[i][j], end=" ") 108 | print() 109 | 110 | if __name__ == "__main__": 111 | main() 112 | -------------------------------------------------------------------------------- /gu-ito-5.py: -------------------------------------------------------------------------------- 1 | '''You are required to write a program that calculates and prints the area of a triangle given its base and height. Implement a class named 'Triangle' without any parameter in its constructor. 2 | 3 | Input: 4 | 5 | The input consists of two lines. Each line contains an integer representing either the base or the height of the triangle. 6 | 7 | Output: 8 | 9 | Output the area of the triangle. 10 | 11 | Sample Input: 12 | 13 | 6 14 | 6 15 | 16 | Sample Output: 17 | 18 | 18''' 19 | 20 | 21 | class Triangle: 22 | #..... YOUR CODE STARTS HERE ..... 23 | 24 | def calculate_area(self,b,h): 25 | return 0.5*b*h 26 | 27 | #..... YOUR CODE ENDS HERE ..... 28 | 29 | def main(): 30 | triangle = Triangle() 31 | 32 | # Input for the base of the triangle 33 | base = int(input()) 34 | 35 | # Input for the height of the triangle 36 | height = int(input()) 37 | 38 | # Calculate and print the area of the triangle 39 | area = triangle.calculate_area(base, height) 40 | print(area) 41 | 42 | if __name__ == "__main__": 43 | main() 44 | -------------------------------------------------------------------------------- /gu-ito-6.py: -------------------------------------------------------------------------------- 1 | '''You are required to implement a Python program for managing employee salaries. The program should define an Employee class with the following methods: 2 | 3 | getInfo(salary, hours_worked): This method takes the salary and the number of hours worked per day by the employee as input parameters. 4 | AddSal(): This method adds $100 to the salary of the employee if it is less than $500. 5 | AddWorkSal(amount): This method adds a specified amount to the salary of the employee. 6 | Input: 7 | 8 | The input consists of the following: 9 | 10 | The first line contains two integers separated by a space: employee_id and option. employee_id is an integer representing the ID of the employee (always 1 for this problem). option is an integer representing the selected operation (1 for getInfo(), 2 for AddSal(), and 3 for AddWorkSal()). 11 | If option is 1 (getInfo()), the second line contains two integers separated by a space: salary (an integer) and hours_worked (an integer). 12 | if the option is 2, there will be no second line input 13 | If option is 3 (AddWorkSal()), the second line contains an integer amount representing the amount to be added to the salary. 14 | Output: 15 | 16 | Print the following: 17 | 18 | For options 1 and 3, output the final salary of the employee after performing the operation. 19 | For option 2, print the updated salary 20 | Note 21 | 22 | The initial salary of the employee is $100. 23 | The final salary of the employee should be output with a '$' symbol. 24 | Sample Input: 25 | 26 | 1 1 27 | 200 8 28 | 29 | Sample Output: 30 | 31 | 200$''' 32 | 33 | 34 | 35 | class Employee: 36 | def __init__(self): 37 | self.salary = 100 # Initial salary 38 | self.hours_worked = 0 39 | 40 | #..... YOUR CODE STARTS HERE ..... 41 | 42 | def getInfo(self,s,h): 43 | self.salary=s 44 | self.hours_worked=h 45 | def AddSal(self): 46 | return self.salary 47 | def AddWorkSal(self,a): 48 | self.salary+=a 49 | 50 | #..... YOUR CODE ENDS HERE ..... 51 | 52 | # Main program 53 | employee = Employee() 54 | employee_id, option = map(int, input().split()) 55 | 56 | if employee_id == 1: 57 | if option == 1: 58 | salary, hours_worked = map(int, input().split()) 59 | employee.getInfo(salary, hours_worked) 60 | elif option == 2: 61 | employee.AddSal() 62 | elif option == 3: 63 | amount = int(input()) 64 | employee.AddWorkSal(amount) 65 | 66 | print(f"{employee.salary}$") 67 | -------------------------------------------------------------------------------- /gu-ito-7.py: -------------------------------------------------------------------------------- 1 | '''You are tasked with writing a program to calculate and print the area and circumference of a circle given its radius r units. Implement a class named 'Circle' without any parameter in its constructor. 2 | 3 | Input: 4 | 5 | The input consists of a single line containing an integer r representing the radius of the circle. 6 | 7 | Output: 8 | 9 | Output the area and circumference of the circle. Round the output to one decimal value. 10 | 11 | Sample Input: 12 | 13 | 3 14 | 15 | Sample Output: 16 | 17 | 28.3 18 | 18.8''' 19 | 20 | 21 | 22 | import math 23 | 24 | class Circle: 25 | #..... YOUR CODE STARTS HERE ..... 26 | 27 | def area(self,radius): 28 | a=math.pi*radius*radius 29 | a=round(a,1) 30 | return a 31 | 32 | def circumference(self,radius): 33 | c=2*math.pi*radius 34 | c=round(c,1) 35 | return c 36 | #..... YOUR CODE ENDS HERE ..... 37 | 38 | def main(): 39 | circle = Circle() 40 | 41 | # Input for the radius of the circle 42 | r = int(input()) 43 | 44 | # Calculate and print the area and circumference of the circle 45 | print(circle.area(r)) 46 | print(circle.circumference(r)) 47 | 48 | if __name__ == "__main__": 49 | main() 50 | -------------------------------------------------------------------------------- /gu-ito-8.py: -------------------------------------------------------------------------------- 1 | '''You are required to implement a program that calculates the service tax on every transaction for different types of accounts: Savings, Checking, and Demat. The service tax rates are 10%, 20%, and 5% respectively. 2 | 3 | Create an abstract class Account with three private data member variables: accountNumber of type String, balance of type double, holderName of type String, and methods display() and an abstract method calculateServiceTax() with an argument of type int and return type as double. 4 | 5 | Create the classes CheckingAccount, SavingsAccount, and DematAccount which extend the class Account. Use appropriate getters and setters for the above classes. 6 | 7 | Input: 8 | 9 | The input consists of a single line with the following information separated by space: 10 | 11 | Account type (1 for Checking Account, 2 for Savings Account, 3 for Demat Account) 12 | Holder's name 13 | Account number 14 | Current balance 15 | Amount to be transferred 16 | Output: 17 | 18 | Output the remaining balance after the transaction. 19 | 20 | Sample Input: 21 | 22 | 3 Rohan 562263 985.32 155 23 | 24 | Sample Output: 25 | 26 | Your remaining balance is Rs.822.57''' 27 | 28 | 29 | 30 | from abc import ABC, abstractmethod 31 | 32 | class Account(ABC): 33 | #..... YOUR CODE STARTS HERE ..... 34 | 35 | def __init__(self,holder_name,account_number,balance): 36 | self.account_number=account_number 37 | self.holder_name=holder_name 38 | self.balance=balance 39 | 40 | @abstractmethod 41 | 42 | def calculate_service_tax(self,transfer_amount): 43 | pass 44 | 45 | def display(self): 46 | print(f"Your remaining balance is Rs.{self.balance:.2f}") 47 | 48 | 49 | #..... YOUR CODE ENDS HERE ..... 50 | 51 | class CheckingAccount(Account): 52 | #..... YOUR CODE STARTS HERE ..... 53 | 54 | def calculate_service_tax(self,ta): 55 | return ta*0.2 56 | 57 | 58 | #..... YOUR CODE ENDS HERE ..... 59 | 60 | class SavingsAccount(Account): 61 | #..... YOUR CODE STARTS HERE ..... 62 | 63 | def calculate_service_tax(self,ta): 64 | return ta*0.1 65 | 66 | 67 | #..... YOUR CODE ENDS HERE ..... 68 | 69 | class DematAccount(Account): 70 | #..... YOUR CODE STARTS HERE ..... 71 | 72 | def calculate_service_tax(self,ta): 73 | return ta*0.05 74 | 75 | #..... YOUR CODE ENDS HERE ..... 76 | 77 | def main(): 78 | # Input 79 | account_type, holder_name, account_number, current_balance, transfer_amount = input().split() 80 | account_number = int(account_number) 81 | current_balance = float(current_balance) 82 | transfer_amount = float(transfer_amount) 83 | 84 | # Create account object based on account type 85 | if account_type == '1': 86 | account = CheckingAccount(holder_name, account_number, current_balance) 87 | elif account_type == '2': 88 | account = SavingsAccount(holder_name, account_number, current_balance) 89 | elif account_type == '3': 90 | account = DematAccount(holder_name, account_number, current_balance) 91 | else: 92 | print("Invalid input") 93 | return 94 | 95 | # Calculate service tax 96 | service_tax = account.calculate_service_tax(transfer_amount) 97 | 98 | # Update balance 99 | account.balance -= (transfer_amount + service_tax) 100 | 101 | # Display remaining balance 102 | account.display() 103 | 104 | if __name__ == "__main__": 105 | main() 106 | -------------------------------------------------------------------------------- /gu-ito-9.py: -------------------------------------------------------------------------------- 1 | '''You are required to implement a class called 'Matrix' containing a constructor that initializes the number of rows and the number of columns of a new Matrix object. The Matrix class should have the following methods: 2 | 3 | print_rows(): Print the number of rows of the matrix. 4 | print_cols(): Print the number of columns of the matrix. 5 | print_elements(): Print the elements of the matrix in the form of a 2D array. 6 | If the input is invalid, print 'invalid'. 7 | 8 | Input: 9 | 10 | The input consists of a single line in the format rowsxcols total_elements, where rows and cols are integers representing the number of rows and columns of the matrix respectively, and total_elements is the total number of elements in the matrix. This is followed by the elements of the matrix, each element separated by a space. 11 | 12 | Output: 13 | 14 | Output the number of rows and columns of the matrix on separate lines, followed by the elements of the matrix in the form of a 2D array. 15 | 16 | Constraints: 17 | 18 | The total number of elements in the matrix must equal rows * cols. 19 | 20 | Sample Input: 21 | 22 | 3x3 9 23 | 1 2 3 24 | 4 5 6 25 | 7 8 9 26 | 27 | Sample Output: 28 | 29 | 3 30 | 3 31 | 1 2 3 32 | 4 5 6 33 | 7 8 9''' 34 | 35 | 36 | 37 | class Matrix: 38 | def __init__(self, rows, cols, elements): 39 | self.rows = rows 40 | self.cols = cols 41 | self.elements = elements 42 | 43 | def print_rows(self): 44 | print(self.rows) 45 | 46 | def print_cols(self): 47 | print(self.cols) 48 | 49 | def print_elements(self): 50 | for row in self.elements: 51 | print(*row) 52 | 53 | def main(): 54 | try: 55 | # Input 56 | rows_cols, total_elements = input().split() 57 | rows, cols = map(int, rows_cols.split("x")) 58 | total_elements = int(total_elements) 59 | 60 | # Validate input 61 | if rows * cols!= total_elements: 62 | print("invalid") 63 | return 64 | 65 | elements = [list(map(int, input().split())) for _ in range(rows)] 66 | 67 | matrix = Matrix(rows, cols, elements) 68 | 69 | # Output 70 | matrix.print_rows() 71 | matrix.print_cols() 72 | matrix.print_elements() 73 | 74 | except ValueError: 75 | print("invalid") 76 | 77 | if __name__ == "__main__": 78 | main() --------------------------------------------------------------------------------