DON'T WANT TO MISS A THING?

Certification Exam Passing Tips

Latest exam news and discount info

Curated and up-to-date by our experts

Yes, send me the newsletter

Python Developer Interview Questions & Answers | SPOTO

Whether you're preparing for your first job interview or leveling up your career, having the right preparation makes all the difference. This comprehensive resource covers the most common and challenging Interview Questions and Answers across a wide range of roles and industries — from technical positions to managerial and entry-level jobs. Browse our curated lists of Frequently Asked Interview Questions, behavioral interview questions and answers, situational interview questions, and role-specific interview prep guides designed to help you walk into any interview with confidence. Whether you're looking for IT interview questions and answers, project management interview questions, or top interview questions for freshers, our expert-reviewed content gives you real-world sample answers, proven tips, and insider strategies to help you stand out.
Make your resume stand out — at SPOTO, you can accelerate your career growth by preparing for job interviews while studying for your certification. Click Learn More to take the first step toward career advancement.
View Other Interview Questions

1
Write a Python function to find the longest increasing subsequence in a list.
Reference answer
Sample Answer: The longest increasing subsequence (LIS) problem involves finding the length of the longest subsequence where each element is greater than the previous one. This can be solved using dynamic programming. Here is the code for finding the longest increasing subsequence in a list: def longest_increasing_subsequence(nums): if not nums: return 0 dp = [1] * len(nums) for i in range(1, len(nums)): for j in range(i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
2
How do you find the largest element in a list?
Reference answer
Use the max() function: nums = [3, 7, 2, 9, 5] max_num = max(nums) print(max_num) # Output: 9
Career Acceleration

Earn a certification to make your resume stand out.

According to data analysis, IT certification holders earn an annual salary that is 26% higher than that of average job seekers. At SPOTO, you have the opportunity to accelerate your career growth by pursuing certification and preparing for job interviews simultaneously.

1 100% Pass Rate
2 2 Weeks of Dump Practice
3 Pass the Certification Exam
3
Define the Interpreted Language
Reference answer
An Interpreted programming language executes its code line by line. Python, Javascript, R, PHP, and Ruby are all examples of interpreted programming languages. Programs written in an interpreted language execute directly from the source code, with no compilation step in between.
4
Explain the concept of scope in Python.
Reference answer
Scope defines the region in a program where a variable is accessible. Python has local, enclosing, global, and built-in scopes.
5
What are Python namespaces?
Reference answer
Python namespaces are systems that ensure names (identifiers) are unique and avoid conflicts. They map names to objects and are implemented as dictionaries. Examples include local, global, and built-in namespaces, each with a different scope.
6
What are embeddings, and how are they used in machine learning?
Reference answer
Embeddings are dense vector representations of data (text, images, etc.) that capture semantic meaning. Similar items have similar embeddings, enabling tasks like semantic search, clustering, and recommendation systems. Example: Creating text embeddings: from sentence_transformers import SentenceTransformer import numpy as np # Load embedding model model = SentenceTransformer('all-MiniLM-L6-v2') # Create embeddings sentences = [ "Python is a programming language", "JavaScript is used for web development", "Python is great for data science" ] embeddings = model.encode(sentences) # Calculate similarity def cosine_similarity(a, b): return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b)) # Python sentences are more similar to each other print(f"Similarity 0-2: {cosine_similarity(embeddings[0], embeddings[2]):.3f}") # Higher print(f"Similarity 0-1: {cosine_similarity(embeddings[0], embeddings[1]):.3f}") # Lower
7
What are Python's namespaces?
Reference answer
Namespaces are containers that hold identifiers and their corresponding objects. Examples include local, global, and built-in namespaces.
8
Find the Fibonacci sequence
Reference answer
Output : Fibonacci sequence : 0 1 1 2 3
9
What is the difference between the except and finally blocks in Python?
Reference answer
The except block in Python is executed only if an exception is raised in the try block, whereas the finally block is executed regardless of whether an exception is raised or not. The finally block is typically used to perform cleanup tasks, such as closing a file or releasing a resource.
10
What does the Python pass statement do?
Reference answer
The Python pass statement is used when a statement is required, but you do not want a command or code to execute.
11
Write a function to find the longest substring without repeating characters.
Reference answer
def longest_unique_substring(s): char_index = {} max_length = 0 start = 0 for i, char in enumerate(s): if char in char_index and char_index[char] >= start: start = char_index[char] + 1 char_index[char] = i max_length = max(max_length, i - start + 1) return max_length
12
What are the differences between mutable and immutable data types in Python, and can you provide examples of each?
Reference answer
Mutable types can be changed in place (e.g., lists), while immutable types cannot (e.g., tuples). Changing an immutable type creates a new object``.
13
How do you handle outliers in a DataFrame using Pandas?
Reference answer
You can identify and handle outliers by using statistical methods like z-scores or IQR (Interquartile Range``) and filtering or transforming the data accordingly.
14
Discuss Django architecture.
Reference answer
Django MVT Pattern: Figure:Django Architecture The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user.
15
What is multi threading and how it can be achieved ?
Reference answer
Multithreading is a programming technique that allows multiple threads of execution to run concurrently within a single process. A thread is a lightweight unit of execution within a program that can perform tasks independently. Multithreading can be achieved in various programming languages, including Python, by utilizing the operating system's threading capabilities or using libraries that provide threading functionality. Here are the basic steps to achieve multithreading in Python: - Import the threading module: In Python, multithreading is facilitated by the built-in threading module. Import the module to gain access to its classes and functions. - Define a task or function: Create a function or task that you want each thread to execute concurrently. This function represents the work that will be performed by each thread. - Create thread objects: Instantiate thread objects from the Thread class provided by the threading module. Specify the target function or task to be executed by each thread. You can also pass any required arguments to the target function. - Start the threads: Call the start() method on each thread object to start the execution of the threads. Each thread will begin running concurrently. Wait for thread completion: If needed, use the join() method on each thread to wait for its completion. This ensures that the main program doesn't proceed until all threads have finished their execution.
16
What is a virtual environment in Python, and why is it useful?
Reference answer
A virtual environment is an isolated Python environment that allows you to manage dependencies for a specific project. It helps avoid conflicts between different projects' dependencies.
17
What is __init__?
Reference answer
__init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables. # class definition class Student: def __init__(self, fname, lname, age, section): self.firstname = fname self.lastname = lname self.age = age self.section = section # creating a new object stu1 = Student("Sara", "Ansh", 22, "A2")
18
What is caching in Joblib, and why is it important?
Reference answer
Caching in Joblib refers to the ability to save the results of a computationally expensive function to disk or memory so that it can be reused later without recomputing the function. This is important because many data science and machine learning functions can take a long time to compute, especially on large datasets. By caching the results, we can save time and computational resources by reusing them rather than recomputing them.
19
Have you worked with real-time data processing or streaming data in Python, using libraries like Apache Kafka or Apache Spark Streaming? If so, can you describe a scenario and how you handled it?
Reference answer
Yes, I've worked with Apache Kafka for real-time data processing. In a project, we integrated Kafka to ingest and process streaming data from IoT devices. We used Kafka consumer groups and Python clients to handle data efficiently.
20
Check if a string is a palindrome or not
Reference answer
Output : RADAR is a Palindrome
21
What is the difference between a generator function and a normal function in Python? Provide an example of a generator function.
Reference answer
- Generator function is a type of function that yields a sequence of values instead of returning a single value. - Normal function returns a single value and then exits. - Generator functions use the yield keyword to return a value and pause the execution of the function. - Normal functions use the return keyword to return a value and immediately exit the function. Example of a generator function: def my_generator(n): i = 0 while i < n: yield i i += 1 This generator function returns a sequence of numbers from 0 to n-1. It does not use the return keyword but instead uses yield to pause and resume the function.
22
How to drop a row or column in a Pandas dataframe?
Reference answer
A Pandas dataframe is a two dimensional data structure which allows you to store data in rows and columns. To drop a row or column in a dataframe, you need to use the drop() method available in the dataframe. Syntax: DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise') Parameters: Return type: Dataframe with dropped values.
23
What is a class in Python, and how do you use it?
Reference answer
A Class is like an object constructor, or a "blueprint" for creating objects. You can create a class with the class keyword: class MyClass: x = 5 Now we can use the class named MyClass to create objects: Create an object named p1, and print the value of x: p1 = MyClass() print(p1.x)
24
Why does finally sometimes override a return?
Reference answer
The finally block always runs, even if there is a return in try or except, so if you also put a return inside finally, it will replace the earlier return, which is confusing and often a bug, this is why people avoid returning from finally in real code. def test(): try: return 1 finally: return 2 print(test()) # 2 Gotcha: many think the first return will win, but finally always has the last word.
25
How can you find the shortest path between two vertices in a graph in Python?
Reference answer
The shortest path between two vertices in a graph can be found using BFS, where you keep track of the distance from the starting vertex to each visited vertex.
26
Implement wildcards in Python
Reference answer
In Python, you can implement wildcards using the regex (regular expressions) library. The dot . character is used in place of the question mark ? symbol. Hence, to search for all words matching the color pattern, the code would look something like as follows. # Regular expression library import re # Add or remove the words in this list to vary the results wordlist = ["color", "colour", "work", "working", "fox", "worker", "working"] for word in wordlist: # The . symbol is used in place of ? symbol if re.search('col.r', word) : print (word) Output: color
27
Explain list, dictionary, and tuple comprehension with an example.
Reference answer
List List comprehension offers one-liner syntax to create a new list based on the values of the existing list. You can use a for loop to replicate the same thing, but it will require you to write multiple lines, and sometimes it can get complex. List comprehension eases the creation of the list based on existing iterable. my_list = [i for i in range(1, 10)] my_list # [1, 2, 3, 4, 5, 6, 7, 8, 9] Dictionary Similar to a List comprehension, you can create a dictionary based on an existing table with a single line of code. You need to enclose the operation with curly brackets {}. # Creating a dictionary using dictionary comprehension my_dict = {i: i**2 for i in range(1, 10)} # Output the dictionary my_dict {1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} Tuple Unlike lists and dictionaries, there is no special “tuple comprehension.” When you use parentheses with a comprehension, Python actually creates a generator expression, not a tuple. To get a tuple, you must either convert the generator with tuple() or define a tuple literal directly. # Generator expression (not a tuple) my_gen = (i for i in range(1, 10)) my_gen # ...> # Converting generator to tuple my_tuple = tuple(i for i in range(1, 10)) my_tuple # (1, 2, 3, 4, 5, 6, 7, 8, 9) # Or simply define a tuple directly literal_tuple = (1, 2, 3) literal_tuple # (1, 2, 3)
28
What is the purpose of the PYTHONHOME variable?
Reference answer
This is an alternate path to search for Python modules.
29
What are Python's magic methods?
Reference answer
Magic methods are special methods with double underscores, like __init__, __str__, and __len__. They allow customization of object behavior for built-in operations like addition, comparison, or iteration. Example: class MyClass: def __init__(self, value): self.value = value def __str__(self): return f"MyClass({self.value})" def __add__(self, other): return self.value + other.value
30
What are some built in data types in python ?
Reference answer
Numeric Types: - int: Represents integer values (e.g., 1, 5, -10). - float: Represents floating-point numbers with decimal values (e.g., 3.14, -0.5). Sequence Types: - str: Represents a sequence of characters, also known as strings (e.g., “hello”, ‘world'). - list: Represents an ordered collection of items (e.g., [1, 2, 3], [‘apple', ‘banana']). - tuple: Represents an ordered, immutable collection of items (e.g., (1, 2, 3), (‘a', ‘b', ‘c')). Mapping Type: dict: Represents a collection of key-value pairs (e.g., {‘name': ‘John', ‘age': 25}). Set Types: set: Represents an unordered collection of unique elements (e.g., {1, 2, 3}). Boolean Type: bool: Represents the truth values True and False. None Type: None: Represents the absence of a value or the null value.
31
When designing APIs, how do you ensure proper documentation for developers who will consume the API? Any specific tools or practices you follow?
Reference answer
Documentation is vital. We often use tools like Swagger or Sphinx, generating documentation directly from code comments. It's important to keep documentation up-to-date and comprehensive to facilitate API adoption.
32
What are the steps to compile and link new extensions in Python?
Reference answer
The compiling and linking allow the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter. The steps that are required in this as:
33
What is the difference between xrange and range functions?
Reference answer
range() and xrange() were both used in Python 2 to generate sequences of numbers for iteration. In Python 3, there is no xrange, but the range function behaves like xrange. - range(): This returns a range object, which is an immutable sequence type that generates the numbers on demand. - xrange(): This function returns the generator object that can be used to display numbers only by looping. The only particular range is displayed on demand and hence called lazy evaluation.
34
How do you create a Series in Pandas?
Reference answer
You can create a Series in Pandas using the pd.Series() constructor, passing a Python list or array as an argument.
35
How do you implement a queue using two stacks?
Reference answer
Sample Answer: A queue follows a first-in, first-out (FIFO) principle, while stacks operate on a last-in, first-out (LIFO) basis. You can implement a queue using two stacks: one for handling enqueue operations and the other for managing dequeue operations. This method effectively simulates the queue's behavior by reversing the order of elements when necessary. Here's how you can code a queue using two stacks in Python: class Queue: def __init__(self): self.stack1 = [] self.stack2 = [] def enqueue(self, item): self.stack1.append(item) def dequeue(self): if not self.stack2: while self.stack1: self.stack2.append(self.stack1.pop()) return self.stack2.pop() if self.stack2 else None
36
What is 'self' in Python?
Reference answer
Self is an instance or an object of a class. In Python, this is explicitly included as the first parameter. However, this is not the case in Java where it's optional. It helps to differentiate between the methods and attributes of a class with local variables. The self variable in the init method refers to the newly created object while in other methods, it refers to the object whose method was called.
37
What are some common NumPy functions?
Reference answer
NumPy provides a wide range of functions for numerical operations, including arithmetic functions like add(), subtract(), multiply(), and divide(), as well as statistical functions like mean(), median(), and std().
38
How do you securely store and use API keys or credentials in a Python application?
Reference answer
Store sensitive credentials in environment variables or secure vault services. Do not hardcode secrets in your code base and load them at runtime using the os module. Example: import os # Retrieve the database password from environment variables db_password = os.environ.get('DB_PASSWORD') # Check if the password is not found in the environment variables if db_password is None: # Raise an exception if the password is not set raise Exception("Database password not found in environment variables.")
39
80. What are the primary keys and foreign keys in SQL databases?
Reference answer
Primary keys are used to uniquely identify each row in a SQL database table. Primary keys can be a single column or a combination of columns.This means that no two rows can have the same primary key values. It ensures the uniqueness of the row and plays a pivotal role in indexing. Foreign keys are used to establish relationships between two tables. A foreign key is a column or combination of columns in one table that references the primary key of another table. Ensuring data consistency, foreign keys enforce referential integrity in the database. For example, A table has a foreign key that references the primary key of another table, the database ensures that the referenced primary key value exists, preserving data coherence.
40
What is the difference between dict.get() and indexing dict[key]?
Reference answer
Using dict[key] throws an error if the key is missing, while dict.get(key) returns None or a default value, this is useful when you are not sure if a key exists, so get() is safer in scripts, while indexing is good when the key must be present. d = {"a": 1} print(d.get("b")) # None print(d.get("b", 0)) # 0 # print(d["b"]) # KeyError
41
Discuss your experience with data processing in Python. Have you used libraries like Pandas, NumPy, or Dask for handling large datasets?
Reference answer
Yes, I've used Pandas for data manipulation and analysis. In one project, I processed millions of records with Pandas and optimized performance using vectorized operations.
42
What is the purpose of functions in Python? How do you define and call a function?
Reference answer
- Functions encapsulate code for reusability and modularity. - Use def keyword to define a function, and call it with its name and arguments.
43
What is self in Python?
Reference answer
self in Python is a convention for the first parameter of instance methods in a class. It refers to the instance of the class itself and is used to access instance attributes and methods within the class.
44
31. What is the proper way of writing a Python function to reverse a string?
Reference answer
The proper way of writing a Python function to reverse a string is using Python's slicing mechanism. Define a function, say `reverse_string` , and inside it, return the input string with a slice that steps backward. To illustrate, the function would look like this: `def reverse_string(s): return s[::-1] `. def reverse_string(s): return s[::-1] This approach leverages Python's inherent capabilities, making the solution both concise and efficient. The function will provide the reversed version of that string, when called with a string,
45
What is Self-used for in Python?
Reference answer
It is used to represent the instance of the class. This is because in Python, the ‘@' syntax is not used to refer to the instance attributes.
46
Write a Python function called reverse_words that takes a sentence as input and returns the sentence with the order of words reversed.
Reference answer
def reverse_words(sentence): words = sentence.split() reversed_sentence = ' '.join(reversed(words)) return reversed_sentence Explanation: - The reverse_words function starts by splitting the sentence into individual words using the split() method. This creates a list of words. - Next, the function uses the reversed() function to reverse the order of the words in the list. - The reversed words are then joined back together using the ' '.join() method, where the space character ' ' is used as the separator. - Finally, the reversed sentence is returned.
47
Is Python a scripting language or a programming language?
Reference answer
Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language.
48
How do you detect a cycle in a directed graph using DFS?
Reference answer
Sample Answer: To detect cycle in a directed graph, you can use depth-first search (DFS). You keep track of the nodes currently being explored, and if you visit a node that's already in this exploration path, it means there's a cycle. Here's how you can implement this: def has_cycle(graph): def dfs(node): if node in visiting: return True if node in visited: return False visiting.add(node) for neighbor in graph[node]: if dfs(neighbor): return True visiting.remove(node) visited.add(node) return False visited, visiting = set(), set() for vertex in graph: if dfs(vertex): return True return False
49
Describe how you would handle exceptions in Python.
Reference answer
- Use try-except blocks to catch and handle specific exceptions gracefully. - finally block can be used to run cleanup code regardless of exceptions.
50
How can you copy objects in Python?
Reference answer
Objects in Python can be copied using the copy module. The copy.copy() function creates a shallow copy, while copy.deepcopy() creates a deep copy. For simple sequences, slicing or the list() constructor can also be used.
51
Write a Python function to find the second largest element in a list.
Reference answer
Solution: def second_largest(nums): if len(nums) < 2: return None # If the list has less than two elements, return None sorted_nums = sorted(nums, reverse=True) # Sort the list in descending order return sorted_nums[1] # Return the second element (index 1) # Example usage numbers = [10, 30, 20, 40, 50] result = second_largest(numbers) if result is not None: print("Second largest element in the list:", result) else: print("The list has less than two elements.") Output: Second largest element in the list: 40
52
What is Python's GIL (Global Interpreter Lock)?
Reference answer
GIL is a mutex that protects access to Python objects, preventing multiple native threads from executing Python bytecodes at once in a single process. It's a limitation for multi-threaded applications.
53
What are ways to generate a random number in Python?
Reference answer
Developers use the 'random' module to generate a series of numbers. There are several statements a programmer can use to create different random number generators: - random.random – returns a floating value in the range from 1 to 10. - randrange(a,b) returns a random integer number within a given range. Note that the method doesn't create a range object. - uniform(a,b) returns a random float value located within a given range.
54
What is a function in Python?
Reference answer
A function in Python is a reusable block of code that performs a specific task. It is defined using the def keyword.
55
How do you handle exceptions in Python?
Reference answer
Exceptions in Python are handled using try, except, and optionally finally blocks. The try block encloses code that may raise an exception, and the except block specifies what to do if an exception is raised.
56
How can you balance the tradeoff between code readability and performance?
Reference answer
To balance the tradeoff between code readability and performance, it's important to prioritize readability when working on code that is likely to change frequently or be maintained by other developers. For code critical to performance, such as inner loops or frequently-called functions, it may be necessary to sacrifice some readability to achieve optimal performance.
57
What are Python's conditional statements?
Reference answer
Python uses if, elif, and else to execute code based on conditions. Example: age = 18 if age < 18: print("Minor") elif age == 18: print("Just turned adult") else: print("Adult")
58
Explain the differences between Python 2 and Python 3
Reference answer
| Python 2 | Python 3 | |---|---| | String Encoding Python 2 stores them as ASCII. Unicode is a superset of ASCII and hence, can encode more characters including foreign ones. | String Encoding Python 3 stores strings as Unicode by default. | | Division Python 2 division applies the floor function to the decimal output and returns an integer. So dividing 5 by 2 would return floor(2.5) = 2. | Division Division in Python 3 returns the expected output, even if it is in decimals. | | Printing Python 2 does not require parentheses. | Printing The syntax for the print statement is different in Python 2 and 3. Python 3 requires parentheses around what is to be printed. | | Libraries Many older libraries were built specifically for Python 2 and are not “forward compatible.” | Libraries Some newer libraries are built specifically for Python 3 and do not work with Python 2. | Python 2 is entrenched in the software landscape to the point that co-dependency between several softwares makes it almost impossible to make the shift.
59
What are the steps to create 1D, 2D and 3D arrays?
Reference answer
- 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 two_dimensional_list=[[1,2,3],[4,5,6]] two_dimensional_arr = np.array(two_dimensional_list) print("2D array is : ",two_dimensional_arr) - 3D array creation: import numpy as np three_dimensional_list=[[[1,2,3],[4,5,6],[7,8,9]]] three_dimensional_arr = np.array(three_dimensional_list) print("3D array is : ",three_dimensional_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 ndArray = np.array([1, 2, 3, 4], ndmin=6) print(ndArray) print('Dimensions of array:', ndArray.ndim)
60
How would you design a RESTful API in Python, and what libraries or frameworks would you use?
Reference answer
I would use Flask or FastAPI to create a RESTful API, implement CRUD operations with appropriate HTTP methods, and use libraries like SQLAlchemy for database interaction.
61
Write python function which takes a variable number of arguments.
Reference answer
A function that takes variable arguments is called a function prototype. Syntax: def function_name(*arg_list) For example: def func(*var): for i in var: print(i) func(1) func(20,1,6) The * in the function argument represents variable arguments in the function.
62
Write a Django view function to display a list of Book instances (from Question 1). Then, demonstrate how to configure the URL pattern for this view in Django's URL dispatcher.
Reference answer
# views.py from django.http import HttpResponse from .models import Book def book_list(request): books = Book.objects.all() output = ', '.join([book.title for book in books]) return HttpResponse(output) # urls.py from django.urls import path from . import views urlpatterns = [ path('books/', views.book_list, name='book_list'), ] Explanation of solution: A view function book_list is created in views.py. It retrieves all Book instances and returns a simple HTTP response with the titles. The URL pattern for this view is defined in urls.py, mapping the route 'books/' to the book_list view.
63
Write a Python program to check for a palindrome.
Reference answer
a=input("enter sequence") b=a[::-1] if a==b: print("palindrome") else: print("Not a Palindrome") Output: enter sequence 323 palindrome
64
How can you work with XML and JSON data in Python, and what are some libraries and modules for parsing and generating XML and JSON data?
Reference answer
Python provides libraries like `xml.etree.ElementTree` for XML and the `json` module for JSON``. You can parse, manipulate, and generate XML and JSON data with these libraries.
65
What is polymorphism in Python?
Reference answer
Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism.
66
How does Python handle memory management?
Reference answer
Python has automatic memory management based on reference counting and having a garbage collector to free unneeded memory.
67
What is a namespace?
Reference answer
Namespace is a naming system adopted in Python that helps developers avoid name duplicates. You can think of it like a Python dictionary where object names are the keys and the contents of an object are values.
68
How do you automate user interactions like clicking buttons, entering text, and submitting forms?
Reference answer
- Use corresponding methods like click(), send_keys(), and submit() on identified elements. - Consider handling JavaScript alerts and confirmations if encountered.
69
Write a Python function to convert Celsius to Fahrenheit.
Reference answer
Solution: def celsius_to_fahrenheit(celsius): fahrenheit = (celsius * 9/5) + 32 return fahrenheit # Example usage celsius_temperature = 25 fahrenheit_temperature = celsius_to_fahrenheit(celsius_temperature) print("Celsius:", celsius_temperature, "Fahrenheit:", fahrenheit_temperature) Output: Celsius: 25 Fahrenheit: 77.0
70
Explain the difference between lists and tuples in Python?
Reference answer
Lists and tuples are both used to store collections of items, but they have some key differences. Lists are mutable, meaning you can add, remove, or modify elements after creation. Tuples, on the other hand, are immutable, and once created, their elements cannot be changed. Lists are defined using square brackets [ ], while tuples are defined using parentheses ( ).
71
79. What is indexing and why is it important in databases?
Reference answer
An index offers an efficient way to quickly access the records from the database files stored. Indexing is the process of creating a data structure that improves the speed of data retrieval operations on a database. Indexes enhance performance, reduce the time it takes to fetch data, and ensure efficient use of resources. They also consume space and can slow down write operations. Therefore, it's essential to strike a balance: create indexes where they provide the most benefit and omit them where they can be counterproductive. Your engineers should not be hiring. They should be coding. Help your team focus on what they were hired for. Flexiple will manage your entire hiring process and scale your tech team.
72
74. How do you write raw SQL queries in Python?
Reference answer
To write raw SQL queries in Python, use the SQLite3 or SQLAlchemy libraries, which are commonly utilized for database interactions. A connection to the database is established, and then the cursor method is invoked to execute SQL statements. using the SQLite3 library, first establish a connection with `conn = sqlite3.connect('database_name.db')` and then create a cursor with `cursor = conn.cursor()`. Execute your SQL query using the `cursor.execute('YOUR_RAW_SQL_QUERY')` method. Always close the connection after operations to free up resources, especially in production environments. SQLAlchemy offers an Object Relational Mapper (ORM) layer; you can still bypass the ORM and execute raw SQL. Use the `text` function to ensure safety against SQL injection attacks. Obtain results by invoking the `execute` method on the engine or session object. Remember to handle exceptions and always ensure secure practices when interacting directly with databases. It's essential to be cautious about SQL injection attacks, regardless of the method or library. Utilize parameterized queries or the respective library's safety measures, like the `text` function in SQLAlchemy, to maintain security.
73
How would you get a user's home directory (~) in Python?
Reference answer
You can do this with the os module. import os print(os.path.expanduser('~')) This will return the path to the current user's directory.
74
What are nested loop,s and when are they used?
Reference answer
Nested loops are loops inside other loops, often used for working with matrices or multi-dimensional data. Example: matrix = [[1, 2], [3, 4]] for row in matrix: for val in row: print(val)
75
Write a Python function to find the maximum value in a list without using built-in functions.
Reference answer
def find_max(lst): max_value = lst[0] for num in lst: if num > max_value: max_value = num return max_value # Example usage: # print(find_max([3, 1, 4, 1, 5, 9, 2, 6, 5])) # Output: 9
76
Find the height of a binary search tree (BST)
Reference answer
Here you can use recursion to find the heights of the left and right sub-trees. To see the code solution in action, visit the original post. Explanation Here, we return -1 if the given node is None. Then, we call the findHeight() function on the left and right subtrees and return the one that has a greater value plus 1. We will not return 0 if the given node is None as the leaf node will have a height of 0. Time Complexity The time complexity of the code is O(n)O(n) as all the nodes of the entire tree have to be traversed.
77
What is a Python PATH?
Reference answer
This is an environment variable used to import a variable and check for the presence of variables present in different directories.
78
What type of language is Python?
Reference answer
Python is a general-purpose, object-oriented language. It is also an interpreted language.
79
What is monkey patching in Python?
Reference answer
Monkey patching in Python is a dynamic technique that can change the behavior of the code at run-time. In short, you can modify a class or module at run-time. Example: Let's learn monkey patching with an example. - We have created a class monkey with a patch() function. We have also created a monk_p function outside the class. - We will now replace the patch with the monk_p function by assigning monkey.patch to monk_p. - In the end, we will test the modification by creating the object using the monkey class and running the patch() function. Instead of displaying patch() is being called, it has displayed monk_p() is being called. class monkey: def patch(self): print ("patch() is being called") def monk_p(self): print ("monk_p() is being called") # replacing address of "patch" with "monk_p" monkey.patch = monk_p obj = monkey() obj.patch() # monk_p() is being called Caution: Use these sparingly; monkey patching can make your code harder to read and may surprise others working with your code or tests.
80
How does Python's compilation and interpretation process work?
Reference answer
Python utilizes a hybrid model. When a script runs, the interpreter first compiles high-level source code into bytecode, an intermediate platform-independent representation stored in __pycache__ directories as .pyc files. The Python Virtual Machine (PVM) then executes the bytecode by iterating through instructions and mapping them to machine-specific actions. The transformation follows standard compiler phases: lexical analysis (breaking code into tokens), syntax parsing (organizing tokens into an AST), semantic analysis (analyzing context), and bytecode generation. Python 3.11+ introduced the Specializing Adaptive Interpreter that optimizes 'hot' code by replacing generic bytecode with specialized versions. Python 3.13 introduced an experimental JIT compiler using 'copy-and-patch' architecture.
81
What are context managers in Python, and how are they implemented?
Reference answer
Context managers in Python are used to manage resources, ensuring that they are properly acquired and released. The most common use of context managers is the with statement, as you can see here: class FileManager: def __init__(self, filename, mode): self.filename = filename self.mode = mode def __enter__(self): self.file = open(self.filename, self.mode) return self.file def __exit__(self, exc_type, exc_value, traceback): self.file.close() with FileManager('test.txt', 'w') as f: f.write('Hello, world!') In this example, the FileManager class is a context manager that ensures the file is properly closed after it is used within the with statement.
82
What are some potential drawbacks of code optimization?
Reference answer
One potential drawback of code optimization is that it can make the code more complex and difficult to understand or maintain. Optimization can also make the code more difficult to debug or modify in the future and may not always result in a significant improvement in performance.
83
How did you handle database migrations and version control in your web projects, and did you encounter any database schema evolution challenges?
Reference answer
We used Django's built-in migration system. As the project evolved, we faced schema migration challenges, particularly when modifying existing tables. We handled these by creating data migration scripts to preserve existing data.
84
What is the Difference Between Python Scope and Namespace in Python
Reference answer
A Python scope defines where a name appears in your Python program. Python scopes work as dictionaries that map names to objects. These dictionaries are popularly known as namespaces. These are the conceptual mechanisms that Python uses to store names. Names at the module's top level are stored in the module's namespace. In other words, they are saved in the . dict__ attribute of the module.
85
25. What is a Python module, and how is it different from a package?
Reference answer
A Python module is a single file containing python code and a package is a collection of modules that are organized in directory hierarchy. Modules are created simply by writing a .py file with functions, classes, or variables. Reuse the code in a module by importing it into other scripts or modules. Packages contain multiple module files. They come with a special `__init__.py` file, enabling the directory to be considered as a package. This file is empty or has initialization code. You use packages to group related modules together, providing a namespace for the contained modules.
86
Create a Python class Rectangle with methods to calculate the area and perimeter.
Reference answer
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) # Example usage: # rect = Rectangle(4, 5) # print(rect.area()) # Output: 20 # print(rect.perimeter()) # Output: 18
87
List the functions which are used to modify the string in Python?
Reference answer
Split(), sub() and subn() are the functions that can be used to modify the strings in python.
88
Python Global Interpreter Lock (GIL)?
Reference answer
Python Global Interpreter Lock (GIL) is a mechanism used in the CPython interpreter that allows only one thread to execute Python bytecode at a time. This simplifies memory management and makes the interpreter thread-safe. - Python supports multithreading. - In CPython, only one thread can execute Python bytecode at a time because of the GIL. - The GIL mainly affects CPU-bound multithreaded programs. - I/O-bound programs can still benefit from multithreading. - Multiprocessing can be used to achieve true parallelism across multiple CPU cores.
89
What are decorators in Python?
Reference answer
Decorators are used to add some design patterns to a function without changing its structure. Decorators generally are defined before the function they are enhancing. To apply a decorator we first define the decorator function. Then we write the function it is applied to and simply add the decorator function above the function it has to be applied to. For this, we use the @ symbol before the decorator.
90
What is the purpose of the .pivot_table() method in Pandas?
Reference answer
The `.pivot_table()` method is used to create a pivot table from a DataFrame, summarizing and aggregating data based on specified columns and functions.
91
Write a Python function to calculate the factorial of a number.
Reference answer
Solution: With Function: def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) # Example usage number = 5 result = factorial(number) print("Factorial of", number, "is", result) Output: Factorial of 5 is 120 Without Function: number = 5 factorial = 1 if number < 0: print("Factorial is not defined for negative numbers.") elif number == 0: print("Factorial of 0 is 1") else: for i in range(1, number + 1): factorial *= i print("Factorial of", number, "is", factorial) Output: Factorial of 5 is 120
92
How would you use the ternary operators in Python?
Reference answer
Ternary operators are also known as conditional expressions. They are operators that evaluate expressions based on conditions being True and False. You can write conditional expressions in a single line instead of writing using multiple lines of if-else statements. It allows you to write clean and compact code. For example, we can convert nested if-else statements into one line, as shown below. If-else statement score = 75 if score < 70: if score < 50: print('Fail') else: print('Merit') else: print('Distinction') # Distinction Nested Ternary Operator print('Fail' if score < 50 else 'Merit' if score < 70 else 'Distinction') # Distinction
93
How do you handle I/O-bound tasks efficiently in Python?
Reference answer
For I/O bound tasks (like file operations or network), use multithreading or asynchronous code to improve performance. Example (multithreading): import threading def download_file(url): # Code to download file from URL pass # Create and start the thread thread = threading.Thread(target=download_file, args=('https://example.com/file',)) thread.start() # Wait for the thread to finish thread.join()
94
What is a coroutine in Python?
Reference answer
A coroutine is a specialized version of a Python generator that allows for asynchronous programming, using the async/await syntax.
95
How does Python manage memory?
Reference answer
Python uses automatic memory management, which involves: - Reference Counting: Tracks the number of references to an object. - Garbage Collection: Frees memory of unused objects automatically when the reference count reaches zero.
96
What Tools Can You Use to Unit Test Your Python Code?
Reference answer
There is a standard tool called Unittest within the standard Python package.
97
What is the map function in Python?
Reference answer
map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given.
98
Write a Python program to convert a decimal number to binary.
Reference answer
You can use a function called decimal_to_binary to convert a decimal number into its binary representation as a string. def decimal_to_binary(decimal): return bin(decimal)[2:] print(decimal_to_binary(10)) # 1010 Output: '1010'
99
Multiple Choice Question: When is the else part of a try-except block executed? a) always b) when an exception occurs c) when no exception occurs d) when an exception occurs in except block
Reference answer
Answer: c) when no exception occurs The else part is executed when no exception occurs.
100
What is monkey patching in Python?
Reference answer
In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time. Consider the below example: # m.py class MyClass: def f(self): print "f()" We can then run the monkey-patch testing like this: import m def monkey_f(self): print "monkey_f()" m.MyClass.f = monkey_f obj = m.MyClass() obj.f() The output will be as below: monkey_f() As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m.
101
Python program to print following ‘*' pattern: **** *** ** *
Reference answer
def pattern(rows): for i in range(rows, 0, -1): print("*" * i) # Take input from the user num_rows = int(input("Enter the number of rows: ")) # Call the function to print the pattern pattern(num_rows)
102
How do you run another command/program from a Python script?
Reference answer
You can run other commands using the subprocess module, this is very useful in automation where you need to call git, docker, ls, or any system tool, it lets you capture output, errors, and exit codes, this is much safer than old methods like os.system. import subprocess result = subprocess.run(["ls"], capture_output=True, text=True) print(result.stdout)
103
How can you modify strings in Python?
Reference answer
To modify the strings, Python's “re” module is providing 3 methods. They are:
104
Explain the while loop in Python.
Reference answer
A while loop repeatedly executes a block of code as long as a specified condition is true.
105
How would you approach solving a complex problem in Python?
Reference answer
Break down the problem into smaller, manageable parts, write pseudocode, implement step-by-step, and test each part thoroughly.
106
63. What is a hash table, and how does it work in Python?
Reference answer
A Hash Table in Python utilizes an array as a medium of storage and uses the hash method to create an index where an element is to be searched from or needs to be inserted. Hash table works by using a hash function to map keys to specific locations, making it quick to find values associated with those keys. The built-in `dict` type is used to implement hash tables In Python. Python computes a hash code for the key using its hash function, when you add a key-value pair to a dictionary. This hash code determines the index where the value associated with that key will be stored. Python calculates the hash code again, locates the corresponding index, and returns the value, When you later want to retrieve the value for a given key. This process is extremely fast, making hash tables an efficient way to perform lookups, insertions, and deletions. Hash tables can encounter collisions, where two different keys produce the same hash code. Python uses techniques like chaining or open addressing to handle the collisions. Chaining involves storing multiple key-value pairs at the same index in a linked list, while open addressing searches for the next available slot if a collision occurs.
107
What is scope in Python?
Reference answer
All objects in Python have a scope. Scope is the block of code where the variable is accessible. Here are some scope designations in Python: • Local scope: Local objects available in the current function. • Global scope: Objects available through the code execution since their inception. • Module-level scope: Global objects of the current module accessible in the program. • Outermost scope: Built-in names callable in the program.
108
70. What is a graph, and how is it represented in Python?
Reference answer
Graph is a network consisting of nodes connected by edges or arcs. A graph is a data structure that consists of a finite set of vertices and a set of edges connecting these vertices. Graphs are represented using dictionaries or adjacency matrices in Python. An adjacency list uses a dictionary where keys represent vertices and values are lists of neighboring vertices. A two-dimensional array or matrix is utilized for adjacency matrices; the rows represent source vertices, the columns represent destination vertices, and the value at a matrix's cell indicates the presence or weight of an edge. Graph libraries, such as NetworkX, simplify the creation, manipulation, and study of complex networks in Python. One can easily model both directed and undirected graphs, using NetworkX. It's crucial to understand their type and properties, as this impacts algorithms and operations applied to them, when representing graphs. For example, a traversal in a directed graph differs from that in an undirected one. It's also essential to consider whether the graph is weighted or not, as this can influence paths and shortest route calculations.
109
How do you copy an object in Python?
Reference answer
In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between the existing object and the target variable name. To create copies of an object in Python, we need to use the copy module. Moreover, there are two ways of creating copies for the given object using the copy module - Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values is a reference to other objects, just the reference addresses for the same are copied. Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object. from copy import copy, deepcopy list_1 = [1, 2, [3, 5], 4] ## shallow copy list_2 = copy(list_1) list_2[3] = 7 list_2[2].append(6) list_2 # output => [1, 2, [3, 5, 6], 7] list_1 # output => [1, 2, [3, 5, 6], 4] ## deep copy list_3 = deepcopy(list_1) list_3[3] = 8 list_3[2].append(7) list_3 # output => [1, 2, [3, 5, 6, 7], 8] list_1 # output => [1, 2, [3, 5, 6], 4]
110
How can you handle exceptions in Python, and why is exception handling important?
Reference answer
In Python, exceptions can be handled using try, except, else, and finally blocks. Exception handling is crucial for preventing program crashes and providing informative error messages to users or developers, making debugging easier.
111
What are Python lists and tuples?
Reference answer
Lists and tuples are fundamental Python data structures with distinct characteristics and use cases. List: - Mutable: Elements can be changed after creation. - Memory Usage: Consumes more memory. - Performance: Slower iteration compared to tuples but better for insertion and deletion operations. - Methods: Offers various built-in methods for manipulation. Example: a_list = ["Data", "Camp", "Tutorial"] a_list.append("Session") print(a_list) # Output: ['Data', 'Camp', 'Tutorial', 'Session'] Tuple: - Immutable: Elements cannot be changed after creation. - Memory Usage: Consumes less memory. - Performance: Faster iteration compared to lists but lacks the flexibility of lists. - Methods: Limited built-in methods. Example: a_tuple = ("Data", "Camp", "Tutorial") print(a_tuple) # Output: ('Data', 'Camp', 'Tutorial')
112
Write a one-liner to count the number of uppercase letters in a file.
Reference answer
Let us first write a multiple line solution and then convert it to one-liner code. with open(SOME_LARGE_FILE) as fh: count = 0 text = fh.read() for character in text: if character.isupper(): count += 1 We will now try to transform this into a single line. count sum(1 for line in fh for character in line if character.isupper())
113
How do you import and use modules in Python?
Reference answer
- Use the import keyword to import specific modules or functions from libraries. - Use aliases to avoid long module names.
114
What are the benefits of using Python for data science and machine learning projects?
Reference answer
Python's vast ecosystem of data science and machine learning libraries, such as NumPy, Pandas, scikit-learn, and TensorFlow, make it a preferred choice for data science projects. Its simple syntax and ease of integration with other tools also contribute to its popularity.
115
What is the purpose of the asyncio library in Python, and how does it enable asynchronous programming?
Reference answer
The `asyncio` library allows asynchronous I/O, making it possible to write concurrent code that performs I/O-bound tasks without blocking the event loop.
116
What is the difference between a mutable data type and an immutable data type?
Reference answer
Mutable data types: - Definition: Mutable data types are those that can be modified after their creation. - Examples: List, Dictionary, Set. - Characteristics: Elements can be added, removed, or changed. - Use Case: Suitable for collections of items where frequent updates are needed. Example: # List Example a_list = [1, 2, 3] a_list.append(4) print(a_list) # Output: [1, 2, 3, 4] # Dictionary Example a_dict = {'a': 1, 'b': 2} a_dict['c'] = 3 print(a_dict) # Output: {'a': 1, 'b': 2, 'c': 3} Immutable data types: - Definition: Immutable data types are those that cannot be modified after their creation. - Examples: Numeric (int, float), String, Tuple. - Characteristics: Elements cannot be changed once set; any operation that appears to modify an immutable object will create a new object. Example: # Numeric Example a_num = 10 a_num = 20 # Creates a new integer object print(a_num) # Output: 20 # String Example a_str = "hello" a_str = "world" # Creates a new string object print(a_str) # Output: world # Tuple Example a_tuple = (1, 2, 3) # a_tuple[0] = 4 # This will raise a TypeError print(a_tuple) # Output: (1, 2, 3)
117
Explain how can you make a Python Script executable on Unix?
Reference answer
- Script file must begin with #!/usr/bin/env python
118
What are Decorators?
Reference answer
Decorators is a flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are often used in scenarios such as logging, authentication and memorization, allowing us to add additional functionality to existing functions or methods in a clean, reusable way.
119
Can we override the dir() function behaviour?
Reference answer
Yes, you can. By overriding __dir__ function.
120
What is slicing in Python?
Reference answer
- As the name suggests, 'slicing' is taking parts of. - Syntax for slicing is [start : stop : step] - start is the starting index from where to slice a list or tuple - stop is the ending index or where to sop. - step is the number of steps to jump. - Default value for start is 0, stop is number of items, step is 1. - Slicing can be done on strings, arrays, lists, and tuples. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10]
121
68. How would you explain the difference between linear and binary search?
Reference answer
The difference between the linear search and binary search is that Linear Search sequentially checks each element in the list until it finds a match or exhausts the list. Binary Search continuously divides the sorted list, comparing the middle element with the target value. Linear search involves sequentially checking each element in a list or array until a match is found. It starts from the beginning and continues until either the desired element is located or the entire list is traversed. Linear search is straightforward and easy to implement, but its time complexity is O(n), where n is the number of elements in the list. In the worst case scenario, it may need to inspect every element. Binary search is a more efficient algorithm for finding an element in a sorted list or array. It follows a divide-and-conquer approach. Binary search begins by comparing the target value with the middle element of the sorted list. The search is complete, if the middle element matches the target. The search continues in the lower half of the list, If the target is less than the middle element; the search continues in the upper half, if it's greater. This process repeats, cutting the search space in half with each iteration. Binary search has a time complexity of O(log n), making it significantly faster than linear search for large datasets.
122
What is the difference between an inner join and an outer join in Pandas?
Reference answer
In an inner join``, only the common rows between two DataFrames are included in the result. In an outer join``, all rows from both DataFrames are included, and missing values are filled with NaN.
123
What is self in Python?
Reference answer
In Python, self represents the object or instance of a class when referring to itself internally. In other languages, this variable is often called this. In Python classes, you must explicitly pass self as the first parameter in methods. class Car(): def __init__(self, model, color): self.model = model self.color = color def display(self): print("Model is", self.model ) print("color is", self.color )
124
Why is Python best for scripting?
Reference answer
Due to its Short and Simple Syntax, Python can we easily used for Scripting purpose.
125
How to do 3D plotting in Python?
Reference answer
Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine.
126
What is the crosstab() function in Pandas, and how is it used?
Reference answer
The `crosstab()` function is used to compute a cross-tabulation table that shows the frequency of variables in a DataFrame. It is helpful for categorical data analysis.
127
How do you use Pytest or Unittest for testing in Python?
Reference answer
Both of these are tools for writing and running tests. Example (Pytest): def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 # Run the test test_add() print("Test passed!")
128
The following code is supposed to create a class for a basic calculator, but it is not working correctly. Fix the code. class Calculator: def __init__(self): self.result = 0 def add(self, num1, num2): self.result = num1 + num2 def subtract(self, num1, num2): self.result = num1 - num2
Reference answer
The add and subtract methods are not actually returning any values, so they are not useful for external code that wants to use the calculator. To fix this, we can modify the methods to return the result instead of storing it as an attribute of the object: class Calculator: def __init__(self): self.result = 0 def add(self, num1, num2): return num1 + num2 def subtract(self, num1, num2): return num1 - num2
129
What are Python dictionary and list comprehensions?
Reference answer
Comprehensions in Python are like decorators. They are what is called syntactic sugar that helps create filtered and modified lists and dictionaries from existing lists, dictionaries, or sets. They are handy and quick because you can write them in one line of code. the_list = [2, 3, 5, 7, 11] # list comprehension squared_list = [x**2 for x in the_list] # output is [4 , 9 , 25 , 49 , 121] # dict comprehension squared_dict = {x:x**2 for x in the_list} # output is {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49}
130
Explain the concept of method resolution order (MRO) in Python, and how does it affect class inheritance in multiple inheritance scenarios?
Reference answer
MRO determines the order in which base classes are searched for attributes. It``'s resolved using the C3 linearization algorithm and affects attribute lookup in multiple inheritance.
131
Multiple Choice Question: What is the maximum length of a Python identifier? a) 32 characters b) 16 characters c) 8 characters d) None of the above
Reference answer
Answer: d) None of the above Identifiers can be of any length.
132
Write a code in Python that implements a simple calculator.
Reference answer
def calculator(a, b, operation): if operation == 'add': return a + b elif operation == 'subtract': return a - b elif operation == 'multiply': return a * b elif operation == 'divide': return a / b if b != 0 else "Cannot divide by zero" else: return "Invalid operation" print(calculator(5, 3, 'add')) # 8 print(calculator(5, 0, 'divide')) # Cannot divide by zero print(calculator(5, 3, 'multiply')) # 15
133
What is hashability and why is it important in Python?
Reference answer
Only immutable objects can serve as dictionary keys or set elements because their hash values must remain constant. For example, strings and tuples can be used as keys, but lists and dictionaries cannot. Misunderstanding this can lead to runtime errors, especially in production code.
134
Can the String Be Split into Dictionary Words?
Reference answer
You are provided with a large string and a dictionary of the words. You have to find if the input string can be segmented into words using the dictionary or not. The solution is reasonably straightforward. You have to segment a large string at each point and check if the string can be segmented to the words in the dictionary. - Run the loop using the length of the large string. - We will create two substrings. - The first substring will check each point in the large string from s[0:i]. - If the first substring is not in the dictionary, it will return False. - If the first substring is in the dictionary, it will create the second substring using s[i:]. - If the second substring is in the dictionary or the second substring is of zero length, then return True. Recursively call can_segment_str() with the second substring and return True if it can be segmented. - To make the solution efficient for longer strings, we add memoization so substrings are not recomputed again and again. def can_segment_str(s, dictionary, memo=None): if memo is None: memo = {} if s in memo: return memo[s] if not s: return True for i in range(1, len(s) + 1): first_str = s[0:i] if first_str in dictionary: second_str = s[i:] if ( not second_str or second_str in dictionary or can_segment_str(second_str, dictionary, memo) ): memo[s] = True return True memo[s] = False return False s = "datacamp" dictionary = ["data", "camp", "cam", "lack"] can_segment_str(s, dictionary) # True
135
What is the use of *args and **kwargs in Python?
Reference answer
We use *args when we aren't sure how many arguments are going to be passed to a function, or if we want to pass a stored list or tuple of arguments to a function. **kwargs is used when we don't know how many keyword arguments will be passed to a function, or it can be used to pass the values of a dictionary as keyword arguments. The identifiers args and kwargs are a convention, you could also use *bob and **billy but that would not be wise.
136
Write a Python function to find the maximum product of two integers in a list.
Reference answer
Sample Answer: To find the maximum product of two integers in a list, you need to consider both the two largest numbers and the two smallest numbers (in the case of negative integers, their product can be larger). This approach ensures that you capture all potential pairs that could yield the highest product. Here's how you can write a Python function to find the maximum product of two integers in a given list: def max_product(lst): if len(lst) < 2: return None # Not enough elements to form a product # Sort the list to easily access the largest and smallest values lst.sort() # Calculate the product of the two largest and two smallest numbers return max(lst[-1] * lst[-2], lst[0] * lst[1])
137
Explain the different Selenium WebDriver options available (Chrome, Firefox, etc.).
Reference answer
- Each WebDriver interacts with a specific browser. Choose based on project requirements and compatibility. - Some popular options include ChromeDriver, FirefoxDriver, EdgeDriver.
138
Write a Python function to find the least common multiple (LCM) of two numbers.
Reference answer
Solution: import math def lcm(a, b): return abs(a * b) // math.gcd(a, b) # Example usage num1 = 12 num2 = 18 result = lcm(num1, num2) print("LCM of", num1, "and", num2, "is", result) Output: LCM of 12 and 18 is 36
139
What is method resolution order (MRO) in Python, and how is it determined for classes with multiple inheritance?
Reference answer
MRO determines the order in which base classes are searched for a method or attribute. It``'s determined using the C3 linearization algorithm in Python.
140
How would you debug a memory leak in a Python application?
Reference answer
Use tools like objgraph, gc module, or tracemalloc to trace memory allocations and identify references preventing garbage collection.
141
What is a variable in Python?
Reference answer
A variable is a name used to store data values. In Python, you can create a variable like this: x = 10
142
What is PEP8? Do You Think it is Worth Following?
Reference answer
PEP or Python Enhancement Proposal is a document explaining the latest key features of Python introduced and standard practices recommended for Python. The latest PEP document is the PEP 693 released in May 2022. PEP 8 is a style guide created in 2001 to codify Python development to make it more readable, manageable, and consistent. The answer to the second half of this Python interview question should be a resounding yes.
143
What is a generator in Python, and how does it differ from a list?
Reference answer
A generator is an iterable that generates values on-the-fly, saving memory compared to creating a full list of values. Generators are defined using functions with the yield keyword.
144
How do you debug a Python program?
Reference answer
1. Using pdb (Python Debugger): pdb is a built-in module that allows you to set breakpoints and step through the code line by line. You can start the debugger by adding import pdb; pdb.set_trace() in your code where you want to begin debugging. import pdb x = 5 pdb.set_trace() # Debugger starts here print(x) Output > /home/repl/02c07243-5df9-4fb0-a2cd-54fe6d597c80/main.py(4)() -> print(x) (Pdb) 2. Using logging Module: For more advanced debugging, the logging module provides a flexible way to log messages with different severity levels (INFO, DEBUG, WARNING, ERROR, CRITICAL). import logging logging.basicConfig(level=logging.DEBUG) logging.debug("This is a debug message") Output DEBUG:root:This is a debug message
145
Which Python Web Framework Do You Prefer and Why?
Reference answer
There are numerous frameworks so the answers may vary greatly. However, the most popular Python web frameworks are: - Django: it is a full-stack library, meaning it has everything for web development - CherryPy: it is a web server framework only, so it is less complex. It is good for prototyping - Pyramid: it is a lighter alternative to Django, with fewer functions but a more flexible one - Flask: it is mostly used to create simple web applications It is not really a typical question of preference but the question of using the right tool for the right project. So it is one of the tricky Python advanced interview questions.
146
Explain the concept of context managers in Python.
Reference answer
- Provide safe and efficient handling of resources like files, databases, or network connections. - Use the with statement to automatically perform resource allocation upon entering the block and deallocation upon exiting, even if exceptions occur. - Ensures resources are properly closed and prevents leaks. - Python Example: with open('file.txt', 'r') as file: content = file.read()
147
What is the difference between a list and a tuple in Python?
Reference answer
Lists are mutable i.e., they can be edited. Tuples are immutable, meaning they cannot be edited after creation. Lists are slower than tuples. Tuples are faster than lists. Syntax: list_1 = [10, 'Chelsea', 20] Syntax: tup_1 = (10, 'Chelsea', 20)
148
Write the python code to append operation in existing file ?
Reference answer
#Appending operation file = open("file.txt", "a") file.write("\nHello we are PrepInsta.") file.write("\nPrepInsta and PrepInsta Prime.") contents = file.read() print(contents) file.close()
149
Why is finalize used?
Reference answer
Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks.
150
Write a Python function to find all prime numbers in a given range.
Reference answer
Solution: def is_prime(num): if num <= 1: return False for i in range(2, int(num ** 0.5) + 1): if num % i == 0: return False return True def find_primes(start, end): primes = [] for num in range(start, end + 1): if is_prime(num): primes.append(num) return primes # Example usage start_range = 1 end_range = 50 prime_numbers = find_primes(start_range, end_range) print("Prime numbers between", start_range, "and", end_range, "are:", prime_numbers) Output: Prime numbers between 1 and 50 are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
151
What is the difference between class variables and instance variables?
Reference answer
Class variables are shared across all instances of a class, whereas instance variables are specific to each object instance. Class variables are defined within the class but outside any methods.
152
What is a Python Docstring?
Reference answer
The Python docstrings provide a suitable way of associating documentation with: - Python modules - Python functions - Python classes It is a specified document for the written code. Unlike conventional code comments, the doctoring should describe what a function does, not how it works. The docstring can be accessed using - __doc__ method of the object - help function Example def Examplefunc(str): #function that outputs the str parameter print "The value is", str #no return statement needed in this function def Multiply(x,y): #function that computes the product of x and y return x*y #returning the product of x and y #Calling the functions Examplefunc(9) #9 passed as the parameter) answer = Multiply(4,2) #4 and 2 passed as the parameters print "The product of x and y is:",answer Output: The value is 9 The product of x and y is: 8 Explanation The function Examplefunc above takes a variable str as parameter and then prints this value. Since it only prints the value there is no need for a return command. The function Multiply takes two parameters x and y as parameters. It then computes the product and uses the return statement to return back the answer.
153
How can you achieve multithreading in Python, and why is it beneficial?
Reference answer
Multithreading in Python can be achieved using the threading module. It allows concurrent execution of multiple threads, which is beneficial for utilizing multiple CPU cores and improving the performance of I/O-bound tasks.
154
Implement a stack data structure in Python using lists. Your stack should support push, pop, and peek operations.
Reference answer
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def peek(self): return self.items[-1] if self.items else None def is_empty(self): return len(self.items) == 0 Explanation of solution: The Stack class uses a Python list to store elements. push adds an item to the end of the list, pop removes the last item, and peek returns the last item without removing it. is_empty checks whether the stack is empty, which is crucial for the subsequent questions.
155
Write a Python function to check if a string or number is a palindrome.
Reference answer
Solution: For String: def is_palindrome(s): # Remove spaces and convert to lowercase for case-insensitive comparison s = s.replace(" ", "").lower() return s == s[::-1] # Example usage input_string = "A man, a plan, a canal, Panama" if is_palindrome(input_string): print("The string is a palindrome.") else: print("The string is not a palindrome.") Output: The string is not a palindrome. For Number: def is_palindrome(number): # Convert number to string for easy manipulation num_str = str(number) return num_str == num_str[::-1] # Example usage input_number = 12321 if is_palindrome(input_number): print("The number is a palindrome.") else: print("The number is not a palindrome.") Output: The number is not a palindrome.
156
What is the purpose of the collections module in Python, and can you name some useful data structures it provides?
Reference answer
The collections module offers specialized container datatypes like deque, Counter, and namedtuple for various use cases.
157
This code is supposed to create a metaclass that allows classes to be initialized with a dictionary of attributes. Fix the code. class DictMeta(type): def __new__(mcs, name, bases, attrs): obj = super().__new__(mcs, name, bases, attrs) obj.__dict__.update(attrs) return obj class MyClass(metaclass=DictMeta): def __init__(self, data): self.data = data my_instance = MyClass({'name': 'Alice', 'age': 28}) print(my_instance.name, my_instance.age)
Reference answer
class DictMeta(type): def __new__(mcs, name, bases, attrs, **kwargs): new_attrs = {} for key, value in attrs.items(): if isinstance(value, dict): new_attrs.update(value) else: new_attrs[key] = value return super().__new__(mcs, name, bases, new_attrs) class MyClass(metaclass=DictMeta): def __init__(self, name=None, age=None): self.name = name self.age = age my_instance = MyClass({'name': 'Alice', 'age': 28}) print(my_instance.name, my_instance.age) In the DictMeta class, the __new__ method should call __init__ instead of obj.__dict__.update(attrs) to properly initialize the attributes of the class. In the MyClass class, the __init__ method should update the __dict__ attribute of the instance with the data parameter to properly initialize the instance attributes.
158
What is map() function ?
Reference answer
map() function in Python is a built-in function that allows you to apply a specified function to every item in one or more iterable objects, such as lists, tuples, or strings. It takes in two or more arguments: the function to be applied and the iterable(s) on which the function should operate.
159
Write a Python function to check if a number is a power of two.
Reference answer
Solution: def is_power_of_two(number): if number <= 0: return False # Numbers less than or equal to 0 are not powers of two while number > 1: if number % 2 != 0: return False # If the number is not divisible by 2, it's not a power of two number //= 2 return True # Example usage number = 16 if is_power_of_two(number): print(number, "is a power of two.") else: print(number, "is not a power of two.") Output: 16 is a power of two.
160
How do you import external libraries in Python?
Reference answer
- Use import statement to import modules: import module_name
161
What are list comprehensions, and why are they used?
Reference answer
Creating lists with list comprehensions is concise. Traditional for loops are more readable and often faster than this. Example: squares = [x**2 for x in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
162
What are Generators in Python?
Reference answer
Generators are a simple and memory-efficient way to create iterators in Python. They generate values one at a time only when needed, rather than storing all values in memory at once. A function becomes a generator if it contains the yield statement. Each time yield is executed, the function returns a value and pauses its execution. When the next value is requested, execution resumes from where it left off. Generators automatically implement the __iter__() and __next__() methods, which allows them to be used directly in loops and with the next() function.
163
How can you check if a graph is connected in Python?
Reference answer
A graph is connected if there is a path between any two vertices. You can check if a graph is connected in Python by performing DFS or BFS from any vertex and checking if all the vertices are visited.
164
What do you know about PEP 8? Why is it considered to be important?
Reference answer
PEP 8 is python's style guide which has set of rules for how to format your python code.It is considered to be important because it shows how python code should be formatted.
165
Can you list Python's primary built-in data types, in categories?
Reference answer
Text Type: str Numeric Types: int,float,complex Sequence Types: list,tuple,range Mapping Type: dict Set Types: set,frozenset Boolean Type: bool Binary Types: bytes,bytearray,memoryview
166
Multiple Choice Question: What is the correct syntax for floor division? a) / b) // c) % d) None of the above
Reference answer
Answer: b) // When both of the operands are integer then python chops out the fraction part and gives you the round off value, to get the accurate answer use floor division. For ex, 5/2 = 2.5 but both of the operands are integer so answer of this expression in python is 2. To get the 2.5 as the answer, use floor division using //. So, 5//2 = 2.5
167
How do you handle and log exceptions in Python to aid in debugging?
Reference answer
In Python, you can use the logging module to handle and log exceptions. This module allows you to configure logging levels, capture exception details, and write logs to files or other destinations. Properly logging exceptions can help in debugging and monitoring the application's behavior.
168
What is pickling and unpickling in Python?
Reference answer
Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling.
169
What design patterns in Python are important for scalability?
Reference answer
Understanding design patterns is crucial for developing scalable Python applications. Key patterns include: - Singleton Pattern: Ensures a class has only one instance, useful for managing connections to a database or configuration file. - Factory Method Pattern: Creates objects without specifying the exact class, promoting loose coupling and easier maintenance for scalability. - Adapter Pattern: Enables communication between two incompatible interfaces, allowing integration of new functionalities without disrupting existing code. - Strategy Pattern: Defines a family of algorithms, encapsulates each, and makes them interchangeable, allowing the algorithm to vary independently from clients. - Observer Pattern: Used for one-to-many dependencies, where when one object changes state, all dependents are notified and updated automatically, great for event-driven systems. - Decorator Pattern: Adds behavior to an individual object without affecting others, useful for extending functionality without modifying structure. - MVC (Model-View-Controller) Pattern: Separates application into Model (data), View (display), and Controller (input mediation), improving scalability by decoupling data handling, UI, and user input.
170
Explain the concept of class and object in Python.
Reference answer
- Classes define blueprints for objects (instances) with attributes and methods. - Objects represent specific instances of a class with unique attribute values.
171
What is the use of help() and dir() functions in Python?
Reference answer
Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
172
What is the difference between @classmethod, @staticmethod and instance methods in Python?
Reference answer
- Instance Method: Operates on an instance of the class and has access to instance attributes and takes self as the first parameter. - Class Method: Works with the class and takes cls as the first parameter. It is defined using @classmethod. - Static Method: Does not access instance (self) or class (cls) data. It is defined using @staticmethod and is commonly used for utility functions related to the class. Example: class Student: school = "ABC School" # Instance method def display(self, name): print(f"Student Name: {name}") # Class method @classmethod def show_school(cls): print(f"School: {cls.school}") # Static method @staticmethod def is_adult(age): return age >= 18 s = Student() # Instance method s.display("Kevin") # Class method Student.show_school() # Static method print(Student.is_adult(20)) Output Student Name: Kevin School: ABC School True
173
What is TensorFlow or PyTorch used for?
Reference answer
Both are libraries that are used for machine learning and deep learning. Example (PyTorch): import torch # Create a PyTorch tensor x = torch.tensor([1.0, 2.0, 3.0]) # Multiply tensor by 2 print(x * 2) # tensor([2., 4., 6.])
174
Did you encounter any trade-offs between optimization and code maintainability? If so, how did you balance them?
Reference answer
Yes, there were trade-offs. In some cases, we had to sacrifice code readability for performance. To balance this, we heavily commented the optimized sections and used meaningful variable names to make the code maintainable.
175
How do you sort a DataFrame by a specific column in Pandas?
Reference answer
You can use the `.sort_values()` method to sort a DataFrame by one or more columns, specifying the column(s) by which to sort.
176
Make a linear search program in python.
Reference answer
def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i return -1 elements = input("Enter the list of numbers = ").split() target = int(input("Enter the number to be searched = ")) arr = [int(element) for element in elements] arr = sorted(arr) print("Sorted Array = ",arr) index = linear_search(arr, target) if index != -1: print(f"{target} is at index {index}") else: print(f"{target} is not present in list")
177
Write a function in Python to reverse a string.
Reference answer
def reverse_string(s): return s[::-1] # Example usage: # print(reverse_string("hello")) # Output: "olleh"
178
What are lists and tuples? What is the key difference between the two?
Reference answer
Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97). But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference: my_tuple = ('sara', 6, 5, 0.97) my_list = ['sara', 6, 5, 0.97] print(my_tuple[0]) # output => 'sara' print(my_list[0]) # output => 'sara' my_tuple[0] = 'ansh' # modifying tuple => throws an error my_list[0] = 'ansh' # modifying list => list modified print(my_tuple[0]) # output => 'sara' print(my_list[0]) # output => 'ansh'
179
Explain the purpose of the try, except, and finally blocks in exception handling in Python.
Reference answer
The `try` block encloses code that may raise an exception. The `except` block is used to handle specific exceptions. The `finally` block is executed regardless of whether an exception is raised and is used for cleanup.
180
Is Python an object-oriented programming language?
Reference answer
Python is an object-oriented programming language. This means that any program can be solved in python by creating an object model. However, Python can be treated as a procedural as well as structural language.
181
Explain the difference between == and is operators.
Reference answer
- == checks values for equality. - is checks object identity (same location in memory).
182
Calculate the sum of all the digits in a number
Reference answer
Output : Sum of digits : 5
183
How do you handle file I/O errors and exceptions in Python when working with files?
Reference answer
When working with files in Python, you should handle file I/O errors and exceptions to prevent unexpected crashes or data corruption. You can use the try-except block to catch exceptions that may occur during file operations and handle them gracefully. Example: try: with open(file.txt', r') as file: content = file.read() except FileNotFoundError: print(File not found.;) except IOError as e: print(f;An I/O error occurred: {e};)
184
Explain the difference between deep copy and shallow copy.
Reference answer
- Shallow Copy: Creates a new object but inserts references to the original objects' contents. Changes in nested objects affect both copies. - Deep Copy: Creates a new object and recursively copies all objects inside it. Changes in the original do not affect the deep copy. Example: import copy list1 = [[1, 2], [3, 4]] shallow = copy.copy(list1) deep = copy.deepcopy(list1) shallow[0][0] = 100 # Affects list1 deep[0][0] = 200 # Does not affect list1
185
41. How to write a Python program to read a file line by line and store it in a list?
Reference answer
To write a Python program that reads a file line by line and stores it in a list, use the built-in `open` function and a list comprehension. First, open the file in read mode using the `open` function. Use a list comprehension to iterate over each line, with the file object. This approach ensures that each line from the file gets appended to the list. Here's a concise example: In this program, the `with` statement manages the file's context, ensuring it's properly closed after reading. The `strip` method removes any trailing newline characters, ensuring clean data storage in the list.
186
Differentiate between a package and a module in python.
Reference answer
The module is a single python file. A module can import other modules (other python files) as objects. Whereas, a package is the folder/directory where different sub-packages and the modules reside. A python module is created by saving a file with the extension of .py. This file will have classes and functions that are reusable in the code as well as across modules. A python package is created by following the below steps: - Create a directory and give a valid name that represents its operation. - Place modules of one kind in this directory. - Create __init__.py file in this directory. This lets python know the directory we created is a package. The contents of this package can be imported across different modules in other packages to reuse the functionality.
187
What is the difference between mutable and immutable objects in Python?
Reference answer
- Mutable: Can be changed after creation (e.g., list, dict, set). - Immutable: Cannot be changed after creation (e.g., int, tuple, str). Example: mutable_list = [1, 2, 3] mutable_list[0] = 100 # Allowed immutable_tuple = (1, 2, 3) # immutable_tuple[0] = 100 # Raises TypeError
188
What is a Package in Python?
Reference answer
A package is a collection of different related modules. It normally contains a file with the name init . py.
189
40. How to implement a queue in Python?
Reference answer
A queue is implemented in Python using the collections module's `deque` class. The `deque` class provides methods like `append()` and `popleft()`, which is used to add elements to the rear and remove elements from the front, respectively. This mimics the behavior of a standard First In, First Out (FIFO) queue. For example, to enqueue an item, you use `append()`, and to dequeue an item, you use `popleft()`. Python's standard library also offers the `queue` module, which provides different types of queues, including a basic FIFO queue. The `deque` class suffices and is efficient due to its double-ended nature, for most scenarios. Remember to always use the appropriate data structure based on specific requirements and performance considerations.
190
How are comments written in Python?
Reference answer
Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes). Example: #Comments in Python start like this print("Comments in Python start with a #") Output: Comments in Python start with a #
191
How can you count the occurrences of each character in a string?
Reference answer
Sample Answer: Counting the occurrences of each character in a string can be useful for various text analysis tasks, such as frequency analysis or data compression. A convenient way to achieve this in Python is by using the 'collections.Counter', which efficiently counts the frequency of each element in an iterable. Here's an example of how to implement this: from collections import Counter def count_characters(s): return dict(Counter(s))
192
What are Keywords in Python?
Reference answer
Keywords in Python are reserved words that have special meanings and cannot be used as identifiers, such as variable or function names. Examples include 'if', 'else', 'while', 'def', and 'return'.
193
Write a python program to print Star (*) Triangle: * *** ***** ******* *********
Reference answer
def star_triangle(rows): for i in range(1, rows + 1): print(" " * (rows - i), end="") print("*" * (2*i - 1)) num_rows = int(input("Enter the number of ROWS: ")) star_triangle(num_rows)
194
What is Python? Enlist some of its benefits.
Reference answer
Python is a high-level, object-oriented programming language that enhances user interaction through objects, modules, and automatic memory. Due to Python being a cross-platform programming language, it can run on a myriad of different Operating Systems such as Windows, Linux, Macintosh, and UNIX. The language finds widespread use in data science, artificial intelligence, and machine learning because of its in-built data structures. Despite being a high-level language, the simplicity of its syntax makes Python a very easy language to grasp. Moreover, because Python supports various modules and packages, making applications using Python becomes extremely easy as less code is required.
195
How do you perform web scraping in Python?
Reference answer
Leverage libraries such as requests to retrieve a web page's context, and BeautifulSoup to parse the HTML. Example: import requests from bs4 import BeautifulSoup response = requests.get('https://example.com') soup = BeautifulSoup(response.text, 'html.parser') titles = [h1.text for h1 in soup.find_all('h1')] print(titles)
196
Write a function to find the shortest path in a maze using BFS.
Reference answer
Sample Answer: To find the shortest path in a maze, use the breadth-first search (BFS) algorithm. This method explores all possible paths level by level, ensuring that the shortest path from the starting point to the endpoint is found. Here's how you can implement this: from collections import deque def shortest_path(maze, start, end): rows, cols = len(maze), len(maze[0]) directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] queue = deque([(start, 0)]) visited = set() visited.add(start) while queue: (x, y), steps = queue.popleft() if (x, y) == end: return steps for dx, dy in directions: nx, ny = x + dx, y + dy if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 0 and (nx, ny) not in visited: visited.add((nx, ny)) queue.append(((nx, ny), steps + 1)) return -1 # return -1 if no path is found
197
Write a NumPy script to create a 2×3 array of ones and then reshape it to a 3×2 array. Discuss the implications of reshaping an array in terms of data layout in memory.
Reference answer
import numpy as np # Creating a 2x3 array of ones array = np.ones((2, 3)) # Reshaping to a 3x2 array reshaped_array = array.reshape((3, 2)) # Reshaping an array does not modify the underlying data in memory. # It creates a new view on the existing data, arranged in the new shape. Explanation of solution: A 2×3 array of ones is created using np.ones((2, 3)). The array is reshaped to 3×2 using reshape((3, 2)). Reshaping provides a new view on the same data, so it's memory efficient as the data is not duplicated.
198
What is a decorator in Python, and how is it used?
Reference answer
A decorator is a function that can modify or enhance the behavior of another function or method without changing its source code. They are often used for aspects like logging, authentication, and memoization.
199
Write a Python function called merge_intervals that takes a list of intervals as input and returns a new list of intervals where overlapping intervals are merged.
Reference answer
def merge_intervals(intervals): intervals.sort(key=lambda x: x[0]) merged = [] for interval in intervals: if not merged or merged[-1][1] < interval[0]: merged.append(interval) else: merged[-1][1] = max(merged[-1][1], interval[1]) return merged Explanation: - The merge_intervals function sorts the intervals based on their start points. - It initializes an empty list called merged to store the merged intervals. - Then, it iterates through each interval in the sorted list. - If the merged list is empty or the current interval does not overlap with the last merged interval, the current interval is appended to merged. - If the current interval overlaps with the last merged interval, the end point of the last merged interval is updated to the maximum of the two end points. - Finally, the function returns the merged list, which contains the merged intervals with no overlaps.
200
Write a Python program to find the longest word in a sentence
Reference answer
def longest_word(sentence): words = sentence.split() return max(words, key=len) print(longest_word("The fox jumps over the lazy dog")) # jumps