{"id":26239,"date":"2022-01-04T12:26:10","date_gmt":"2022-01-04T12:26:10","guid":{"rendered":"https:\/\/www.devopsschool.com\/blog\/?p=26239"},"modified":"2022-04-13T16:55:37","modified_gmt":"2022-04-13T16:55:37","slug":"top-100-interview-questions-for-python","status":"publish","type":"post","link":"https:\/\/www.devopsschool.com\/blog\/top-100-interview-questions-for-python\/","title":{"rendered":"TOP 100+ INTERVIEW QUESTIONS FOR PYTHON:-"},"content":{"rendered":"\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"700\" height=\"400\" src=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/01\/100-Python-Interview-Questions-and-Answers.png\" alt=\"\" class=\"wp-image-26240\" srcset=\"https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/01\/100-Python-Interview-Questions-and-Answers.png 700w, https:\/\/www.devopsschool.com\/blog\/wp-content\/uploads\/2022\/01\/100-Python-Interview-Questions-and-Answers-300x171.png 300w\" sizes=\"auto, (max-width: 700px) 100vw, 700px\" \/><\/figure>\n\n\n\n<p><strong>Python Basic Interview Questions:-<\/strong><\/p>\n\n\n\n<p>1. What are the key features of Python?<\/p>\n\n\n\n<p>Python is one of the most popular programming languages used by data scientists and AIML professionals. This popularity is due to the following key features of Python:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Python is easy to learn due to its clear syntax and readability<\/li><li>Python is easy to interpret, making debugging easy<\/li><li>Python is free and Open-source<\/li><li>It can be used across different languages<\/li><li>It is an object-oriented language which supports concepts of classes<\/li><li>It can be easily integrated with other languages like C++, Java and more<\/li><\/ul>\n\n\n\n<p>2. What are Keywords in Python?<\/p>\n\n\n\n<p>Keywords in Python are reserved words which are used as identifiers, function name or variable name. They help define the structure and syntax of the language.<\/p>\n\n\n\n<p>There are a total of 33 keywords in Python 3.7 which can change in the next version, i.e., Python 3.8<\/p>\n\n\n\n<p>3. What are Literals in Python and explain about different Literals?<\/p>\n\n\n\n<p>Literals in Python refer to the data that is given in a variable or constant. Python has various kinds of literals including:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>String Literals: It is a sequence of characters enclosed in codes. There can be single, double and triple strings based on the number of quotes used. Character literals are single characters surrounded by single or double-quotes.<\/li><li>Numeric Literals: These are unchangeable kind and belong to three different types \u2013 integer, float and complex.<\/li><li>Boolean Literals: They can have either of the two values- True or False which represents \u20181\u2019 and \u20180\u2019 respectively.<\/li><li>Special Literals: Special literals are sued to classify fields that are not created. It is represented by the value \u2018none\u2019.<\/li><\/ul>\n\n\n\n<p>4. How can you concatenate two tuples?<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>Let\u2019s say we have two tuples like this -&gt;<\/p>\n\n\n\n<p>tup1 = (1,\u201da\u201d,True)<\/p>\n\n\n\n<p>tup2 = (4,5,6)<\/p>\n\n\n\n<p>Concatenation of tuples means that we are adding the elements of one tuple at the end of another tuple.<\/p>\n\n\n\n<p>Now, let\u2019s go ahead and concatenate tuple2 with tuple1:<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>tup1=(1,&#8221;a&#8221;,True)<\/p>\n\n\n\n<p>tup2=(4,5,6)<\/p>\n\n\n\n<p>tup1+tup2<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>All you have to do is, use the \u2018+\u2019 operator between the two tuples and you\u2019ll get the concatenated result.<\/p>\n\n\n\n<p>Similarly, let\u2019s concatenate tuple1 with tuple2:<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>tup1=(1,&#8221;a&#8221;,True)<\/p>\n\n\n\n<p>tup2=(4,5,6)<\/p>\n\n\n\n<p>tup2+tup1<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>Python<\/p>\n\n\n\n<p>Before we deep dive further, if you are keen to explore a career in Python, do check out our free certificate course on Python Interview prep. This course will not only help you cover all the key concepts of Python but will also earn you a certificate that\u2019s sure to offer you a competitive advantage.<\/p>\n\n\n\n<p>5. What are functions in Python?<\/p>\n\n\n\n<p>Ans: Functions in Python refer to blocks that have organised, and reusable codes to perform single, and related events. Functions are important to create better modularity for applications which reuse high degree of coding. Python has a number of built-in functions like print(). However, it also allows you to create user-defined functions.<\/p>\n\n\n\n<p>6. How to Install Python?<\/p>\n\n\n\n<p>To Install Python, first go to Anaconda.org and click on \u201cDownload Anaconda\u201d. Here, you can download the latest version of Python. After Python is installed, it is a pretty straightforward process. The next step is to power up an IDE and start coding in Python. If you wish to learn more about the process, check out this Python Tutorial.<\/p>\n\n\n\n<p>7. What is Python Used For?<\/p>\n\n\n\n<p>Python is one of the most popular programming languages in the world today. Whether you\u2019re browsing through Google, scrolling through Instagram, watching videos on YouTube, or listening to music on Spotify, all of these applications make use of Python for their key programming requirements. Python is used across various platforms, applications, and services such as web development.<\/p>\n\n\n\n<p>8. How can you initialize a 5*5 numpy array with only zeroes?<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>We will be using the .zeros() method<\/p>\n\n\n\n<p>import numpy as np<\/p>\n\n\n\n<p>n1=np.zeros((5,5))<\/p>\n\n\n\n<p>n1<\/p>\n\n\n\n<p>Use np.zeros() and pass in the dimensions inside it. Since, we want a 5*5 matrix, we will pass (5,5) inside the .zeros() method.<\/p>\n\n\n\n<p>This will be the output:<\/p>\n\n\n\n<p>9. What is Pandas?<\/p>\n\n\n\n<p>Pandas is an open source python library which has a very rich set of data structures for data based operations. Pandas with it\u2019s cool features fits in every role of data operation, whether it be academics or solving complex business problems. Pandas can deal with a large variety of files and is one of the most important tools to have a grip on.<\/p>\n\n\n\n<p>10. What are data frames?<\/p>\n\n\n\n<p>A panda\u2019s data frame is a data structure in pandas which is mutable. Pandas has support for heterogeneous data which is arranged across two axes.( rows and columns).<\/p>\n\n\n\n<p>Reading files into pandas:-<\/p>\n\n\n\n<p>1<\/p>\n\n\n\n<p>2<\/p>\n\n\n\n<p>Import pandas as pd<\/p>\n\n\n\n<p>df=p.read_csv(\u201cmydata.csv\u201d)<\/p>\n\n\n\n<p>Here df is a pandas data frame. read_csv() is used to read a comma delimited file as a dataframe in pandas.<\/p>\n\n\n\n<p>11. What is a Pandas Series?<\/p>\n\n\n\n<p>Series is a one dimensional pandas data structure which can data of almost any type. It resembles an excel column. It supports multiple operations and is used for single dimensional data operations.<\/p>\n\n\n\n<p>Creating a series from data:<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>data=[&#8220;1&#8243;,2,&#8221;three&#8221;,4.0]<\/p>\n\n\n\n<p>series=pd.Series(data)<\/p>\n\n\n\n<p>print(series)<\/p>\n\n\n\n<p>print(type(series))<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>12. What is pandas groupby?<\/p>\n\n\n\n<p>A pandas groupby is a feature supported by pandas which is used to split and group an object.&nbsp; Like the sql\/mysql\/oracle groupby it used to group data by classes, entities which can be further used for aggregation. A dataframe can be grouped by one or more columns.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>df = pd.DataFrame({&#8216;Vehicle&#8217;:[&#8216;Etios&#8217;,&#8217;Lamborghini&#8217;,&#8217;Apache200&#8242;,&#8217;Pulsar200&#8242;], &#8216;Type&#8217;:[&#8220;car&#8221;,&#8221;car&#8221;,&#8221;motorcycle&#8221;,&#8221;motorcycle&#8221;]})<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>To perform groupby type the following code:<\/p>\n\n\n\n<p>df.groupby(&#8216;Type&#8217;).count()<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>13. How to create a dataframe from lists?<\/p>\n\n\n\n<p>To create a dataframe from lists ,<\/p>\n\n\n\n<p>1)create an empty dataframe<\/p>\n\n\n\n<p>2)add lists as individuals columns to the list<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>df=pd.DataFrame()<\/p>\n\n\n\n<p>bikes=[&#8220;bajaj&#8221;,&#8221;tvs&#8221;,&#8221;herohonda&#8221;,&#8221;kawasaki&#8221;,&#8221;bmw&#8221;]<\/p>\n\n\n\n<p>cars=[&#8220;lamborghini&#8221;,&#8221;masserati&#8221;,&#8221;ferrari&#8221;,&#8221;hyundai&#8221;,&#8221;ford&#8221;]<\/p>\n\n\n\n<p>df[&#8220;cars&#8221;]=cars<\/p>\n\n\n\n<p>df[&#8220;bikes&#8221;]=bikes<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>14. How to create data frame from a dictionary?<\/p>\n\n\n\n<p>A dictionary can be directly passed as an argument to the DataFrame() function to create the data frame.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>bikes=[&#8220;bajaj&#8221;,&#8221;tvs&#8221;,&#8221;herohonda&#8221;,&#8221;kawasaki&#8221;,&#8221;bmw&#8221;]<\/p>\n\n\n\n<p>cars=[&#8220;lamborghini&#8221;,&#8221;masserati&#8221;,&#8221;ferrari&#8221;,&#8221;hyundai&#8221;,&#8221;ford&#8221;]<\/p>\n\n\n\n<p>d={&#8220;cars&#8221;:cars,&#8221;bikes&#8221;:bikes}<\/p>\n\n\n\n<p>df=pd.DataFrame(d)<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>15. How to combine dataframes in pandas?<\/p>\n\n\n\n<p>Two different data frames can be stacked either horizontally or vertically by the concat(), append() and join() functions in pandas.<\/p>\n\n\n\n<p>Concat works best when the dataframes have the same columns and can be used for concatenation of data having similar fields and is basically vertical stacking of dataframes into a single dataframe.<\/p>\n\n\n\n<p>Append() is used for horizontal stacking of dataframes. If two tables(dataframes) are to be merged together then this is the best concatenation function.<\/p>\n\n\n\n<p>Join is used when we need to extract data from different dataframes which are having one or more common columns. The stacking is horizontal in this case.<\/p>\n\n\n\n<p>Before going through the questions, here\u2019s a quick video to help you refresh your memory on Python.<\/p>\n\n\n\n<p>16. What kind of joins does pandas offer?<\/p>\n\n\n\n<p>Pandas has a left join, inner join, right join and an outer join.<\/p>\n\n\n\n<p>17. How to merge dataframes in pandas?<\/p>\n\n\n\n<p>Merging depends on the type and fields of different dataframes being merged. If data is having similar fields data is merged along axis 0 else they are merged along axis 1.<\/p>\n\n\n\n<p>18. Give the below dataframe drop all rows having Nan.<\/p>\n\n\n\n<p>The dropna function can be used to do that.<\/p>\n\n\n\n<p>df.dropna(inplace=True)<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>19. How to access the first five entries of a dataframe?<\/p>\n\n\n\n<p>By using the head(5) function we can get the top five entries of a dataframe. By default df.head() returns the top 5 rows. To get the top n rows df.head(n) will be used.<\/p>\n\n\n\n<p>20. How to access the last five entries of a dataframe?<\/p>\n\n\n\n<p>By using tail(5) function we can get the top five entries of a dataframe. By default df.tail() returns the top 5 rows. To get the last n rows df.tail(n) will be used.<\/p>\n\n\n\n<p>21. How to fetch a data entry from a pandas dataframe using a given value in index?<\/p>\n\n\n\n<p>To fetch a row from dataframe given index x, we can use loc.<\/p>\n\n\n\n<p>Df.loc[10] where 10 is the value of the index.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>bikes=[&#8220;bajaj&#8221;,&#8221;tvs&#8221;,&#8221;herohonda&#8221;,&#8221;kawasaki&#8221;,&#8221;bmw&#8221;]<\/p>\n\n\n\n<p>cars=[&#8220;lamborghini&#8221;,&#8221;masserati&#8221;,&#8221;ferrari&#8221;,&#8221;hyundai&#8221;,&#8221;ford&#8221;]<\/p>\n\n\n\n<p>d={&#8220;cars&#8221;:cars,&#8221;bikes&#8221;:bikes}<\/p>\n\n\n\n<p>df=pd.DataFrame(d)<\/p>\n\n\n\n<p>a=[10,20,30,40,50]<\/p>\n\n\n\n<p>df.index=a<\/p>\n\n\n\n<p>df.loc[10]<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>22. What are comments and how can you add comments in Python?<\/p>\n\n\n\n<p>Comments in Python refer to a piece of text intended for information. It is especially relevant when more than one person works on a set of codes. It can be used to analyse code, leave feedback, and debug it. There are two types of comments which includes:<\/p>\n\n\n\n<p>Single-line comment<\/p>\n\n\n\n<p>Multiple-line comment<\/p>\n\n\n\n<p>Codes needed for adding comment<\/p>\n\n\n\n<p>#Note \u2013single line comment<\/p>\n\n\n\n<p>\u201c\u201d\u201dNote<\/p>\n\n\n\n<p>Note<\/p>\n\n\n\n<p>Note\u201d\u201d\u201d\u2014\u2013multiline comment<\/p>\n\n\n\n<p>23. What is the difference between list and tuples in Python?<\/p>\n\n\n\n<p>Lists are mutable, but tuples are immutable.<\/p>\n\n\n\n<p>24. What is dictionary in Python? Give an example.<\/p>\n\n\n\n<p>A Python dictionary is a collection of items in no particular order. Python dictionaries are written in curly brackets with keys and values. Dictionaries are optimised to retrieve value for known keys.<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<p>d={\u201ca\u201d:1,\u201db\u201d:2}<\/p>\n\n\n\n<p>25. Find out the mean, median and standard deviation of this numpy array -&gt; np.array([1,5,3,100,4,48])<\/p>\n\n\n\n<p>import numpy as np<\/p>\n\n\n\n<p>n1=np.array([10,20,30,40,50,60])<\/p>\n\n\n\n<p>print(np.mean(n1))<\/p>\n\n\n\n<p>print(np.median(n1))<\/p>\n\n\n\n<p>print(np.std(n1))<\/p>\n\n\n\n<p>26. What is a classifier?<\/p>\n\n\n\n<p>A classifier is used to predict the class of any data point. Classifiers are special hypotheses that are used to assign class labels to any particular data points. A classifier often uses training data to understand the relation between input variables and the class. Classification is a method used in supervised learning in Machine Learning.<\/p>\n\n\n\n<p>27. In Python how do you convert a string into lowercase?<\/p>\n\n\n\n<p>All the upper cases in a string can be converted into lowercase by using the method: string.lower()<\/p>\n\n\n\n<p>ex: string = \u2018GREATLEARNING\u2019 print(string.lower())<\/p>\n\n\n\n<p>o\/p: greatlearning<\/p>\n\n\n\n<p>28. How do you get a list of all the keys in a dictionary?<\/p>\n\n\n\n<p>One of the ways we can get a list of keys is by using: dict.keys()<\/p>\n\n\n\n<p>This method returns all the available keys in the dictionary. dict = {1:a, 2:b, 3:c} dict.keys()<\/p>\n\n\n\n<p>o\/p: [1, 2, 3]<\/p>\n\n\n\n<p>29. How can you capitalize the first letter of a string?<\/p>\n\n\n\n<p>We can use the capitalize() function to capitalize the first character of a string. If the first character is already in capital then it returns the original string.<\/p>\n\n\n\n<p>Syntax: string_name.capitalize() ex: n = \u201cgreatlearning\u201d print(n.capitalize())<\/p>\n\n\n\n<p>o\/p: Greatlearning<\/p>\n\n\n\n<p>30. How can you insert an element at a given index in Python?<\/p>\n\n\n\n<p>Python has an inbuilt function called the insert() function.<\/p>\n\n\n\n<p>It can be used used to insert an element at a given index.<\/p>\n\n\n\n<p>Syntax: list_name.insert(index, element)<\/p>\n\n\n\n<p>ex: list = [ 0,1, 2, 3, 4, 5, 6, 7 ]<\/p>\n\n\n\n<p>#insert 10 at 6th index<\/p>\n\n\n\n<p>list.insert(6, 10)<\/p>\n\n\n\n<p>o\/p: [0,1,2,3,4,5,10,6,7]<\/p>\n\n\n\n<p>31. How will you remove duplicate elements from a list?<\/p>\n\n\n\n<p>There are various methods to remove duplicate elements from a list. But, the most common one is, converting the list into a set by using the set() function and using the list() function to convert it back to a list, if required. ex: list0 = [2, 6, 4, 7, 4, 6, 7, 2]<\/p>\n\n\n\n<p>list1 = list(set(list0)) print (\u201cThe list without duplicates : \u201d + str(list1))<\/p>\n\n\n\n<p>o\/p: The list without duplicates : [2, 4, 6, 7]<\/p>\n\n\n\n<p>32. What is recursion?<\/p>\n\n\n\n<p>Recursion is a function calling itself one or more times in it body. One very important condition a recursive function should have to be used in a program is, it should terminate, else there would be a problem of an infinite loop.<\/p>\n\n\n\n<p>33. Explain Python List Comprehension<\/p>\n\n\n\n<p>List comprehensions are used for transforming one list into another list. Elements can be conditionally included in the new list and each element can be transformed as needed. It consists of an expression leading a for clause, enclosed in brackets. for ex: list = [i for i in range(1000)]<\/p>\n\n\n\n<p>print list<\/p>\n\n\n\n<p>34. What is the bytes() function?<\/p>\n\n\n\n<p>The bytes() function returns a bytes object. It is used to convert objects into bytes objects, or create empty bytes object of the specified size.<\/p>\n\n\n\n<p>35. What are the different types of operators in Python?<\/p>\n\n\n\n<p>Python has the following basic operators:<\/p>\n\n\n\n<p>Arithmetic( Addition(+), Substraction(-), Multiplication(*), Division(\/), Modulus(%) ), Relational ( &lt;, &gt;, &lt;=, &gt;=, ==, !=, ),<\/p>\n\n\n\n<p>Assignment ( =. +=, -=, \/=, *=, %= ),<\/p>\n\n\n\n<p>Logical ( and, or not ), Membership, Identity, and Bitwise Operators<\/p>\n\n\n\n<p>36. What is the \u2018with statement\u2019?<\/p>\n\n\n\n<p>\u201cwith\u201d statement in python is used in exception handling. A file can be opened and closed while executing a block of code, containing the \u201cwith\u201d statement., without using the close() function. It essentially makes the code much more easy to read.<\/p>\n\n\n\n<p>37. What is a map() function in Python?<\/p>\n\n\n\n<p>The map() function in Python is used for applying a function on all elements of a specified iterable. It consists of two parameters, function and iterable. The function is taken as an argument and then applied to all the elements of an iterable(passed as the second argument). An object list is returned as a result.<\/p>\n\n\n\n<p>def add(n):<\/p>\n\n\n\n<p>return n + n number= (15, 25, 35, 45)<\/p>\n\n\n\n<p>res= map(add, num)<\/p>\n\n\n\n<p>print(list(res))<\/p>\n\n\n\n<p>o\/p: 30,50,70,90<\/p>\n\n\n\n<p>38. What is __init__ in Python?<\/p>\n\n\n\n<p>_init_ methodology is a reserved method in Python aka constructor in OOP. When an object is created from a class and _init_ methodolgy is called to acess the class attributes.<\/p>\n\n\n\n<p>39. What are the tools present to perform statics analysis?<\/p>\n\n\n\n<p>The two static analysis tool used to find bugs in Python are: Pychecker and Pylint. Pychecker detects bugs from the source code and warns about its style and complexity.While, Pylint checks whether the module matches upto a coding standard.<\/p>\n\n\n\n<p>40. What is the difference between tuple and dictionary?<\/p>\n\n\n\n<p>One major difference between a tuple and a dictionary is that dictionary is mutable while a tuple is not. Meaning the content of a dictionary can be changed without changing it\u2019s identity, but in tuple that\u2019s not possible.<\/p>\n\n\n\n<p>41. What is pass in Python?<\/p>\n\n\n\n<p>Pass is a statentemen which does nothing when executed. In other words it is a Null statement. This statement is not ignored by the interpreter, but the statement results in no operation. It is used when you do not want any command to execute but a statement is required.<\/p>\n\n\n\n<p>42. How can an object be copied in Python?<\/p>\n\n\n\n<p>Not all objects can be copied in Python, but most can. We ca use the \u201c=\u201d operator to copy an obect to a variable.<\/p>\n\n\n\n<p>ex: var=copy.copy(obj)<\/p>\n\n\n\n<p>43. How can a number be converted to a string?<\/p>\n\n\n\n<p>The inbuilt function str() can be used to convert a nuber to a string.<\/p>\n\n\n\n<p>44. What are module and package in Python?<\/p>\n\n\n\n<p>Modules are the way to structure a program. Each Python program file is a module, importing other attributes and objects. The folder of a program is a package of modules. A package can have modules or subfolders.<\/p>\n\n\n\n<p>45. What is object() function in Python?<\/p>\n\n\n\n<p>In Python the object() function returns an empty object. New properties or methods cannot be added to this object.<\/p>\n\n\n\n<p>46. What is the difference between NumPy and SciPy?<\/p>\n\n\n\n<p>NumPy stands for Numerical Python while SciPy stands for Scientific Python. NumPy is the basic library for defining arrays and simple mathematica problems, while SciPy is used for more complex problems like numerical integration and optimization and machine learning and so on.<\/p>\n\n\n\n<p>47. What does len() do?<\/p>\n\n\n\n<p>len() is used to determine the length of a string, a list, an array, and so on. ex: str = \u201cgreatlearning\u201d<\/p>\n\n\n\n<p>print(len(str))<\/p>\n\n\n\n<p>o\/p: 13<\/p>\n\n\n\n<p>48. Define encapsulation in Python?<\/p>\n\n\n\n<p>Encapsulation means binding the code and the data together. A Python class for example.<\/p>\n\n\n\n<p>49. What is the type () in Python?<\/p>\n\n\n\n<p>type() is a built-in method which either returns the type of the object or returns a new type object based on the arguments passed.<\/p>\n\n\n\n<p>ex: a = 100<\/p>\n\n\n\n<p>type(a)<\/p>\n\n\n\n<p>o\/p: int<\/p>\n\n\n\n<p>50. What is split() function used for?<\/p>\n\n\n\n<p>Split fuction is used to split a string into shorter string using defined seperatos. letters = (\u201d A, B, C\u201d)<\/p>\n\n\n\n<p>n = text.split(\u201c,\u201d)<\/p>\n\n\n\n<p>print(n)<\/p>\n\n\n\n<p>o\/p: [\u2018A\u2019, \u2018B\u2019, \u2018C\u2019 ]<\/p>\n\n\n\n<p>51. What are the built-in types does python provide?<\/p>\n\n\n\n<p>Ans. Python has following built-in data types:<\/p>\n\n\n\n<p>Numbers: Python identifies three types of numbers:<\/p>\n\n\n\n<p>Integer: All positive and negative numbers without a fractional part<\/p>\n\n\n\n<p>Float: Any real number with floating-point representation<\/p>\n\n\n\n<p>Complex numbers: A number with a real and imaginary component represented as x+yj. x and y are floats and j is -1(square root of -1 called an imaginary number)<\/p>\n\n\n\n<p>Boolean: The Boolean data type is a data type that has one of two possible values i.e. True or False. Note that \u2018T\u2019 and \u2018F\u2019 are capital letters.<\/p>\n\n\n\n<p>String: A string value is a collection of one or more characters put in single, double or triple quotes.<\/p>\n\n\n\n<p>List: A list object is an ordered collection of one or more data items which can be of different types, put in square brackets. A list is mutable and thus can be modified, we can add, edit or delete individual elements in a list.<\/p>\n\n\n\n<p>Set: An unordered collection of unique objects enclosed in curly brackets<\/p>\n\n\n\n<p>Frozen set: They are like a set but immutable, which means we cannot modify their values once they are created.<\/p>\n\n\n\n<p>Dictionary: A dictionary object is unordered in which there is a key associated with each value and we can access each value through its key. A collection of such pairs is enclosed in curly brackets. For example {\u2018First Name\u2019 : \u2019Tom\u2019 , \u2019last name\u2019 : \u2019Hardy\u2019} Note that Number values, strings, and tuple are immutable while as List or Dictionary object are mutable.<\/p>\n\n\n\n<p>52. What is docstring in Python?<\/p>\n\n\n\n<p>Ans. Python docstrings are the string literals enclosed in triple quotes that appear right after the definition of a function, method, class, or module. These are generally used to describe the functionality of a particular function, method, class, or module. We can access these docstrings using the __doc__ attribute. Here is an example:<\/p>\n\n\n\n<p>def square(n):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; &#8221;&#8217;Takes in a number n, returns the square of n&#8221;&#8217;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; return n**2<\/p>\n\n\n\n<p>print(square.__doc__)<\/p>\n\n\n\n<p>Ouput: Takes in a number n, returns the square of n.<\/p>\n\n\n\n<p>53. How to Reverse a String in Python?<\/p>\n\n\n\n<p>In Python, there are no in-built functions that help us reverse a string. We need to make use of an array slicing operation for the same.<\/p>\n\n\n\n<p>1<\/p>\n\n\n\n<p>str_reverse = string[::-1]<\/p>\n\n\n\n<p>Learn more: How To Reverse a String In Python<\/p>\n\n\n\n<p>54. How to check Python Version in CMD?<\/p>\n\n\n\n<p>To check the Python Version in CMD, press CMD + Space. This opens Spotlight. Here, type \u201cterminal\u201d and press enter. To execute the command, type python \u2013version or python -V and press enter. This will return the python version in the next line below the command.<\/p>\n\n\n\n<p>55. Is Python case sensitive when dealing with identifiers?<\/p>\n\n\n\n<p>Yes. Python is case sensitive when dealing with identifiers. It is a case sensitive language. Thus, variable and Variable would not be the same.<\/p>\n\n\n\n<p>Python Interview Questions for Experienced Professionals:-<\/p>\n\n\n\n<p>1. How to create a new column in pandas by using values from other columns?<\/p>\n\n\n\n<p>We can perform column based mathematical operations on a pandas dataframe. Pandas columns containing numeric values can be operated upon by operators.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>a=[1,2,3]<\/p>\n\n\n\n<p>b=[2,3,5]<\/p>\n\n\n\n<p>d={&#8220;col1&#8243;:a,&#8221;col2&#8221;:b}<\/p>\n\n\n\n<p>df=pd.DataFrame(d)<\/p>\n\n\n\n<p>df[&#8220;Sum&#8221;]=df[&#8220;col1&#8221;]+df[&#8220;col2&#8221;]<\/p>\n\n\n\n<p>df[&#8220;Difference&#8221;]=df[&#8220;col1&#8221;]-df[&#8220;col2&#8221;]<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>pandas<\/p>\n\n\n\n<p>2. What are the different functions that can be used by grouby in pandas ?<\/p>\n\n\n\n<p>grouby() in pandas can be used with multiple aggregate functions. Some of which are sum(),mean(), count(),std().<\/p>\n\n\n\n<p>Data is divided into groups based on categories and then the data in these individual groups can be aggregated by the aforementioned functions.<\/p>\n\n\n\n<p>3. How to select columns in pandas and add them to a new dataframe? What if there are two columns with the same name?<\/p>\n\n\n\n<p>If df is dataframe in pandas df.columns gives the list of all columns. We can then form new columns by selecting columns.<\/p>\n\n\n\n<p>If there are two columns with the same name then both columns get copied to the new dataframe.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>print(d_new.columns)<\/p>\n\n\n\n<p>d=d_new[[&#8220;col1&#8221;]]<\/p>\n\n\n\n<p>d<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>output<\/p>\n\n\n\n<p>4. How to delete a column or group of columns in pandas? Given the below dataframe drop column \u201ccol1\u201d.<\/p>\n\n\n\n<p>drop() function can be used to delete the columns from a dataframe.<\/p>\n\n\n\n<p>d={&#8220;col1&#8243;:[1,2,3],&#8221;col2&#8221;:[&#8220;A&#8221;,&#8221;B&#8221;,&#8221;C&#8221;]}<\/p>\n\n\n\n<p>df=pd.DataFrame(d)<\/p>\n\n\n\n<p>df=df.drop([&#8220;col1&#8221;],axis=1)<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>5. Given the following data frame drop rows having column values as A.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>d={&#8220;col1&#8243;:[1,2,3],&#8221;col2&#8221;:[&#8220;A&#8221;,&#8221;B&#8221;,&#8221;C&#8221;]}<\/p>\n\n\n\n<p>df=pd.DataFrame(d)<\/p>\n\n\n\n<p>df.dropna(inplace=True)<\/p>\n\n\n\n<p>df=df[df.col1!=1]<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>6. Given the below dataset find the highest paid player in each college in each team.<\/p>\n\n\n\n<p>df.groupby([&#8220;Team&#8221;,&#8221;College&#8221;])[&#8220;Salary&#8221;].max()<\/p>\n\n\n\n<p>7. Given the above dataset find the min max and average salary of a player collegewise and teamwise.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>df.groupby([&#8220;Team&#8221;,&#8221;College&#8221;])[&#8220;Salary&#8221;].max.agg([(&#8216;max&#8217;,&#8217;max&#8217;),(&#8216;min&#8217;,&#8217;min&#8217;),(&#8216;count&#8217;,&#8217;count&#8217;),(&#8216;avg&#8217;,&#8217;min&#8217;)])<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>8. What is Reindexing in pandas?<\/p>\n\n\n\n<p>Reindexing is the process of re-assigning the index of a pandas dataframe.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>bikes=[&#8220;bajaj&#8221;,&#8221;tvs&#8221;,&#8221;herohonda&#8221;,&#8221;kawasaki&#8221;,&#8221;bmw&#8221;]<\/p>\n\n\n\n<p>cars=[&#8220;lamborghini&#8221;,&#8221;masserati&#8221;,&#8221;ferrari&#8221;,&#8221;hyundai&#8221;,&#8221;ford&#8221;]<\/p>\n\n\n\n<p>d={&#8220;cars&#8221;:cars,&#8221;bikes&#8221;:bikes}<\/p>\n\n\n\n<p>df=pd.DataFrame(d)<\/p>\n\n\n\n<p>a=[10,20,30,40,50]<\/p>\n\n\n\n<p>df.index=a<\/p>\n\n\n\n<p>df<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>9. What do you understand by lambda function? Create a lambda function which will print the sum of all the elements in this list -&gt; [5, 8, 10, 20, 50, 100]<\/p>\n\n\n\n<p>from functools import reduce<\/p>\n\n\n\n<p>sequences = [5, 8, 10, 20, 50, 100]<\/p>\n\n\n\n<p>sum = reduce (lambda x, y: x+y, sequences)<\/p>\n\n\n\n<p>print(sum)<\/p>\n\n\n\n<p>10. What is vstack() in numpy? Give an example<\/p>\n\n\n\n<p>Ans. vstack() is a function to align rows vertically. All rows must have same number of elements.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import numpy as np<\/p>\n\n\n\n<p>n1=np.array([10,20,30,40,50])<\/p>\n\n\n\n<p>n2=np.array([50,60,70,80,90])<\/p>\n\n\n\n<p>print(np.vstack((n1,n2)))<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>11. How do we interpret Python?<\/p>\n\n\n\n<p>When a python program is written, it converts the source code written by the developer into intermediate language, which is then coverted into machine language that needs to be executed.<\/p>\n\n\n\n<p>12. How to remove spaces from a string in Python?<\/p>\n\n\n\n<p>Spaces can be removed from a string in python by using strip() or replace() functions. Strip() function is used to remove the leading and trailing white spaces while the replace() function is used to remove all the white spaces in the string:<\/p>\n\n\n\n<p>string.replace(\u201d \u201c,\u201d\u201d) ex1: str1= \u201cgreat learning\u201d<\/p>\n\n\n\n<p>print (str.strip())<\/p>\n\n\n\n<p>o\/p: great learning<\/p>\n\n\n\n<p>ex2: str2=\u201dgreat learning\u201d<\/p>\n\n\n\n<p>print (str.replace(\u201d \u201c,\u201d\u201d))<\/p>\n\n\n\n<p>o\/p: greatlearning<\/p>\n\n\n\n<p>13. Explain the file processing modes that Python supports.<\/p>\n\n\n\n<p>There are three file processing modes in Python: read-only(r), write-only(w), read-write(rw) and append (a). So, if you are opening a text file in say, read mode. The preceding modes become \u201crt\u201d for read-only, \u201cwt\u201d for write and so on. Similarly, a binary file can be opened by specifying \u201cb\u201d along with the file accessing flags (\u201cr\u201d, \u201cw\u201d, \u201crw\u201d and \u201ca\u201d) preceding it.<\/p>\n\n\n\n<p>14. What is pickling and unpickling?<\/p>\n\n\n\n<p>Pickling is the process of converting a Python object hierarchy into a byte stream for storing it into a database. It is also known as serialization. Unpickling is the reverse of pickling. The byte stream is converted back into an object hierarchy.<\/p>\n\n\n\n<p>15. How is memory managed in Python?<\/p>\n\n\n\n<p>Memory management in python comprises of a private heap containing all objects and data stucture. The heap is managed by the interpreter and the programmer does not have acess to it at all. The Python memory manger does all the memory allocation. Moreover, there is an inbuilt garbage collector that recycles and frees memory for the heap space.<\/p>\n\n\n\n<p>16. What is unittest in Python?<\/p>\n\n\n\n<p>Unittest is a unit testinf framework in Python. It supports sharing of setup and shutdown code for tests, aggregation of tests into collections,test automation, and independence of the tests from the reporting framework.<\/p>\n\n\n\n<p>17. How do you delete a file in Python?<\/p>\n\n\n\n<p>Files can be deleted in Python by using the command os.remove (filename) or os.unlink(filename)<\/p>\n\n\n\n<p>18. How do you create an empty class in Python?<\/p>\n\n\n\n<p>To create an empty class we can use the pass command after the definition of the class object. A pass is a statement in Python that does nothing.<\/p>\n\n\n\n<p>19. What are Python decorators?<\/p>\n\n\n\n<p>Ans. Decorators are functions that take another functions as argument to modify its behaviour without changing the function itself. These are useful when we want to dynamically increase the functionality of a function without changing it. Here is an example :<\/p>\n\n\n\n<p>def smart_divide(func):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; def inner(a, b):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;Dividing&#8221;, a, &#8220;by&#8221;, b)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if b == 0:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;Make sure Denominator is not zero&#8221;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return<\/p>\n\n\n\n<p>return func(a, b)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; return inner<\/p>\n\n\n\n<p>@smart_divide<\/p>\n\n\n\n<p>def divide(a, b):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(a\/b)<\/p>\n\n\n\n<p>divide(1,0)<\/p>\n\n\n\n<p><strong>Python Interview Questions for Advanced Levels:-<\/strong><\/p>\n\n\n\n<p>1. You have this covid-19 dataset below:<\/p>\n\n\n\n<p>From this dataset, how will you make a bar-plot for the top 5 states having maximum confirmed cases as of 17=07-2020?<\/p>\n\n\n\n<p>sol:<\/p>\n\n\n\n<p>#keeping only required columns<\/p>\n\n\n\n<p>df = df[[\u2018Date\u2019, \u2018State\/UnionTerritory\u2019,\u2019Cured\u2019,\u2019Deaths\u2019,\u2019Confirmed\u2019]]<\/p>\n\n\n\n<p>#renaming column names<\/p>\n\n\n\n<p>df.columns = [\u2018date\u2019, \u2018state\u2019,\u2019cured\u2019,\u2019deaths\u2019,\u2019confirmed\u2019]<\/p>\n\n\n\n<p>#current date<\/p>\n\n\n\n<p>today = df[df.date == \u20182020-07-17\u2019]<\/p>\n\n\n\n<p>#Sorting data w.r.t number of confirmed cases<\/p>\n\n\n\n<p>max_confirmed_cases=today.sort_values(by=\u201dconfirmed\u201d,ascending=False)<\/p>\n\n\n\n<p>max_confirmed_cases<\/p>\n\n\n\n<p>#Getting states with maximum number of confirmed cases<\/p>\n\n\n\n<p>top_states_confirmed=max_confirmed_cases[0:5]<\/p>\n\n\n\n<p>#Making bar-plot for states with top confirmed cases<\/p>\n\n\n\n<p>sns.set(rc={\u2018figure.figsize\u2019:(15,10)})<\/p>\n\n\n\n<p>sns.barplot(x=\u201dstate\u201d,y=\u201dconfirmed\u201d,data=top_states_confirmed,hue=\u201dstate\u201d)<\/p>\n\n\n\n<p>plt.show()<\/p>\n\n\n\n<p>Code explanation:<\/p>\n\n\n\n<p>We start off by taking only the required columns with this command:<\/p>\n\n\n\n<p>df = df[[\u2018Date\u2019, \u2018State\/UnionTerritory\u2019,\u2019Cured\u2019,\u2019Deaths\u2019,\u2019Confirmed\u2019]]<\/p>\n\n\n\n<p>Then, we go ahead and rename the columns:<\/p>\n\n\n\n<p>df.columns = [\u2018date\u2019, \u2018state\u2019,\u2019cured\u2019,\u2019deaths\u2019,\u2019confirmed\u2019]<\/p>\n\n\n\n<p>After that, we extract only those records, where the date is equal to 17th July:<\/p>\n\n\n\n<p>today = df[df.date == \u20182020-07-17\u2019]<\/p>\n\n\n\n<p>Then, we go ahead and select the top 5 states with maximum no. of covide cases:<\/p>\n\n\n\n<p>max_confirmed_cases=today.sort_values(by=\u201dconfirmed\u201d,ascending=False)<\/p>\n\n\n\n<p>max_confirmed_cases<\/p>\n\n\n\n<p>top_states_confirmed=max_confirmed_cases[0:5]<\/p>\n\n\n\n<p>Finally, we go ahead and make a bar-plot with this:<\/p>\n\n\n\n<p>sns.set(rc={\u2018figure.figsize\u2019:(15,10)})<\/p>\n\n\n\n<p>sns.barplot(x=\u201dstate\u201d,y=\u201dconfirmed\u201d,data=top_states_confirmed,hue=\u201dstate\u201d)<\/p>\n\n\n\n<p>plt.show()<\/p>\n\n\n\n<p>Here, we are using seaborn library to make the bar-plot. \u201cState\u201d column is mapped onto the x-axis and \u201cconfirmed\u201d column is mapped onto the y-axis. The color of the bars is being determined by the \u201cstate\u201d column.<\/p>\n\n\n\n<p>2. From this covid-19 dataset:<\/p>\n\n\n\n<p>How can you make a bar-plot for the top-5 states with the most amount of deaths?<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>max_death_cases=today.sort_values(by=\u201ddeaths\u201d,ascending=False)<\/p>\n\n\n\n<p>max_death_cases<\/p>\n\n\n\n<p>sns.set(rc={\u2018figure.figsize\u2019:(15,10)})<\/p>\n\n\n\n<p>sns.barplot(x=\u201dstate\u201d,y=\u201ddeaths\u201d,data=top_states_death,hue=\u201dstate\u201d)<\/p>\n\n\n\n<p>plt.show()<\/p>\n\n\n\n<p>Code Explanation:<\/p>\n\n\n\n<p>We start off by sorting our dataframe in descending order w.r.t the \u201cdeaths\u201d column:<\/p>\n\n\n\n<p>max_death_cases=today.sort_values(by=\u201ddeaths\u201d,ascending=False)<\/p>\n\n\n\n<p>Max_death_cases<\/p>\n\n\n\n<p>Then, we go ahead and make the bar-plot with the help of seaborn library:<\/p>\n\n\n\n<p>sns.set(rc={\u2018figure.figsize\u2019:(15,10)})<\/p>\n\n\n\n<p>sns.barplot(x=\u201dstate\u201d,y=\u201ddeaths\u201d,data=top_states_death,hue=\u201dstate\u201d)<\/p>\n\n\n\n<p>plt.show()<\/p>\n\n\n\n<p>Here, we are mapping \u201cstate\u201d column onto the x-axis and \u201cdeaths\u201d column onto the y-axis.<\/p>\n\n\n\n<p>3. From this covid-19 dataset:<\/p>\n\n\n\n<p>How can you make a line plot indicating the confirmed cases with respect to date?<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>maha = df[df.state == \u2018Maharashtra\u2019]<\/p>\n\n\n\n<p>sns.set(rc={\u2018figure.figsize\u2019:(15,10)})<\/p>\n\n\n\n<p>sns.lineplot(x=\u201ddate\u201d,y=\u201dconfirmed\u201d,data=maha,color=\u201dg\u201d)<\/p>\n\n\n\n<p>plt.show()<\/p>\n\n\n\n<p>Code Explanation:<\/p>\n\n\n\n<p>We start off by extracting all the records where the state is equal to \u201cMaharashtra\u201d:<\/p>\n\n\n\n<p>maha = df[df.state == \u2018Maharashtra\u2019]<\/p>\n\n\n\n<p>Then, we go ahead and make a line-plot using seaborn library:<\/p>\n\n\n\n<p>sns.set(rc={\u2018figure.figsize\u2019:(15,10)})<\/p>\n\n\n\n<p>sns.lineplot(x=\u201ddate\u201d,y=\u201dconfirmed\u201d,data=maha,color=\u201dg\u201d)<\/p>\n\n\n\n<p>plt.show()<\/p>\n\n\n\n<p>Here, we map the \u201cdate\u201d column onto the x-axis and \u201cconfirmed\u201d column onto y-axis.<\/p>\n\n\n\n<p>4. On this \u201cMaharashtra\u201d dataset:<\/p>\n\n\n\n<p>How will you implement a linear regression algorithm with \u201cdate\u201d as independent variable and \u201cconfirmed\u201d as dependent variable. That is you have to predict the number of confirmed cases w.r.t date.<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>maha[\u2018date\u2019]=maha[\u2018date\u2019].map(dt.datetime.toordinal)<\/p>\n\n\n\n<p>maha.head()<\/p>\n\n\n\n<p>x=maha[\u2018date\u2019]<\/p>\n\n\n\n<p>y=maha[\u2018confirmed\u2019]<\/p>\n\n\n\n<p>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)<\/p>\n\n\n\n<p>from sklearn.linear_model import LinearRegression<\/p>\n\n\n\n<p>lr = LinearRegression()<\/p>\n\n\n\n<p>lr.fit(np.array(x_train).reshape(-1,1),np.array(y_train).reshape(-1,1))<\/p>\n\n\n\n<p>lr.predict(np.array([[737630]]))<\/p>\n\n\n\n<p>Code solution:<\/p>\n\n\n\n<p>We will start off by converting the date to ordinal type:<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>maha[\u2018date\u2019]=maha[\u2018date\u2019].map(dt.datetime.toordinal)<\/p>\n\n\n\n<p>This is done because we cannot build the linear regression algorithm on top of the date column.<\/p>\n\n\n\n<p>Then, we go ahead and divide the dataset into train and test sets:<\/p>\n\n\n\n<p>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3)<\/p>\n\n\n\n<p>Finally, we go ahead and build the model:<\/p>\n\n\n\n<p>from sklearn.linear_model import LinearRegression<\/p>\n\n\n\n<p>lr = LinearRegression()<\/p>\n\n\n\n<p>lr.fit(np.array(x_train).reshape(-1,1),np.array(y_train).reshape(-1,1))<\/p>\n\n\n\n<p>lr.predict(np.array([[737630]]))<\/p>\n\n\n\n<p>5. On this customer_churn dataset:<\/p>\n\n\n\n<p>Build a keras sequential model to find out how many customers will churn out on the basis of tenure of customer?<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>from keras.models import Sequential<\/p>\n\n\n\n<p>from keras.layers import Dense<\/p>\n\n\n\n<p>model = Sequential()<\/p>\n\n\n\n<p>model.add(Dense(12, input_dim=1, activation=\u2019relu\u2019))<\/p>\n\n\n\n<p>model.add(Dense(8, activation=\u2019relu\u2019))<\/p>\n\n\n\n<p>model.add(Dense(1, activation=\u2019sigmoid\u2019))<\/p>\n\n\n\n<p>model.compile(loss=\u2019binary_crossentropy\u2019, optimizer=\u2019adam\u2019, metrics=[\u2018accuracy\u2019])<\/p>\n\n\n\n<p>model.fit(x_train, y_train, epochs=150,validation_data=(x_test,y_test))<\/p>\n\n\n\n<p>y_pred = model.predict_classes(x_test)<\/p>\n\n\n\n<p>from sklearn.metrics import confusion_matrix<\/p>\n\n\n\n<p>confusion_matrix(y_test,y_pred)<\/p>\n\n\n\n<p>Code explanation:<\/p>\n\n\n\n<p>We will start off by importing the required libraries:<\/p>\n\n\n\n<p>from keras.models import Sequential<\/p>\n\n\n\n<p>from keras.layers import Dense<\/p>\n\n\n\n<p>Then, we go ahead and build the structure of the sequential model:<\/p>\n\n\n\n<p>model = Sequential()<\/p>\n\n\n\n<p>model.add(Dense(12, input_dim=1, activation=\u2019relu\u2019))<\/p>\n\n\n\n<p>model.add(Dense(8, activation=\u2019relu\u2019))<\/p>\n\n\n\n<p>model.add(Dense(1, activation=\u2019sigmoid\u2019))<\/p>\n\n\n\n<p>Finally, we will go ahead and predict the values:<\/p>\n\n\n\n<p>model.compile(loss=\u2019binary_crossentropy\u2019, optimizer=\u2019adam\u2019, metrics=[\u2018accuracy\u2019])<\/p>\n\n\n\n<p>model.fit(x_train, y_train, epochs=150,validation_data=(x_test,y_test))<\/p>\n\n\n\n<p>y_pred = model.predict_classes(x_test)<\/p>\n\n\n\n<p>from sklearn.metrics import confusion_matrix<\/p>\n\n\n\n<p>confusion_matrix(y_test,y_pred)<\/p>\n\n\n\n<p>6. On this iris dataset:<\/p>\n\n\n\n<p>Build a decision tree classification model, where dependent variable is \u201cSpecies\u201d and independent variable is \u201cSepal.Length\u201d.<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>y = iris[[\u2018Species\u2019]]<\/p>\n\n\n\n<p>x = iris[[\u2018Sepal.Length\u2019]]<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.4)<\/p>\n\n\n\n<p>from sklearn.tree import DecisionTreeClassifier<\/p>\n\n\n\n<p>dtc = DecisionTreeClassifier()<\/p>\n\n\n\n<p>dtc.fit(x_train,y_train)<\/p>\n\n\n\n<p>y_pred=dtc.predict(x_test)<\/p>\n\n\n\n<p>from sklearn.metrics import confusion_matrix<\/p>\n\n\n\n<p>confusion_matrix(y_test,y_pred)<\/p>\n\n\n\n<p>(22+7+9)\/(22+2+0+7+7+11+1+1+9)<\/p>\n\n\n\n<p>Code explanation:<\/p>\n\n\n\n<p>We start off by extracting the independent variable and dependent variable:<\/p>\n\n\n\n<p>y = iris[[\u2018Species\u2019]]<\/p>\n\n\n\n<p>x = iris[[\u2018Sepal.Length\u2019]]<\/p>\n\n\n\n<p>Then, we go ahead and divide the data into train and test set:<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.4)<\/p>\n\n\n\n<p>After that, we go ahead and build the model:<\/p>\n\n\n\n<p>from sklearn.tree import DecisionTreeClassifier<\/p>\n\n\n\n<p>dtc = DecisionTreeClassifier()<\/p>\n\n\n\n<p>dtc.fit(x_train,y_train)<\/p>\n\n\n\n<p>y_pred=dtc.predict(x_test)<\/p>\n\n\n\n<p>Finally, we build the confusion matrix:<\/p>\n\n\n\n<p>from sklearn.metrics import confusion_matrix<\/p>\n\n\n\n<p>confusion_matrix(y_test,y_pred)<\/p>\n\n\n\n<p>(22+7+9)\/(22+2+0+7+7+11+1+1+9)<\/p>\n\n\n\n<p>7. On this iris dataset:<\/p>\n\n\n\n<p>Build a decision tree regression model where the independent variable is \u201cpetal length\u201d and dependent variable is \u201cSepal length\u201d.<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>x= iris[[\u2018Petal.Length\u2019]]<\/p>\n\n\n\n<p>y = iris[[\u2018Sepal.Length\u2019]]<\/p>\n\n\n\n<p>x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.25)<\/p>\n\n\n\n<p>from sklearn.tree import DecisionTreeRegressor<\/p>\n\n\n\n<p>dtr = DecisionTreeRegressor()<\/p>\n\n\n\n<p>dtr.fit(x_train,y_train)<\/p>\n\n\n\n<p>y_pred=dtr.predict(x_test)<\/p>\n\n\n\n<p>y_pred[0:5]<\/p>\n\n\n\n<p>from sklearn.metrics import mean_squared_error<\/p>\n\n\n\n<p>mean_squared_error(y_test,y_pred)<\/p>\n\n\n\n<p>8. How will you scrape data from the website \u201ccricbuzz\u201d?<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>import sys<\/p>\n\n\n\n<p>import time<\/p>\n\n\n\n<p>from bs4 import BeautifulSoup<\/p>\n\n\n\n<p>import requests<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>try:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #use the browser to get the url. This is suspicious command that might blow up.<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; page=requests.get(\u2018cricbuzz.com\u2019)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # this might throw an exception if something goes wrong.<\/p>\n\n\n\n<p>except Exception as e:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # this describes what to do if an exception is thrown<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; error_type, error_obj, error_info = sys.exc_info()&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # get the exception information<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print (\u2018ERROR FOR LINK:\u2019,url)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #print the link that cause the problem<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print (error_type, \u2018Line:\u2019, error_info.tb_lineno)&nbsp;&nbsp;&nbsp;&nbsp; #print error info and line that threw the exception<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; #ignore this page. Abandon this and go back.<\/p>\n\n\n\n<p>time.sleep(2)&nbsp;&nbsp;<\/p>\n\n\n\n<p>soup=BeautifulSoup(page.text,\u2019html.parser\u2019)<\/p>\n\n\n\n<p>links=soup.find_all(\u2018span\u2019,attrs={\u2018class\u2019:\u2019w_tle\u2019})<\/p>\n\n\n\n<p>links<\/p>\n\n\n\n<p>for i in links:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(i.text)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(\u201c\\n\u201d)<\/p>\n\n\n\n<p>9. Write a user-defined function to implement central-limit theorem. You have to implement central limit theorem on this \u201cinsurance\u201d dataset:<\/p>\n\n\n\n<p>You also have to build two plots on \u201cSampling Distribution of bmi\u201d and \u201cPopulation distribution of&nbsp; bmi\u201d.<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>df = pd.read_csv(\u2018insurance.csv\u2019)<\/p>\n\n\n\n<p>series1 = df.charges<\/p>\n\n\n\n<p>series1.dtype<\/p>\n\n\n\n<p>def central_limit_theorem(data,n_samples = 1000, sample_size = 500, min_value = 0, max_value = 1338):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; \u201c\u201d\u201d Use this function to demonstrate Central Limit Theorem.<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; data = 1D array, or a pd.Series<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; n_samples = number of samples to be created<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; sample_size = size of the individual sample<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; min_value = minimum index of the data<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; max_value = maximum index value of the data \u201c\u201d\u201d<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; %matplotlib inline<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import pandas as pd<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import numpy as np<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import matplotlib.pyplot as plt<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import seaborn as sns<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; b = {}<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(n_samples):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; x = np.unique(np.random.randint(min_value, max_value, size = sample_size)) # set of random numbers with a specific size<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; b[i] = data[x].mean()&nbsp;&nbsp; # Mean of each sample<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; c = pd.DataFrame()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; c[\u2018sample\u2019] = b.keys()&nbsp; # Sample number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; c[\u2018Mean\u2019] = b.values()&nbsp; # mean of that particular sample<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.figure(figsize= (15,5))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.subplot(1,2,1)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; sns.distplot(c.Mean)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.title(f\u201dSampling Distribution of bmi. \\n \\u03bc = {round(c.Mean.mean(), 3)} &amp; SE = {round(c.Mean.std(),3)}\u201d)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.xlabel(\u2018data\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.ylabel(\u2018freq\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.subplot(1,2,2)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; sns.distplot(data)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.title(f\u201dpopulation Distribution of bmi. \\n \\u03bc = {round(data.mean(), 3)} &amp; \\u03C3 = {round(data.std(),3)}\u201d)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.xlabel(\u2018data\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.ylabel(\u2018freq\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.show()<\/p>\n\n\n\n<p>central_limit_theorem(series1,n_samples = 5000, sample_size = 500)<\/p>\n\n\n\n<p>Code Explanation:<\/p>\n\n\n\n<p>We start off by importing the insurance.csv file with this command:<\/p>\n\n\n\n<p>df = pd.read_csv(\u2018insurance.csv\u2019)<\/p>\n\n\n\n<p>Then we go ahead and define the central limit theorem method:<\/p>\n\n\n\n<p>def central_limit_theorem(data,n_samples = 1000, sample_size = 500, min_value = 0, max_value = 1338):<\/p>\n\n\n\n<p>This method comprises of these parameters:<\/p>\n\n\n\n<p>Data<\/p>\n\n\n\n<p>N_samples<\/p>\n\n\n\n<p>Sample_size<\/p>\n\n\n\n<p>Min_value<\/p>\n\n\n\n<p>Max_value<\/p>\n\n\n\n<p>Inside this method, we import all the required libraries:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import pandas as pd<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import numpy as np<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import matplotlib.pyplot as plt<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; import seaborn as sns<\/p>\n\n\n\n<p>Then, we go ahead and create the first sub-plot for \u201cSampling distribution of bmi\u201d:<\/p>\n\n\n\n<p>&nbsp; plt.subplot(1,2,1)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; sns.distplot(c.Mean)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.title(f\u201dSampling Distribution of bmi. \\n \\u03bc = {round(c.Mean.mean(), 3)} &amp; SE = {round(c.Mean.std(),3)}\u201d)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.xlabel(\u2018data\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.ylabel(\u2018freq\u2019)<\/p>\n\n\n\n<p>Finally, we create the sub-plot for \u201cPopulation distribution of bmi\u201d:<\/p>\n\n\n\n<p>&nbsp;plt.subplot(1,2,2)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; sns.distplot(data)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.title(f\u201dpopulation Distribution of bmi. \\n \\u03bc = {round(data.mean(), 3)} &amp; \\u03C3 = {round(data.std(),3)}\u201d)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.xlabel(\u2018data\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.ylabel(\u2018freq\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.show()<\/p>\n\n\n\n<p>10. Write code to perform sentiment analysis on amazon reviews:<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>import numpy as np<\/p>\n\n\n\n<p>import matplotlib.pyplot as plt<\/p>\n\n\n\n<p>from tensorflow.python.keras import models, layers, optimizers<\/p>\n\n\n\n<p>import tensorflow<\/p>\n\n\n\n<p>from tensorflow.keras.preprocessing.text import Tokenizer, text_to_word_sequence<\/p>\n\n\n\n<p>from tensorflow.keras.preprocessing.sequence import pad_sequences<\/p>\n\n\n\n<p>import bz2<\/p>\n\n\n\n<p>from sklearn.metrics import f1_score, roc_auc_score, accuracy_score<\/p>\n\n\n\n<p>import re<\/p>\n\n\n\n<p>%matplotlib inline<\/p>\n\n\n\n<p>def get_labels_and_texts(file):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; labels = []<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; texts = []<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for line in bz2.BZ2File(file):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; x = line.decode(\u201cutf-8\u201d)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; labels.append(int(x[9]) \u2013 1)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; texts.append(x[10:].strip())<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; return np.array(labels), texts<\/p>\n\n\n\n<p>train_labels, train_texts = get_labels_and_texts(\u2018train.ft.txt.bz2\u2019)<\/p>\n\n\n\n<p>test_labels, test_texts = get_labels_and_texts(\u2018test.ft.txt.bz2\u2019)<\/p>\n\n\n\n<p>Train_labels[0]<\/p>\n\n\n\n<p>Train_texts[0]<\/p>\n\n\n\n<p>train_labels=train_labels[0:500]<\/p>\n\n\n\n<p>train_texts=train_texts[0:500]<\/p>\n\n\n\n<p>import re<\/p>\n\n\n\n<p>NON_ALPHANUM = re.compile(r'[\\W]\u2019)<\/p>\n\n\n\n<p>NON_ASCII = re.compile(r'[^a-z0-1\\s]\u2019)<\/p>\n\n\n\n<p>def normalize_texts(texts):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; normalized_texts = []<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for text in texts:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; lower = text.lower()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; no_punctuation = NON_ALPHANUM.sub(r\u2019 \u2018, lower)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; no_non_ascii = NON_ASCII.sub(r\u201d, no_punctuation)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; normalized_texts.append(no_non_ascii)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; return normalized_texts<\/p>\n\n\n\n<p>train_texts = normalize_texts(train_texts)<\/p>\n\n\n\n<p>test_texts = normalize_texts(test_texts)<\/p>\n\n\n\n<p>from sklearn.feature_extraction.text import CountVectorizer<\/p>\n\n\n\n<p>cv = CountVectorizer(binary=True)<\/p>\n\n\n\n<p>cv.fit(train_texts)<\/p>\n\n\n\n<p>X = cv.transform(train_texts)<\/p>\n\n\n\n<p>X_test = cv.transform(test_texts)<\/p>\n\n\n\n<p>from sklearn.linear_model import LogisticRegression<\/p>\n\n\n\n<p>from sklearn.metrics import accuracy_score<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>X_train, X_val, y_train, y_val = train_test_split(<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; X, train_labels, train_size = 0.75)<\/p>\n\n\n\n<p>for c in [0.01, 0.05, 0.25, 0.5, 1]:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; lr = LogisticRegression(C=c)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; lr.fit(X_train, y_train)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print (\u201cAccuracy for C=%s: %s\u201d<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; % (c, accuracy_score(y_val, lr.predict(X_val))))<\/p>\n\n\n\n<p>lr.predict(X_test[29])<\/p>\n\n\n\n<p>11. Implement a probability plot using numpy and matplotlib:<\/p>\n\n\n\n<p>sol:<\/p>\n\n\n\n<p>import numpy as np<\/p>\n\n\n\n<p>import pylab<\/p>\n\n\n\n<p>import scipy.stats as stats<\/p>\n\n\n\n<p>from matplotlib import pyplot as plt<\/p>\n\n\n\n<p>n1=np.random.normal(loc=0,scale=1,size=1000)<\/p>\n\n\n\n<p>np.percentile(n1,100)<\/p>\n\n\n\n<p>n1=np.random.normal(loc=20,scale=3,size=100)<\/p>\n\n\n\n<p>stats.probplot(n1,dist=\u201dnorm\u201d,plot=pylab)<\/p>\n\n\n\n<p>plt.show()<\/p>\n\n\n\n<p>12. Implement multiple linear regression on this iris dataset:<\/p>\n\n\n\n<p>The independent variables should be \u201cSepal.Width\u201d, \u201cPetal.Length\u201d, \u201cPetal.Width\u201d, while the dependent variable should be \u201cSepal.Length\u201d.<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>iris = pd.read_csv(\u201ciris.csv\u201d)<\/p>\n\n\n\n<p>iris.head()<\/p>\n\n\n\n<p>x = iris[[\u2018Sepal.Width\u2019,\u2019Petal.Length\u2019,\u2019Petal.Width\u2019]]<\/p>\n\n\n\n<p>y = iris[[\u2018Sepal.Length\u2019]]<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.35)<\/p>\n\n\n\n<p>from sklearn.linear_model import LinearRegression<\/p>\n\n\n\n<p>lr = LinearRegression()<\/p>\n\n\n\n<p>lr.fit(x_train, y_train)<\/p>\n\n\n\n<p>y_pred = lr.predict(x_test)<\/p>\n\n\n\n<p>from sklearn.metrics import mean_squared_error<\/p>\n\n\n\n<p>mean_squared_error(y_test, y_pred)<\/p>\n\n\n\n<p>Code solution:<\/p>\n\n\n\n<p>We start off by importing the required libraries:<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>iris = pd.read_csv(\u201ciris.csv\u201d)<\/p>\n\n\n\n<p>iris.head()<\/p>\n\n\n\n<p>Then, we will go ahead and extract the independent variables and dependent variable:<\/p>\n\n\n\n<p>x = iris[[\u2018Sepal.Width\u2019,\u2019Petal.Length\u2019,\u2019Petal.Width\u2019]]<\/p>\n\n\n\n<p>y = iris[[\u2018Sepal.Length\u2019]]<\/p>\n\n\n\n<p>Following which, we divide the data into train and test sets:<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.35)<\/p>\n\n\n\n<p>Then, we go ahead and build the model:<\/p>\n\n\n\n<p>from sklearn.linear_model import LinearRegression<\/p>\n\n\n\n<p>lr = LinearRegression()<\/p>\n\n\n\n<p>lr.fit(x_train, y_train)<\/p>\n\n\n\n<p>y_pred = lr.predict(x_test)<\/p>\n\n\n\n<p>Finally, we will find out the mean squared error:<\/p>\n\n\n\n<p>from sklearn.metrics import mean_squared_error<\/p>\n\n\n\n<p>mean_squared_error(y_test, y_pred)<\/p>\n\n\n\n<p>13. From this credit fraud dataset:<\/p>\n\n\n\n<p>Find the percentage of transactions which are fraudulent and not fraudulent. Also build a logistic regression model, to find out if the transaction is fraudulent or not.<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>nfcount=0<\/p>\n\n\n\n<p>notFraud=data_df[\u2018Class\u2019]<\/p>\n\n\n\n<p>for i in range(len(notFraud)):<\/p>\n\n\n\n<p>&nbsp; if notFraud[i]==0:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; nfcount=nfcount+1<\/p>\n\n\n\n<p>nfcount&nbsp;&nbsp;&nbsp;<\/p>\n\n\n\n<p>per_nf=(nfcount\/len(notFraud))*100<\/p>\n\n\n\n<p>print(\u2018percentage of total not fraud transaction in the dataset: \u2018,per_nf)<\/p>\n\n\n\n<p>fcount=0<\/p>\n\n\n\n<p>Fraud=data_df[\u2018Class\u2019]<\/p>\n\n\n\n<p>for i in range(len(Fraud)):<\/p>\n\n\n\n<p>&nbsp; if Fraud[i]==1:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; fcount=fcount+1<\/p>\n\n\n\n<p>fcount&nbsp;&nbsp;&nbsp;<\/p>\n\n\n\n<p>per_f=(fcount\/len(Fraud))*100<\/p>\n\n\n\n<p>print(\u2018percentage of total fraud transaction in the dataset: \u2018,per_f)<\/p>\n\n\n\n<p>x=data_df.drop([\u2018Class\u2019], axis = 1)#drop the target variable<\/p>\n\n\n\n<p>y=data_df[\u2018Class\u2019]<\/p>\n\n\n\n<p>xtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size = 0.2, random_state = 42)<\/p>\n\n\n\n<p>logisticreg = LogisticRegression()<\/p>\n\n\n\n<p>logisticreg.fit(xtrain, ytrain)<\/p>\n\n\n\n<p>y_pred = logisticreg.predict(xtest)<\/p>\n\n\n\n<p>accuracy= logisticreg.score(xtest,ytest)<\/p>\n\n\n\n<p>cm = metrics.confusion_matrix(ytest, y_pred)<\/p>\n\n\n\n<p>print(cm)<\/p>\n\n\n\n<p>14.&nbsp; Implement a simple CNN on the MNIST dataset using Keras. Following which, also add in drop out layers.<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>from __future__ import absolute_import, division, print_function<\/p>\n\n\n\n<p>import numpy as np<\/p>\n\n\n\n<p># import keras<\/p>\n\n\n\n<p>from tensorflow.keras.datasets import cifar10, mnist<\/p>\n\n\n\n<p>from tensorflow.keras.models import Sequential<\/p>\n\n\n\n<p>from tensorflow.keras.layers import Dense, Activation, Dropout, Flatten, Reshape<\/p>\n\n\n\n<p>from tensorflow.keras.layers import Convolution2D, MaxPooling2D<\/p>\n\n\n\n<p>from tensorflow.keras import utils<\/p>\n\n\n\n<p>import pickle<\/p>\n\n\n\n<p>from matplotlib import pyplot as plt<\/p>\n\n\n\n<p>import seaborn as sns<\/p>\n\n\n\n<p>plt.rcParams[\u2018figure.figsize\u2019] = (15, 8)<\/p>\n\n\n\n<p>%matplotlib inline<\/p>\n\n\n\n<p># Load\/Prep the Data<\/p>\n\n\n\n<p>(x_train, y_train_num), (x_test, y_test_num) = mnist.load_data()<\/p>\n\n\n\n<p>x_train = x_train.reshape(x_train.shape[0], 28, 28, 1).astype(\u2018float32\u2019)<\/p>\n\n\n\n<p>x_test = x_test.reshape(x_test.shape[0], 28, 28, 1).astype(\u2018float32\u2019)<\/p>\n\n\n\n<p>x_train \/= 255<\/p>\n\n\n\n<p>x_test \/= 255<\/p>\n\n\n\n<p>y_train = utils.to_categorical(y_train_num, 10)<\/p>\n\n\n\n<p>y_test = utils.to_categorical(y_test_num, 10)<\/p>\n\n\n\n<p>print(\u2018\u2014 THE DATA \u2014\u2018)<\/p>\n\n\n\n<p>print(\u2018x_train shape:\u2019, x_train.shape)<\/p>\n\n\n\n<p>print(x_train.shape[0], \u2018train samples\u2019)<\/p>\n\n\n\n<p>print(x_test.shape[0], \u2018test samples\u2019)<\/p>\n\n\n\n<p>TRAIN = False<\/p>\n\n\n\n<p>BATCH_SIZE = 32<\/p>\n\n\n\n<p>EPOCHS = 1<\/p>\n\n\n\n<p># Define the Type of Model<\/p>\n\n\n\n<p>model1 = tf.keras.Sequential()<\/p>\n\n\n\n<p># Flatten Imgaes to Vector<\/p>\n\n\n\n<p>model1.add(Reshape((784,), input_shape=(28, 28, 1)))<\/p>\n\n\n\n<p># Layer 1<\/p>\n\n\n\n<p>model1.add(Dense(128, kernel_initializer=\u2019he_normal\u2019, use_bias=True))<\/p>\n\n\n\n<p>model1.add(Activation(\u201crelu\u201d))<\/p>\n\n\n\n<p># Layer 2<\/p>\n\n\n\n<p>model1.add(Dense(10, kernel_initializer=\u2019he_normal\u2019, use_bias=True))<\/p>\n\n\n\n<p>model1.add(Activation(\u201csoftmax\u201d))<\/p>\n\n\n\n<p># Loss and Optimizer<\/p>\n\n\n\n<p>model1.compile(loss=\u2019categorical_crossentropy\u2019, optimizer=\u2019adam\u2019, metrics=[\u2018accuracy\u2019])<\/p>\n\n\n\n<p># Store Training Results<\/p>\n\n\n\n<p>early_stopping = keras.callbacks.EarlyStopping(monitor=\u2019val_acc\u2019, patience=10, verbose=1, mode=\u2019auto\u2019)<\/p>\n\n\n\n<p>callback_list = [early_stopping]# [stats, early_stopping]<\/p>\n\n\n\n<p># Train the model<\/p>\n\n\n\n<p>model1.fit(x_train, y_train, nb_epoch=EPOCHS, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=callback_list, verbose=True)<\/p>\n\n\n\n<p>#drop-out layers:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Define Model<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3 = tf.keras.Sequential()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # 1st Conv Layer<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Convolution2D(32, (3, 3), input_shape=(28, 28, 1)))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Activation(\u2018relu\u2019))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # 2nd Conv Layer<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Convolution2D(32, (3, 3)))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Activation(\u2018relu\u2019))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Max Pooling<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(MaxPooling2D(pool_size=(2,2)))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Dropout<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Dropout(0.25))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Fully Connected Layer<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Flatten())<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Dense(128))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Activation(\u2018relu\u2019))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # More Dropout<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Dropout(0.5))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Prediction Layer<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Dense(10))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.add(Activation(\u2018softmax\u2019))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Loss and Optimizer<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.compile(loss=\u2019categorical_crossentropy\u2019, optimizer=\u2019adam\u2019, metrics=[\u2018accuracy\u2019])<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Store Training Results<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; early_stopping = tf.keras.callbacks.EarlyStopping(monitor=\u2019val_acc\u2019, patience=7, verbose=1, mode=\u2019auto\u2019)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; callback_list = [early_stopping]<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # Train the model<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; model3.fit(x_train, y_train, batch_size=BATCH_SIZE, nb_epoch=EPOCHS,<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; validation_data=(x_test, y_test), callbacks=callback_list)<\/p>\n\n\n\n<p>15. Implement a popularity based recommendation system on this movie lens dataset:<\/p>\n\n\n\n<p>import os<\/p>\n\n\n\n<p>import numpy as np&nbsp;<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>ratings_data = pd.read_csv(\u201cratings.csv\u201d)&nbsp;<\/p>\n\n\n\n<p>ratings_data.head()<\/p>\n\n\n\n<p>movie_names = pd.read_csv(\u201cmovies.csv\u201d)&nbsp;<\/p>\n\n\n\n<p>movie_names.head()&nbsp;<\/p>\n\n\n\n<p>movie_data = pd.merge(ratings_data, movie_names, on=\u2019movieId\u2019)&nbsp;<\/p>\n\n\n\n<p>movie_data.groupby(\u2018title\u2019)[\u2018rating\u2019].mean().head()&nbsp;<\/p>\n\n\n\n<p>movie_data.groupby(\u2018title\u2019)[\u2018rating\u2019].mean().sort_values(ascending=False).head()<\/p>\n\n\n\n<p>movie_data.groupby(\u2018title\u2019)[\u2018rating\u2019].count().sort_values(ascending=False).head()&nbsp;<\/p>\n\n\n\n<p>ratings_mean_count = pd.DataFrame(movie_data.groupby(\u2018title\u2019)[\u2018rating\u2019].mean())<\/p>\n\n\n\n<p>ratings_mean_count.head()<\/p>\n\n\n\n<p>ratings_mean_count[\u2018rating_counts\u2019] = pd.DataFrame(movie_data.groupby(\u2018title\u2019)[\u2018rating\u2019].count())<\/p>\n\n\n\n<p>ratings_mean_count.head()&nbsp;<\/p>\n\n\n\n<p>16. Implement the naive bayes algorithm on top of the diabetes dataset:<\/p>\n\n\n\n<p>Sol:<\/p>\n\n\n\n<p>import numpy as np # linear algebra<\/p>\n\n\n\n<p>import pandas as pd # data processing, CSV file I\/O (e.g. pd.read_csv)<\/p>\n\n\n\n<p>import matplotlib.pyplot as plt&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # matplotlib.pyplot plots data<\/p>\n\n\n\n<p>%matplotlib inline<\/p>\n\n\n\n<p>import seaborn as sns<\/p>\n\n\n\n<p>pdata = pd.read_csv(\u201cpima-indians-diabetes.csv\u201d)<\/p>\n\n\n\n<p>columns = list(pdata)[0:-1] # Excluding Outcome column which has only<\/p>\n\n\n\n<p>pdata[columns].hist(stacked=False, bins=100, figsize=(12,30), layout=(14,2));<\/p>\n\n\n\n<p># Histogram of first 8 columns<\/p>\n\n\n\n<p># However we want to see correlation in graphical representation so below is function for that<\/p>\n\n\n\n<p>def plot_corr(df, size=11):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; corr = df.corr()<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; fig, ax = plt.subplots(figsize=(size, size))<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; ax.matshow(corr)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.xticks(range(len(corr.columns)), corr.columns)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; plt.yticks(range(len(corr.columns)), corr.columns)<\/p>\n\n\n\n<p>plot_corr(pdata)<\/p>\n\n\n\n<p>from sklearn.model_selection import train_test_split<\/p>\n\n\n\n<p>X = pdata.drop(\u2018class\u2019,axis=1)&nbsp;&nbsp;&nbsp;&nbsp; # Predictor feature columns (8 X m)<\/p>\n\n\n\n<p>Y = pdata[\u2018class\u2019]&nbsp;&nbsp; # Predicted class (1=True, 0=False) (1 X m)<\/p>\n\n\n\n<p>x_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=1)<\/p>\n\n\n\n<p># 1 is just any random seed number<\/p>\n\n\n\n<p>x_train.head()<\/p>\n\n\n\n<p>from sklearn.naive_bayes import GaussianNB # using Gaussian algorithm from Naive Bayes<\/p>\n\n\n\n<p># creatw the model<\/p>\n\n\n\n<p>diab_model = GaussianNB()<\/p>\n\n\n\n<p>diab_model.fit(x_train, y_train.ravel())<\/p>\n\n\n\n<p>diab_train_predict = diab_model.predict(x_train)<\/p>\n\n\n\n<p>from sklearn import metrics<\/p>\n\n\n\n<p>print(\u201cModel Accuracy: {0:.4f}\u201d.format(metrics.accuracy_score(y_train, diab_train_predict)))<\/p>\n\n\n\n<p>print()<\/p>\n\n\n\n<p>diab_test_predict = diab_model.predict(x_test)<\/p>\n\n\n\n<p>from sklearn import metrics<\/p>\n\n\n\n<p>print(\u201cModel Accuracy: {0:.4f}\u201d.format(metrics.accuracy_score(y_test, diab_test_predict)))<\/p>\n\n\n\n<p>print()<\/p>\n\n\n\n<p>print(\u201cConfusion Matrix\u201d)<\/p>\n\n\n\n<p>cm=metrics.confusion_matrix(y_test, diab_test_predict, labels=[1, 0])<\/p>\n\n\n\n<p>df_cm = pd.DataFrame(cm, index = [i for i in [\u201c1\u2033,\u201d0\u201d]],<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; columns = [i for i in [\u201cPredict 1\u2033,\u201dPredict 0\u201d]])<\/p>\n\n\n\n<p>plt.figure(figsize = (7,5))<\/p>\n\n\n\n<p>sns.heatmap(df_cm, annot=True)<\/p>\n\n\n\n<p><strong>Python object-oriented problem interview questions:-<\/strong><\/p>\n\n\n\n<p>1. What do you understand by object oriented programming in Python?<\/p>\n\n\n\n<p>Object oriented programming refers to the process of solving a problem by creating objects. This approach takes into account two key factors of an object- attributes and behaviour.<\/p>\n\n\n\n<p>2. How are classes created in Python? Give an example<\/p>\n\n\n\n<p>class Node(object):<\/p>\n\n\n\n<p>&nbsp; def __init__(self):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; self.x=0<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; self.y=0<\/p>\n\n\n\n<p>Here Node is a class<\/p>\n\n\n\n<p>3. What is inheritance in Object oriented programming? Give an example of multiple inheritance.<\/p>\n\n\n\n<p>Inheritance is one of the core concepts of object-oriented programming. It is a process of deriving a class from a different class and form a hierarchy of classes that share the same attributes and methods. It is generally used for deriving different kinds of exceptions, create custom logic for existing frameworks and even map domain models for database.<\/p>\n\n\n\n<p>Example<\/p>\n\n\n\n<p>class Node(object):<\/p>\n\n\n\n<p>&nbsp; def __init__(self):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; self.x=0<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; self.y=0<\/p>\n\n\n\n<p>Here class Node inherits from the object class.<\/p>\n\n\n\n<p>Wish to upskill? Take up a data science course and learn now!<\/p>\n\n\n\n<p>4. What is multi-level inheritance? Give an example for multi-level inheritance?<\/p>\n\n\n\n<p>If class A inherits from B and C inherits from A it\u2019s called multilevel inheritance.<\/p>\n\n\n\n<p>class B(object):<\/p>\n\n\n\n<p>&nbsp; def __init__(self):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; self.b=0<\/p>\n\n\n\n<p>class A(B):<\/p>\n\n\n\n<p>&nbsp; def __init__(self):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; self.a=0<\/p>\n\n\n\n<p>class C(A):<\/p>\n\n\n\n<p>&nbsp; def __init__(self):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; self.c=0<\/p>\n\n\n\n<p><strong>Python Programming for Interview:-<\/strong><\/p>\n\n\n\n<p>1. How can you find the minimum and maximum values present in a tuple?<\/p>\n\n\n\n<p>&nbsp;Solution -&gt;<\/p>\n\n\n\n<p>We can use the min() function on top of the tuple to find out the minimum value present in the tuple:<\/p>\n\n\n\n<p>tup1=(1,2,3,4,5)<\/p>\n\n\n\n<p>min(tup1)<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>1<\/p>\n\n\n\n<p>We see that the minimum value present in the tuple is 1.<\/p>\n\n\n\n<p>Analogous to the min() function is the max() function, which will help us to find out the maximum value present in the tuple:<\/p>\n\n\n\n<p>tup1=(1,2,3,4,5)<\/p>\n\n\n\n<p>max(tup1)<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>5<\/p>\n\n\n\n<p>We see that the maximum value present in the tuple is 5<\/p>\n\n\n\n<p>2. If you have a list like this -&gt; [1,\u201da\u201d,2,\u201db\u201d,3,\u201dc\u201d]. How can you access the 2nd, 4th and 5th elements from this list?<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>We will start off by creating a tuple which will comprise of the indices of elements which we want to access:<\/p>\n\n\n\n<p>Then, we will use a for loop to go through the index values and print them out:<\/p>\n\n\n\n<p>Below is the entire code for the process:<\/p>\n\n\n\n<p>indices = (1,3,4)<\/p>\n\n\n\n<p>for i in indices:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(a[i])<\/p>\n\n\n\n<p>3. If you have a list like this -&gt; [\u201csparta\u201d,True,3+4j,False]. How would you reverse the elements of this list?<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>We can use&nbsp; the reverse() function on the list:<\/p>\n\n\n\n<p>a.reverse()<\/p>\n\n\n\n<p>a<\/p>\n\n\n\n<p>4. If you have dictionary like this \u2013 &gt; fruit={\u201cApple\u201d:10,\u201dOrange\u201d:20,\u201dBanana\u201d:30,\u201dGuava\u201d:40}. How would you update the value of \u2018Apple\u2019 from 10 to 100?<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>&nbsp;This is how you can do it:<\/p>\n\n\n\n<p>fruit[&#8220;Apple&#8221;]=100<\/p>\n\n\n\n<p>fruit<\/p>\n\n\n\n<p>Give in the name of the key inside the parenthesis and assign it a new value.<\/p>\n\n\n\n<p>5. If you have two sets like this -&gt; s1 = {1,2,3,4,5,6}, s2 = {5,6,7,8,9}. How would you find the common elements in these sets.<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>You can use the intersection() function to find the common elements between the two sets:<\/p>\n\n\n\n<p>s1 = {1,2,3,4,5,6}<\/p>\n\n\n\n<p>s2 = {5,6,7,8,9}<\/p>\n\n\n\n<p>s1.intersection(s2)<\/p>\n\n\n\n<p>We see that the common elements between the two sets are 5 &amp; 6.<\/p>\n\n\n\n<p>6. Write a program to print out the 2-table using while loop.<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>Below is the code to print out the 2-table:<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>i=1<\/p>\n\n\n\n<p>n=2<\/p>\n\n\n\n<p>while i&lt;=10:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(n,&#8221;*&#8221;, i, &#8220;=&#8221;, n*i)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; i=i+1<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>code with output<\/p>\n\n\n\n<p>We start off by initializing two variables \u2018i\u2019 and \u2018n\u2019. \u2018i\u2019 is initialized to 1 and \u2018n\u2019 is initialized to \u20182\u2019.<\/p>\n\n\n\n<p>Inside the while loop, since the \u2018i\u2019 value goes from 1 to 10, the loop iterates 10 times.<\/p>\n\n\n\n<p>Initially n*i is equal to 2*1, and we print out the value.<\/p>\n\n\n\n<p>Then, \u2018i\u2019 value is incremented and n*i becomes 2*2. We go ahead and print it out.<\/p>\n\n\n\n<p>This process goes on until i value becomes 10.<\/p>\n\n\n\n<p>7. Write a function, which will take in a value and print out if it is even or odd.<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>The below code will do the job:<\/p>\n\n\n\n<p>def even_odd(x):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; if x%2==0:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(x,&#8221; is even&#8221;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; else:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(x, &#8221; is odd&#8221;)<\/p>\n\n\n\n<p>Here, we start off by creating a method, with the name \u2018even_odd()\u2019. This function takes a single parameter and prints out if the number taken is even or odd.<\/p>\n\n\n\n<p>Now, let\u2019s invoke the function:<\/p>\n\n\n\n<p>even_odd(5)<\/p>\n\n\n\n<p>We see that, when 5 is passed as a parameter into the function, we get the output -&gt; \u20185 is odd\u2019.<\/p>\n\n\n\n<p>8. Write a python program to print the factorial of a number.<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>Below is the code to print the factorial of a number:<\/p>\n\n\n\n<p>factorial = 1<\/p>\n\n\n\n<p>#check if the number is negative, positive or zero<\/p>\n\n\n\n<p>if num&lt;0:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(&#8220;Sorry, factorial does not exist for negative numbers&#8221;)<\/p>\n\n\n\n<p>elif num==0:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(&#8220;The factorial of 0 is 1&#8221;)<\/p>\n\n\n\n<p>else<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(1,num+1):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;factorial = factorial*i<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(&#8220;The factorial of&#8221;,num,&#8221;is&#8221;,factorial)<\/p>\n\n\n\n<p>We start off by taking an input which is stored in \u2018num\u2019. Then, we check if \u2018num\u2019 is less than zero and if it is actually less than 0, we print out \u2018Sorry, factorial does not exist for negative numbers\u2019.<\/p>\n\n\n\n<p>After that, we check,if \u2018num\u2019 is equal to zero, and it that\u2019s the case, we print out \u2018The factorial of 0 is 1\u2019.<\/p>\n\n\n\n<p>On the other hand, if \u2018num\u2019 is greater than 1, we enter the for loop and calculate the factorial of the number.<\/p>\n\n\n\n<p>9. Write a python program to check if the number given is a palindrome or not<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>Below is the code to Check whether the given number is palindrome or not:<\/p>\n\n\n\n<p>n=int(input(&#8220;Enter number:&#8221;))<\/p>\n\n\n\n<p>temp=n<\/p>\n\n\n\n<p>rev=0<\/p>\n\n\n\n<p>while(n&gt;0)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; dig=n%10<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; rev=rev*10+dig<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; n=n\/\/10<\/p>\n\n\n\n<p>if(temp==rev):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(&#8220;The number is a palindrome!&#8221;)<\/p>\n\n\n\n<p>else:<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(&#8220;The number isn&#8217;t a palindrome!&#8221;)<\/p>\n\n\n\n<p>We will start off by taking an input and store it in \u2018n\u2019 and make a duplicate of it in \u2018temp\u2019. We will also initialize another variable \u2018rev\u2019 to 0.<\/p>\n\n\n\n<p>Then, we will enter a while loop which will go on until \u2018n\u2019 becomes 0.<\/p>\n\n\n\n<p>Inside the loop, we will start off by dividing \u2018n\u2019 with 10 and then store the remainder in \u2018dig\u2019.<\/p>\n\n\n\n<p>Then, we will multiply \u2018rev\u2019 with 10 and then add \u2018dig\u2019 to it. This result will be stored back in \u2018rev\u2019.<\/p>\n\n\n\n<p>Going ahead, we will divide \u2018n\u2019 by 10 and store the result back in \u2018n\u2019<\/p>\n\n\n\n<p>Once the for loop ends, we will compare the values of \u2018rev\u2019 and \u2018temp\u2019. If they are equal, we will print \u2018The number is a palindrome\u2019, else we will print \u2018The number isn\u2019t a palindrome\u2019.<\/p>\n\n\n\n<p>10. Write a python program to print the following pattern -&gt;<\/p>\n\n\n\n<p>1<\/p>\n\n\n\n<p>2 2<\/p>\n\n\n\n<p>3 3 3<\/p>\n\n\n\n<p>4 4 4 4<\/p>\n\n\n\n<p>5 5 5 5 5<\/p>\n\n\n\n<p>Solution -&gt;<\/p>\n\n\n\n<p>Below is the code to print this pattern:<\/p>\n\n\n\n<p>#10 is the total number to print<\/p>\n\n\n\n<p>for num in range(6):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(num,end=&#8221; &#8220;)#print number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; #new line after each row to display pattern correctly<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; print(&#8220;\\n&#8221;)<\/p>\n\n\n\n<p>We are solving the problem with the help of nested for loop. We will have an outer for loop, which goes from 1 to 5. Then, we have an inner for loop, which would print the respective numbers.<\/p>\n\n\n\n<p>11. Pattern questions. Print the following pattern<\/p>\n\n\n\n<p>#<\/p>\n\n\n\n<p># #<\/p>\n\n\n\n<p># # #<\/p>\n\n\n\n<p># # # #<\/p>\n\n\n\n<p># # # # #<\/p>\n\n\n\n<p>Solution \u2013&gt;<\/p>\n\n\n\n<p>def pattern_1(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # outer loop handles the number of rows<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # inner loop handles the number of columns<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # n is the number of rows.<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(0, n):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # value of j depends on i<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, i+1):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # printing hashes<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;#&#8221;,end=&#8221;&#8221;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ending line after each row<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;\\r&#8221;)&nbsp;<\/p>\n\n\n\n<p>num = int(input(&#8220;Enter the number of rows in pattern: &#8220;))<\/p>\n\n\n\n<p>pattern_1(num)<\/p>\n\n\n\n<p>12. Print the following pattern<\/p>\n\n\n\n<p>&nbsp; #<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # #<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # # #<\/p>\n\n\n\n<p>&nbsp; # # # #<\/p>\n\n\n\n<p># # # # #<\/p>\n\n\n\n<p>Solution \u2013&gt;<\/p>\n\n\n\n<p>Code:<\/p>\n\n\n\n<p>def pattern_2(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # define the number of spaces<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; k = 2*num &#8211; 2<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # outer loop always handles the number of rows<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # let us use the inner loop to control the number of spaces<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # we need the number of spaces as maximum initially and then decrement it after every iteration<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(0, num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, k):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(end=&#8221; &#8220;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # decrementing k after each loop<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; k = k &#8211; 2<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # reinitializing the inner loop to keep a track of the number of columns<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # similar to pattern_1 function<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, i+1):&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;# &#8220;, end=&#8221;&#8221;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ending line after each row<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;\\r&#8221;)<\/p>\n\n\n\n<p>num = int(input(&#8220;Enter the number of rows in pattern: &#8220;))<\/p>\n\n\n\n<p>pattern_2(num)<\/p>\n\n\n\n<p>13. Print the following pattern:<\/p>\n\n\n\n<p>0<\/p>\n\n\n\n<p>0 1<\/p>\n\n\n\n<p>0 1 2<\/p>\n\n\n\n<p>0 1 2 3<\/p>\n\n\n\n<p>0 1 2 3 4<\/p>\n\n\n\n<p>Solution \u2013&gt;<\/p>\n\n\n\n<p>Code:<\/p>\n\n\n\n<p>def pattern_3(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # initialising starting number&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; number = 1<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # outer loop always handles the number of rows<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # let us use the inner loop to control the number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(0, num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # re assigning number after every iteration<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ensure the column starts from 0<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; number = 0<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # inner loop to handle number of columns<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, i+1):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # printing number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(number, end=&#8221; &#8220;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # increment number column wise<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; number = number + 1<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ending line after each row<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;\\r&#8221;)<\/p>\n\n\n\n<p>num = int(input(&#8220;Enter the number of rows in pattern: &#8220;))<\/p>\n\n\n\n<p>pattern_3(num)<\/p>\n\n\n\n<p>14. Print the following pattern:<\/p>\n\n\n\n<p>1<\/p>\n\n\n\n<p>2 3<\/p>\n\n\n\n<p>4 5 6<\/p>\n\n\n\n<p>7 8 9 10<\/p>\n\n\n\n<p>11 12 13 14 15<\/p>\n\n\n\n<p>Solution \u2013&gt;<\/p>\n\n\n\n<p>Code:<\/p>\n\n\n\n<p>def pattern_4(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # initialising starting number&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; number = 1<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # outer loop always handles the number of rows<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # let us use the inner loop to control the number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(0, num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # commenting the reinitialization part ensure that numbers are printed continuously<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ensure the column starts from 0<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; number = 0<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # inner loop to handle number of columns<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, i+1):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # printing number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(number, end=&#8221; &#8220;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # increment number column wise<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; number = number + 1<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ending line after each row<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;\\r&#8221;)<\/p>\n\n\n\n<p>num = int(input(&#8220;Enter the number of rows in pattern: &#8220;))<\/p>\n\n\n\n<p>pattern_4(num)<\/p>\n\n\n\n<p>15. Print the following pattern:<\/p>\n\n\n\n<p>A<\/p>\n\n\n\n<p>B B<\/p>\n\n\n\n<p>C C C<\/p>\n\n\n\n<p>D D D D<\/p>\n\n\n\n<p>Solution \u2013&gt;<\/p>\n\n\n\n<p>def pattern_5(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # initializing value of A as 65<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # ASCII value&nbsp; equivalent<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; number = 65<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # outer loop always handles the number of rows<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(0, num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # inner loop handles the number of columns<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, i+1):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # finding the ascii equivalent of the number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; char = chr(number)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # printing char value&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(char, end=&#8221; &#8220;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # incrementing number<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; number = number + 1<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ending line after each row<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;\\r&#8221;)<\/p>\n\n\n\n<p>num = int(input(&#8220;Enter the number of rows in pattern: &#8220;))<\/p>\n\n\n\n<p>pattern_5(num)<\/p>\n\n\n\n<p>16. Print the following pattern:<\/p>\n\n\n\n<p>A<\/p>\n\n\n\n<p>B C<\/p>\n\n\n\n<p>D E F<\/p>\n\n\n\n<p>G H I J<\/p>\n\n\n\n<p>K L M N O<\/p>\n\n\n\n<p>P Q R S T U<\/p>\n\n\n\n<p>Solution \u2013&gt;<\/p>\n\n\n\n<p>def&nbsp; pattern_6(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # initializing value equivalent to &#8216;A&#8217; in ASCII&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # ASCII value<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; number = 65<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # outer loop always handles the number of rows<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(0, num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # inner loop to handle number of columns<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # values changing acc. to outer loop<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, i+1):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # explicit conversion of int to char<\/p>\n\n\n\n<p># returns character equivalent to ASCII.<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; char = chr(number)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # printing char value&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(char, end=&#8221; &#8220;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # printing the next character by incrementing<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;number = number +1&nbsp;&nbsp;&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ending line after each row<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;\\r&#8221;)<\/p>\n\n\n\n<p>num = int(input(&#8220;enter the number of rows in the pattern: &#8220;))<\/p>\n\n\n\n<p>pattern_6(num)<\/p>\n\n\n\n<p>17. Print the following pattern<\/p>\n\n\n\n<p>&nbsp; #<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # #<\/p>\n\n\n\n<p>&nbsp;&nbsp; # # #<\/p>\n\n\n\n<p>&nbsp; # # # #<\/p>\n\n\n\n<p>&nbsp;# # # # #<\/p>\n\n\n\n<p>Solution \u2013&gt;<\/p>\n\n\n\n<p>Code:<\/p>\n\n\n\n<p>def pattern_7(num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # number of spaces is a function of the input num<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; k = 2*num &#8211; 2<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; # outer loop always handle the number of rows<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; for i in range(0, num):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # inner loop used to handle the number of spaces<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;for j in range(0, k):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(end=&#8221; &#8220;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # the variable holding information about number of spaces<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # is decremented after every iteration<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; k = k &#8211; 1<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # inner loop reinitialized to handle the number of columns&nbsp;<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for j in range(0, i+1):<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # printing hash<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;# &#8220;, end=&#8221;&#8221;)<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; # ending line after each row<\/p>\n\n\n\n<p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; print(&#8220;\\r&#8221;)<\/p>\n\n\n\n<p>num = int(input(&#8220;Enter the number of rows: &#8220;))<\/p>\n\n\n\n<p>pattern_7(n)<\/p>\n\n\n\n<p>18. Given the below dataframes form a single dataframe by vertical stacking.<\/p>\n\n\n\n<p>We use the pd.concat and axis as 0 to stack them horizontally.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>d={&#8220;col1&#8243;:[1,2,3],&#8221;col2&#8221;:[&#8216;A&#8217;,&#8217;B&#8217;,&#8217;C&#8217;]}<\/p>\n\n\n\n<p>df1=pd.DataFrame(d)<\/p>\n\n\n\n<p>d={&#8220;col1&#8243;:[4,5,6],&#8221;col2&#8221;:[&#8216;D&#8217;,&#8217;E&#8217;,&#8217;F&#8217;]}<\/p>\n\n\n\n<p>df2=pd.DataFrame(d)<\/p>\n\n\n\n<p>d_new=pd.comcat([df1,df2],axis=0)<\/p>\n\n\n\n<p>d_new<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>19. Given the below dataframes stack them horizontally to form a single data frame.<\/p>\n\n\n\n<p>We use the pd.concat and axis as 0 to stack them horizontally.<\/p>\n\n\n\n<p>Code<\/p>\n\n\n\n<p>import pandas as pd<\/p>\n\n\n\n<p>d={&#8220;col1&#8243;:[1,2,3],&#8221;col2&#8221;:[&#8216;A&#8217;,&#8217;B&#8217;,&#8217;C&#8217;]}<\/p>\n\n\n\n<p>df1=pd.DataFrame(d)<\/p>\n\n\n\n<p>d={&#8220;col1&#8243;:[4,5,6],&#8221;col2&#8221;:[&#8216;D&#8217;,&#8217;E&#8217;,&#8217;F&#8217;]}<\/p>\n\n\n\n<p>df2=pd.DataFrame(d)<\/p>\n\n\n\n<p>d_new=pd.comcat([df1,df2],axis=1)<\/p>\n\n\n\n<p>d_new<\/p>\n\n\n\n<p>Output<\/p>\n\n\n\n<p>20. If you have a dictionary like this -&gt; d1={\u201ck1\u2033:10,\u201dk2\u2033:20,\u201dk3\u201d:30}. How would you increment values of all the keys ?<\/p>\n\n\n\n<p>d1={&#8220;k1&#8243;:10,&#8221;k2&#8243;:20,&#8221;k3&#8221;:30}<\/p>\n\n\n\n<p>for i in d1.keys():<\/p>\n\n\n\n<p>&nbsp; d1[i]=d1[i]+1<\/p>\n\n\n\n<p>21. How can you get a random number in python?<\/p>\n\n\n\n<p>Ans. To generate a random, we use a random module of python. Here are some examples To generate a floating-point number from 0-1<\/p>\n\n\n\n<p>import random<\/p>\n\n\n\n<p>n = random.random()<\/p>\n\n\n\n<p>print(n)<\/p>\n\n\n\n<p>To generate a integer between a certain range (say from a to b):<\/p>\n\n\n\n<p>import random<\/p>\n\n\n\n<p>n = random.randint(a,b)<\/p>\n\n\n\n<p>print(n)<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Python Basic Interview Questions:- 1. What are the key features of Python? Python is one of the most popular programming languages used by data scientists and AIML professionals. This popularity&#8230; <\/p>\n","protected":false},"author":1,"featured_media":26241,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_joinchat":[],"footnotes":""},"categories":[499],"tags":[1003,5449,5431,7120,766,176,7122,482,637],"class_list":["post-26239","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python-programming-scripting-languages","tag-code","tag-devopsschool","tag-function","tag-hundred","tag-interview","tag-python","tag-python-interview","tag-questions","tag-top"],"_links":{"self":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/26239","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/comments?post=26239"}],"version-history":[{"count":1,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/26239\/revisions"}],"predecessor-version":[{"id":26242,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/posts\/26239\/revisions\/26242"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media\/26241"}],"wp:attachment":[{"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/media?parent=26239"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/categories?post=26239"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.devopsschool.com\/blog\/wp-json\/wp\/v2\/tags?post=26239"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}