LogoLogo

Python [Advanced] Interview Questions — 2022

Prasun Das| June 25, 2022 at 7:44 PM | 9 minutes Read

Interview Questions are a great source to test your knowledge about any specific field. But remember whenever you are adding java as your strength in your resume do mention the details of the domain you have worked on that language. Otherwise the interviewer can question you from any of the fields in Python

 

Following are some Advanced Python Interview questions and answers for Freshers.

 



1. How is memory managed in Python?

  • Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space.
  • Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.




2. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google Drive?

We can use the StringIO module from the io module to read from the Google Drive link and then we can use the pandas library using the obtained data source.

from io import StringIO

import pandas



csv_link = "https://docs.google.com/spreadsheets/d/..."
data_source = StringIO.StringIO(requests.get(csv_link).content))
dataframe = pd.read_csv(data_source)
print(dataframe.head())




3. Write a program to check and return the pairs of a given array A whose sum value is equal to a target value N.

This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current value of the array, x. If the map has the value of (N-x), then there is our pair.



def print_pairs(arr, N):
   # hash set
   hash_set = set()
    
   for i in range(0, len(arr)):
       val = N-arr[i]
       if (val in hash_set):    #check if N-x is there in set, print the pair
           print("Pairs " + str(arr[i]) + ", " + str(val))
       hash_set.add(arr[i])

# driver code
arr = [1, 2, 40, 3, 9, 4]
N = 3
print_pairs(arr, N)




 4. Write a Program to add two integers >0 without using the plus operator.

We can use bitwise operators to achieve this.



def sum(n1, n2):
   while num2 != 0:
       data = n1 & n2
       n1 = n1 ^ n2
       n2 = data << 1
   return n1
print(sum(2, 10))



5.What are the steps to create 1D, 2D and 3D arrays?



  • 1D array creation:
import numpy as np
one_dimensional_list = [1,2,4]
one_dimensional_arr = np.array(one_dimensional_list)
print("1D array is : ",one_dimensional_arr)
  • 2D array creation:
import numpy as np
twoD_list=[[1,2,3],[4,5,6]]
twoD_arr = np.array(twoD_list)
print("2D array is : ",twoD_arr)
  • 3D array creation:
import numpy as np
threeD_list=[[[1,2,3],[4,5,6],[7,8,9]]]
threeD_arr = np.array(threeD_list)
print("3D array is : ",threeD_arr)
  • ND array creation: This can be achieved by giving the ndmin attribute. The below example demonstrates the creation of a 6D array:
import numpy as np
ndArr = np.array([1, 2, 3, 4], ndmin=6)
print(ndArr)
print('Dimensions of array:', ndArr.ndim)




Question From Python Library:




1. How will you distinguish between NumPy and SciPy?

 Typically, NumPy contains nothing but the array data type and the most basic operations, such as basic element-wise functions, indexing, reshaping, and sorting. All the numerical code resides in SciPy.

As one of NumPy’s most important goals is compatibility, the library tries to retain all features supported by either of its predecessors. Hence, NumPy contains a few linear algebra functions despite the fact that these more appropriately belong to the SciPy library.

SciPy contains fully-featured versions of the linear algebra modules available to NumPy in addition to several other numerical algorithms.

 

2. What is Django?

Django is an advanced python web framework that supports agile growth and clean pragmatic design, built through experienced developers, this cares much about the trouble of web development, so you can concentrate on writing your app without wanting to reinvent that wheel.

Features of Django:


  • Excellent documentation
  • Python web framework
  • SEO optimised
  • High scalability
  • Versatile in nature
  • Offers high security
  • Thoroughly tested
  • Provides rapid Development

Reasons to use Django:

The main goal to designing Django is to make it simple to its users, to do this   Django uses:


  • The principles concerning rapid development, which implies developers can complete more than one iteration at a time without beginning the full schedule from scratch;
  • DRY philosophy — Do not Replicate Yourself — that means developers can reuse surviving code and also focus on the individual one.

Advantage of Django:


  • One of the important advantages of Django is it is a framework of python language which is very simple to learn
  • Django is a multifaceted framework
  • When it comes to security Django is the best framework
  • Scalability is added advantage of Django

 Disadvantage of Django


  • Uses routing pattern specify its URL.
  • Django is too monolithic.
  • Everything is based on Django ORM.
  • Components get deployed together.
  • Knowledge of full system is required to work.

 



