├── BigStoryEncrypted.txt ├── BigStory_Decrypted.txt ├── BigStory_TextFile.txt ├── CodeFromLectures ├── W10_1_ClassesAndObjects.py ├── W10_2_AttributesAndMethods.py ├── W10_3_Employee.py ├── W10_3_Inheritance-MethodOverriding.py ├── W10_3_Person.py ├── W10_3_Student.py ├── W10_4_List VsNumpyArray.png ├── W10_4_NumpyLibrary.py ├── W10_5_MatplotlibLibrary.py ├── W11_1_ExceptionHandling.py ├── W11_2_ExceptionHandling2.py ├── W11_3_FunctionalProgramming1.py ├── W11_4_FunctionalProgramming2.py ├── W11_5_FunctionalProgramming3.py ├── W1_1_BasicThings.py ├── W1_2_DataTypes2.py ├── W1_3_OperatorsExpressions.py ├── W1_4_Strings.py ├── W1_5_Strings2.py ├── W2_1_DynamicTyping.py ├── W2_2_VariableRulesandTricks.py ├── W2_3_EscapeCharactersList.txt ├── W2_3_EscapeCharsAndQuotes.py ├── W2_4_String Methods │ ├── String Methods1.png │ ├── String Methods2.png │ ├── String Methods3.png │ ├── String Methods4.png │ ├── String Methods5.png │ └── String Methods6.png ├── W2_5_MoreOnStrings.py ├── W2_6_IfElseIfConditionals.py ├── W2_7_FlowChartProblem.py ├── W2_8_ImportLibrary1.py ├── W2_9_ImportLibrary2.py ├── W3_1_WhileLoop.py ├── W3_2_WhileLoop2.py ├── W3_3_ForLoop.py ├── W3_4_FormattedPrinting.py ├── W3_5_MoreOnLoops.py ├── W3_6_ApplyNestedLoops1.py ├── W4_1_ListsWarmup.py ├── W4_2_BirthdayParadox.py ├── W4_3_NaiveSearchInList.py ├── W4_4_TheObviousSort.py ├── W4_5_DotProduct.py ├── W4_6_MatrixAddition.py ├── W4_7_MatrixMultiplication.py ├── W4_ListsNotesForAssignments.md ├── W5_1_IntroToFunctions.py ├── W5_2_MoreOnFunctions.py ├── W5_3_SortingUsingFunctions.py ├── W5_4_MatrixMultiplyUsingFunctions.py ├── W5_5_RecursionIllustration.py ├── W5_6_FunctionArguments.py ├── W5_7_ScopeOfVariables.py ├── W5_8_TypesOfFunctions.py ├── W5_9_FunctionTutorial1.py ├── W5_9_FunctionTutorial2.py ├── W5_9_FunctionTutorial3.py ├── W6_1_ListsAndSets.py ├── W6_2_Dictionaries.py ├── W6_3_Tuples.py ├── W6_4_MoreOnLists.py ├── W6_5_MoreOnTuples.py ├── W6_6_MoreOnDictionaries.py ├── W6_7_MoreOnSets.py ├── W6_CollectionsSummary_1.png ├── W6_CollectionsSummary_2.png ├── W8_1_0InListRecursion.py ├── W8_2_SortingRecursively.py ├── W8_3_BinarySearchWarmup.py ├── W8_3_Search.py ├── W8_4_BinarySearchImplementation.py ├── W8_5_BinarySearch_RecursiveWay.py ├── W9_1_ReadingWritingToFile.py ├── W9_2_BigTextFileHandling.py ├── W9_3_CeaserCipherEncryption.py ├── W9_4_WhyPandas1.py ├── W9_5_WhyPandas2.py ├── W9_6_PandasSeriesDataframes1.py ├── W9_7_PandasSeriesDataframes2.py └── __pycache__ │ ├── BasicThings.cpython-38.pyc │ ├── DataTypes2.cpython-38.pyc │ ├── W10_3_Person.cpython-39.pyc │ ├── W4_3_NaiveSearchInList.cpython-39.pyc │ ├── W8_3_Search.cpython-39.pyc │ ├── W8_4_BinarySearchImplementation.cpython-39.pyc │ └── W8_Search.cpython-39.pyc ├── ExamScores.csv ├── PPA, GrPA and Assignment Codes ├── W10_GrPA1.py ├── W10_GrPA2.py ├── W10_GrPA3.py ├── W10_GrPA4.py ├── W12_PPA1.py ├── W12_PPA3.py ├── W12_PPA5.py ├── W12_PPA6.py ├── W1_GrPA6.py ├── W2_GrPA1.py ├── W2_GrPA3.py ├── W2_GrPA4.py ├── W2_GrPA5.py ├── W2_PPA5.py ├── W2_PPA6.py ├── W2_PPA7.py ├── W2_PPA8.py ├── W2_PPA9.py ├── W3_GrPA1.py ├── W3_GrPA2.py ├── W3_GrPA3.py ├── W3_GrPA4.py ├── W3_GrPA5.py ├── W3_GrPA6.py ├── W3_PPA11.py ├── W3_PPA12.py ├── W3_PPA5.py ├── W3_PPA6.py ├── W4_GrPA1.py ├── W4_GrPA2.py ├── W4_GrPA3.py ├── W4_GrPA4.py ├── W4_GrPA5.py ├── W4_PPA10.py ├── W4_PPA11.py ├── W4_PPA3.py ├── W4_PPA5.py ├── W4_PPA6.py ├── W4_PPA7.py ├── W4_PPA8.py ├── W4_PPA9.py ├── W5_GA5_Q9.py ├── W5_GrPA1.py ├── W5_GrPA3.py ├── W5_GrPA4.py ├── W5_GrPA5.py ├── W5_PPA10.py ├── W5_PPA5.py ├── W5_PPA7.py ├── W5_PPA8.py ├── W5_PPA9.py ├── W6_PPA10.py ├── W6_PPA6.py ├── W6_PPA7.py ├── W6_PPA8.py ├── W6_PPA9.py ├── W7_GrPA1.py ├── W7_GrPA2.py ├── W7_GrPA3.py ├── W7_GrPA4.py ├── W8_PPA3.py ├── W8_PPA4.py ├── W8_PPA5.py ├── W9_GrPA1.py ├── W9_GrPA2.py ├── W9_GrPA3.py ├── W9_GrPA4.py ├── W9_PPA1.py ├── W9_PPA10.py ├── W9_PPA11.py ├── W9_PPA12.py ├── W9_PPA2.py ├── W9_PPA3.py ├── W9_PPA4.py ├── W9_PPA5.py ├── W9_PPA6.py ├── W9_PPA7.py ├── W9_PPA8.py ├── W9_PPA9.py └── test.py ├── Practice Test Codes ├── OPPE1_Mock1.py ├── OPPE1_Mock2.py ├── OPPE1_Mock3.py ├── OPPE1_Mock4.py ├── OPPE1_Mock5.py ├── OPPE1_Mock6.py ├── PracticeTest1_5.py └── PracticeTest2_1.py ├── Programming exam codes ├── CodeChef Practice by IITM │ ├── IITMPP01_LECANDY.py │ ├── IITMPP01_NOTINCOM.py │ ├── IITMPP01_SMSDICT.py │ ├── IITMPP01_SMTFAC3.py │ ├── IITMPP01_SMTFAC3_Alternative.class │ ├── IITMPP01_SMTFAC3_Alternative.java │ ├── IITMPP01_TheLeadGame.py │ ├── IITMPP01_VCS.py │ ├── IITMPP02_ABROADS.py │ ├── IITMPP02_COLDPLAY.py │ ├── IITMPP02_JFY.py │ ├── IITMPP02_JOKRBTMN.py │ ├── IITMPP02_KJCP3.py │ ├── IITMPP04CHEFSLP.py │ ├── IITMPP04_CARVANS.py │ ├── IITMPP04_ERROR.py │ ├── IITMPP04_GOLDTRIP.py │ ├── IITMPP04_ODDSEVENS.py │ ├── IITMPP05_CM164364.py │ ├── IITMPP05_CORTSENT.py │ ├── IITMPP05_DIRECTN.py │ ├── IITMPP05_EQDIFFER.py │ ├── IITMPP05_HIRETEST.py │ ├── IITMPP06_EMPR.py │ ├── IITMPP06_EXPRESSION_3.py │ ├── IITMPP06_FNDINT.py │ ├── IITMPP06_MONSTER1.py │ └── IITMPP06_MONSTER2.py └── Test2Q2.py ├── README.md ├── directory.txt ├── myText.txt ├── out.txt ├── pattern.csv └── testing.py /CodeFromLectures/W10_1_ClassesAndObjects.py: -------------------------------------------------------------------------------- 1 | class Student: #By convention, first letter of class name is always written in capital letters. We can also use Student() i.e. paranthesis after classname 2 | roll_no=None 3 | name=None 4 | s0=Student() #Here, Student() is a constructor, which is used to construct the object s0 5 | s0.roll_no=0 6 | s0.name='Bhuvanesh' 7 | print(s0.roll_no, " : ", s0.name) 8 | 9 | s1=Student() 10 | print(s1.roll_no,",",s1.name) 11 | 12 | s2=Student() 13 | s2.roll_no=2 14 | s2.name='Harish' 15 | print(s2.roll_no, " : ", s2.name) 16 | 17 | s50=Student() 18 | s50.name='Ashmita' 19 | print(s50.roll_no, ":", s50.name) -------------------------------------------------------------------------------- /CodeFromLectures/W10_2_AttributesAndMethods.py: -------------------------------------------------------------------------------- 1 | class Student: 2 | count=0 3 | def __init__(self,roll_no,name,total): # __init__ is 2 underscores followed by 'init' followed by 2 underscores and its used to initialize attributes of a class and parameters of the objects of the class. We must use self as the first parameter in every method within the class. 4 | self.roll_no=roll_no 5 | self.name=name 6 | self.total=total 7 | #self and __init__ are keywords here 8 | def display(self): 9 | print(self.roll_no,":",self.name, " : ", self.total) 10 | 11 | def result(self): #This is to add a behaviour to the objects inside the class 12 | if(self.total>90): 13 | print("Pass") 14 | else: 15 | print("Fail") 16 | # Note : When any function is inside a class or belongs to a class, it is called as method. Eg: String methods and the above methods inside class Student 17 | s0=Student(0,"Bhuvanesh",96) #Here, Student() is a constructor, which is used to construct the object s0 18 | Student.count+=1 19 | s0.display() 20 | s0.result() 21 | 22 | s1=Student(1,"Harish",85) 23 | Student.count+=1 24 | s1.display() 25 | s1.result() 26 | 27 | print(Student.count) -------------------------------------------------------------------------------- /CodeFromLectures/W10_3_Employee.py: -------------------------------------------------------------------------------- 1 | from W10_3_Person import Person #Thus we import class Person from file W10_3_Person.py 2 | class Employee(Person): #class Employee inherits the attributes of parent class Person 3 | count=0 4 | def __init__(self,name,age,Aadhar,salary): 5 | super().__init__(name,age,Aadhar) 6 | self.salary=salary 7 | 8 | def display(self):#Here we observe a case of method overriding 9 | print(self.name,self.age,self._AadharNumber,self.salary) 10 | 11 | e=Employee('Aritra Roy', 24, '8554-7559-6993', 2400000) 12 | e.display() -------------------------------------------------------------------------------- /CodeFromLectures/W10_3_Inheritance-MethodOverriding.py: -------------------------------------------------------------------------------- 1 | class Person: #Here, Person is the parent class or super class 2 | def __init__(self,name,age): 3 | self.name=name 4 | self.age=age 5 | 6 | def display(self): 7 | print(self.name,self.age) 8 | 9 | class Student(Person): #class Student inherits the attributes of parent class Person 10 | def __init__(self,name,age,marks): 11 | super().__init__(name,age) 12 | self.marks=marks 13 | 14 | def display(self): 15 | super().display() 16 | print(self.marks) 17 | 18 | class Employee(Person): #class Employee inherits the attributes of parent class Person 19 | count=0 20 | def __init__(self,name,age,salary): 21 | super().__init__(name,age) 22 | self.salary=salary 23 | 24 | def display(self):#Here we observe a case of method overriding 25 | print(self.name,self.age,self.salary) 26 | 27 | s=Student('Sandesh YM',19,90) 28 | s.display() 29 | 30 | e=Employee('Aritra Roy', 24, 2400000) 31 | e.display() -------------------------------------------------------------------------------- /CodeFromLectures/W10_3_Person.py: -------------------------------------------------------------------------------- 1 | class Person: #Here, Person is the parent class or super class 2 | def __init__(self,name,age,Aadhar): 3 | self.name=name 4 | self.age=age 5 | self._AadharNumber=Aadhar # The ._ is used to indicate private attributes or member that are protected and not accessible from outside. 6 | 7 | def display(self): 8 | print("Name : ",self.name," Age : ", self.age," Aadhar Number : ",self._AadharNumber) 9 | 10 | #m=Person("Aritra Roy",21,'9841-5225-8775') 11 | #m.display() -------------------------------------------------------------------------------- /CodeFromLectures/W10_3_Student.py: -------------------------------------------------------------------------------- 1 | from W10_3_Person import Person #Thus we import class Person from file W10_3_Person.py 2 | class Student(Person): #class Student inherits the attributes of parent class Person 3 | def __init__(self,name,age,marks,Aadhar): 4 | super().__init__(name,age,Aadhar) 5 | self.marks=marks 6 | 7 | def display(self): 8 | super().display() 9 | print("Marks = ", self.marks) 10 | 11 | s=Student('Sandesh YM',19,90,'8554-7554-1221') 12 | s.display() -------------------------------------------------------------------------------- /CodeFromLectures/W10_4_List VsNumpyArray.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W10_4_List VsNumpyArray.png -------------------------------------------------------------------------------- /CodeFromLectures/W10_4_NumpyLibrary.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | a=np.array(42) 4 | b=np.array([1,2,3,4,5]) 5 | c=np.array([[1,2,3],[4,5,6]]) 6 | d=np.array([[[1,2,3],[4,5,6]],[[-1,-2,-3],[-4,-5,-6]]]) 7 | 8 | print(a, a.ndim, '\n') #.ndim gives the dimensions of a numpy array 9 | print(b, b.ndim, '\n') 10 | print(c, c.ndim, '\n') 11 | print(d, d.ndim, '\n') 12 | -------------------------------------------------------------------------------- /CodeFromLectures/W10_5_MatplotlibLibrary.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot as plt 2 | import numpy as np 3 | 4 | x=np.array([5,7,8,7,2,17,2,9,4,11,12,9,6]) 5 | y=np.array([99,86,87,88,111,86,103,87,94,78,77,85,86]) 6 | plt.scatter(x,y) 7 | 8 | 9 | a=np.array([1,3,5,7,9,11,13,15,17]) 10 | b=np.array([84,86,88,90,92,94,96,98,100]) 11 | plt.plot(a,b,color='red',marker='.') 12 | 13 | plt.show() # First it will show the scatter plot and the line graph together 14 | 15 | #Bar Charts:- 16 | m=np.array(['A','B','C','D']) 17 | n=np.array([3,8,1,10]) 18 | plt.bar(m,n) 19 | plt.show() #Secondly, it will show this bar graph 20 | plt.barh(m,n) 21 | plt.show() #Next, it will show the Horizontal Bar graph 22 | 23 | #Histograms:- 24 | x=np.random.normal(170,10,250) #This is the way to generate random numbers using numpy 25 | plt.hist(x) 26 | plt.show() # Next it will show the histogram 27 | 28 | #Pie Charts:- 29 | p=np.array([35,25,25,15]) 30 | myLabels=["Apples","Bananas",'Cherries','Dates'] 31 | plt.pie(p,labels=myLabels,startangle=90) 32 | plt.show() 33 | 34 | #Code for Matplotlib subplots not included here as it is explained too fast in video. Link to learn Matplotlib subplots properly:- 35 | #https://www.youtube.com/watch?v=XFZRVnP-MTU&list=PL-osiE80TeTvipOqomVEeZ1HRrcEvtZB_&index=10 -------------------------------------------------------------------------------- /CodeFromLectures/W11_1_ExceptionHandling.py: -------------------------------------------------------------------------------- 1 | # 3 types of errors that are exception, and can be handled with Exception Handling are : 1) Divide by 0, 2) Variable not defined, 3) File Not Found. There are many more (nearly 30) exceptions that can be handled in python. 2 | # https://www.programiz.com/python-programming/exception-handling 3 | 4 | a=int(input()) 5 | b=int(input()) 6 | try: 7 | f=open('abc.txt','r') 8 | c=a/b 9 | print(d) 10 | print(c) 11 | f.close() 12 | except ZeroDivisionError: 13 | print("Invalid Input - Division by 0 is not possible") 14 | except NameError: 15 | print("Variable not Defined!") 16 | except FileNotFoundError: 17 | print("File not Found!") 18 | except: 19 | print("Something went wrong!") 20 | else: 21 | print("Nothing Went Wrong") 22 | finally: 23 | #f.close() 24 | print("This is finally block which will be always executed even if there are no exceptions to handle!") 25 | -------------------------------------------------------------------------------- /CodeFromLectures/W11_2_ExceptionHandling2.py: -------------------------------------------------------------------------------- 1 | a=int(input()) 2 | if(a<18): 3 | raise Exception("You are underage") -------------------------------------------------------------------------------- /CodeFromLectures/W11_3_FunctionalProgramming1.py: -------------------------------------------------------------------------------- 1 | # About Iterators and Generators:- 2 | 3 | fruits=['mango','apple','banana','guava','pear','grape','watermelon'] 4 | #for fruit in fruits: 5 | #print(fruit) 6 | basket=iter(fruits) #Only works for all iterable entities like Strings, Lists, Tuples. Here basket is an iterator created using the 'iter()' function 7 | print(basket) 8 | print(next(basket)) 9 | print(next(basket)) 10 | print(next(basket)) 11 | 12 | def square(limit): 13 | x=0 14 | while x0): 15 | print(a) 16 | a=a-1 17 | ''' 18 | #To convert a while loop to a single line of code:- 19 | while x>0: print(x); x-=1 20 | 21 | #List Comprehension:- 22 | fruits=['mango','apple','banana','guava','pear','grape','watermelon'] 23 | newlist=[fruit.capitalize() for fruit in fruits if 'n' in fruit] #We print all those fruit names in the list fruits (after capitalizing their first letters) names, only if the letter n is in them 24 | print(newlist) 25 | -------------------------------------------------------------------------------- /CodeFromLectures/W11_5_FunctionalProgramming3.py: -------------------------------------------------------------------------------- 1 | #Using lambda function to shorten function code-blocks into single line code:- 2 | add = lambda x,y:x+y 3 | substract=lambda x,y:x-y 4 | divide=lambda x,y:x/y 5 | multiply=lambda x,y:x*y 6 | 7 | print(add) 8 | print(type(substract)) 9 | print(add(8,10)) 10 | print(divide(15000,30)) 11 | print(multiply(81,9)) 12 | print(substract(50,9)) 13 | 14 | #Using enumerate function and zip function:- 15 | fruits=['mango','apple','banana','guava','pear','grape','watermelon','kiwi','avocado'] 16 | size=[5,5,6,5,4,5,10,4,7] 17 | for fruit in enumerate(fruits): 18 | print(fruit) 19 | 20 | print(dict(zip(fruits,size))) 21 | 22 | #Using maps in python:- 23 | a=[1,2,3,4,5,6,7,8,9,10] 24 | b=[100,90,80,70,60,50,40,30,20,10] 25 | def increment(x): 26 | return x+1 27 | c=map(substract,a,b) #substract is already a predefined function here 28 | d=map(increment,a) 29 | print(list(c)) 30 | print(list(d)) 31 | 32 | #Using map and filter functions to compute square root of all +ve integers in a given list:- 33 | import math 34 | x=[25,-16,9,81,-100,625] 35 | def is_positive(a): 36 | if(a>=0): 37 | return a 38 | SquareRoot=lambda u:math.sqrt(u) 39 | e=map(SquareRoot,filter(is_positive,x)) # Or, we could have used 'lambda u:u>0,x' within the filter() function and completely gotten rid of the is_positive() function. 40 | print(list(e)) -------------------------------------------------------------------------------- /CodeFromLectures/W1_1_BasicThings.py: -------------------------------------------------------------------------------- 1 | # Basic Introduction Stuff:- 2 | print("Hello world," " Kaisa hein bro?", "Printing using double quote.") 3 | print('Printing 10 using single quote.', 'Thats how we print') 4 | a = 10 # Declaring variable 5 | print(a) 6 | a = a+1 # Incrementing value of variable 7 | print(a) 8 | # Taking user input of an integer and printing that number:- 9 | print("Enter a number") 10 | n = int(input()) # That's how we take user input of an integer 11 | print("The number entered is = ", n) 12 | # Combining input and print commands:- 13 | name = str(input('What is your name? ')) 14 | age = int(input("What is your age? ")) 15 | place = str(input('Where do you live? ')) 16 | print('Good to know that you are only ', age, ' years old.') 17 | # Area of circle with radius as user input:- 18 | r = float( 19 | input('Enter the radius of the circle whose area you want to be calculated.')) 20 | area = 3.14*r*r 21 | print('Area of the circle is = ', area, " square units") 22 | # Data Types:- 23 | print('In this program, variable r is of type : ', type(r)) 24 | print('In this program, variable name is of type : ', type(name)) 25 | print('In this program, variable area is of type : ', type(area)) 26 | l = [10, 20, 30, 68, 732] 27 | print(l) 28 | print("First and last element of l : ", 29 | l[0], ",", l[4], " and Data type of an individual element of list is : ", type(l[2])) 30 | print("l is of datatype : ", type(l)) 31 | -------------------------------------------------------------------------------- /CodeFromLectures/W1_2_DataTypes2.py: -------------------------------------------------------------------------------- 1 | b1 = True 2 | b2 = False 3 | print('Data types of b1 and b2 are : ', type(b1), 'and', type(b2)) 4 | # Converting one data type into another:- 5 | a = int(5.695) # Converting decimal (float) into integer 6 | b = int('10') # Converting String into integer 7 | c = float('9') # Converting integer to float 8 | d = float('10.567') # Converting String to float 9 | print(a, type(a)) 10 | print(b, type(b)) 11 | print(c, type(c)) 12 | print(d, type(d)) 13 | # Type conversion to and from boolean data type:- 14 | m = bool(10) # Converting integer to boolean 15 | n = bool(0) # Converting 0 to boolean 16 | o = bool(-10.25) # Converting floating point value to boolean 17 | p = bool(0.00) 18 | q = bool('India') # Converting String to boolean 19 | r = bool('10.4') 20 | s = bool('-52.6') 21 | t = bool('0') 22 | e = bool('') # Converting empty String to boolean 23 | print(m, type(m)) 24 | print(n, type(n)) 25 | print(o, type(o)) 26 | print(p, type(p)) 27 | # Note : In boolean, 0 means False and rest any other number means True value. In boolean, any String value is converted to True value, except the empty String. 28 | print(q, type(q)) 29 | print(r, type(r)) 30 | print(s, type(s)) 31 | print(t, type(t)) 32 | print(e, type(e)) 33 | -------------------------------------------------------------------------------- /CodeFromLectures/W1_3_OperatorsExpressions.py: -------------------------------------------------------------------------------- 1 | a = "Aritra Roy" 2 | b = ' is a good boy.' 3 | print(a+b) # Concatenation of Strings 4 | c = [1, 3, 5] 5 | d = [7, 9, 11] 6 | print(d+c) # Putting together two lists into one list 7 | print(11/85) 8 | print(10+13*4/2) # Displaying Operator Precendence 9 | # Arithmetic Operators : +, -, *, /, //, %, ** 10 | print('Floor Division Operator returns integer part on division : ', 7 // 2) 11 | print('Modulus operator :', 7 % 3) 12 | print('Exponential operator : ', 6**2) 13 | print('-------------------------------------') 14 | # Relational Operators : >, <, >=, <=, ==, != [They always return boolean values] 15 | print(5 < 10) 16 | print(48 >= 154) 17 | print(64 <= 66) 18 | print(88 == 88) # Equal to Operator 19 | print(48 != 48) # Not Equal To Operator 20 | print('-------------------------------------') 21 | # Logical Operators : and, or, not 22 | print(True and True) # and operator 23 | print(True and False) 24 | print(False and False) 25 | print(False and True) 26 | print(True or True) # or operator 27 | print(True or False) 28 | print(False or False) 29 | print(False or True) 30 | # not operator - It can be used either with or without brackets, as we see here 31 | print(not (True)) 32 | print(not False) 33 | -------------------------------------------------------------------------------- /CodeFromLectures/W1_4_Strings.py: -------------------------------------------------------------------------------- 1 | a='coffee' 2 | b="beater" 3 | c='0123456789' 4 | d=c[4] 5 | print(a[4]) 6 | print(a[0:4]) #This prints the cut out String from 0th character to 3rd character 7 | print(a[1:4]+b[0:4]) 8 | print(d+c[7]) #Concatenation of integers taken as string 9 | n=int(d+c[9]) #Converting the concatenated string back to integer 10 | print(n) 11 | s1=int(d) 12 | s2=int(c[8]) 13 | print(s1+s2) 14 | -------------------------------------------------------------------------------- /CodeFromLectures/W1_5_Strings2.py: -------------------------------------------------------------------------------- 1 | s = 'good' 2 | print(s*5) # Replication of a String (Here String s has been replicated 5 times) 3 | print(s[0]*5) 4 | # Comparison of Strings:- 5 | x = 'India' 6 | y = 'apple' 7 | print(x == 'India') 8 | # Relational operators are case-sensitive while comparing between strings 9 | print(x == 'india') 10 | # Computer starts comparing strings character by character. 0th letter of the 2 strings will be compared first. 11 | print(x >= y) 12 | print(y > 'one') # a is not greater than o in alphabetical order 13 | print('four' < 'ten') # f is less than t in alphabetical order 14 | # First character is same. But 2nd character b is less than z in alphabetical order 15 | print('ab' < 'az') 16 | # First 2 characters are same. But 3rd character c is not greater than f in alphabetical order 17 | print('abc' > 'abf') 18 | # First 5 characters are equal but when 5th character 'f' of first string is compared to nothing in second character, first string is declared greater than second string. 19 | print('abcdef' > 'abcde') 20 | # Negative indexing of String:- 21 | m = 'Aritra Roy' 22 | print(m[-1]) 23 | print(m[-2]) 24 | print(m[-3]) 25 | print(m[-4]) 26 | print(m[-5]) 27 | print(m[-6]) 28 | print(m[-7]) 29 | print(m[-8]) 30 | print(m[-9]) 31 | print(m[-10]) 32 | # We observe that negative index of String denotes its characters in the reverse order 33 | # Finding length of string using len function:- 34 | print('Length of the string m is = ', len(m)) 35 | -------------------------------------------------------------------------------- /CodeFromLectures/W2_1_DynamicTyping.py: -------------------------------------------------------------------------------- 1 | #Dynamic Typing - In python, the data type of a variable is flexible or dynamic. It can change with respect to what type of value is assigned to it. 2 | a=10 3 | print(type(a)) 4 | a='India' 5 | print(type(a)) 6 | n=10 7 | print(type(n)) 8 | n=n/2 # The moment we use division operator, python changes data type of variable to float 9 | print(type(n)) -------------------------------------------------------------------------------- /CodeFromLectures/W2_2_VariableRulesandTricks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Rules for naming variables in python:- 3 | 1) We can not use Python Keywords like 'for', 'and', 'while' etc. as variable names. 4 | 2) Only alphanumeric characters (all upper and lower case characters and integers from 0 to 9) and underscore(_) in variable names. 5 | 3) A variable name must be started with an alphabet or an underscore, but variable name cannot start with a number. 6 | 4) Variable names are case-sensitive. 7 | """ 8 | x,y=1,2 #multiple assignments 9 | print(x,y) 10 | a=b=c=10 11 | print(a,b,c) 12 | x,y=y,x #swapping values of variables 13 | print(x,y) # Now x=2, y=1 14 | del(a,b,c) #The variables a, b are deleted now 15 | # print(c) or print(b) or print(a) will give error now since those variables are deleted. 16 | x+=1 #means x=x+1 17 | x*=2 #means x=x*2 18 | x/=6 #means x=x/6 19 | x-=6 #means x=x-6 20 | print(x) 21 | # Using 'in' operator to check if a particular string/character exists in another String:- 22 | print('alpha' in 'A variable name can only contain alpha-numeric characters and underscores') 23 | print('alpha' in 'A variable name must start with a letter or the underscore character') 24 | print("----------------------------") 25 | #Using Chaining operators (When we use multiple relational operators in a single statement, it is called Chaining Operator) to check validity of expressions:- 26 | p=5 27 | print(1 p <=9) 31 | print(5 == p > 4) 32 | -------------------------------------------------------------------------------- /CodeFromLectures/W2_3_EscapeCharactersList.txt: -------------------------------------------------------------------------------- 1 | Escape Sequence Reference List:- 2 | \ Prints in new line 3 | \\ Prints Backslash (\) 4 | \' Prints Single quote (') 5 | \" Prints Double quote (") 6 | \a ASCII Bell (BEL) - makes bell alert sounds 7 | \b ASCII Backspace (BS) - removes previous Character 8 | \f ASCII Formfeed (FF) 9 | \n ASCII Linefeed (LF) 10 | \r ASCII Carriage Return (CR) 11 | \t ASCII Horizontal Tab (TAB) 12 | \v ASCII Vertical Tab (VT) 13 | \ooo Character with octal value ooo 14 | \xhh Character with hex value hh -------------------------------------------------------------------------------- /CodeFromLectures/W2_3_EscapeCharsAndQuotes.py: -------------------------------------------------------------------------------- 1 | #Inserting single quote or apostrophe symbol (using \):- 2 | print('Hey What\'s up! Welcome to Aritra Roy\'s party.') 3 | #or 4 | print("Hey What's up! Welcome to Aritra Roy's party.") 5 | #Inserting double quote in print statement (using \):- 6 | print ('Aritra Roy says, \" I am a B.Sc student of IIT Madras also, apart from a being civil engineering student at BMSCE, Bangalore\"') 7 | #or 8 | print ('Aritra Roy says, "I am a B.Sc student of IIT Madras also, apart from a being civil engineering student at BMSCE, Bangalore"') 9 | #Inserting extra space or tab space using \t :- 10 | print("This is how we insert horizontal tab. \t That is, we add extra space using this escape sequence.") 11 | #Printing in new line using \n :- 12 | print ("My name is Aritra Roy. This is the first line. \nI am from West Bengal. This is a new second line.") 13 | # Note : To store a string spread over multiple lines we use """ :- 14 | z="""Aritra Roy 15 | can store 16 | strings 17 | in different 18 | lines in a variable""" 19 | print(z) 20 | 21 | -------------------------------------------------------------------------------- /CodeFromLectures/W2_4_String Methods/String Methods1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W2_4_String Methods/String Methods1.png -------------------------------------------------------------------------------- /CodeFromLectures/W2_4_String Methods/String Methods2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W2_4_String Methods/String Methods2.png -------------------------------------------------------------------------------- /CodeFromLectures/W2_4_String Methods/String Methods3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W2_4_String Methods/String Methods3.png -------------------------------------------------------------------------------- /CodeFromLectures/W2_4_String Methods/String Methods4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W2_4_String Methods/String Methods4.png -------------------------------------------------------------------------------- /CodeFromLectures/W2_4_String Methods/String Methods5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W2_4_String Methods/String Methods5.png -------------------------------------------------------------------------------- /CodeFromLectures/W2_4_String Methods/String Methods6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W2_4_String Methods/String Methods6.png -------------------------------------------------------------------------------- /CodeFromLectures/W2_5_MoreOnStrings.py: -------------------------------------------------------------------------------- 1 | alpha = 'abcdefghijklmnopqrstuvwxyz' # Set of English alphabets in a String 2 | i = 22 3 | print(alpha[i]) 4 | print(alpha[i+1]) 5 | print(alpha[i+2]) 6 | print(alpha[i+3]) 7 | print("........................................") 8 | j = 29 9 | print(alpha[j % 26]) 10 | print(alpha[(j+1) % 26]) 11 | print(alpha[(j+2) % 26]) 12 | print("........................................") 13 | # CEASER CIPHER - To output string with k-unit letter shift:- [Important programming concept useful in cryptography] 14 | n = 'aritra' 15 | t = '' 16 | x = 0 17 | k = 2 # The letter is to be shifted by k units on English alphabets 18 | t = t+(alpha[(((alpha.index(n[x])) + k) % 26)]) 19 | t = t+(alpha[(((alpha.index(n[x+1])) + k) % 26)]) 20 | t = t+(alpha[(((alpha.index(n[x+2])) + k) % 26)]) 21 | t = t+(alpha[(((alpha.index(n[x+3])) + k) % 26)]) 22 | t = t+(alpha[(((alpha.index(n[x+4])) + k) % 26)]) 23 | t = t+(alpha[(((alpha.index(n[x+5])) + k) % 26)]) 24 | print(t) 25 | -------------------------------------------------------------------------------- /CodeFromLectures/W2_6_IfElseIfConditionals.py: -------------------------------------------------------------------------------- 1 | # Movie Ticket Scenario:- 2 | birth_year = int(input('Please enter your year of birth')) 3 | current_year = 2021 4 | age = current_year-birth_year 5 | if(age < 13): 6 | print('You are under-age and hence, can\'t watch this movie.') 7 | print('Wait until you are 13 years of age at least to watch this movie.') 8 | else: 9 | print('You are old enough to watch the movie.') 10 | print('Don\'t forget to watch the prequels and sequels.') 11 | 12 | print('Have a nice time') 13 | # Even Odd Numbers Program:- 14 | num = int(input('Enter an integer to check if it is even or not : ')) 15 | if(num % 2 == 0): 16 | print('Even number') 17 | else: 18 | print('Odd number') 19 | 20 | # Number Ending with 5 or 0 or anything else:- 21 | n = int(input('Enter a number : ')) 22 | if(n % 5 == 0): 23 | if(n % 10 == 0): 24 | print('0') 25 | else: 26 | print('5') 27 | else: 28 | print('Other') 29 | 30 | # Marks Classification and Gradation of student:- 31 | marks = int(input('Enter marks : ')) 32 | if(marks >= 0 and marks <= 100): 33 | if(marks >= 90): 34 | print('Grade A') 35 | elif(marks >= 80 and marks < 90): 36 | print('Grade B') 37 | elif(marks >= 70 and marks < 80): 38 | print('Grade C') 39 | elif(marks >= 60 and marks < 70): 40 | print('Grade D') 41 | else: 42 | print('Grade E') 43 | else: 44 | print('Invalid Input') 45 | -------------------------------------------------------------------------------- /CodeFromLectures/W2_7_FlowChartProblem.py: -------------------------------------------------------------------------------- 1 | print("Travel from City A to B Flowchart Based Problem") 2 | time=int(input('Enter time : ')) 3 | longer=int(input('Define longer : ')) 4 | if(time >= longer): 5 | price=int(input('Enter Price : ')) 6 | higher=int(input('Define higher : ')) 7 | if(price >= higher): 8 | print('Train') 9 | else: 10 | print('Coach') 11 | else: 12 | price=int(input('Enter Price : ')) 13 | higher=int(input('Define higher : ')) 14 | if(price >= higher): 15 | print('Daytime Flight') 16 | else: 17 | print('Red eye Flight') 18 | 19 | print('You have arrived at city B.') 20 | 21 | -------------------------------------------------------------------------------- /CodeFromLectures/W2_8_ImportLibrary1.py: -------------------------------------------------------------------------------- 1 | print('First We import the math library:-') 2 | import math 3 | print(math.log(10)) 4 | print(math.cos(30)) 5 | print(math.sqrt(16)) 6 | print(math.factorial(5)) 7 | print(math.pow(10,3)) 8 | 9 | print('Now we shall import the random library:-') 10 | import random 11 | print(random.random()) #Gives us a random number between 0 and 1 12 | 13 | print('Simulating coin toss using the random function of the random function in random library:- ') 14 | a=random.random() 15 | print (a) 16 | if(a<0.5): 17 | print('Heads') 18 | else: 19 | print('Tail') 20 | 21 | print('Simulating Dice Roll of six-faced dice using random function:-') 22 | print(random.randrange(1,7)) # Gives us a random integer between the specified range of integers excluding the upper range. 23 | 24 | print('Simulating the sum of outcome out of rolling 2 six-faced dice simultaneously:- ') 25 | dice1=random.randrange(1,7) 26 | dice2=random.randrange(1,7) 27 | total=dice1 + dice2 28 | print('Your sum of the outcomes of a pair of dice is = ', total) 29 | # You can verify central limit theorem by running the code multiple times and seeing the random outcome -------------------------------------------------------------------------------- /CodeFromLectures/W2_9_ImportLibrary2.py: -------------------------------------------------------------------------------- 1 | print('We shall import the calendar library and other libraries in 5 different ways and note the differences in code :-') 2 | import calendar #First way to import 3 | print(calendar.month(2000,4)) # Shows the calendar of the 4th month in the year 2000 AD. 4 | print(calendar.calendar(2021)) #Displays the entire calendar of the year 2021 AD. 5 | ''' 6 | from calendar import * # Second way to import [Not an optimum way as we are importing everything from the calendar library] 7 | 8 | print(calendar(2020)) # Prints entire calendar of the year 2020 AD. Note here we do not use calendar.calendar() since we already imported everything(meant by *) from the calendar library. 9 | 10 | print(month(2024,8)) # Shows the calendar of the 8th months in the year 2024 AD. Note here we do not use calendar.calendar() since we already imported everything(meant by *) from the calendar library. 11 | 12 | ''' 13 | from calendar import month # 3rd Way to import 14 | print(month(2020,4)) 15 | 16 | import random as c # 4th way to import 17 | print(c.randrange(1,10)) 18 | 19 | from math import sqrt as b #5th way to import 20 | print(b(64)) -------------------------------------------------------------------------------- /CodeFromLectures/W3_1_WhileLoop.py: -------------------------------------------------------------------------------- 1 | #Program 1:- 2 | year=int(input('Enter the year of Independence of India: ')) 3 | while(year != 1947): 4 | print('You got it wrong. Please try again.') 5 | year=int(input()) 6 | 7 | print('Yeah! You got it right. India got independence in the year 1947') 8 | # Program 2:- 9 | print('Now we shall compute factorial using while loop.') 10 | num=int(input('Enter the number whose factorial you want to find: ')) 11 | i=1 12 | fact=1 13 | while(i<=num): 14 | fact=fact*i 15 | i+=1 16 | 17 | print('Factorial of the number', num, 'is = ', fact) 18 | 19 | -------------------------------------------------------------------------------- /CodeFromLectures/W3_2_WhileLoop2.py: -------------------------------------------------------------------------------- 1 | # Better Factorial Program:- [To fit all possible test cases] 2 | num=int(input('Enter a number whose factorial you want to find: ')) 3 | fact=1 4 | original=num 5 | if(num<0): 6 | print('Undefined') 7 | else: 8 | while(num>0): 9 | fact=fact*num 10 | num=num-1 11 | print('The factorial of the number ', original, 'is = ', fact) 12 | 13 | # Program to find number of digits in given number:- 14 | print('This is a program to find number of digits in given number:-') 15 | n=abs(int(input('Enter the number whose number of digits you want to find'))) #Takes absolute value of the user-input number 16 | digits=1 17 | while(n>9): 18 | n=n//10 #Remember the // (floor division) operator only returns the integer part of quotient on division 19 | digits+=1 20 | print('The number has ', digits, ' digit(s)') 21 | 22 | # Program to reverse the digits of a given number and check if number is palindrome or not:- 23 | print('This is a program to reverse the digits of a given number:-') 24 | num2=(int(input('Enter the number which you want to be printed in the reverse order'))) 25 | absolute=abs(num2) #Takes absolute value of the user-input number 26 | rev=0 27 | while(absolute>0): 28 | last=absolute%10 29 | rev=rev*10+last 30 | absolute=absolute//10 31 | if(num2>=0): 32 | result=rev 33 | else: 34 | result=rev-2*rev #Or, we can simply write result = (0-rev) 35 | print(result) 36 | if(num2==result): 37 | print('The number ', num2, 'is a palindrome number.') 38 | else: 39 | print('The number ', num2, 'is not a palindrome number.') -------------------------------------------------------------------------------- /CodeFromLectures/W3_3_ForLoop.py: -------------------------------------------------------------------------------- 1 | # Understanding for loop syntax in Python:- 2 | j = int(input('Enter number of times you want for loop to run: ')) 3 | for i in range(j): 4 | print(i, "Hello India") 5 | print("Happy Independence Day") 6 | if(i % 2 == 0): 7 | print(i, 'Jai Hind!') 8 | else: 9 | print(i, 'Bharat Mata Ki Jai!') 10 | 11 | # Program to add the sum of first n natural numbers:- 12 | print("This is a Program to add the sum of first n natural numbers:-") 13 | n = int(input('Enter the value of n: ')) 14 | sum = 0 15 | for i in range(1, n+1): # This means the loop runs from 1,2,3,..,n 16 | sum = sum+i 17 | print('The sum of first ', n, 'numbers is = ', sum) 18 | 19 | # Program to print multiplication table of a natural number:- 20 | print("This is a program to print multiplication table for a natural number from 1 to 10") 21 | num = int( 22 | input('Enter the number whose multiplication table you want to be printed: ')) 23 | for i in range(1, 11): # Loop runs from 1,2,...,10 24 | product = num*i 25 | print(num, ' * ', i, ' = ', product) 26 | 27 | # 2 Programs demonstrating for loop with 3 parameters as range i.e. (initial value, end value, step/iteration) :- 28 | print(' This is a program to print only odd numbers from 1 to 10 without using if statement:-') 29 | for i in range(1, 11, 2): # Loop runs from 1,3,5,7,9 30 | print(i) 31 | print('This is a program to reverse print even numbers within 20 and 0:-') 32 | for i in range(20, -1, -2): # Loop runs from 20,18,16,...,0 33 | print(i) 34 | 35 | # Demonstration of For loop without range or For-Each Loop :- 36 | print('Demonstration of For loop without range or For-Each Loop :-') 37 | country = 'India' 38 | for letter in country: 39 | print(letter) 40 | -------------------------------------------------------------------------------- /CodeFromLectures/W3_4_FormattedPrinting.py: -------------------------------------------------------------------------------- 1 | for x in range(10): 2 | print(x, end=', ') # end is used to print in a single line according to our requirements 3 | print() # Now we go to next line 4 | print('To print today\'s date:- ') 5 | d=int(input('Enter the day of the month: ')) 6 | m=int(input('Enter the month number: ')) 7 | y=int(input('Enter the year: ')) 8 | print('Today\'s date is : ', end=' ') 9 | print(d,m,y,sep='/') # sep decides the seperator character between variables to be printed 10 | 11 | # Printing multiplication table using Formatted Printing in 3 possible ways:- [Change the commented code to practice the other 2 methods] 12 | num=int(input('Enter the number whose multiplication table you want to print: ')) 13 | for i in range(1,11): 14 | # print(f'{num} x {i} = {num * i}') #1st way 15 | # print('{0} x {1} = {2}'.format(num,i,num*i)) #2nd way : Using format function 16 | print('%d x %d = %d' % (num,i,num*i)) #3rd way: Using String Modulo operator 17 | 18 | #Printing the value of pi in 3 ways of formatted printing:- [Using format specifiers] 19 | pi=22/7 20 | print(f'Value of pi is = {pi:.4f}') # :.4f ensures only 4 decimal places will be printed 21 | print('Value of pi is = {0:.3f}'.format(pi)) 22 | print('Value of pi is = %.2f' % (pi)) # %.2f ensures only 2 decimal places will be printed 23 | 24 | #Printing a right-aligned pattern:- [using formatted printing and format specifiers] 25 | print('{0:5d}'.format(1)) 26 | print('{0:5d}'.format(11)) 27 | print('{0:5d}'.format(111)) 28 | print('{0:5d}'.format(1111)) 29 | print('{0:5d}'.format(11111)) 30 | # 5d here specifies that we want to use minimum 5 integers (specified by d) in a print statement 31 | 32 | -------------------------------------------------------------------------------- /CodeFromLectures/W3_5_MoreOnLoops.py: -------------------------------------------------------------------------------- 1 | #For Each loop to find the number of digits in a number:- 2 | num=abs(int(input())) 3 | strNum=str(num) 4 | digits = 0 5 | for c in strNum: 6 | digits=digits+1 7 | print(digits) 8 | #Reversing a number using for each loop:- 9 | num2=int(input()) 10 | absnum2=abs(num2) 11 | str2=str(absnum2) 12 | rev='' 13 | for b in str2: 14 | rev=b+rev 15 | if(num2>0): 16 | print(rev) 17 | else: 18 | rev='-'+ rev 19 | print(rev) 20 | #Checking for palindrome number using for each loop:- (Checking if variable 'num 2' input is palindrome or not) 21 | if(rev==str(num2)): 22 | print(num2 ,' is a palindrome number') 23 | else: 24 | print(num2 ,'is not a palindrome number') -------------------------------------------------------------------------------- /CodeFromLectures/W3_6_ApplyNestedLoops1.py: -------------------------------------------------------------------------------- 1 | #Using nested for loop, find all prime numbers less than the entered number:- 2 | n=int(input('Enter a number till which you want to find all prime numbers')) 3 | if(n>2): 4 | print(2, end=' ') 5 | for i in range(3,n): 6 | flag=False 7 | for j in range(2,i): 8 | if(i%j==0): 9 | flag=False 10 | break 11 | else: 12 | flag=True 13 | if(flag==True): 14 | print(i, end=' ') 15 | #Find the length of the longest word from a set of words entered by user:- [Each word input stops when user inputs -1] 16 | print() 17 | word=input() 18 | maxLen=0 19 | while(word!='-1'): 20 | c=0 21 | for letter in word: 22 | c=c+1 23 | if(c>maxLen): 24 | maxLen=c 25 | longest=word 26 | word=input('Enter another word : ') 27 | print('The length of the longest word "', longest,'" is = ', maxLen) 28 | -------------------------------------------------------------------------------- /CodeFromLectures/W4_1_ListsWarmup.py: -------------------------------------------------------------------------------- 1 | l=[1,2,3,4,5] 2 | print (l) 3 | l.append(100) 4 | l.append(2) #Even when 2 is already present in the list l, once again 2 will be appended 5 | l.remove(2) #It will remove the first occurance of the element 2 6 | print(l) 7 | l.remove(2) #Now it removes the other remaining occurance of 2 as well 8 | print(l) 9 | x=[] 10 | x.append(l) #A list inside a list or, an array within as array 11 | print(x) 12 | m=[10,20,30] 13 | x.append(m) #2 lists l, m within the list x now 14 | print(x) 15 | t=[] 16 | t.append(x) 17 | t.append([50,60,70]) 18 | print(t) #1st element is the list x with 2 lists l,m within itself and 2nd element is the list [50,60,70] 19 | print("Now, 1st element [index=0] of the list t is ", t[0]," and 2nd element [index=1] of the list t is ", t[1]) 20 | #Now we shall create/store and print a matrix (A matrix is like 2 dimensional array) M:- 21 | M=[] 22 | M.append([1,2,3]) 23 | M.append([4,5,6]) 24 | M.append([7,8,9]) 25 | print(M) #Now M is a 3x3 matrix 26 | for i in range (3): 27 | for j in range (3): 28 | print("The element M[",i,"][",j,"] is = ", M[i][j]) -------------------------------------------------------------------------------- /CodeFromLectures/W4_2_BirthdayParadox.py: -------------------------------------------------------------------------------- 1 | import random 2 | l = [] 3 | for i in range(30): 4 | l.append(random.randint(1, 365)) 5 | l.sort() 6 | print(l) 7 | i=c=0 8 | while(i <= len(l)-2): 9 | if(l[i+1] == l[i]): 10 | print(l[i], "repeats") 11 | c += 1 12 | i = i+1 13 | if(c == 0): 14 | print('There is no repitition') 15 | -------------------------------------------------------------------------------- /CodeFromLectures/W4_3_NaiveSearchInList.py: -------------------------------------------------------------------------------- 1 | import random 2 | l = [11, 99, 88, 56, 25] 3 | for i in range(100000): 4 | l.append(random.randint(1, 10000)) 5 | print(l) 6 | print() 7 | 8 | a=0 9 | while(a > -1): 10 | a = int(input('Enter the number whose position(s) you want to find in the above list: ')) 11 | flag = 0 12 | print('The number ', a, 'is present at the following postion(s) of our list above:- ') 13 | for j in range(len(l)): 14 | if(l[j] == a): 15 | print(j) 16 | flag += 1 17 | if(flag == 0): 18 | print('Element is not found') -------------------------------------------------------------------------------- /CodeFromLectures/W4_4_TheObviousSort.py: -------------------------------------------------------------------------------- 1 | l=[1,58,12,-98,589,58,61,70] 2 | l.sort() #Its easy to do sorting using the built in sort() function 3 | print(l) 4 | #Now comes the obvious sort:- 5 | a=[4,10,95,-87,-569,2614,45,98,95,4] 6 | x=[] 7 | while(len(a)>0): 8 | min=a[0] 9 | for i in range(len(a)): 10 | if(a[i] maxi): 14 | maxi=l[i] 15 | return maxi 16 | def append_before(a,b): #To append list b before list a 17 | m=b+a 18 | return m 19 | ''' 20 | #Sudarshan sir's more complicated way:- 21 | newl=[] 22 | for i in range(len(b)): 23 | newl.append(b[i]) 24 | for i in range(len(a)): 25 | newl.append(a[i]) 26 | return newl 27 | ''' 28 | def list_average(l): 29 | sum=0 30 | for i in range(len(l)): 31 | sum=sum+l[i] 32 | avg=sum/len(l) 33 | return(avg) 34 | x=[] 35 | for i in range(5): 36 | n=int(input()) 37 | x.append(n) 38 | print (x) 39 | print('The first element of the list you have input is =', first_element(x)) 40 | print('The minimum value in the list you have input is = ', list_min(x)) 41 | print('The maximum value in the list you have input is = ', list_max(x)) 42 | p=[45,84,-9854,-63] 43 | print(append_before(p,x)) 44 | print("The average of all elements in the new list is = ", list_average(append_before(p,x))) -------------------------------------------------------------------------------- /CodeFromLectures/W5_3_SortingUsingFunctions.py: -------------------------------------------------------------------------------- 1 | def list_min(l): 2 | mini = l[0] 3 | for i in range(len(l)): 4 | if(l[i] < mini): 5 | mini = l[i] 6 | return mini 7 | 8 | 9 | def obvious_sort(l): 10 | x = [] 11 | while(len(l) > 0): 12 | mini = list_min(l) 13 | x.append(mini) 14 | l.remove(mini) 15 | return x 16 | 17 | 18 | p = [10, 8, 54, 9, 6, -8] 19 | print(obvious_sort(p)) 20 | -------------------------------------------------------------------------------- /CodeFromLectures/W5_4_MatrixMultiplyUsingFunctions.py: -------------------------------------------------------------------------------- 1 | #The code below is only valid for multiplication of square matrices:- 2 | def initialize_matrix(dim): 3 | c=[] 4 | for i in range(dim): 5 | c.append([]) 6 | for i in range(dim): 7 | for j in range(dim): 8 | c[i].append(0) 9 | return c 10 | 11 | def dot_product(a,b): 12 | dim=len(a) 13 | ans=0 14 | for i in range(dim): 15 | ans=ans+(a[i]*b[i]) 16 | return ans 17 | 18 | def row(M,i): 19 | dim=len(M) 20 | l=[] 21 | for k in range(dim): 22 | l.append(M[i][k]) 23 | return l 24 | 25 | def coloumn(M,j): 26 | dim=len(M) 27 | l=[] 28 | for k in range(dim): 29 | l.append(M[k][j]) 30 | return l 31 | 32 | def mat_multiply(a,b): 33 | dim=len(a) 34 | c=initialize_matrix(dim) 35 | for i in range(dim): 36 | for j in range(dim): 37 | c[i][j]=dot_product(row(a,i),coloumn(b,j)) 38 | return c 39 | 40 | m1=[] 41 | m2=[] 42 | r1=int(input('Enter the number of rows of the first matrix: ')) 43 | c1=int(input('Enter the number of coloumns of the first matrix: ')) 44 | print('Now enter the elements of the first matrix row-wise :- ') 45 | for i in range(r1): 46 | x=[] 47 | for j in range(c1): 48 | x.append(int(input())) 49 | m1.append(x) 50 | r2=int(input('Enter the number of rows of the second matrix: ')) 51 | c2=int(input('Enter the number of coloumns of the second matrix: ')) 52 | print('Now enter the elements of the second matrix row-wise :- ') 53 | for i in range(r2): 54 | y=[] 55 | for j in range(c2): 56 | y.append(int(input())) 57 | m2.append(y) 58 | 59 | print(mat_multiply(m1,m2)) -------------------------------------------------------------------------------- /CodeFromLectures/W5_5_RecursionIllustration.py: -------------------------------------------------------------------------------- 1 | def sum(n): 2 | if(n==1): 3 | return 1 4 | else: 5 | return n+sum(n-1) 6 | 7 | def compound(p,n): #Calculating Compound interest assuming 10% rate of interest where p is principal and n is number of years 8 | if(n==1): 9 | return p*1.1 10 | else: 11 | return (compound(p,n-1)*1.1) 12 | 13 | def factorial(n): 14 | if(n==1): 15 | return 1 16 | else: 17 | return (factorial(n-1)*n) 18 | 19 | print(sum(10)) 20 | print(compound(10000,5)) 21 | print(factorial(5)) -------------------------------------------------------------------------------- /CodeFromLectures/W5_6_FunctionArguments.py: -------------------------------------------------------------------------------- 1 | # Keyword arguments:- 2 | def calculate(c,b,a): 3 | return(a+b-c) 4 | print(calculate(a=20,b=30,c=40)) 5 | 6 | def DefCalc(c, a= 20, b=40): #Default arguments are set for a and b 7 | return (a*b-c) 8 | print(DefCalc(50)) #Here a,b has default values and c=50 9 | print(DefCalc(10,50)) #Here c=10, a=50 and b has default value 10 | print(DefCalc(10,50,30)) #All default values are replaced with c=10, a=50, b=30 11 | print(DefCalc(10,b=60,a=50)) -------------------------------------------------------------------------------- /CodeFromLectures/W5_7_ScopeOfVariables.py: -------------------------------------------------------------------------------- 1 | def myFunction1(x): #This x has a local scope within the myFunction1() method 2 | x=x*2 3 | print('Value of x in the 1st function is = ',x) 4 | 5 | def myFunction2(x): #This x has a local scope within the myFunction2() method 6 | x=x*3 7 | print('Value of x in the 2nd function is = ',x) 8 | 9 | def myFunction3(): # Note : We do not take any parameters in the function declaration when we want to use globally accessible value of x 10 | global x # By using the 'global' keyword and then typing the variable, we specify the computer to access the globally accessible value of x 11 | x=x*10 12 | print('Value of x in the 3rd function is = ',x) 13 | 14 | x=5 #This variable x is globally accessible 15 | print('Value of x before function call is = ', x) 16 | myFunction1(x) 17 | myFunction2(x) 18 | print('Value of x after 1st and 2nd function calls is = ', x) 19 | myFunction3() 20 | print('Value of x after 3rd function call is = ', x) -------------------------------------------------------------------------------- /CodeFromLectures/W5_8_TypesOfFunctions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | # Inbuilt functions :- 3 | print() , input() , len() 4 | 5 | #Library functions :- 6 | import math (To import from math library) 7 | import calendar (To import from calendar library) 8 | import random (To import from random library) 9 | math.log(), math.sqrt() , random.random() , randrange() , calendar() , calendar.month() 10 | 11 | #String methods(Functions) :- 12 | upper(), lower(), strip() , replace() , count() , index() 13 | 14 | ''' 15 | # User-defined functions:- 16 | def square(x): 17 | sqr=x**2 18 | return sqr 19 | 20 | print(square(5)) -------------------------------------------------------------------------------- /CodeFromLectures/W5_9_FunctionTutorial1.py: -------------------------------------------------------------------------------- 1 | '''Problem 1: Write a Python code using functions which calculates the number of upper case letters, lower case letters, total number of characters and number of words''' 2 | 3 | def upper(s): 4 | upper = 0 5 | for c in s: 6 | if(c.isupper()): 7 | upper += 1 8 | return(upper) 9 | 10 | def lower(s): 11 | lower = 0 12 | for c in s: 13 | if(c.islower()): 14 | lower += 1 15 | return(lower) 16 | 17 | def characters(s): 18 | chars = 0 19 | for c in s: 20 | chars += 1 21 | return(chars) 22 | 23 | def words(s): 24 | words = 1 25 | for c in s: 26 | if(c == ' '): 27 | words += 1 28 | return(words) 29 | 30 | sentence = input('Enter the sentence: ') 31 | uLetters = upper(sentence) 32 | print(f'\nTotal number of upper case characters: {uLetters}') 33 | lLetters = lower(sentence) 34 | print(f'\nTotal number of lower case characters: {lLetters}') 35 | chars = characters(sentence) 36 | print(f'\nTotal number of characters: {chars}') 37 | words = words(sentence) 38 | print(f'\nTotal number of words: {words}') -------------------------------------------------------------------------------- /CodeFromLectures/W5_9_FunctionTutorial2.py: -------------------------------------------------------------------------------- 1 | #Problem 2: Write a Python code using functions to calculate area and perimeter of circle and rectangle 2 | ''' 3 | # Approach 1: Standard code:- 4 | PI = 22 / 7 5 | def circle_area(r): 6 | return(PI * r * r) 7 | 8 | def circle_perimeter(r): 9 | return(2 * PI * r) 10 | 11 | def rectangle_area(l, b): 12 | return(l * b) 13 | 14 | def rectangle_perimeter(l, b): 15 | return(2 * (l + b)) 16 | 17 | r = float(input('\nEnter the radius of the circle: ')) 18 | cArea = circle_area(r) 19 | print(f'\nArea of circle with radius {r} = {cArea} sq. units') 20 | cPerimeter = circle_perimeter(r) 21 | print(f'\nPerimeter of circle with radius {r} = {cPerimeter} units') 22 | l = float(input('\nEnter the length of the rectangle: ')) 23 | b = float(input('Enter the breadth of the rectangle: ')) 24 | rArea = rectangle_area(l, b) 25 | print(f'\nArea of rectangle with length {l} and breadth {b} = {rArea} sq. units') 26 | rPerimeter = rectangle_perimeter(l, b) 27 | print(f'\nPerimeter of rectangle with length {l} and breadth {b} = {rPerimeter} units') 28 | 29 | ''' 30 | #Approach 2: Menu driven code :- 31 | import math 32 | 33 | PI = math.pi 34 | def circle_area(r): 35 | return(PI * r * r) 36 | 37 | def circle_perimeter(r): 38 | return(2 * PI * r) 39 | 40 | def rectangle_area(l, b): 41 | return(l * b) 42 | 43 | def rectangle_perimeter(l, b): 44 | return(2 * (l + b)) 45 | 46 | polygon = '' 47 | while(polygon != 'exit'): 48 | print('\nPOLYGONS\ncircle\nrectangle\nexit') 49 | polygon = input('\nChoose the polygon type or exit: ') 50 | property = '' 51 | if(polygon == 'circle'): 52 | r = float(input('\nEnter the radius of the circle: ')) 53 | while(property == ''): 54 | print('\nCIRCLE PROPERTIES\narea\nperimeter\nback') 55 | property = input('\nChoose the circle property or go back: ') 56 | if(property == 'area'): 57 | cArea = circle_area(r) 58 | print(f'Area of circle with radius {r} = {cArea} sq. units') 59 | property = '' 60 | elif(property == 'perimeter'): 61 | cPerimeter = circle_perimeter(r) 62 | print(f'Perimeter of circle with radius {r} = {cPerimeter} units') 63 | property = '' 64 | elif(property == 'back'): 65 | break 66 | else: 67 | print('Please select the correct polygon property') 68 | property = '' 69 | elif(polygon == 'rectangle'): 70 | l = float(input('\nEnter the length of the rectangle: ')) 71 | b = float(input('Enter the breadth of the rectangle: ')) 72 | while(property == ''): 73 | print('\nRECTANGLE PROPERTIES\narea\nperimeter\nback') 74 | property = input('\nChoose the rectangle property or go back: ') 75 | if(property == 'area'): 76 | rArea = rectangle_area(l, b) 77 | print(f'Area of rectangle with length {l} and breadth {b} = {rArea} sq. units') 78 | property = '' 79 | elif(property == 'perimeter'): 80 | rPerimeter = rectangle_perimeter(l, b) 81 | print(f'Perimeter of rectangle with length {l} and breadth {b} = {rPerimeter} units') 82 | property = '' 83 | elif(property == 'back'): 84 | break 85 | else: 86 | print('Please select the correct polygon property') 87 | property = '' 88 | elif(polygon == 'exit'): 89 | break 90 | else: 91 | print('Please select the correct polygon type or exit') -------------------------------------------------------------------------------- /CodeFromLectures/W5_9_FunctionTutorial3.py: -------------------------------------------------------------------------------- 1 | #Problem 3: Write a Python code using functions which checks whether the input coordinates form a triangle or not 2 | ''' 3 | # Approach 1: Using distance between points:- 4 | def distance(xi, yi, xj, yj): 5 | return((((xj - xi) ** 2) + ((yj - yi) ** 2)) ** 0.5) 6 | 7 | def isTriangle(max, a, b): 8 | if((a + b) > max): 9 | print('\nTriangle') 10 | else: 11 | print('\nNot a triangle') 12 | 13 | x1 = float(input('Enter x coordinate of 1st point: ')) 14 | y1 = float(input('Enter y coordinate of 1st point: ')) 15 | x2 = float(input('\nEnter x coordinate of 2nd point: ')) 16 | y2 = float(input('Enter y coordinate of 2nd point: ')) 17 | x3 = float(input('\nEnter x coordinate of 3rd point: ')) 18 | y3 = float(input('Enter y coordinate of 3rd point: ')) 19 | d1 = distance(x1, y1, x2, y2) 20 | print(f'\nDistance between points ({x1}, {y1}) and ({x2}, {y2}) = {d1}') 21 | d2 = distance(x2, y2, x3, y3) 22 | print(f'\nDistance between points ({x2}, {y2}) and ({x3}, {y3}) = {d2}') 23 | d3 = distance(x3, y3, x1, y1) 24 | print(f'\nDistance between points ({x3}, {y3}) and ({x1}, {y1}) = {d3}') 25 | 26 | if(d1 > d2): 27 | if(d1 > d3): 28 | isTriangle(d1, d2, d3) 29 | else: 30 | isTriangle(d3, d1, d2) 31 | elif(d2 > d3): 32 | isTriangle(d2, d1, d3) 33 | else: 34 | isTriangle(d3, d1, d2) 35 | ''' 36 | #Approach 2: Using slope of lines connecting two points:- 37 | import math 38 | 39 | def slope(xi, yi, xj, yj): 40 | if(xi == xj): 41 | return(math.inf) 42 | else: 43 | return((yj - yi) / (xj - xi)) 44 | 45 | x1 = float(input('Enter x coorinate of 1st point: ')) 46 | y1 = float(input('Enter y coorinate of 1st point: ')) 47 | x2 = float(input('\nEnter x coorinate of 2nd point: ')) 48 | y2 = float(input('Enter y coorinate of 2nd point: ')) 49 | x3 = float(input('\nEnter x coorinate of 3rd point: ')) 50 | y3 = float(input('Enter y coorinate of 3rd point: ')) 51 | s1 = slope(x1, y1, x2, y2) 52 | print(f'\nSlope of the line connecting points ({x1}, {y1}) and ({x2}, {y2}) = {s1}') 53 | s2 = slope(x2, y2, x3, y3) 54 | print(f'\nSlope of the line connecting points ({x2}, {y2}) and ({x3}, {y3}) = {s2}') 55 | if(s1 != s2): 56 | print('\nTriangle') 57 | else: 58 | print('\nNot a triangle') -------------------------------------------------------------------------------- /CodeFromLectures/W6_1_ListsAndSets.py: -------------------------------------------------------------------------------- 1 | x= [1,2,3,4,5,6,'aritra',77,85,3] 2 | y={5,9,8,7,5,52,-78} 3 | print(x,type(x)) #List can have repeated elements 4 | print(y,type(y)) #Set can not have repeated elements 5 | l=list(range(100)) 6 | s=set(range(100)) 7 | print(l) 8 | print(s) 9 | # Searching is easier in set than in list 10 | # But, it takes the computer much more time to process and produce a set than a list as set takes a lot more memory space than list 11 | import numpy 12 | import sys 13 | l0=[] 14 | l1=[0] 15 | l2=[0,1] 16 | print(sys.getsizeof(l0)) # Amount of space allocated to the list l0 in bytes 17 | print(sys.getsizeof(l2)) 18 | 19 | print(sys.getsizeof(s)) # 8408 bytes! Set for same elemets is allocated much larger space than its counterpart list 20 | # Note: s[1],s[0] won't work! There is no first, second element etc. in a set. Set object is not subscriptable. 21 | print(sys.getsizeof(l)) # Only 856 bytes allocated 22 | s1={'amit','aritra','dhanwanth','ayan','abhijit'} 23 | s1.add('sudarshan') 24 | print(s1) 25 | print('Sandesh' in s1) 26 | 27 | x[4]=154 28 | print(x) #Similar kind of replacement of an element is not possible in a set 29 | print(set(x)) -------------------------------------------------------------------------------- /CodeFromLectures/W6_2_Dictionaries.py: -------------------------------------------------------------------------------- 1 | dic={} #Basic syntax of dictionary data structure. If elements are included within {} then, it becomes a set data structure. 2 | dic['aritra']=6295666946 3 | dic['abhijit']=9474071064 4 | dic['sutapa']=8145695936 5 | print(dic) 6 | print(dic['aritra']) #Here dic[0], dic[1] won't work. We have to specify the proper key. 7 | malgudi=['It','was','Monday','morning','Swaminathan','was','reluctant','to','open','his','eyes','He','considered','Monday','specially','unpleasant','in','the','calendar','After','the','delicious','freedom','of','Saturday','and','Sunday','it','was','difficult','to','get','into','the','Monday','mood','of','work','and','discipline','He','shuddered','at','the','very','thought','of','school:','the','dismal','yellow','building:','the','fire','eyed','Vedanayagam','his','class','teacher','and','headmaster','with','his','thin','long','cane'] 8 | print(len(malgudi)) 9 | s=set(malgudi) 10 | print(s) #All repeated words will be gone 11 | print(len(s)) 12 | malgudi[47]="school" 13 | malgudi[51]="building" 14 | print(malgudi) 15 | print("\n") 16 | # Using dictionary to find the frequency of all words in the list malgudi:- 17 | d={} 18 | s=set(malgudi) 19 | for x in s: 20 | d[x]=0 #Initialization of the dictionary 21 | for x in malgudi: 22 | d[x]=d[x]+1 23 | print(d) 24 | #Using dictionary to find the word repeated maximum number of times in the list malgudi:- 25 | max=0 26 | maxWord='' 27 | for x in malgudi: 28 | if(d[x]>max): 29 | max=d[x] 30 | maxWord=x 31 | print('\nThe word "',maxWord, '" has been repeated the maximum number of times in the list malgudi. It has been repeated for a total of %d times.'%(max)) 32 | #Example of storing lists within dictionary:- [We can even store dictionary within dictionary] 33 | a={} 34 | a['Aritra']=[90,85,96,"theroyaritra@gmail.com"] 35 | a['Madhura']=[85,63,95,'madhura123@hotmail.com'] 36 | a['Pratik']=[56,96,95,'pratik_super@yahoo.co.in'] 37 | print(a) 38 | print(a['Aritra'][1]) 39 | print(a['Pratik'][3]) -------------------------------------------------------------------------------- /CodeFromLectures/W6_3_Tuples.py: -------------------------------------------------------------------------------- 1 | t=(108,5,7,9,65,20,19,2) 2 | print("A tuple is unchangable or its immutable unlike lists, which are mutable. We can't append or remove elements from a tuple. We can find elements at particular indices in a tuple. ") 3 | l=list(range(10)) 4 | print(l.__sizeof__()) #We observe that size of list of similar size is 120 bytes 5 | t1=tuple(range(10)) 6 | print(t1.__sizeof__()) #We observe that size of tuple of similar size in 104 bytes and hence, tuples also consume much less memory than lists. 7 | print(t1) 8 | 9 | import string 10 | #Some more applications of special string methods:- 11 | print(string.ascii_letters) 12 | print(string.ascii_lowercase) 13 | print(string.ascii_uppercase) 14 | 15 | s=string.ascii_letters 16 | #s=set(s) 17 | print(s) 18 | alpha=tuple(list(s)) #So that we get ordered/sorted elements in the tuple. In list elements are in specific order, unlike sets or tuples. Here alpha is a tuple but the order of elements is not altered because we first convert the string to a list. Here we don't want alpha to change in any condition. So, we use tuple which is immutable. 19 | print(alpha,"\n") 20 | 21 | # We write a small code to print only those chracters in x that are present in alpha, in the form of a list:- 22 | x="Karnataka West Bengal Jai Hind! 1#2$3%4^5& 6 Tamil Nadu Koi MIl gaya!@)(*+_" 23 | l=list(x) 24 | r=[] 25 | for element in l: 26 | if element in alpha: 27 | r.append(element) 28 | print(r,"\n") -------------------------------------------------------------------------------- /CodeFromLectures/W6_4_MoreOnLists.py: -------------------------------------------------------------------------------- 1 | # + as concatenation operator in lists:- 2 | l1=[1,2,3] 3 | l2=[10,20,30] 4 | l12=l1+l2 5 | l21=l2+l1 6 | print(l12, l21,"\n") 7 | 8 | #Repeating elements in lists with * :- 9 | l1=[0]*5 10 | l2=[1,2,3]*5 11 | print(l1, l2) 12 | 13 | #Relational operators and their usages with lists:- 14 | l1=[1,2,3] 15 | l2=[1,2,3] 16 | l3=[1,3,2] 17 | print(l1==l2) 18 | print(l2==l3) 19 | print(l2 list2 and list1 belong to the same memory location 32 | 33 | # 4 ways of creating copy of a list, that will create a new memory location:- 34 | list1=[1,2,3,4] 35 | l2=list(list1) 36 | l3=list1[:] 37 | l4=list1.copy() 38 | l5=list1 #not a seperate copy though 39 | print() 40 | print(l2,l3,l4,l5) 41 | 42 | print(list1 is list1) # Returns True => l5 and list1 belong to the same memory location 43 | print(l2 is list1) # Return False => l2 and list1 belong to different memory locations 44 | print(l3 is list1) # Return False => l3 and list1 belong to different memory locations 45 | print(l4 is list1) # Return False => l4 and list1 belong to different memory locations 46 | print(l5 is list1) # Returns True => l5 and list1 belong to the same memory location 47 | print() 48 | 49 | #Passing lists through functions:- [In case of lists, its call by reference while in case of normal integers its call by value] 50 | def add(x,y): 51 | x.append(1) 52 | y=y+1 53 | return x,y 54 | x=[5] 55 | y=5 56 | print(add(x,y)) 57 | print(x,y,"\n") 58 | 59 | # Some more list methods:- 60 | list1.insert(2,65) #append() adds the element to the last of the list, while insert() inserts the element at the specified index 61 | print(list1) 62 | 63 | list1.pop(2) #remove() removes specified element from the list, whereas pop() removes the element at the specified index 64 | print(list1) 65 | newlist=[52,85,96,-85,-65,20,415,623,554,-988,14] 66 | newlist2=["ari","JaiHind!","KyaRee","hmm","India","TussiGreatHo"] 67 | 68 | newlist.sort() #sort() sorts the list (of either only numbers or only Strings as well) in ascending order 69 | print(newlist) 70 | newlist.reverse() # reverse() just reverses the list 71 | print(newlist) 72 | #Note that we can use sort() and then reverse() methods to sort a list in descending order as well! 73 | newlist2.sort() 74 | print(newlist2) 75 | newlist2.reverse() 76 | print(newlist2) 77 | ''' This is also a more effective method to sort lists in descending order:- 78 | newlist2.sort(reverse=True) 79 | print(newlist2) 80 | ''' -------------------------------------------------------------------------------- /CodeFromLectures/W6_5_MoreOnTuples.py: -------------------------------------------------------------------------------- 1 | #Packing and unpacking using tuples:- 2 | 3 | t=1,2,3 #Packing 4 | print(t,type(t)) 5 | 6 | x,y,z=t #Unpacking 7 | print(x,y,z) 8 | 9 | a=5 10 | b=10 11 | a,b=b,a #Internally packing and then unpacking happens 12 | print(a,b) 13 | 14 | #Tuples of single element and their comparison to list of single element:- 15 | l=[10] 16 | print(l,type(l)) 17 | 18 | t1=(10) #Whenever there is only 1 element in a tuple, python considers it as a single value (integer or anything else) and not a tuple 19 | t2=(10,) #Now that we add a ',' after the single element in the (), python recognizes it as a tuple 20 | print(t1,type(t1)) 21 | print(t2,type(t2)) 22 | 23 | #Creating tuples with lists and tuples inside them and manupulating lists inside tuples:- 24 | t=([1,2],['a','b'],(4,5,85)) 25 | print(t) 26 | ''' 27 | t[0]=(10,20) #Not possible as tuples are immutable 28 | print(t) #Shows error as expected 29 | ''' 30 | t[0][0]=10 31 | t[1][0]='Aritra' 32 | print(t) 33 | 34 | #Hashable and non-Hashable:- 35 | #If the values inside a tuple are also immutable then the tuple is considered as hashable and if the values inside a tuple are mutable then the tuple is considered as non-hashable. 36 | tic1=(1,2,3) #Hashable 37 | tic2=([1,2,3],) #Non-Hashable -------------------------------------------------------------------------------- /CodeFromLectures/W6_6_MoreOnDictionaries.py: -------------------------------------------------------------------------------- 1 | ''' d={'key':'value'} 2 | Every key in a dictionary must be unique although duplication is allowed in case of values. 3 | 4 | Integers, Float, Boolean, Strings, Hashable Tuples and other immutable datatypes can be used as dictioanry keys. 5 | Lists, Non-Hashable Tuples and Dictionaries can not be used as dictionary keys as they mutable. 6 | Values can be of any datatype. 7 | 8 | All properties of copying mutable datatypes like lists apply to dictionaries as well. That means, to copy a dictionary to new memory location we have to use .copy() method etc. 9 | Dictionaries are only passed by call-by-reference through functions. 10 | ''' 11 | d={0:12,1:45.365,2:96.52,3:"Aritra",4:[0.2564,45,True,"Hello World!"]} 12 | print(d) 13 | for key in d: 14 | print(key," ", d[key]) 15 | 16 | print(d.keys()) #Prints a list of all keys in the dictionary 17 | print(d.values()) #Prints a list of all values in the dictionary 18 | print(d.items()) # Prints a list of all elements in the dictionary as tuples of two i.e. Each key-value pair is a tuple. 19 | 20 | -------------------------------------------------------------------------------- /CodeFromLectures/W6_7_MoreOnSets.py: -------------------------------------------------------------------------------- 1 | #Set is an unordered entity. Set is not subscriptable as well. 2 | #Set itself is mutable but every value inside a set has to be hashable and immutable. Hence we cannot add a list or a dictionary or a tuple containing a list or a dictionary to a set. 3 | #We can iterate over a set. 4 | 5 | A= {1,2,3,4,5,1,2,3,5} #A[0] or A[1] is undefined 6 | print(A) 7 | B={1,2,3,4,3,5} 8 | C={1,3,5} 9 | D={1,2,3} 10 | print(A.issubset(B)) 11 | print(C.issuperset(B)) 12 | 13 | C1=A|C #Union without using union method 14 | print(A.union(C),C1) 15 | 16 | C2=A&C #Intersection without using intersection method 17 | print(A.intersection(C),C2) 18 | 19 | D1=D.difference(C) 20 | D2=D-C 21 | print(D1,D2) 22 | 23 | #Thus, we can use many other methods on sets. -------------------------------------------------------------------------------- /CodeFromLectures/W6_CollectionsSummary_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W6_CollectionsSummary_1.png -------------------------------------------------------------------------------- /CodeFromLectures/W6_CollectionsSummary_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/W6_CollectionsSummary_2.png -------------------------------------------------------------------------------- /CodeFromLectures/W8_1_0InListRecursion.py: -------------------------------------------------------------------------------- 1 | # Not an efficient or optimized code! 2 | def check0(L): 3 | if(len(L)==0): 4 | return False 5 | else: 6 | if(L[0]==0): 7 | return True 8 | else: 9 | return check0(L[1:len(L)]) #You can also write it as "return check0(L[1:])" 10 | 11 | print(check0([1,2,6,9,8,45,8])) 12 | print(check0([45,-98,56,5.23,0,145,63,85])) -------------------------------------------------------------------------------- /CodeFromLectures/W8_2_SortingRecursively.py: -------------------------------------------------------------------------------- 1 | def findMin(L): 2 | min=L[0] 3 | for e in L: 4 | if(emax): 12 | max=e 13 | return max 14 | 15 | def AscendingSort(L): 16 | if(L==[] or len(L)==1): 17 | return L 18 | else: 19 | m=findMin(L) 20 | L.remove(m) 21 | return [m]+AscendingSort(L) 22 | 23 | def DescendingSort(L): 24 | if(L==[] or len(L)==1): 25 | return L 26 | else: 27 | m=findMax(L) 28 | L.remove(m) 29 | return [m]+DescendingSort(L) 30 | 31 | print(DescendingSort([54,85,96,-98,69,52.25,65.5,-695.55])) 32 | print(AscendingSort([54,85,96,-98,69,52.25,65.5,-695.55])) -------------------------------------------------------------------------------- /CodeFromLectures/W8_3_BinarySearchWarmup.py: -------------------------------------------------------------------------------- 1 | import time 2 | import W8_3_Search as w 3 | import W8_4_BinarySearchImplementation as bin 4 | def sum(a): 5 | s=0 6 | for i in range(a): 7 | s=s+i 8 | return s 9 | a=time.time() 10 | print(sum(100000)) 11 | b=time.time() 12 | print(b-a) #This gives us the time in seconds that the program took to execute : print(sum(100000)) including the sum function within it 13 | 14 | l=[1,2,3,4,5,6,7,8,9,10] 15 | begin,end=0,9 16 | mid=(begin+end)//2 #gives us midpoint of a list 17 | print(w.obvious_search(l,5)) 18 | print("\n") 19 | m=list(range(1000000)) 20 | 21 | # Now we note the time taken for linear search and binary search:- 22 | a=time.time() 23 | print(w.obvious_search(m,98598956)) 24 | print(w.obvious_search(m,985095)) 25 | b=time.time() 26 | print(b-a) 27 | 28 | m=list(range(1000000)) 29 | a=time.time() 30 | print(bin.binary_search1(m,98598956)) 31 | print(bin.binary_search1(m,985095)) 32 | b=time.time() 33 | print(b-a) 34 | #We observe that binary search takes much less time than linear search. 35 | 36 | -------------------------------------------------------------------------------- /CodeFromLectures/W8_3_Search.py: -------------------------------------------------------------------------------- 1 | def obvious_search(l,x): 2 | for e in l: 3 | if(e==x): 4 | return True 5 | return False 6 | #print(obvious_search([58,96,57,25,-96],69)) -------------------------------------------------------------------------------- /CodeFromLectures/W8_4_BinarySearchImplementation.py: -------------------------------------------------------------------------------- 1 | # Only condition for these kind of binary searches to run successfully is that the list has to be sorted in the Ascending order:- 2 | def binary_search1(l,k): #Logic of IITM by Prof. Iyengar 3 | begin=0 4 | end=len(l)-1 5 | mid=0 6 | while(end-begin>1): 7 | mid=(begin+end)//2 8 | if(l[mid]==k): 9 | return True 10 | if(l[mid]>k): 11 | end=mid-1 12 | if(l[mid]end or, end-begin <= 1 i.e. end-begin = 0 or 1 15 | return True 16 | return False #If we reach here, it implies element has not been found at all 17 | l=[12,15,85,96,-85,69,5,6,38,2,9,-46,82,6,200] 18 | l.sort() 19 | print(binary_search1(l,58)) 20 | print(binary_search1(l,5)) 21 | print(binary_search1(l,38)) 22 | print(binary_search1(l,15)) 23 | 24 | def binary_search2(arr, x): #Simple and standard logic that gives you direct index of element if found 25 | begin = 0 26 | end = len(arr) - 1 27 | mid = 0 28 | while (begin <= end): 29 | mid = (end + begin) // 2 30 | # If x is greater, ignore left half 31 | if arr[mid] < x: 32 | begin = mid + 1 33 | # If x is smaller, ignore right half 34 | elif arr[mid] > x: 35 | end = mid - 1 36 | # means x is present at mid 37 | else: 38 | return mid 39 | # If we reach here, then the element was not present 40 | return -1 41 | 42 | arr = [ 2, 3, 4, 10, 40, -85, 69 , -8569, -58, 52, 63 ] 43 | arr.sort() 44 | result = binary_search2(arr, -85695) 45 | result = binary_search2(arr,10) 46 | if result != -1: 47 | print("In the list sorted in ascending order, element is present at index ", str(result)) 48 | else: 49 | print("Element is not present in the list") 50 | -------------------------------------------------------------------------------- /CodeFromLectures/W8_5_BinarySearch_RecursiveWay.py: -------------------------------------------------------------------------------- 1 | #There is a limit to the number of recursions that can be computed in python. So, keep in mind that number of recursions should not exceed that limit, for the recursive Binary Search to run successfully 2 | #Once again, this kind of Binary search will only run successfully on lists, that have been sorted in ascending order. 3 | def recursive_BinarySearch(l,k,begin,end): 4 | if(begin==end): 5 | if(l[begin]==k): 6 | return True 7 | else: 8 | return False 9 | if(end-begin == 1): #if end and begin are consecutive indices 10 | if(l[begin]==k or l[end]==k): 11 | return True 12 | else: 13 | return False 14 | if(end-begin > 1): 15 | mid=(begin+end)//2 16 | if(l[mid]>k): 17 | end=mid-1 18 | elif(l[mid]85].shape[0]," students got A grade in Physics") 19 | print(scores[scores['Physics Scores'].between(70,85)].shape[0]," students got B grade in Physics") 20 | print(scores[scores['Physics Scores'].between(60,70)].shape[0]," students got C grade in Physics") 21 | print(scores[scores['Physics Scores']<60].shape[0]," students got D grade in Physics") 22 | 23 | print(scores[(scores['gender']=='female') & (scores['Chemistry Scores']>85)].shape[0]," female students got A grade in Chemistry") 24 | print(scores[(scores['gender']=='male') & (scores['Chemistry Scores']>85)].shape[0]," male students got A grade in Chemistry") 25 | ''' 26 | #Note: Pandas doesn't support regular Python 'and' operator. Here, and operator is denoted by '&' 27 | subject=['Maths Scores','Physics Scores','Chemistry Scores'] 28 | for sub in subject: 29 | avg=scores[sub].mean() 30 | print(scores[(scores['gender']=='male') & (scores[sub]>85)].shape[0]," male students got A grade(above 85) in", sub.split()[0]) 31 | print(scores[(scores['gender']=='male') & (scores[sub]>avg)].shape[0]," male students got above the average marks of", avg, "in", sub.split()[0]) 32 | print(scores[(scores['gender']=='female') & (scores[sub]>85)].shape[0]," female students got A grade(above 85) in ",sub.split()[0]) 33 | print(scores[(scores['gender']=='female') & (scores[sub]>avg)].shape[0]," female students got above the average marks of", avg, "in", sub.split()[0]) 34 | print(scores[(scores['gender']=='female') & (scores['Total']>85)].shape[0]," female students got A grade(above 85) in Total") 35 | print(scores[(scores['gender']=='male') & (scores['Total']>85)].shape[0]," male students got A grade(above 85) in Total") -------------------------------------------------------------------------------- /CodeFromLectures/W9_7_PandasSeriesDataframes2.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | scores=pd.read_csv("ExamScores.csv") 3 | print(scores.groupby('gender').groups) #Gives a dictionary of lists of the index numbers of the keys under 'gender' 4 | subject=['Maths Scores','Physics Scores','Chemistry Scores'] 5 | for sub in subject: 6 | print("Students above Average in ", sub, " are:-") 7 | avg=scores[sub].mean() 8 | print(scores[scores[sub]>avg].groupby('gender').groups) -------------------------------------------------------------------------------- /CodeFromLectures/__pycache__/BasicThings.cpython-38.pyc: -------------------------------------------------------------------------------- 1 | U 2 | �a�� @sedd�edd�dZee�edZee�ed�ee��Zede�eed��Zeed ��Zeed 3 | ��Zed ed �e ed ��Z 4 | de 5 | e 6 | Z ede d�ede e 7 | ��ede e��ede e ��dddddgZ ee �ede dde dde e d��ede e ��dS) zHello world, Kaisa hein bro?zPrinting using double quote.zPrinting 10 using single quote.zThats how we print� 8 | �zEnter a numberzThe number entered is = zWhat is your name? zWhat is your age? zWhere do you live? zGood to know that you are only z years old.zDEnter the radius of the circle whose area you want to be calculated.g�Q� @zArea of the circle is = z square unitsz)In this program, variable r is of type : z,In this program, variable name is of type : z,In this program, variable area is of type : ���Di�zFirst and last element of l : ��,�z5 and Data type of an individual element of list is : �zl is of datatype : N)�print�a�int�input�n�str�nameZageZplace�float�rZarea�type�l�rr�Y/home/runner/IITM-Foundation-Course-Programming-in-Python/CodeFromLectures/BasicThings.py�s, 9 |  10 |  11 |  12 |        " -------------------------------------------------------------------------------- /CodeFromLectures/__pycache__/DataTypes2.cpython-38.pyc: -------------------------------------------------------------------------------- 1 | U 2 | v�a�@s@dZdZedee�dee��ed�Zed�Zed�Zed�Z eeee��eeee��eeee��ee ee ��e 3 | d�Z e 4 | d �Z e 5 | d 6 | �Z e 7 | d �Ze 8 | d �Ze 9 | d �Ze 10 | d�Ze 11 | d�Ze 12 | d�Zee ee ��ee ee ��ee ee ��eeee��eeee��eeee��eeee��eeee��eeee��dS)TFzData types of b1 and b2 are : �andgH�z�@Z10�9z10.567� 13 | �g�$�gZIndiaz10.4z-52.6�0�N)Zb1Zb2�print�type�int�a�b�float�c�d�bool�m�n�o�p�q�r�s�t�e�rr�X/home/runner/IITM-Foundation-Course-Programming-in-Python/CodeFromLectures/DataTypes2.py�s8 -------------------------------------------------------------------------------- /CodeFromLectures/__pycache__/W10_3_Person.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/__pycache__/W10_3_Person.cpython-39.pyc -------------------------------------------------------------------------------- /CodeFromLectures/__pycache__/W4_3_NaiveSearchInList.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/__pycache__/W4_3_NaiveSearchInList.cpython-39.pyc -------------------------------------------------------------------------------- /CodeFromLectures/__pycache__/W8_3_Search.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/__pycache__/W8_3_Search.cpython-39.pyc -------------------------------------------------------------------------------- /CodeFromLectures/__pycache__/W8_4_BinarySearchImplementation.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/__pycache__/W8_4_BinarySearchImplementation.cpython-39.pyc -------------------------------------------------------------------------------- /CodeFromLectures/__pycache__/W8_Search.cpython-39.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/CodeFromLectures/__pycache__/W8_Search.cpython-39.pyc -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W10_GrPA1.py: -------------------------------------------------------------------------------- 1 | class Calculator: 2 | def __init__(self,a,b): 3 | self.a=a 4 | self.b=b 5 | def add(self): 6 | return(self.a+self.b) 7 | def multiply(self): 8 | return(self.a * self.b) 9 | def subtract(self): 10 | return(self.a - self.b) 11 | def quotient(self): 12 | return(self.a//self.b) 13 | def remainder(self): 14 | return(self.a%self.b) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W10_GrPA2.py: -------------------------------------------------------------------------------- 1 | class StringManipulation: 2 | def __init__(self,words): 3 | self.words=words 4 | def total_words(self): 5 | return len(self.words) 6 | def count(self,some_word): 7 | return self.words.count(some_word) 8 | def words_of_length(self,length): 9 | l=[] 10 | for each in self.words: 11 | if(length==len(each)): 12 | l.append(each) 13 | return l 14 | def words_start_with(self,char): 15 | x=len(char) 16 | f=True 17 | l=[] 18 | for each in self.words: 19 | for i in range(x): 20 | if(each[i]==char[i]): 21 | l.append(each) 22 | return l 23 | def longest_word(self): 24 | s='' 25 | max=len(self.words[0]) 26 | for each in self.words: 27 | if(len(each)>max): 28 | max=len(each) 29 | s=each 30 | return s 31 | def palindromes(self): 32 | l=[] 33 | for each in self.words: 34 | if(each==each[::-1]): 35 | l.append(each) 36 | return l 37 | 38 | 39 | s=StringManipulation(['the', 'this','wonderful', 'though', 'thou', 'many', 'mom', 'malayalam', 'manorama', 'was', 'wisdom','the']) 40 | print(s.longest_word()) 41 | print(s.palindromes()) 42 | print(s.words_start_with('m')) 43 | print(s.count('the')) 44 | print(s.words_of_length(4)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W10_GrPA3.py: -------------------------------------------------------------------------------- 1 | class Shape: 2 | def __init__(self, name): 3 | self.name = name 4 | self.area = None 5 | self.perimeter = None 6 | 7 | def display(self): 8 | print(f'{self.name} has an area of {self.area} and perimeter of {self.perimeter}') 9 | class Shape: 10 | def __init__(self, name): 11 | self.name = name 12 | self.area = None 13 | self.perimeter = None 14 | 15 | def display(self): 16 | print(f'{self.name} has an area of {self.area} and perimeter of {self.perimeter}') 17 | 18 | class Square(Shape): 19 | def __init__(self, side): 20 | super().__init__('Square') 21 | self.side = side 22 | self.compute_area() 23 | self.compute_perimeter() 24 | 25 | def compute_area(self): 26 | self.area = self.side ** 2 27 | 28 | def compute_perimeter(self): 29 | self.perimeter = 4 * self.side -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W10_GrPA4.py: -------------------------------------------------------------------------------- 1 | class Time: 2 | def __init__(self, time): 3 | self.time = time 4 | def seconds_to_minutes(self): 5 | self.minutes = self.time // 60 6 | self.seconds = self.time % 60 7 | return f'{self.minutes} min {self.seconds} sec' 8 | 9 | def seconds_to_hours(self): 10 | self.seconds_to_minutes() 11 | self.hours = self.minutes // 60 12 | self.minutes = self.minutes % 60 13 | return f'{self.hours} hrs {self.minutes} min {self.seconds} sec' 14 | 15 | def seconds_to_days(self): 16 | self.seconds_to_hours() 17 | self.days = self.hours // 24 18 | self.hours = self.hours % 24 19 | return f'{self.days} days {self.hours} hrs {self.minutes} min {self.seconds} sec' 20 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W12_PPA1.py: -------------------------------------------------------------------------------- 1 | def prime(n): 2 | f=True 3 | if n==2: 4 | return f 5 | if n==0 or n==1: 6 | return False 7 | for i in range(2,n): 8 | if(n%i==0): 9 | f=False 10 | break 11 | return f 12 | def primes_galore(L): 13 | c=0 14 | for i in range(len(L)): 15 | if(prime(i) and prime(L[i])): 16 | c=c+1 17 | return c 18 | 19 | print(primes_galore([1, 3, 11, 18, 17, 5, 6, 8, 10])) 20 | print(primes_galore([1, 2, 3, 4, 5, 6, 7, 8, 9])) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W12_PPA3.py: -------------------------------------------------------------------------------- 1 | def survival(T): 2 | """ 3 | Determine if the organism will survive or not 4 | 5 | Argument: 6 | T: integer 7 | Return: 8 | result: bool 9 | """ 10 | f=False 11 | for x in range(6): 12 | for y in range(6): 13 | m=30+x**2+y**2-3*x-4*y 14 | if(m<=T): 15 | f=True 16 | break 17 | return f 18 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W12_PPA5.py: -------------------------------------------------------------------------------- 1 | def balanced(word): 2 | """ 3 | Determine if a string is balanced 4 | Argument: 5 | word: string 6 | Return: 7 | result: bool 8 | """ 9 | l=len(word) 10 | f=True 11 | o=['(','[','{'] 12 | fo=word.count('(') 13 | fc=word.count(')') 14 | so=word.count('{') 15 | sc=word.count('}') 16 | to=word.count('[') 17 | tc=word.count(']') 18 | if(fo!=fc and so!=sc and to!=tc): 19 | return False 20 | for i in range(l-1): 21 | if(word[i]=='[' and (word[i+1]!=']' or word[i+1] not in o)) or (word[i]=='{' and (word[i+1]!='}' or word[i+1] not in o)) or (word[i]=='(' and (word[i+1]!=')' or word[i+1] not in o)): 22 | return False 23 | for i in range(l): 24 | if(word[i]=='(' and ')' not in word[i:]) or (word[i]=='{' and '}' not in word[i:]) or (word[i]=='[' and ']' not in word[i:]): 25 | return False 26 | return f -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W12_PPA6.py: -------------------------------------------------------------------------------- 1 | import string 2 | s=input() 3 | d1,d2={},{} 4 | a=string.ascii_lowercase 5 | for i in range(1,14): 6 | d1[a[i-1]]=a[-i] 7 | d2[a[-i]]=a[i-1] 8 | encrypt='' 9 | for e in s: 10 | if e in d1: 11 | encrypt+=d1[e] 12 | elif e in d2: 13 | encrypt+=d2[e] 14 | else: 15 | encrypt+=e 16 | print(encrypt) 17 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W1_GrPA6.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept two positive integers M and N as input. There are two cases to consider: 3 | (1) If M < N, then print M as output. 4 | (2) If M >= N, subtract N from M. Call the difference M1. If M1 >= N, then subtract N from M1 and call the difference M2. Keep doing this operation until you reach a value k, such that, Mk < N. You have to print the value of Mk as output. 5 | You should be able to solve this problem using the concepts covered in week-1. 6 | ''' 7 | M = int(input()) 8 | N = int(input()) 9 | print(M % N) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_GrPA1.py: -------------------------------------------------------------------------------- 1 | import math 2 | b, p, h = int(input()), int(input()), int(input()) 3 | calc1 = (math.pow(b, 2)+math.pow(p, 2)) == (math.pow(h, 2)) 4 | calc2 = (math.pow(b, 2)+math.pow(h, 2)) == (math.pow(p, 2)) 5 | calc3 = (math.pow(h, 2)+math.pow(p, 2)) == (math.pow(b, 2)) 6 | if(b > 0 and p > 0 and h > 0): 7 | if calc1 or calc2 or calc3: 8 | print('YES') 9 | else: 10 | print('NO') 11 | else: 12 | print('NO') 13 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_GrPA3.py: -------------------------------------------------------------------------------- 1 | s=input() 2 | x=s.lower() 3 | a,e,i,o,u=x.find('a'),x.find('e'),x.find('i'),x.find('o'),x.find('u') 4 | out='' 5 | if(a>=0): 6 | out=out+'a' 7 | if(e>=0): 8 | out=out+'e' 9 | if(i>=0): 10 | out=out+'i' 11 | if(o>=0): 12 | out=out+'o' 13 | if(u>=0): 14 | out=out+'u' 15 | if(a+e+i+o+u)<0: 16 | out='none' 17 | print(out) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_GrPA4.py: -------------------------------------------------------------------------------- 1 | n1,dob1,n2,dob2=input(),input(),input(),input() 2 | d1,d2=int(dob1[0:2]),int(dob2[0:2]) 3 | m1,m2=int(dob1[3:5]),int(dob2[3:5]) 4 | y1,y2=int(dob1[6:10]),int(dob2[6:10]) 5 | if(dob1==dob2): 6 | if(n1y2) or (y1==y2 and m1>m2) or (y1==y2 and m1==m2 and d1>d2): 12 | print(n1) 13 | else: 14 | print(n2) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_GrPA5.py: -------------------------------------------------------------------------------- 1 | a=input() 2 | if(len(a)>=8 and len(a)<=32) and (a[0].isalpha()) and not(('=' in a) or ('/' in a) or ('\\' in a) or ("'" in a) or ('"' in a) or (' ' in a)): 3 | print('True') 4 | else: 5 | print('False') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_PPA5.py: -------------------------------------------------------------------------------- 1 | x1, y1, x2, y2, x3 = float(input()), float(input()), float(input()), float(input()), float(input()) 2 | if(x2-x1 != 0): 3 | slope = (y2-y1)/(x2-x1) 4 | if(slope > 0): 5 | y3 = y1+(((x3-x1)*(y2-y1))/(x2-x1)) 6 | print(y3) 7 | print("Positive Slope") 8 | elif(slope == 0): 9 | y3 = y1+(((x3-x1)*(y2-y1))/(x2-x1)) 10 | print(y3) 11 | print("Horizontal Line") 12 | elif(slope < 0): 13 | y3 = y1+(((x3-x1)*(y2-y1))/(x2-x1)) 14 | print(y3) 15 | print("Negative Slope") 16 | else: 17 | print("Vertical Line") 18 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_PPA6.py: -------------------------------------------------------------------------------- 1 | a=str(input()) 2 | if(len(a)%2==0): 3 | if(a.endswith('.')): 4 | x=a.rstrip('.') 5 | else: 6 | x=a+'.' 7 | else: 8 | x=a 9 | m=int((len(x)-3)/2) 10 | #print(m) 11 | print(x[m:(m+3)]) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_PPA7.py: -------------------------------------------------------------------------------- 1 | a,b,c,d,e=input(),input(),input(),input(),input() 2 | if (b.find(a)!=-1) and (c.find(b)!=-1) and (d.find(c)!=-1) and (e.find(d)!=-1): 3 | print('magical') 4 | else: 5 | print('non-magical') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_PPA8.py: -------------------------------------------------------------------------------- 1 | # The Chessboard and checking legality of any Bishop's moves problem:- 2 | list,a,b='ABCDEFGH',input(),input() 3 | if abs(list.index(a[0])-list.index(b[0]))==abs(int(a[1])-int(b[1])): 4 | print('YES') 5 | else: 6 | print('NO') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W2_PPA9.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You have n gold coins with you. You wish to divide this among three of your friends under the following conditions: 3 | (1) All three of them should get a non-zero share. 4 | (2) No two of them should get the same number of coins. 5 | (3) You should not have any coins with you at the end of this sharing process. 6 | The input has four lines. The first line contains the number of coins with you. The next three lines will have the share given to your three friends. All inputs shall be non-negative integers. 7 | If the division satisfies these conditions, then print the string FAIR. If not, print UNFAIR. 8 | ''' 9 | n=int(input()) 10 | a=int(input()) 11 | b=int(input()) 12 | c=int(input()) 13 | if(a!=0 and b!=0 and c!=0) and (a!=b and b!=c and c!=a) and (a+b+c==n): 14 | print('FAIR') 15 | else: 16 | print('UNFAIR') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_GrPA1.py: -------------------------------------------------------------------------------- 1 | ''' Easy Solution using functions:- 2 | def add(n): 3 | sum=0 4 | for i in range(1,n+1): 5 | sum=sum+i 6 | return sum 7 | n=int(input()) 8 | c=0 9 | for j in range(1,n+1): 10 | c=c+add(j) 11 | print(c) 12 | ''' 13 | n=int(input()) 14 | sum=0 15 | for i in range(1,n+1): 16 | for j in range(1,i+1): 17 | sum=sum+j 18 | print (sum) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_GrPA2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept a positive integer n, with n > 1, as input from the user and print all the prime factors of n in ascending order. 3 | ''' 4 | n=int(input()) 5 | if(n>1): 6 | for i in range(2,n+1): 7 | if(n%i==0): 8 | flag=False 9 | for j in range(2,i): 10 | if(i%j==0): 11 | flag=True 12 | if(flag==False): 13 | print(i) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_GrPA3.py: -------------------------------------------------------------------------------- 1 | a = input() 2 | x,y=0,0 3 | dist=0 4 | b='' 5 | if(a == 'START'): 6 | while(b != 'STOP'): 7 | b=input() 8 | if(b=='UP'): 9 | y+=1 10 | elif(b=='DOWN'): 11 | y-=1 12 | elif(b=='RIGHT'): 13 | x+=1 14 | elif(b=='LEFT'): 15 | x-=1 16 | dist=abs(x)+abs(y) 17 | print(dist) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_GrPA4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept a string as input, convert it to lower case, sort the string in alphabetical order, and print the sorted string to the console. You can assume that the string will only contain letters. 3 | ''' 4 | ''' Code using 1st logic:- 5 | s=input().lower() 6 | x='' 7 | if(s.isalpha()): 8 | x=x.join(sorted(s)) 9 | print(x) 10 | ''' 11 | #Code using another logic:- 12 | A=sorted(input().lower()) 13 | for i in range(len(A)): 14 | print(A[i],end='') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_GrPA5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept a phone number as input. A valid phone number should satisfy the following constraints. 3 | (1) The number should start with one of these digits: 6, 7, 8, 9 4 | (2) The number should be exactly 10 digits long. 5 | (3) No digit should appear more than 7 times in the number. 6 | (4) No digit should appear more than 5 times in a row in the number. 7 | If the fourth condition is not very clear, then consider this example: the number 9888888765 is invalid because the digit 8 appears more than 5 times in a row. 8 | Print the string valid if the phone number is valid. If not, print the string invalid. 9 | ''' 10 | n,flag,Flag,f=input(),False,False,False 11 | if len(n)==10 and (n[0]=='6' or n[0]=='7' or n[0]=='8' or n[0]=='9') and n.isnumeric(): 12 | f=True 13 | for i in range(5): 14 | if n[i]==n[i+1]==n[i+2]==n[i+3]==n[i+4]==n[i+5]: 15 | flag=True 16 | for j in range(len(n)): 17 | if n.count(n[j])>7: 18 | Flag=True 19 | if flag==True or Flag==True or f==False: 20 | print('invalid') 21 | if flag==False and Flag==False and f==True: 22 | print('valid') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_GrPA6.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept a positive integer n as input and print a "number arrow" of size n. For example, n = 5 should produce the following output: 3 | 1 4 | 1,2 5 | 1,2,3 6 | 1,2,3,4 7 | 1,2,3,4,5 8 | 1,2,3,4 9 | 1,2,3 10 | 1,2 11 | 1 12 | 13 | You can assume that n is greater than or equal to 2 for all test cases. 14 | Hint: range(5, 0, -1) is the sequence 5, 4, 3, 2, 1 15 | ''' 16 | n = int(input()) 17 | for i in range(1, n+1): 18 | for j in range(1, i+1): 19 | if(j < i): 20 | print(j, end=',') 21 | else: 22 | print(j, end='') 23 | print() 24 | for k in range(n-1, 0, -1): 25 | for l in range(1, k+1): 26 | if(l < k): 27 | print(l, end=',') 28 | else: 29 | print(l, end='') 30 | print() 31 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_PPA11.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | a=b=c=0 3 | for x in range(1,n): 4 | for y in range(x+1,n): 5 | for z in range(y+1,n): 6 | if(x**2 + y**2 == z**2): 7 | print(x,y,z,sep=",") 8 | a=x 9 | b=y 10 | c=z 11 | if(a==0 and b==0 and c==0): 12 | print('NO SOLUTION') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_PPA12.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept two strings as input and form a new string by removing all characters from the second string which are present in the first string. Print this new string as output. You can assume that all input strings will be in lower case. 3 | ''' 4 | first,second=input().lower(),input().lower() 5 | end='' 6 | for i in first: 7 | for j in second: 8 | if(i==j): 9 | second =second.replace(j,'') 10 | 11 | print(second) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_PPA5.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | max=0 3 | while(n!=0): 4 | if(n>max): 5 | max=n 6 | n=int(input()) 7 | print(max) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W3_PPA6.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept a sequence of words as input and print the the shortest word in the sequence. The input will have n + 1 lines, where n denotes the number of terms in the sequence. The ith line in the input will contain the ith word in the sequence for 1 <= i <= n. 3 | The last line of the input will always be the string abcdefghijklmnopqrstuvwxyz. This string is not a part of the sequence. You can assume that each test case corresponds to a non-empty sequence of words. If there are multiple words that have the same minimum length, print the first such occurrence. 4 | ''' 5 | word=input() 6 | minLen=500 7 | shortest='' 8 | while(word!='abcdefghijklmnopqrstuvwxyz'): 9 | c=0 10 | for letter in word: 11 | c=c+1 12 | if(c0): 8 | print('YES') 9 | print(x) 10 | else: 11 | print('NO') 12 | 13 | ''' 14 | Solution by IIT Madras:- 15 | words = input().split(' ') 16 | test = input() 17 | 18 | if test not in words: 19 | print('NO') 20 | else: 21 | print('YES') 22 | count = 0 23 | for word in words: 24 | if test == word: 25 | count += 1 26 | print(count) 27 | ''' -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_GrPA2.py: -------------------------------------------------------------------------------- 1 | #Important Question 2 | def solution(marks): 3 | ### Enter your solution below this line 4 | ### Indent your entire code by one unit (4 spaces) to the right 5 | sorted_marks = [ ] # list to store the sorted marks 6 | while marks != [ ]: 7 | min_mark = marks[0] 8 | for mark in marks: 9 | if mark < min_mark: 10 | min_mark = mark 11 | marks.remove(min_mark) 12 | sorted_marks.append(min_mark) 13 | 14 | n = len(sorted_marks) 15 | # if n is odd, the middle element is the median 16 | if n % 2 != 0: 17 | mid = n // 2 18 | median = sorted_marks[mid] 19 | # if n is even, get the arithmetic mean of the two middle elements 20 | else: 21 | mid2 = n // 2 22 | mid1 = mid2 - 1 23 | median = (sorted_marks[mid1] + sorted_marks[mid2]) / 2 24 | ### Enter your solution above this line 25 | return median 26 | marks=[60,10,30,40,20,50] 27 | print(solution(marks)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_GrPA3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept two square matrices AA and BB of dimensions nxn as input and compute their product AB. 3 | 4 | The first line of the input will contain the integer nn. This is followed by 2n lines. Out of these, each of the first n lines is a sequence of comma-separated integers that denotes one row of the matrix A. Each of the last nn lines is a sequence of comma-separated integers that denotes one row of the matrix B. 5 | 6 | Your output should again be a sequence of nn lines, where each line is a sequence of comma-separated integers that denotes a row of the matrix AB. 7 | ''' 8 | n = int(input()) 9 | matrix1 = [] 10 | matrix2 = [] 11 | final = [] 12 | for i in range(n): 13 | m1 = [] 14 | x = input().split(',') 15 | for j in x: 16 | m1.append(int(j)) 17 | matrix1.append(m1) 18 | for k in range(n): 19 | m2 = [] 20 | x = input().split(',') 21 | for l in x: 22 | m2.append(int(l)) 23 | matrix2.append(m2) 24 | 25 | for i in range(n): 26 | m3 = [] 27 | for j in x: 28 | m3.append(0) 29 | final.append(m3) 30 | 31 | for i in range(n): 32 | for j in range(n): 33 | for k in range(n): 34 | final[i][j] += matrix1[i][k] * matrix2[k][j] 35 | if j != n - 1: 36 | print(final[i][j], end = ',') 37 | else: 38 | print(final[i][j]) 39 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_GrPA4.py: -------------------------------------------------------------------------------- 1 | names = input().split(',') 2 | bdays = input().split(',') 3 | n = len(names) 4 | for i in range(n): 5 | bdays[i] = int(bdays[i]) 6 | 7 | common = [ ] 8 | for i in range(n): 9 | for j in range(n): 10 | if ((i != j) and 11 | (bdays[i] == bdays[j]) and 12 | names[i] < names[j]): 13 | pair = [names[i], names[j]] 14 | common.append(pair) 15 | 16 | print(common) #This line is not required in the actual code. -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_GrPA5.py: -------------------------------------------------------------------------------- 1 | # Important question 2 | n = int(input()) 3 | L = [ ] 4 | # Append all points in the sequence to the list L 5 | for i in range(n): 6 | L.append(input()) 7 | # Point P 8 | point = input().split(',') 9 | x = int(point[0]) 10 | y = int(point[1]) 11 | 12 | # List to maintain all nearest points 13 | min_list = [] 14 | min_dist = 1000 15 | for i in range(n): 16 | # One of the points in the sequence 17 | temp = L[i].split(',') 18 | # Extract the x and y coordinates of this point 19 | temp_x = int(temp[0]) 20 | temp_y = int(temp[1]) 21 | # Compute the distance 22 | dist = ((x - temp_x) ** 2 + (y - temp_y) ** 2) ** 0.5 23 | # Check if it is the minimum distance 24 | if (dist < min_dist): 25 | min_dist = dist 26 | min_list = [L[i]] 27 | elif dist == min_dist: 28 | min_list.append(L[i]) 29 | for point in min_list: 30 | print(point) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA10.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept two square matrices A and B of dimensions n x n as input and compute their sum A + B. 3 | 4 | The first line will contain the integer n. This is followed by 2n lines. Each of the first n lines is a sequence of comma-separated integers that denotes one row of the matrix A. Each of the last nn lines is a sequence of comma-separated integers that denotes one row of the matrix B. 5 | 6 | Your output should again be a sequence of n lines, where each line is a sequence of comma-separated integer that denotes a row of the matrix A + B. 7 | 8 | 9 | ''' 10 | n = int(input()) 11 | matrix1 = [] 12 | matrix2 = [] 13 | final = [] 14 | for i in range(n): 15 | m1 = [] 16 | x = input().split(',') 17 | for j in x: 18 | m1.append(int(j)) 19 | matrix1.append(m1) 20 | for k in range(n): 21 | m2 = [] 22 | x = input().split(',') 23 | for l in x: 24 | m2.append(int(l)) 25 | matrix2.append(m2) 26 | for i in range(n): 27 | x = [] 28 | for j in range(n): 29 | x.append(matrix1[i][j]+matrix2[i][j]) 30 | final.append(x) 31 | for i in range(n): 32 | for j in range(n): 33 | if(j != n-1): 34 | print(final[i][j], end=",") 35 | else: 36 | print(final[i][j]) 37 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA11.py: -------------------------------------------------------------------------------- 1 | def solution(L): 2 | ### Enter your solution below this line 3 | ### Indent your entire code by one unit (4 spaces) to the right 4 | sorted_L=[] 5 | while(len(L)>0): 6 | max=L[0] 7 | for i in range(len(L)): 8 | if(L[i]>max): 9 | max=L[i] 10 | sorted_L.append(max) 11 | L.remove(max) 12 | ### Enter your solution above this line 13 | return sorted_L 14 | L=[1.1,2.2,3.3] 15 | print(solution(L)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA3.py: -------------------------------------------------------------------------------- 1 | # Accept a sequence of comma-separated integers as input and print the maximum value in the sequence as output. 2 | nums=input() 3 | nums=nums.split(',') 4 | max=int(nums[0]) 5 | for n in nums: 6 | if(int(n)>max): 7 | max=int(n) 8 | print(max) 9 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA5.py: -------------------------------------------------------------------------------- 1 | ''' This question introduces you to the idea of prefix codes. Prefix code is a block of visible code that is already provided to you. You have to type your code below the prefix code. Note that the contents of the prefix cannot be modified. 2 | 3 | A list L of words is already given to you as a part of the prefix code. Print the longest word in the list. If there are multiple words with the same maximum length, print the one which appears at the rightmost end of the list. 4 | 5 | You do not have to accept input from the console as it has already been provided to you. 6 | ''' 7 | 8 | l=input().split(' ') 9 | m=[] 10 | for i in l: 11 | x=float(i) 12 | m.append(int(x)) 13 | for x in range(0,len(m)): 14 | if x != len(m) - 1: 15 | print(m[x], end = ',') 16 | else: 17 | print(m[x]) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA6.py: -------------------------------------------------------------------------------- 1 | # Accept a sequence of comma-separated words as input. Reverse the sequence and print it as output. 2 | s=input().split(',') 3 | m=[] 4 | for i in s: 5 | m.append(i) 6 | for j in range(len(m)-1, -1,-1): 7 | if (j!=0): 8 | print(m[j],end=',') 9 | else: 10 | print(m[j]) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA7.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept a square matrix as input and store it in a variable named matrix. The first line of input will be, nn, the number of rows in the matrix. Each of the next nn lines will have a sequence of nn space-separated integers. 3 | ''' 4 | matrix=[] 5 | n=int(input()) 6 | for i in range(n): 7 | m=[] 8 | x=input().split(" ") 9 | for j in x: 10 | m.append(int(j)) 11 | matrix.append(m) 12 | print(matrix) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA8.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Accept a positive integer n as input and print the identity matrix of size n x n. Your output should have n lines, where each line is a sequence of n comma-separated integers that corresponds to one row of the matrix. 3 | ''' 4 | n=int(input()) 5 | matrix=[] 6 | x=[] 7 | for i in range(n): 8 | x=[] 9 | for j in range(n): 10 | if(i==j): 11 | x.append(1) 12 | else: 13 | x.append(0) 14 | matrix.append(x) 15 | for i in range(n): 16 | for j in range(n): 17 | if(j!=n-1): 18 | print(matrix[i][j],end=',') 19 | else: 20 | print(matrix[i][j]) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W4_PPA9.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The first line of input is a positive integer, n, that denotes the dimension of the matrix A. Each of the next nn lines contains a sequence of space-separated integers. The last line of the input contains the integer s. 3 | Print the matrix s . A as output. Each row of the matrix must be printed as a sequence of space separated integers, one row on each line. There should not be any space after the last number on each line. If the expected output looks exactly like the actual output and still you are getting a wrong answer, it is because of the space at the end. 4 | ''' 5 | n= int(input()) 6 | matrix=[] 7 | for i in range(0,n): 8 | m=[] 9 | x=input().split(' ') 10 | for j in x: 11 | m.append(int(j)) 12 | matrix.append(m) 13 | s= int(input()) 14 | for i in range(n): 15 | for j in range(n): 16 | matrix[i][j]=s*matrix[i][j] 17 | if(j!=n-1): 18 | print(matrix[i][j],end=" ") 19 | else: 20 | print(matrix[i][j]) 21 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_GA5_Q9.py: -------------------------------------------------------------------------------- 1 | def poly(L, x_0): 2 | psum = 0 3 | n = len(L) 4 | for i in range(n): 5 | psum = psum + L[i] * (x_0 ** i) 6 | return psum 7 | 8 | def poly_zeros(L, a, b): 9 | zeros = [ ] 10 | for x in range(a, b + 1): 11 | if poly(L, x) == 0: 12 | zeros.append(x) 13 | return zeros 14 | x=[] 15 | x=poly_zeros([-180,-144,101,52,-18,-4,1],0,4) 16 | print(len(x)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_GrPA1.py: -------------------------------------------------------------------------------- 1 | def get_range(L): 2 | ''' 3 | compute the range of a list L 4 | 5 | Argument: 6 | L: list 7 | Return: 8 | range: float 9 | ''' 10 | max=L[0] 11 | min=L[0] 12 | for e in L: 13 | if(e>max): 14 | max=e 15 | if(e bottom-right 15 | # (i, m - i - 1) goes from top-right -> bottom-left 16 | # note that a single loop is enough; no nesting required 17 | for i in range(m): 18 | d1sum += mat[i][i] 19 | d2sum += mat[i][m - i - 1] 20 | # if the two diagonal sums are unequal, we can return NO 21 | # unnecessary computation can be avoided 22 | if not(d1sum == d2sum): 23 | return 'NO' 24 | # get row-sum and column-sum 25 | for i in range(m): 26 | rsum, csum = 0, 0 27 | for j in range(m): 28 | rsum += mat[i][j] 29 | csum += mat[j][i] 30 | if not(rsum == csum == d1sum): 31 | return 'NO' 32 | # if the code reaches this level 33 | # then all requirements of a magic-square are satisfied 34 | # so we can safely return YES 35 | return 'YES' 36 | print(is_magic([[4, 9, 2],[3, 5, 7],[8, 1, 6]])) 37 | print(is_magic([[1,2,3],[3,2,1],[1,3,2]])) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_GrPA5.py: -------------------------------------------------------------------------------- 1 | def transpose(mat): 2 | """ 3 | compute the transpose of the matrix 4 | 5 | Argument: 6 | mat: list of lists 7 | Return: 8 | mat_trans: list of lists 9 | """ 10 | tmat=[] 11 | row=len(mat) 12 | col=len(mat[0]) 13 | for i in range(col): 14 | m1=[] 15 | for j in range(row): 16 | m1.append(mat[j][i]) 17 | tmat.append(m1) 18 | 19 | return tmat 20 | 21 | m=[[1,2,3],[4,5,6]] 22 | print(transpose(m)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_PPA10.py: -------------------------------------------------------------------------------- 1 | def insert(L, x): 2 | """ 3 | insert an element x into a sorted list L 4 | 5 | Arguments: 6 | L: list 7 | x: integers 8 | Return: 9 | sorted_L: list 10 | """ 11 | list=[] 12 | i=0 13 | if(x>=L[len(L)-1]): 14 | for e in L: 15 | list.append(e) 16 | list.append(x) 17 | return(list) 18 | for i in range(0,len(L)): 19 | if(L[i]>=x): 20 | for j in range(0,i): 21 | list.append(L[j]) 22 | list.append(x) 23 | break 24 | for j in range(i,len(L)): 25 | list.append(L[j]) 26 | return list 27 | 28 | print(insert([10],10)) 29 | print(insert([1,2,3,4,5,6,7,8,9],10)) 30 | print(insert([10,20,30,40,50,60,70,80,90,100],55)) 31 | 32 | ''' 33 | IITM Solution Code:- 34 | def insert(L, x): 35 | out_L = [ ] 36 | inserted = False 37 | for elem in L: 38 | if (not inserted) and (elem > x): 39 | out_L.append(x) 40 | inserted = True 41 | out_L.append(elem) 42 | if (not inserted): 43 | out_L.append(x) 44 | return out_L 45 | ''' -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_PPA5.py: -------------------------------------------------------------------------------- 1 | def first_three(L): 2 | """ 3 | computes the first three maximums 4 | 5 | Argument: 6 | L: list 7 | Return: 8 | fmax, smax, tmax: three integers 9 | """ 10 | x = [] 11 | for i in range(0, 3): 12 | max=L[0] 13 | for e in L: 14 | if(e > max): 15 | max = e 16 | x.append(max) 17 | L.remove(max) 18 | return x 19 | 20 | print(first_three([90,2,3,4,5,6,52,8])) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_PPA7.py: -------------------------------------------------------------------------------- 1 | def is_empty(L): 2 | return L == [ ] 3 | 4 | def first(L): 5 | if is_empty(L): 6 | return None 7 | return L[0] 8 | 9 | def last(L): 10 | if is_empty(L): 11 | return None 12 | return L[-1] 13 | 14 | def init(L): 15 | if is_empty(L): 16 | return None 17 | return L[:-1] 18 | 19 | def rest(L): 20 | if is_empty(L): 21 | return None 22 | return L[1: ] 23 | 24 | print(first([1, 2, 3])) 25 | print(last([1, 2, 3, 4])) 26 | print(is_empty([ ])) 27 | print(is_empty([1, 2])) 28 | print(first([ ])) 29 | print(first([-1, 10, 2])) 30 | print(last([ ])) 31 | print(last([10, 0, -100])) 32 | print(init([ ])) 33 | print(init([1, 2, 3, 4, 5])) 34 | print(rest([ ])) 35 | print(rest([1, 2, 3, 4, 5, 6])) 36 | 37 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_PPA8.py: -------------------------------------------------------------------------------- 1 | def fibo(n): 2 | """ 3 | compute the nth fibonacci integer 4 | 5 | Argument: 6 | n: int 7 | Return: 8 | f_n: int 9 | """ 10 | if(n==1 or n==2): 11 | return 1 12 | else: 13 | return (fibo(n-1)+fibo(n-2)) 14 | 15 | print(fibo(10)) 16 | print(fibo(3)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W5_PPA9.py: -------------------------------------------------------------------------------- 1 | def get_column(mat, col): 2 | """ 3 | extract a specific column from the matrix 4 | 5 | Arguments: 6 | mat: list of lists 7 | col: integer 8 | Return: 9 | col_list: list 10 | """ 11 | x=[] 12 | if(col>=0): 13 | for i in range(0,len(mat)): 14 | x.append(mat[i][col]) 15 | return x 16 | 17 | def get_row(mat, row): 18 | """ 19 | extract a specific row from the matrix 20 | 21 | Arguments: 22 | mat: list of lists 23 | row: integer 24 | Return: 25 | row_list: list 26 | """ 27 | x=[] 28 | if(row>=0): 29 | x=mat[row] 30 | return x 31 | 32 | print(get_column([[1, 2], [3, 4]], 0)) 33 | print(get_row([[1, 2], [3, 4]], 1)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W6_PPA10.py: -------------------------------------------------------------------------------- 1 | # Important Question 2 | '''Write the following functions:- 3 | (1) group_by_city: accepts the scores_dataset as argument. It should return a dictionary named cities whose keys are names of the cities that the students are from. The value corresponding to a key (city) is the list of names of all students who hail from this city. The order in which names are appended to the list doesn't matter. 4 | 5 | (2) busy_cities: accepts the scores_dataset as argument. It should return a list of cities. Each city in this list has the property that the number of students from this city is greater than or equal to the number of students from every other city in the dataset. Your function should make use of group_by_city. The order in which the cities appended to the list doesn't matter. 6 | ''' 7 | def group_by_city(scores_dataset): 8 | cities = dict() 9 | 10 | for student in scores_dataset: 11 | city = student['City'] 12 | name = student['Name'] 13 | if city not in cities: 14 | cities[city] = [ ] 15 | cities[city].append(name) 16 | 17 | return cities 18 | 19 | def busy_cities(scores_dataset): 20 | cities = group_by_city(scores_dataset) 21 | 22 | busy = [ ] 23 | maxpop = 0 24 | for city in cities: 25 | if len(cities[city]) > maxpop: 26 | maxpop = len(cities[city]) 27 | busy = [city] 28 | elif len(cities[city]) == maxpop: 29 | busy.append(city) 30 | 31 | return busy -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W6_PPA6.py: -------------------------------------------------------------------------------- 1 | def get_marks(scores_dataset, subject): 2 | """ 3 | Get the marks scored by all students in subject 4 | 5 | Arguments: 6 | scores_dataset: list of dicts 7 | subject: string 8 | Return: 9 | marks: list of tuples of the form (string, int) 10 | """ 11 | t=[] 12 | l=len(scores_dataset) 13 | for i in range(l): 14 | for e in scores_dataset[i]: 15 | if(subject==e): 16 | a=scores_dataset[i]['Name'],scores_dataset[i][subject] 17 | t.append(a) 18 | return t -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W6_PPA7.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | scores_dataset=[] 3 | d={} 4 | for i in range(n): 5 | d['Name']=input() 6 | d['City']=input() 7 | d['SeqNo']=int(input()) 8 | d['Mathematics']=int(input()) 9 | d['Physics']=int(input()) 10 | d['Chemistry']=int(input()) 11 | scores_dataset.append(d) 12 | d={'Name':'','City':'','SeqNo':-1,'Mathematics':-1,'Physics':-1,'Chemistry':-1} 13 | 14 | 15 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W6_PPA8.py: -------------------------------------------------------------------------------- 1 | def factors(n): 2 | """ 3 | Compute the set of factors of n 4 | 5 | Argument: 6 | n: integer 7 | Return: 8 | factors_of_n: set 9 | """ 10 | a=[] 11 | for i in range(1,n+1): 12 | if(n%i==0): 13 | a.append(i) 14 | return set(a) 15 | 16 | def common_factors(a, b): 17 | """ 18 | Compute the set of common factors of a and b 19 | 20 | Arguments: 21 | a, b: integers 22 | Return: 23 | factors_common: set 24 | """ 25 | m=[] 26 | x,y=factors(a),factors(b) 27 | m=x.intersection(y) 28 | return set(m) 29 | 30 | def factors_upto(n): 31 | """ 32 | Get the factors up to n 33 | 34 | Argument: 35 | n: integer 36 | Return: 37 | result: dict (keys: integers, values: sets) 38 | """ 39 | d= dict() 40 | for i in range(1,n+1): 41 | d[i] = factors(i) 42 | return d -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W6_PPA9.py: -------------------------------------------------------------------------------- 1 | s=input().split(',') 2 | real_dict={} 3 | for e in s: 4 | real_dict[e[0]]=[] 5 | for e in s: 6 | real_dict[e[0]].append(e) 7 | 8 | print(real_dict) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W7_GrPA1.py: -------------------------------------------------------------------------------- 1 | ''' My own Code:- 2 | 3 | d={'CSK':0,'DC':0,'KKR':0,'MI':0,"PK":0,'RCB':0,'RR':0,'SH':0} 4 | x={} 5 | for i in range(8): 6 | s=input().split(',') 7 | for key in d: 8 | if(s[0]==key): 9 | d[key]+=len(s)-1 10 | x=dict(sorted(d.items(), key=lambda x: x[1], reverse=True)) 11 | for key in x: 12 | print(key,d[key],sep=':') 13 | 14 | ''' 15 | # This question is very important to understand how to sort a dictionary based on its values 16 | # IIT Madras Solution Code:- [Better and easy-to-grasp logic] 17 | results = [ ] 18 | for i in range(8): 19 | L = input().split(',') 20 | winner = L[0] # the first team is the winner 21 | losers = L[1: ] # all these teams have lost to the winner 22 | # we only need the number of wins and the winning team 23 | results.append((winner, len(losers))) 24 | 25 | table = [ ] 26 | # two-level-sort 27 | # refer GrPA-4 of week-6 28 | # we first sort by points, then by name 29 | while results != [ ]: 30 | maxteam = results[0] 31 | for i in range(len(results)): 32 | team = results[i] 33 | if team[1] > maxteam[1]: 34 | maxteam = team 35 | elif team[1] == maxteam[1] and team[0] < maxteam[0]: 36 | maxteam = team 37 | results.remove(maxteam) 38 | table.append(maxteam) 39 | 40 | for team in table: 41 | print(f'{team[0]}:{team[1]}') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W7_GrPA2.py: -------------------------------------------------------------------------------- 1 | # My own code:- 2 | def merge(D1, D2, priority): 3 | """ 4 | Merge two dicts 5 | 6 | Arguments: 7 | - D1: first dictionary 8 | - D2: second dictionary 9 | - priority: string 10 | Returns: D; merged dictionary 11 | """ 12 | D={} 13 | x,y=set(D1.keys()),set(D2.keys()) 14 | common=x.intersection(y) 15 | for e in common: 16 | if(priority=="first"): 17 | D[e]=D1[e] 18 | else: 19 | D[e]=D2[e] 20 | D1.pop(e) 21 | D2.pop(e) 22 | for e in D1: 23 | D[e]=D1[e] 24 | for e in D2: 25 | D[e]=D2[e] 26 | return D 27 | 28 | #IIT Madras solution code:- 29 | ''' 30 | # The basic idea is to write the code for priority equal to "first" 31 | # When priority is "second", we can just reverse the order of the dicts 32 | def merge(D1, D2, priority): 33 | if priority == 'second': 34 | return merge(D2, D1, 'first') 35 | D = dict() 36 | # First copy all key-value pairs in D1 to D 37 | for key in D1: 38 | value = D1[key] 39 | D[key] = value 40 | # Copy all those key-value pairs in D2 to D 41 | # where the key is not already present in D 42 | for key in D2: 43 | value = D2[key] 44 | if key not in D: 45 | D[key] = value 46 | return D 47 | ''' 48 | D1={1: 2, 2: 3, 3: 4} 49 | D2={1: 10, 4: 15, 5:10} 50 | print(merge(D1,D2,'first')) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W7_GrPA3.py: -------------------------------------------------------------------------------- 1 | def minor_matrix(M, i, j): 2 | """ 3 | Compute the "minor matrix" 4 | 5 | Arguments: 6 | M: list of lists 7 | i: integer 8 | j: integer 9 | Return: 10 | M_ij: list of lists 11 | """ 12 | M_ij = [] 13 | for row in range(len(M)): 14 | # skip row i 15 | if row == i: 16 | continue 17 | L = [ ] 18 | for col in range(n): 19 | # skip column j 20 | if col == j: 21 | continue 22 | # add all other elements as they are 23 | L.append(M[row][col]) 24 | M_ij.append(L) 25 | return M_ij -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W7_GrPA4.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | station_dict={} 3 | for i in range(n): 4 | train_name=input() 5 | m=int(input()) 6 | x={} 7 | for j in range(m): 8 | s=input().split(',') 9 | x[s[0]]=int(s[1]) 10 | station_dict[train_name]=x 11 | 12 | #print(station_dict) 13 | 14 | -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W8_PPA3.py: -------------------------------------------------------------------------------- 1 | def multiply(a, b): 2 | """ 3 | A recursive function to compute the product of two numbers 4 | 5 | Arguments: 6 | a, b: integers 7 | Return: 8 | result: integer 9 | """ 10 | if(b==0): 11 | return 0 12 | elif(b==1): 13 | return a 14 | return a+multiply(a,b-1) 15 | 16 | print(multiply(7,8)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W8_PPA4.py: -------------------------------------------------------------------------------- 1 | def logarithm(x): 2 | """ 3 | A recursive function to compute the log of x 4 | 5 | Argument: 6 | x: integer 7 | Result: 8 | result: integer 9 | """ 10 | if(x==1): 11 | return 0 12 | return 1+logarithm(x//2) 13 | 14 | print(logarithm(1024)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W8_PPA5.py: -------------------------------------------------------------------------------- 1 | def palindrome(word): 2 | if len(word) <= 1: 3 | return True 4 | if word[0] != word[-1]: 5 | return False 6 | return palindrome(word[1:-1]) 7 | 8 | print(palindrome("mom")) 9 | print(palindrome("random")) 10 | print(palindrome("a")) 11 | print(palindrome("ab")) 12 | print(palindrome("aba")) 13 | print(palindrome("abcba")) 14 | print(palindrome("malayalam")) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_GrPA1.py: -------------------------------------------------------------------------------- 1 | # My solution code:- 2 | def get_freq(filename): 3 | """ 4 | Extract frequency information from the file 5 | 6 | Argument: 7 | filename: string, path to file 8 | Return: 9 | result: dictionary; keys are strings, values are integers 10 | """ 11 | f=open(filename,'r') 12 | s=f.readlines() 13 | f.close() 14 | a={} 15 | for line in s: 16 | if(line.strip() in a): 17 | a[line.strip()]+=1 18 | else: 19 | a[line.strip()]=1 20 | return a 21 | 22 | ''' 23 | #IITM Solution Code:- 24 | def get_freq(filename): 25 | f = open(filename, 'r') 26 | freq = dict() 27 | for line in f: 28 | word = line.strip() 29 | if word not in freq: 30 | freq[word] = 0 31 | freq[word] += 1 32 | f.close() 33 | return freq 34 | ''' -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_GrPA2.py: -------------------------------------------------------------------------------- 1 | def relation(file1, file2): 2 | """ 3 | Determine the relationship between two files 4 | 5 | Arguments: 6 | file1, file2: strings, paths to two files 7 | Return: 8 | string: 'Equal', 'Subset' or 'No Relation' 9 | """ 10 | f1=open(file1,'r') 11 | f2=open(file2,'r') 12 | s1=f1.readlines() 13 | s2=f2.readlines() 14 | f1.close() 15 | f2.close() 16 | if(len(s1)==len(s2)): 17 | f=True 18 | for i in range(len(s1)): 19 | if(s1[i].strip()!=s2[i].strip()): 20 | f=False 21 | break 22 | if(f): 23 | return "Equal" 24 | else: 25 | if(s1len(s)): 15 | return None 16 | return (s[n-1].strip()) 17 | ''' 18 | #IITM Solution Code: 19 | def read_line(filename, n): 20 | f = open(filename, 'r') 21 | count = 0 22 | line = f.readline() 23 | while line != '': 24 | count += 1 25 | line = line.strip() 26 | if count == n: 27 | return line 28 | line = f.readline() 29 | f.close() 30 | return None 31 | ''' 32 | 33 | print(read_line("mytext.txt",5)) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_PPA3.py: -------------------------------------------------------------------------------- 1 | # My own code:- 2 | def get_max_line(filename): 3 | """ 4 | Get the line that houses the maximum value 5 | 6 | Argument: 7 | filename: string, path to the file 8 | Return: 9 | result: integer 10 | """ 11 | f=open(filename,'r') 12 | s=f.readlines() 13 | f.close() 14 | max=int(s[0]) 15 | for line in s: 16 | if(int(line)>max): 17 | max=int(line) 18 | for i in range(0,len(s)-1): 19 | if(int(s[i])==max): 20 | return i+1 21 | return int(s[0]) 22 | 23 | ''' 24 | #IITM Solution Code:- 25 | def get_max_line(filename): 26 | f = open(filename, 'r') 27 | line = f.readline() 28 | maxnum, maxline = int(line.strip()), 1 29 | count = 1 30 | for line in f: 31 | num = int(line.strip()) 32 | count += 1 33 | if num > maxnum: 34 | maxnum = num 35 | maxline = count 36 | return maxline 37 | ''' -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_PPA4.py: -------------------------------------------------------------------------------- 1 | def get_dict(filename): 2 | """ 3 | Convert the contents of the file into a dict 4 | 5 | Argument: 6 | filename: string, path of the file 7 | Return: 8 | result: dict; keys are strings, values are integers 9 | """ 10 | f=open(filename,'r') 11 | s=f.readlines()[1:] 12 | a={} 13 | f.close() 14 | for e in s: 15 | x=e.split(',') 16 | a[x[0]]=int(x[1]) 17 | return a -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_PPA5.py: -------------------------------------------------------------------------------- 1 | def get_matrix(filename): 2 | """ 3 | Convert the contents of the file into a matrix 4 | 5 | Argument: 6 | filename: string 7 | Return: 8 | matrix: list of lists 9 | """ 10 | f=open(filename,'r') 11 | s=f.readlines() 12 | f.close() 13 | b=[] 14 | for i in range(len(s)): 15 | a=[] 16 | x=s[i].split(',') 17 | for i in range(len(x)): 18 | a.append(int(x[i])) 19 | b.append(a) 20 | return b -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_PPA6.py: -------------------------------------------------------------------------------- 1 | def write_AP(a_1, d, n): 2 | """ 3 | Write the AP to a file 4 | 5 | Arguments: 6 | a_1: first term, integer 7 | d: common difference, integer 8 | n: number of terms, integer 9 | Return: 10 | None 11 | """ 12 | x=[] 13 | x.append(a_1) 14 | for i in range(1,n+1): 15 | if(len(x)==n): 16 | break 17 | x.append(a_1+i*d) 18 | f=open('out.txt','w') 19 | for e in x: 20 | f.write(str(e)+"\n") 21 | f.close() 22 | 23 | write_AP(16,9,10) -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_PPA7.py: -------------------------------------------------------------------------------- 1 | def add_period(filename): 2 | """ 3 | Add a period at the end of each line 4 | 5 | Argument: 6 | filename: string; path of the file 7 | Return: 8 | None 9 | """ 10 | f=open(filename,'r') 11 | x=open("out.txt",'w') 12 | for line in f: 13 | line=line.strip() 14 | x.write(line+'.'+'\n') 15 | f.close() 16 | x.close() 17 | 18 | add_period('myText.txt') -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/W9_PPA8.py: -------------------------------------------------------------------------------- 1 | def improvement(filename): 2 | """ 3 | Find all students who have shown an improvement 4 | 5 | Argument: 6 | filename: string, path to file 7 | Return: 8 | count: integer 9 | """ 10 | f=open(filename,'r') 11 | s=f.readlines()[1:] 12 | c=0 13 | for e in s: 14 | x=e.split(',') 15 | if(int(x[2])= 70: 19 | g.write(line) 20 | f.close() 21 | g.close() -------------------------------------------------------------------------------- /PPA, GrPA and Assignment Codes/test.py: -------------------------------------------------------------------------------- 1 | word="([{}])" 2 | word=")([]" 3 | for i in range(len(word)): 4 | if(word[i]=='(' and ')' not in word[i:]) or (word[i]=='{' and '}' not in word[i:]) or (word[i]=='[' and ']' not in word[i:]): 5 | print(word[i:],False) 6 | else: 7 | print(True) -------------------------------------------------------------------------------- /Practice Test Codes/OPPE1_Mock1.py: -------------------------------------------------------------------------------- 1 | n=input() 2 | f=True 3 | c=0 4 | for e in n: 5 | if(e=='l' or e=='o'): 6 | f=False 7 | c=c+1 8 | if(f): 9 | print("No mistakes") 10 | else: 11 | print(c,"mistakes") 12 | x=n.replace('l','1') 13 | x=x.replace('o','0') 14 | print(x) -------------------------------------------------------------------------------- /Practice Test Codes/OPPE1_Mock2.py: -------------------------------------------------------------------------------- 1 | n=input().split(',') 2 | l=[] 3 | for e in n: 4 | l.append(int(e)) 5 | x=int(len(n)/2) 6 | left,right=0,0 7 | for i in range(x): 8 | left=left+l[i] 9 | right=right+l[x+i] 10 | if(left>right): 11 | print("left-heavy") 12 | elif(right>left): 13 | print("right-heavy") 14 | else: 15 | print("balanced") -------------------------------------------------------------------------------- /Practice Test Codes/OPPE1_Mock3.py: -------------------------------------------------------------------------------- 1 | def matrix_type(M): 2 | """ 3 | Determine the type of the matrix 4 | 5 | Argument: 6 | M: list of lists 7 | Return: 8 | mtype: str 9 | """ 10 | d, sc, id = True, True, True 11 | s = '' 12 | x = M[1][1] 13 | for i in range(len(M)): 14 | for j in range(len(M[i])): 15 | if(i!=j and M[i][j]!=0): 16 | d=False 17 | break 18 | for i in range(len(M)): 19 | if(x != M[i][i]): 20 | sc = False 21 | if(M[i][i] != 1): 22 | id = False 23 | if(d): 24 | s = "diagonal" 25 | else: 26 | s="non-diagonal" 27 | if(d == True and sc == True): 28 | s = "scalar" 29 | if(d == True and id == True): 30 | s = "identity" 31 | return s 32 | 33 | 34 | print(matrix_type([[1, 0, 0], [0, 1, 0], [0, 0, 1]])) # identity 35 | print(matrix_type([[4, 0, 0], [0, 4, 0], [0, 0, 4]])) # scalar 36 | print(matrix_type([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 52, 0], [0, 0, 0, 1]])) #diagonal 37 | print(matrix_type([[1, 0, 0, 0], [0, 2, 0, 0],[0, 0, 3, 0], [0, 0, 0, 4]])) # diagonal 38 | print(matrix_type([[1, 2, 3], [4, 9, 56], [2, 7, 8]])) #non-diagonal 39 | -------------------------------------------------------------------------------- /Practice Test Codes/OPPE1_Mock4.py: -------------------------------------------------------------------------------- 1 | def exact_count(para, n): 2 | """ 3 | Determine if at least one word occurs exactly n times 4 | 5 | Arguments: 6 | para: string 7 | n: integer 8 | Return: 9 | result: bool 10 | """ 11 | l=[] 12 | s='' 13 | for e in para: 14 | if(e!=' '): 15 | s=s+e 16 | else: 17 | l.append(s) 18 | s='' 19 | l.append(s) 20 | d={} 21 | for e in l: 22 | if(e not in d): 23 | d[e]=1 24 | else: 25 | d[e]+=1 26 | f=False 27 | for key in d: 28 | if(d[key]==n): 29 | f=True 30 | break 31 | else: 32 | f=False 33 | return f 34 | 35 | print(exact_count("good word many good works good real choice",3)) -------------------------------------------------------------------------------- /Practice Test Codes/OPPE1_Mock5.py: -------------------------------------------------------------------------------- 1 | s=input().split(' ') 2 | m=0 3 | import operator 4 | a={'one':1,'two':2,'three':3,'four':4,'five':5,'six':6,'seven':7,'eight':8,'nine':9,'zero':0} 5 | if(s[0]=='minus'): 6 | m= -int(a[s[1]]) 7 | elif(s[0]=='plus'): 8 | m= +int(a[s[1]]) 9 | sum,c=0,0 10 | for i in range(len(s)): 11 | if(s[i]=='plus'): 12 | sum+=sum 13 | print(m) -------------------------------------------------------------------------------- /Practice Test Codes/OPPE1_Mock6.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/Practice Test Codes/OPPE1_Mock6.py -------------------------------------------------------------------------------- /Practice Test Codes/PracticeTest1_5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | You are given a string and two non-negative integers as input. The two integers specify the start and end indices of a substring in the given string. Create a new string by replicating the substring a minimum number of times so that the resulting string is longer than the input string. 3 | The input parameters are the string, start index of the substring and the end index of substring (endpoints inclusive) each on a different line. 4 | ''' 5 | s,a,b=input(),int(input()),int(input()) 6 | n=s[a:(b+1)] 7 | p=len(s)-len(n) 8 | c=n 9 | if(p>0): 10 | while(len(s)>=len(c)): 11 | c=c+n 12 | else: 13 | c=n 14 | print (c) -------------------------------------------------------------------------------- /Practice Test Codes/PracticeTest2_1.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | s,p,r,e=[],[],[],[] 3 | for i in range(n): 4 | if(i in e or i==0): 5 | s.append(i+1) 6 | if(i in s): 7 | p.append(i+1) 8 | if(i in p): 9 | r.append(i+1) 10 | if(i in r): 11 | e.append(i+1) 12 | if(n in s): 13 | print("Sapphire") 14 | elif(n in p): 15 | print("Peridot") 16 | elif(n in r): 17 | print("Ruby") 18 | elif(n in e): 19 | print("Emerald") -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_LECANDY.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/IITMPP01/problems/LECANDY 2 | t=int(input()) 3 | f=[] 4 | for i in range(t): 5 | sum=0 6 | s1=input().split() 7 | n,c=int(s1[0]),int(s1[1]) 8 | s2=input().split() 9 | l2=[] 10 | for e in s2: 11 | l2.append(int(e)) 12 | for i in range(n): 13 | sum=sum+l2[i] 14 | if(sum>c): 15 | f.append("No") 16 | else: 17 | f.append("Yes") 18 | for e in f: 19 | print(e) 20 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_NOTINCOM.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/IITMPP01/problems/NOTINCOM 2 | t=int(input()) 3 | common=[] 4 | for i in range(t): 5 | s=input().split() 6 | n=int(s[0]) 7 | m=int(s[1]) 8 | s1=input().split(' ') 9 | l1=[] 10 | for e in s1: 11 | l1.append(int(e)) 12 | s2=input().split(' ') 13 | l2=[] 14 | for e in s2: 15 | l2.append(int(e)) 16 | common.append(len(set(l1).intersection(set(l2)))) 17 | for e in common: 18 | print(e) 19 | 20 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_SMSDICT.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/IITMPP01/problems/SMSDICT 2 | def wordtonumber(w,lwords): 3 | s='' 4 | for i in range(0,len(w)): 5 | for j in range(2,10): 6 | if(w[i] in lwords[j]): 7 | s=s+str(j) 8 | return (int(s)) 9 | 10 | lwords={2:['a','b','c'], 3:['d','e','f'], 4:['g','h','i'], 5:['j','k','l'], 6:['m','n','o'], 7:['p','q','r','s'], 8:['t','u','v'],9:['w','x','y','z']} 11 | m=int(input()) 12 | l=[] 13 | for i in range(m): 14 | s=input() 15 | l.append(wordtonumber(s,lwords)) 16 | x=[] 17 | for e in l: 18 | x.append(l.count(e)) 19 | max=x[0] 20 | p=0 21 | for i in range(len(x)): 22 | if(x[i]>max): 23 | max=x[i] 24 | p=i 25 | print(l[p]) -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_SMTFAC3.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/IITMPP01/problems/SNTFAC3 2 | #The solution is correct but still it can't run successfully on codechef probably because the input testcases have multiple spaces in front of them. I haven't found a way to effective remove the spaces from the inputs and get a successfull execution. I have coded the same program with similar logic in JAVA and I was successful to get a full AC. 3 | #It is a very important question. 4 | 5 | t=int(input()) 6 | li=[] 7 | for i in range(t): 8 | s=input().split(' ') 9 | m,n,k=int(s[0]),int(s[1]),int(s[2]) 10 | l=[] 11 | for j in range(m): 12 | l.append(int(input())) 13 | l.sort() 14 | sum=0 15 | for x in range(0,k): 16 | l[x]=n-l[x] 17 | for x in range(0,m): 18 | sum+=l[x] 19 | li.append(sum) 20 | for e in li: 21 | print(e) 22 | 23 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_SMTFAC3_Alternative.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theroyaritra/IITMadrasPythonCodeBase/fa89c6a2d58b7899de7985b8164a357153d6d141/Programming exam codes/CodeChef Practice by IITM/IITMPP01_SMTFAC3_Alternative.class -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_SMTFAC3_Alternative.java: -------------------------------------------------------------------------------- 1 | //https://www.codechef.com/IITMPP01/problems/SNTFAC3 2 | import java.util.*; 3 | 4 | class IITMPP01_SMTFAC3_Alternative 5 | { 6 | public static void main (String[] args) throws java.lang.Exception 7 | { 8 | Scanner sc = new Scanner(System.in); 9 | int t = sc.nextInt(); 10 | while (t!= 0) { 11 | int sum = 0; 12 | int m = sc.nextInt(); 13 | int n = sc.nextInt(); 14 | int k = sc.nextInt(); 15 | int arr[] = new int[m]; 16 | for (int i = 0; i < m; i++) { 17 | arr[i] = sc.nextInt(); 18 | } 19 | Arrays.sort(arr); 20 | for (int i = 0; i < k; i++){ 21 | arr[i] = n - arr[i]; 22 | } 23 | for (int i = 0; i < m; i++) { 24 | sum += arr[i]; 25 | } 26 | System.out.println(sum); 27 | t--; 28 | } 29 | sc.close(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_TheLeadGame.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/IITMPP01/problems/TLG 2 | n=int(input()) 3 | d={} 4 | for i in range(n): 5 | s=input().split() 6 | if (i==0): 7 | d[i]=[int(s[0]),int(s[1])] 8 | else: 9 | d[i]=[int(s[0])+d[i-1][0],int(s[1])+d[i-1][1]] 10 | diff=d[i][1]-d[i][0] 11 | if(d[i][0]max): 25 | max=l1[i] 26 | x=i 27 | print(d) 28 | print(l1) 29 | print(l2) 30 | print(l2[x]," ",max) 31 | 32 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP01_VCS.py: -------------------------------------------------------------------------------- 1 | # https://www.codechef.com/IITMPP01/problems/VCS 2 | def keepcount(l1,l2): 3 | c1,c2=0,0 4 | l=[] 5 | for i in range(1,n+1): 6 | if i in l1 and i in l2: 7 | c1+=1 8 | elif i not in l1 and i not in l2: 9 | c2+=1 10 | l.append(c1) 11 | l.append(c2) 12 | return l 13 | 14 | t=int(input()) 15 | d={} 16 | for i in range(t): 17 | s1=input().split() 18 | n=int(s1[0]) #Number of source files in project 19 | m=int(s1[1]) #Number of ignored source files in project 20 | k=int(s1[2]) #Number of tracked source files in project 21 | ignored=[] 22 | tracked=[] 23 | s2=input().split() 24 | for e in s2: 25 | ignored.append(int(e)) 26 | s3=input().split() 27 | for e in s3: 28 | tracked.append(int(e)) 29 | d[i]=keepcount(ignored,tracked) 30 | for keys in d: 31 | print(d[keys][0]," ",d[keys][1]) -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP02_ABROADS.py: -------------------------------------------------------------------------------- 1 | n,m,q=[int(x) for x in input.split(' ')] 2 | population=[int(x) for x in input.split(' ')] 3 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP02_COLDPLAY.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | s=input() 3 | krushi,mansi='','' 4 | for i in range(len(s)): 5 | if(i%2==0): 6 | krushi+=s[i] 7 | else: 8 | mansi+=s[i] 9 | a={'U':(0,1),'D':(0,-1),'R':(+1,0),'L':(-1,0)} 10 | k,m=[(0,0)],[(0,0)] 11 | for e in krushi: 12 | for i in range(len(k)): 13 | p=(a[e][0]+k[i][0],a[e][1]+k[i][1]) 14 | k.append(p) 15 | for e in mansi: 16 | for j in range(len(m)): 17 | q=(a[e][0]+m[j][0],a[e][1]+m[j][1]) 18 | m.append(q) 19 | x=set(k+m) 20 | print(len(x)) 21 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP02_JFY.py: -------------------------------------------------------------------------------- 1 | n=int(input()) 2 | x,m=[int(x) for x in input().split(' ')] 3 | l=[] 4 | for i in range(x): 5 | l.append(input()) 6 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP02_JOKRBTMN.py: -------------------------------------------------------------------------------- 1 | x=[] 2 | for t in range(int(input())): 3 | n, m, l = input().split(' ') 4 | list_of_lists = {} 5 | for i in range(0, int(m)): 6 | input_list = input().split(' ')[1:] 7 | for j in input_list: 8 | list_of_lists[j] = i 9 | strip = input().split(' ') 10 | 11 | current = list_of_lists[strip[0]] 12 | count = 1 13 | for i in strip: 14 | if list_of_lists[i] != current: 15 | count += 1 16 | current = list_of_lists[i] 17 | x.append(count) 18 | for e in x: 19 | print(e) -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP02_KJCP3.py: -------------------------------------------------------------------------------- 1 | t=int(input()) 2 | x=[] 3 | for i in range(t): 4 | n=int(input()) 5 | l,l1,l2=[],[],[] 6 | s1=input().split(' ') 7 | for e in s1: 8 | l1.append(int(e)) 9 | s2=input().split(' ') 10 | for e in s2: 11 | l2.append(int(e)) 12 | l1.sort() 13 | l2.sort() 14 | for i in range(n): 15 | l.append(l1[i]) 16 | l.append(l2[i]) 17 | x.append(l) 18 | for e in x: 19 | for i in range(len(e)): 20 | print(e[i],end=' ') 21 | print() -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP04CHEFSLP.py: -------------------------------------------------------------------------------- 1 | for i in range(int(input())): 2 | n,l,x=[int(x) for x in input().split(' ')] 3 | r=n-l 4 | pair=min(l,r) 5 | money=pair*x 6 | print(money) -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP04_CARVANS.py: -------------------------------------------------------------------------------- 1 | for i in range(int(input())): 2 | n=int(input()) 3 | s=input().split(' ') 4 | l=[] 5 | for i in range(n): 6 | l.append(int(s[i])) 7 | c=1 8 | for j in range(0,n-1): 9 | if(l[j+1]=x) or (each.count('F')==x-1 and each.count('P')>=y): 11 | result+='1' 12 | else: 13 | result+='0' 14 | print(result) -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP06_EMPR.py: -------------------------------------------------------------------------------- 1 | # cook your dish here 2 | for i in range(int(input())): 3 | p,x,y,z=[int(x) for x in input().split()] 4 | s=0 5 | if(z==1): 6 | s=p+(y/100)*p 7 | else: 8 | s=p-(x/100)*p 9 | print(s) -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP06_EXPRESSION_3.py: -------------------------------------------------------------------------------- 1 | # cook your dish here 2 | for i in range(int(input())): 3 | a,b,c=[int(x) for x in input().split()] 4 | if(a+b+c==0 or -a+b+c==0 or -a-b-c==0 or a-b-c==0 or a-b+c==0 or a+b-c==0 or -a-b+c==0 or a-b-c==0): 5 | print("Yes") 6 | else: 7 | print("No") -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP06_FNDINT.py: -------------------------------------------------------------------------------- 1 | # cook your dish here 2 | from sys import maxsize 3 | 4 | def distinct(n): 5 | a=str(n) 6 | f=True 7 | x={} 8 | if(len(a)==1): 9 | f==True 10 | else: 11 | for e in a: 12 | if(e not in x): 13 | x[e]=1 14 | else: 15 | x[e]+=1 16 | m=list(x.values()) 17 | m.sort(reverse=True) 18 | if(m[0]!=1): 19 | f=False 20 | return f 21 | 22 | for j in range(int(input())): 23 | x=int(input()) 24 | for i in range(x+1,maxsize): 25 | if(distinct(i)): 26 | print(i) 27 | break 28 | -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP06_MONSTER1.py: -------------------------------------------------------------------------------- 1 | # cook your dish here 2 | for i in range(int(input())): 3 | h,x,y=[int(x) for x in input().split()] 4 | health=h 5 | c=0 6 | while(health>0): 7 | health=health+y 8 | health=health-x 9 | c=c+1 10 | if(health<=0 or c==50000): 11 | break 12 | if(health<=0): 13 | print(1) 14 | else: 15 | print(0) -------------------------------------------------------------------------------- /Programming exam codes/CodeChef Practice by IITM/IITMPP06_MONSTER2.py: -------------------------------------------------------------------------------- 1 | for i in range(int(input())): 2 | a,b,x,y=[int(x) for x in input().split()] 3 | if(y>=x): 4 | print(0) 5 | continue 6 | m,n=0,0 7 | m=b//y 8 | if(b%y!=0): 9 | m=m+1 10 | n=a//(x-y) 11 | if(a%(x-y)!=0): 12 | n=n+1 13 | if(m>n): 14 | print(1) 15 | else: 16 | print(0) 17 | -------------------------------------------------------------------------------- /Programming exam codes/Test2Q2.py: -------------------------------------------------------------------------------- 1 | def matrix_multiply(n): 2 | z=[] 3 | for i in range(len(n)): 4 | for j in range(len(n[0])): 5 | z.append([0]) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # IITMadrasPythonCodeBase 2 | This is a repository containing all the Python codes to important questions in assignments (both PPAs and GrPAs), Practice Tests and Programming exams in the IIT Madras Online B.Sc. Degree course. Easy questions have not been included in this repository. 3 | 4 | **Also, most of the code demonstrated in the video lectures can also be found in the CodeFromLectures folder.** 5 | 6 | **Solutions of CodeChef Practice Contests (specifically conducted for IITM BSc Students) are also added here within the "Programming exam codes Folder".** 7 | 8 | ## In my opinion, The most Important and/or difficult-to-solve problems in assignments, practice tests are:- 9 | ### Week 1:- 10 | GrPA 6 11 | ### Week 2:- 12 | PPA 8, GrPA 2 13 | ### Week 3:- 14 | PPA 5, PPA 6, PPA 12, All 6 GrPA Questions are important 15 | ### Week 4:- 16 | PPA 8, PPA 10, PPA 11, GrPA 2, GrPA 3, GrPA 4, GrPA 5 17 | ### Week 5:- 18 | PPA 5, PPA 7, PPA 8, PPA 9, PPA 10, GrPA3, GrPA 4, GrPA5 19 | ### Week 6:- 20 | PPA 6, PPA 10, All 4 GrPAs are important 21 | ### Week 7:- (Refresher Week) 22 | GrPA 1, GrPA3 23 | ### Week 8:- 24 | PPA 5, PPA 7 25 | ### Week 9:- 26 | PPA 6, PPA 9, PPA 10, GrPA 3, GrPA4 27 | ### Week 10:- 28 | GrPA 3, GrPA 4 29 | ### Week 11:- 30 | No PPAs and GrPAs in this week 31 | ### Week 12:- 32 | PPAs 1,5 33 | ## Practice Tests and Mock Programming Exam OPPEs:- 34 | OPPE 5 -------------------------------------------------------------------------------- /directory.txt: -------------------------------------------------------------------------------- 1 | 9945959833 2 | 9149491083 3 | 9474071064 4 | 7029573860 5 | 6362072045 6 | 9480459922 7 | 9492506313 8 | 6287590104 9 | 9162031189 10 | 9194731142 11 | 9916248770 12 | 6350222545 13 | 8957839265 14 | 9916574887 15 | 6306123079 16 | 9598530252 17 | 8158904633 18 | 9434331356 19 | 7019152890 20 | 9779865419 21 | 9448605814 22 | 8972381367 23 | 9838703456 24 | 9013151515 25 | 8073831246 26 | 9660700506 27 | 9686521976 28 | 9886602566 29 | 9380597878 30 | 9492506313 31 | 6294956565 32 | 9614200675 33 | 8608039136 34 | 9886931090 35 | 7001552483 36 | 9332137289 37 | 8431287375 38 | 9197411112 39 | 7795045616 40 | 9434574644 41 | 6395191986 42 | 8088461639 43 | 8657568655 44 | 9474553389 45 | 7891768215 46 | 9874303223 47 | 8902646320 48 | 9972233858 49 | 9535587260 50 | 9900313542 51 | 7384747630 52 | 8569898783 53 | 9916616264 54 | 6361230800 55 | 7678005260 56 | 9448235383 57 | 9880269820 58 | 7981314426 59 | 9182171115 60 | 9434377444 61 | 9021528072 62 | 9003253644 63 | 9732358666 64 | 9733848459 65 | 9448555312 66 | 9571208053 67 | 9742332490 68 | 7304964373 69 | 9741143939 70 | 7001837452 71 | 9188851459 72 | 9086109836 73 | 7760899143 74 | 7076821559 75 | 9197258111 76 | 9483512589 77 | 8145695936 78 | 8167326193 79 | 9606231954 80 | 7042830765 81 | 9530469925 82 | 7761937677 83 | 6295666946 84 | 7063605288 85 | 9035746766 86 | 9606279612 87 | 9064538121 88 | 9535687519 89 | 9902333619 90 | 9845942068 91 | -------------------------------------------------------------------------------- /myText.txt: -------------------------------------------------------------------------------- 1 | Aritra Roy is a good man, from West Bengal, India 2 | He is a student in the IITM B.Sc. degree course in Programming and Data Science 3 | He is also persuing B.E. in Civil Engineering from BMSCE, Bangalore 4 | He plans to complete both the degrees by August, 2024 5 | He is a good singer and a good guitarist as well, though currently little out of practice -------------------------------------------------------------------------------- /out.txt: -------------------------------------------------------------------------------- 1 | Aritra Roy is a good man, from West Bengal, India. 2 | He is a student in the IITM B.Sc. degree course in Programming and Data Science. 3 | He is also persuing B.E. in Civil Engineering from BMSCE, Bangalore. 4 | He plans to complete both the degrees by August, 2024. 5 | He is a good singer and a good guitarist as well, though currently little out of practice. 6 | -------------------------------------------------------------------------------- /pattern.csv: -------------------------------------------------------------------------------- 1 | 1,0,0,0,0,0,1 2 | 0,1,0,0,0,1,0 3 | 0,0,1,0,1,0,0 4 | 0,0,0,1,0,0,0 5 | 0,0,1,0,1,0,0 6 | 0,1,0,0,0,1,0 7 | 1,0,0,0,0,0,1 8 | -------------------------------------------------------------------------------- /testing.py: -------------------------------------------------------------------------------- 1 | import matplotlib, numpy, pandas, scipy 2 | print(scipy.__version__) 3 | print(numpy.__version__) 4 | print(pandas.__version__) 5 | print(matplotlib.__version__) --------------------------------------------------------------------------------