## OOP 1. https://www.scaler.com/hire/test/problem/21896/ ```python= class Bill(): def __init__(self, prev_read, cur_read): self.prev_read= prev_read self.cur_read= cur_read def total_bill(self): i=1 total=0 price=3.5 meter_charge=150 consumed= self.cur_read - self.prev_read if consumed>100: while consumed//100>0: if i==1: price= 3.5 elif i==2: price= 5 else: price=8 total= total + 100*price consumed= consumed-100 i=i+1 if consumed<100: total= total+ consumed*price else: total= consumed*price return total+ meter_charge ``` 2. https://www.scaler.com/hire/test/problem/21407/ ```python The correct answer is [(True, 64), (False, 125), (True, 216)] We are calling the class solution() inside the print function and calling the initial() function of the class. The list passed is [4,5,6]. Now inside the initial() function we are calling the member function final(). For the final function it returns a list of tuples. Class solution’s final function takes a list as an argument and returns a list of tuples with a bool and cube of the number as elements. If the cube of element is even, the first element is True. Otherwise it is False. The second element is the cube of the element in the tuple. For 4, 64 is even. So the element becomes (True, 64) For 5, 125 is odd. So the element becomes (False, 125) For 6, 216 is even. So the element becomes (True, 216) ``` 3. https://www.scaler.com/hire/test/problem/21416/ ``` Correct answer: lose win As final_res is initialized as ‘lose’ in the class. Therefore when we print football.final_res it will print ‘lose’, as it doesn’t get updated for class but it does get updated for the instance of the class created, that is the object match. match = Football(“Juventus”, 3) Here, name = Juventus and score = 3. match.calc(2) This defines winning_score as 2. As our score > winning_score. So, match.final_res becomes win. ``` 4. https://www.scaler.com/hire/test/problem/21673/ ```python= def timeHandle(a,b,c,d): '''inputs: a,b = hours and mins of t1 c,d = hours and mins of t2 Output: Two lines of output for each pair of t1 and t2. The code for printing outputs is already just make sure to return in the methods.''' class Spanoftime: def __init__(self,h,m): self.hours=h self.mins=m def displayTime(self): return ("{} hours and {} min".format(self.hours,self.mins)) def addTime(t1,t2): t3=Spanoftime(0,0) if (t1.mins+t2.mins>60) or (t1.mins+t2.mins==60): t3.hours=(t1.mins+t2.mins)//60 t3.hours=t3.hours+t1.hours+t2.hours t3.mins=(t1.mins+t2.mins)-(((t1.mins+t2.mins)//60)*60) return t3 def returnMinutes(t1,t2): return (t1.hours*60 + t1.mins + t2.hours*60 + t2.mins) # Return the total number of minutes t1=Spanoftime(a,b) t2=Spanoftime(c,d) t3=Spanoftime.addTime(t1,t2) t3.displayTime() totalmin=str(Spanoftime.returnMinutes(t1,t2)) return t3.displayTime(),("The total minutes in time t1 and t2 are: "+totalmin) ``` 5. https://www.scaler.com/hire/test/problem/21755/ ``` A,C are correct answer. Since, “Child” is a sub-class/child class, it will inherit all the properties of the “Parent” class. So, print() can be called with both “self” and “super()”. ``` 6. https://www.scaler.com/hire/test/problem/21410/ ``` B is correct answer. An instance for class B named obj is created. Using this instance we call a function one() from class A. Here Class A is base class and class B is derived class. We have modified the method two() in class B, This concept of modifying the function of parent class is called Method overriding. def one(self): return self.two() obj= B() print(obj.one()) We created object for class B, which is derived class of A, using B’s object we call method one() from class A. Method one() internally calls method two() which was modified in the derived class. Therefore, we get output as B, not A. ``` 7. https://www.scaler.com/hire/test/problem/21683/ ```python= class MachineLearning: def __init__(self,name,category): self.name=name self.category=category def getname(self): return self.name def getcategory(self): return self.category def print(self): print("Name:",self.name) print("Category:",self.category) class Supervised(MachineLearning): def __init__(self,name,category): super().__init__(name,category) def type(self): super().print() print("Supervised Learning Algorithm") class Unsupervised(MachineLearning): def __init__(self,name,category): super().__init__(name,category) def type(self): super().print() print("Unsupervised Learning Algorithm") def mlAnalogy(a,b,c,d): '''input=> a,b = name and category for Supervised class c,d = name and category for Unsupervised class output=> type() is called for both classes in the end, it should first print the Name and Category then the type of class in new lines ''' obj1=Supervised(a,b) obj1.type() obj2=Unsupervised(c,d) obj2.type() return None ``` 8. https://www.scaler.com/hire/test/problem/19910/ ``` Correct Answer: B Explanation: A: We used private modifiers which can only be access within the class, but we are calling that member outside, Hence this code will throw an attribute error. B: We used protected members of a class, which are accessible within the class and are also available to its subclasses. Hence, this code will give our desired output 200. C: We defined salary with protected modifier but called it like it is public which is simply an error, hence this code will throw an attribute error. ``` ## Functional Programming 1. https://www.scaler.com/hire/test/problem/21779/ ```python= def func(n): fibonacci_list=[] factorial_list=[] # Function to calculate the first n Fibonacci numbers def fibo(n): if n <= 1: return n else: return(fibo(n-1) + fibo(n-2)) # Function to calculate the factorial of a number k def fact(k): if k==1: return 1 else: return k*fact(k-1) # Function to check whether the number is prime or not def prime(m): count=0 for i in range(1,m): if m%i==0: count+=1 if count!=1: return m else: return fact(m) for i in range(n): fibonacci_list.append(fibo(i)) for j in fibonacci_list: factorial_list.append(prime(j)) return fibonacci_list, factorial_list ``` 2. https://www.scaler.com/hire/test/problem/22073/ ``` list(map(lambda y:2y, x)) is the correct option. Here a is passed as an argument in result function which is actually a list therefore lambda function’s if block will be executed which leads to statement list(map(lambda y:2y, x)). ``` 3. https://www.scaler.com/hire/test/problem/175/ ```python= class Solution: # @param A : string # @return an integer def isPalindrome(self, A): A = A.lower() n = len(A) low = 0 high = n - 1 ret = 1 while low <= high: if A[low] == A[high]: low += 1 high -= 1 continue if str(A[low]).isalnum() and str(A[high]).isalnum(): ret = 0 break elif str(A[high]).isalnum(): low += 1 else: high -= 1 return ret ``` 4. https://www.scaler.com/hire/test/problem/21742/ ``` [1, 2, 3, 4, 5] is the correct answer. The above snippet is used to flatten the list, so if it finds any [ ], they are removed and the element is retained. lambda x: sum(map(result, x), [ ] ) if isinstance(x, list) else [x]: isinstance(x, list) returns TRUE is x is list else false. ``` 5. https://www.scaler.com/hire/test/problem/22101/ ``` name in x.lower() is the correct option. Explanation (name.upper() or name.lower()) in x returns just those ids that have SAM or uppercase name. Here the requirement is to return all the ids having the name as their substrings, therefore ‘and’ shouldn’t be used. We also need to consider the case where Sam is present in the ids. So we first convert the entire email to lower and check for the presence of the string sam. ``` 6. https://www.scaler.com/hire/test/problem/21743/ ``` [set(), {1}, {2}, {1, 2}, {3}, {1, 3}, {2, 3}, {1, 2, 3}] is the correct asnwer. We start with a list of empty set {}. Now go over all elements x of array. For each element x and each subset in P (list of sets), create a new subset that consists of the union of x and subset. And each time we are also adding P which has all the subsets therefore in the final variable the whole list of subsets is printed. Result stores every subset/set that can be made from the element of the array including the null set. Initially, only the empty set is in the powerset. Now, in each step, we take one element x out of the list s and create a bunch of new subsets that naturally emerge by adding x to all subsets that are already in the powerset. Hence, the size of the powerset doubles each time we add a new element x. In this way, we can grow the powerset one element at-a-time. The reduce() function is used to apply this idea. It maintains the current powerset in the variable P (which initially contains only the empty set). Using list comprehension, it creates new subsets – one for each existing subset – and adds them to the powerset P. In particular, it adds the value x from the dataset to each subset and thus doubles the size of the powerset (containing the subsets with and without the dataset element x). The function of reduce() function is to repeatedly “merge” two elements: the powerset P and an element x from the dataset. ``` 7. https://www.scaler.com/hire/test/problem/21746/ ``` a fully-managed MySQL and PostgreSQL, is the correct answer. Explanation: “SQL” is stored in variable val. “[ key.find(val) -18 : key.find(val) +18 ]” searches for the word “SQL” in the string and then returns the 18 characters before it and 18 characters after it. ``` ## Exception Handling And Modules 1. https://www.scaler.com/hire/test/problem/22023/ ```python= import math def avg_calc(data): n, mean = len(data), 0.0 if n <= 1: return data[0] # calculate mean for el in data: mean = mean + float(el) mean = mean / float(n) return round(mean,3) def sd_calc(data): n = len(data) if n <= 1: return 0.0 mean, sd = avg_calc(data), 0.0 # calculate stan. dev. for el in data: sd += (float(el) - mean)**2 sd = math.sqrt(sd / float(n-1)) return round(sd,3) ``` 2. https://www.scaler.com/hire/test/problem/22189/ ```python= import numpy as np def calc(a,b,c): try: if len(a) ==0: raise Exception("Null value passed") elif b=="Quantile": return np.quantile(a,c) elif b=="Percentile": return np.percentile(a,c) elif b not in ["Quantile", "Percentile"]: raise Exception("Formula Error: Wrong Formula") except Exception as e: return str(e) ``` 3. https://www.scaler.com/hire/test/problem/22067/ ```python= class SalaryNotInRangeError(Exception): """Exception raised for errors in the input salary. Attributes: salary -- input salary which caused the error message -- explanation of the error """ def __init__(self,message= "Salary is not in range"): self.message= message super().__init__(self.message) def check_salary(salary): try: if not 10000 < salary < 100000: raise SalaryNotInRangeError() else: print("Congratulations!!") except SalaryNotInRangeError as e: print(e) ``` 4. https://www.scaler.com/hire/test/problem/21833/ ``` P-B, Q-C, R-A is the correct answer. P.“Mangoes” is of length more than 5, therefore no exception is occurred (nothing printed). Q.“Apple” is of length 5 therefore exception occurs and prints (“Error occurred: Name Should have more than five characters”) R.“Fig” is of length less than 5, print(“Error occurred: Name cannot have less than 5 characters”) ``` 5. https://www.scaler.com/hire/test/problem/22049/ ```python= def divide(a,b): try: return int(a/b) except ZeroDivisionError as ex1: return ex1 def multiply(a,b): return a*b def subtract(a,b): return a-b def calci(list1,list2): arr1=[] arr2=[] arr3=[] if len(list1) != len(list2): print("Not same length") else: for i in range(0,len(list1)): arr1.append(divide(list1[i],list2[i])) arr2.append(multiply(list1[i],list2[i])) arr3.append(subtract(list1[i],list2[i])) return arr1,arr2,arr3 ``` 6. https://www.scaler.com/hire/test/problem/22015/ ``` A. 10**-digits, round(math.ceil(a/n)*n,digits) B. math.pow(10,-digits), round(math.ceil(a/n)xn,digits) Above are the correct answers. In A: 10**-digits returns float values with decimal points i.e. 10**-2 = .01. round(math.ceil(a/n)*n,digits) rounds up the value to the digits decimal places given and ceil is used to convert the float into the nearest upper value. In B: math.pow(10,-digits) returns values in decimal places i.e. math.pow(10,-2)=.01 ``` 7. https://www.scaler.com/hire/test/problem/21839/ ``` a prints “Good” infinite times, b prints “Invalid”, c prints nothing is the correct answer a: '4' as input which became integer 4 after typecasting, it can completely divide 100 and gives remainder 0, therefore will print (“Good”) in an infinite loop. b: '1.5', this input cannot be converted to integer since the input is string not float and the ValueError raised will be handled by the try except block and “Invalid” will be printed. If we directly try to convert float 1.5 to int by using int(1.5) it will simply return 1, but if ‘1.5’ is a string typecasting with int will generate error. c: '3' became integer 4 after typecasting, and since 100%3 !=0, therefore this input won’t be printing anything. ``` ## File handling 1. https://www.scaler.com/hire/test/problem/28579/ ``` Correct Answer: write mode is different from append mode write mode overwrites the content of the text file write mode overwrites the content in the file by creating a new file. If we have a file named f and we do f.write(something) this would completely overwrite the content that was already present in f. append mode just appends the new content to the existing file. If we have a file named f and we do f.append(something) this would add the new content at the end of the content that was already present in f. ``` 2. https://www.scaler.com/hire/test/problem/28578/ ``` Correct Answer: Read everything till the first “\n” character. readline reads a line of the file and returns it in the form of a string. It reads everything until it encounters a newline(“\n”) character. ``` 3. https://www.scaler.com/hire/test/problem/28584/ ``` Correct Answer: A = f.read(), B = data.split() First the entire file is read using read() method. Then we split the string by spaces obtained by the read() method. Then we run through the list and count the number of words. ``` 4. https://www.scaler.com/hire/test/problem/28581/ ``` Correct Answer: A = fr.readlines(), B = fw.write(line) First, we read the text file line by line, using readlines(). Then we write the line which has the word scaler using .write(line). ``` 5. https://www.scaler.com/hire/test/problem/28583/ ``` Correct Answer: A B is wrong since we need to check numeric characters, not lines. Therefore we need to iterate through each char of each line. C is wrong since we need to iterate through the line variable, as well as we need to use f1.read() instead of readline D is wrong since we need to check numeric, so we need i.isnumeric() function, as well as we need to iterate through line variable A B is wrong since we need to check numeric characters, not lines C is wrong since we need to iteratre through the line variable, as well as we need to use f1.read() instead of readline D is wrong since we need to check numeric, so we need i.isnumeric() function, as well as we need to iterate through line variable ```