3. Explain how can we build or set up the database in Django?

we can make use of the edit mysite/setting.py command, which is a simple Python module that consists of levels for presenting or displaying Django settings.

By default Django uses SQLite; this also makes it easy for Django users in case of any other type of installations. For example, if your database choice is different then you need to follow certain keys in the DATABASE like default items to match database connection settings.



  • Engines: By these engines you change the database by using commands such as ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.sqlite3’, ‘django.db.backends.oracle’, ‘django.db.backends.mysql’, and so on.
  • Name: This represents the name of your own database. If you are familiar with using SQLite as your database, in such cases database is available as a file on your particular system. Moreover, the name should be as a fully absolute or exact path along with the file name of the particular file.
  • Suppose if we are not using SQLite as your database then additional settings such as password, user, the host must be added.

Django mainly uses SQLite as its default database to store entire information in a single file of the filesystem. If you want to use different database servers rather than SQLite, then make use of database administration tools to create a new database for the Django project. Another way is by using your own database in that place, and the remaining is to explain Django about how to use it. This is the place in which Python’s project settings.py file comes into the picture. 

We need to add the below code to the setting.py file:



DATABASE  = {
‘Default’ : {
‘ENGINE’ :  ‘django.db.backends.sqlite3’,
‘NAME’ : os.path.join(BASE_DIR, ‘db.sqlite3’),
}
}

 

4. How do I test a Python program or component?

Python comes with two testing frameworks: The documentation test module finds examples in the documentation strings for a module and runs them, comparing the output with the expected output given in the documentation string.

 

The unittest module is a fancier testing framework modelled on Java and Smalltalk testing frameworks.


For testing, it helps to write the program so that it may be easily tested by using good modular design. Your program should have almost all functionality encapsulated in either functions or class methods. And this sometimes has the surprising and delightful effect of making the program run faster because local variable accesses are faster than global accesses.

 

Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do. The "global main logic" of your program may be as simple as:

 



if name=="main":
main_logic()

 

at the bottom of the main module of your program. Once your program is organised as a tractable collection of functions and class behaviours, you should write test functions that exercise the behaviours.

 

A test suite can be associated with each module which automates a sequence of tests.

 

You can make coding much more pleasant by writing your test functions in parallel with the "production code", since this makes it easy to find bugs and even design flaws earlier.

 

"Support modules" that are not intended to be the main module of a program may include a self-test of the module.

 



if name == "main": self_test()

 

Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using "fake" interfaces implemented in Python.

 

5. What is Flask & its benefits?

Python Flask, as we've previously discussed, is a web microframework for Python. It is based on the 'Werkzeug, Jinja 2 and good intentions' BSD licence. Two of its dependencies are Werkzeug and Jinja2. This means that it has around no dependencies on external libraries. Due to this, we can call it a light framework. A session uses a signed cookie to allow the user to look at and modify session contents. It will remember information from one request to another. However, to modify a session, the user must have the secret key Flask.secret_key.

 

Flask is a web micro framework for Python based on "Werkzeug, Jinja 2 and good intentions" BSD licensed. Werkzeug and jinja are two of its dependencies.

Flask is part of the micro-framework. Which means it will have little to no dependencies on external libraries. It makes the framework light while there is little dependency to update and less security bugs.




6. Why would you use NumPy arrays instead of lists in Python?

  • NumPy arrays provide users with three main advantages as shown below:
  • NumPy arrays consume a lot less memory, thereby making the code more efficient.
  • NumPy arrays execute faster and do not add heavy processing to the runtime.
  • NumPy has a highly readable syntax, making it easy and convenient for programmers.

7. Define the different ways a DataFrame can be created in pandas?

We can create a DataFrame using following ways:


  • Lists
  • Dict of ndarrays

Example-1: Create a DataFrame using List:


import pandas as pd    
# a list of strings    
a = ['Python', 'Pandas']    
# Calling DataFrame constructor on list    
info = pd.DataFrame(a)    
print(info)    
Output:
 
	0
0   Python
1   Pandas


Example-2: Create a DataFrame from dict of ndarrays:



import pandas as pd    
info = {'ID' :[101, 102, 103],'Department' :['B.Sc','B.Tech','M.Tech',]}    
info = pd.DataFrame(info)    
print (info)   
Output:
 
       ID      Department
0      101        B.Sc
1      102        B.Tech
2      103        M.Tech


8. What is array slicing and how do you do it in NumPy?

Slicing means extracting a portion of the given array to generate a new view of the same array without copying it. This is done by specifying the following:

 

start: specifies where to start slicing from aka the lower limit

stop: specifies where to stop slicing aka the upper limit

step: determines the increment between each index for slicing

 



#Slicing a 1D array
arr = np.array([2, 3, 7, 11, 13, 17, 19, 23, 29, 31, 37]) 
arr[1:7:2] 
array slicing

 

 

 


Bonus:


Top Python Tips and Tricks 


1. In-place swapping of two numbers




p, q = 20, 40
print(p, q)
p, q = q, p
print(p, q)

Output:
20 40
40 20


2. Reversing a String in Python



x = "PepHubTraining"
print( "Reverse is" , x[: : -1]
Output:
Reverse is gniniarTbuHpeP

3. Create a single string from all the elements in the list



x = ["PepHub", "Online", "Training"]
print(" ".join(x))
Output:
PepHub Online Training


4. Return multiple values from functions



def fun():
return 4, 5, 6, 7
p, q, r, s = fun()  
print(p, q, r, s)
Output:
4, 5, 6, 7

5. Check the memory usage of an object



import sys
x = 10
print(sys.getsizeof(x))
Output:
28


6. Find the most frequent value in a list



max_freq = [1, 2, 3, 9, 2, 7, 3, 5, 9, 9, 9]
print(max(set(test), key = max_freq.count))
Output:
9


7. Print the file path of imported modules



import os;
import socket; 
print(os)
print(socket)
Output:
<module 'os' from '/usr/lib/python3.5/os.py'>
<module 'socket' from '/usr/lib/python3.5/socket.py'>
#python #interview questions#interview preparation#fundamentals to learn
View Count:5.4k
2

Comments

Similar Articles

DSA Cheatsheet Curated list (Leetcode)

If you're looking to prepare for a job in the tech industry, Data Structures and Algorithms (DSA) are essential to master. Practising problems on plat......

Cover image

How to Start with DSA

Each and every programmer needs a strong grasp in DSA to write efficient and optimised codes. However, DSA has a reputation of being one of the most f......

Cover image

Campus Placement Roadmap for Batch 2024

Its that time round the calendar again, but different for you all as for the first time now. You all will be facing the on campus placement season.Wit......

Cover image

Busting myths about web3

WHAT IS WEB3?Web3 is the catch-all term for the vision of an upgraded version of the internet aimed at giving power back to the users. It is truly the......

Cover image

Operating System INTERVIEW QUESTIONS

Operating Systems is one of the core subjects for a computer science student. As such a lot of important questions are asked on this subject in interv......

Cover image

Cognizant previous year QnA and Interview Experience

Cognizant helps organizations remain ahead of the competition by modernizing technology, reinventing processes, and redefining customer experiences. I...

Cover image

Cloud Computing Cheatsheet

Getting started with cloud computing ?The words "cloud" and "web" will be interchangeable. What kind of business operates today without the internet? ...

Cover image

Software Engineering — SOFTWARE MAINTENANCE [Part-4]

SOFTWARE MAINTENANCE:Software Maintenance can be defined as the process of modifying a software product after its delivery. The main purpose of softwa...

Cover image

Software Engineering — Software Process Activities [Part - 3]

A quick summary upto what we did this far&nbsp; from this series:Software EngineeringSoftware engineering is a discipline of engineering concerned wit...

Cover image

Capgemini Previous Year Questions with Study Materials

Capgemini is a global leader in consulting, digital transformation, technology, and engineering services. In the rapidly evolving world of cloud, digi...

Cover image

MINDTREE Interview Experience and Previous Year Questions Part 2

Technical Round :Candidates who pass the online test will be invited to the technical interview...

Cover image

MINDTREE Interview Experience and Previous Year Questions Part 1

About Mindtree:Mindtree Ltd, located in Bangalore, India, is a prominent Indian multinational information technology and outsourcing company. The&nbsp...

Cover image

TCS NQT Latest Questions and Answers

TCS NQT Interview kicks off with the aptitude test. The test follows the following pattern :&nbsp;TCS uses the TCS-iON software for their online aptit...

Cover image

INTERVIEW TIPS AND TRICKS FOR FRESHERS

Increased competition for fewer jobs in the current economy means that just being right for the role on paper, is not enough on its own anymore. You h...

Cover image

TCS NINJA INTERVIEW EXPERIENCE [2023]

About TCS NinjaTCS administers the NQT to select candidates for a variety of positions (National Qualifier Test). Tens of thousands of people apply fo...

Cover image

Understanding Time Complexity with Interview Examples

Introduction:Understanding time complexity of a function is imperative for every programmer to execute a program in the most efficient manner. Time co...

Cover image

Software Engineering — Software Development lifecycle and software process(Part 2)

&nbsp;Software MethodologyA software methodology (which is also known as software process) is a set of related development Phases that leads to the pr...

Cover image

TCS Digital Interview Experience [2023]

About TCS DigitalTCS selects applicants for a variety of jobs by conducting the NQT (National Qualifier Test). About 10,000-15,000 job applicants subm...

Cover image

Software Engineering [Part 1] - Introduction

Software Engineering is a subject that requires when you are a software developer as well as when you are in your college preparing for a semester or ...

Cover image

SQL Interview Questions

Are you getting ready for your SQL developer job interview?You've come to the correct place.This tutorial will assist you in brushing up on your SQL s...

Cover image

SQL CHEATSHEET

Introduction: What is SQL?To understand SQL, we must first understand databases and database management systems (DBMS).Data is essentially a collectio...

Cover image

TCS NQT Technical Interview Questions

TCS Recruitment ProcessInterview RoundsInterview round 1:&nbsp; TCS NQTTCS NQT (National Qualifier T...

Cover image

TCS NQT Aptitude Questions

TCS NQT Aptitude has three sections, namely the Numerical Ability, Verbal Ability, and Reasoning Abi...

Cover image

TCS NQT Interview Experience [2023]

About TCS NQTTCS NQTs, also known as TCS National Qualifier Tests or Tata Consultancy Services Natio...

Cover image

Computer Networking Cheatsheet (Last Minute Notes)

&nbsp;Networking: Importance in real life!Using a computer for work, as well as for personal use, ha...

Cover image

Database Management System Last Minute Notes [Part - 2]

ER-DiagramWhat are ER Models ?An Entity Relationship Diagram (ERD) is a visual representation of dif...

Cover image

Database Management System Last Minute Notes [Part - 1]

What is actually DBMS?A Database Management System (DBMS) is system software used to manage the orga...

Cover image

Final year Placement Roadmap in India

Nowadays students tend to go more for off campus placements rather than on campus placements.One of ...

Cover image

C Cheatsheet

C CHEATSHEETINTRODUCTION:C programming language was developed by Dennis Ritchie of Bell Labs in 1972...

Cover image

C Interview Questions — 2022

C is a general purpose high-level language most popular amongst coders, it is the most compatible, e...

Cover image

Cognizant GenC Next Interview

What is GenC and GenC Next?GenC stands for Generation Cognizant. It basically means the fresher hiri...

Cover image

C++ STL Cheat Sheet

C++ programming language has templates which basically allows functions and classes to work with gen...

Cover image

C++ CHEAT SHEET

C++ was conceived in the late 1970s to overcome the limitations of C. It&nbsp; is an extension of th...

Cover image

Basic Python [Core] Interview Questions for Freshers and Short Sample Answers — 2022

The most popular high-level, multipurpose programming language right now is Python.Python supports p...

Cover image

Python Cheat Sheet - Learn the basics of Python

IntroductionPython is a high-level programming language with dynamic binding and high-level inherent...

Cover image

Basic Java Interview Questions for Freshers and Short Sample Answers — 2022

Interview Questions are a great source to test your knowledge about any specific field. But remember...

Cover image

Java OOP Cheat Sheet — A Quick Guide to Object-Oriented Programming in Java

Object-Oriented Programming or better known as OOPs is one of the major pillars of Java that has lev...

Cover image

Learn Java: Basics to Advanced Concepts [Java Cheatsheet]

Java is a high-level programming language known for its robustness, object-oriented nature, enhanced...

Cover image

A Complete Roadmap for On-Campus Placements

Placements are an important part of engineering life, and while everyone hopes to be placed in a reputable company, only a few are successful. This is primarily due to a...

Cover image