不想錯過任何事?

通過認證考試的技巧

最新考試新聞和折扣資訊

由我們的專家策劃和更新

是的,請向我發送時事通訊

查看其他面試題

1
參考答案
Decorators are functions that modify other functions or methods. They are often used for aspects like logging, authentication, and memoization.
2
參考答案
There are two mathematical operator to help you get quotient and remainder. To get remainder use % modulus operator and / to get the quotient value
職涯加速

考取認證,讓履歷脫穎而出。

數據分析顯示,持有 IT 認證的從業者年薪平均比求職者高出 26%。在 SPOTO,您可以同時備考認證與準備面試,加速職涯成長。

1 100% 通過率
2 2 週題庫練習
3 通過認證考試
3
參考答案
Solution: def merge_sorted_lists(list1, list2): merged_list = [] i = j = 0 while i < len(list1) and j < len(list2): if list1[i] < list2[j]: merged_list.append(list1[i]) i += 1 else: merged_list.append(list2[j]) j += 1 # Append remaining elements from list1, if any while i < len(list1): merged_list.append(list1[i]) i += 1 # Append remaining elements from list2, if any while j < len(list2): merged_list.append(list2[j]) j += 1 return merged_list # Example usage list1 = [1, 3, 5, 7, 9] list2 = [2, 4, 6, 8, 10] merged_list = merge_sorted_lists(list1, list2) print("Merged sorted list:", merged_list) Output: Merged sorted list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
4
參考答案
def reverse_string(s): return s[::-1]
5
參考答案
SET
6
參考答案
In the world of programming languages, the main is considered as an entry point of execution for a program. But in python, it is known that the interpreter serially interprets the file line-by-line. This means that python does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of main. This can be done by defining user-defined main() function and by using the __name__ property of python file. This __name__ variable is a special built-in variable that points to the name of the current module. This can be done as shown below: def main(): print("Hi Interviewbit!") if __name__=="__main__": main()
7
參考答案
You can calculate the dot product of two matrices in NumPy using the numpy.dot() function. For example, numpy.dot(matrix1, matrix2).
8
參考答案
A namespace in Python refers to a container where names (variables, functions, objects) are mapped to objects. In simple terms, a namespace is a space where names are defined and stored and it helps avoid naming conflicts by ensuring that names are unique within a given scope. Types of Namespaces: - Built-in Namespace: Contains all the built-in functions and exceptions, like print(), int(), etc. These are available in every Python program. - Global Namespace: Contains names from all the objects, functions and variables in the program at the top level. - Local Namespace: Refers to names inside a function or method. Each function call creates a new local namespace.
9
參考答案
You can use the import statement to import modules and access their functions and variables.
10
參考答案
The map() function helps execute a function for all items in the iterated object (list, dictionary, set, or tuple). It has two arguments: - Function specifies a function that will be executed on each object. - Iterable specifies a data collection or a sequence to which a function will be applied.
11
參考答案
You can merge and sort two lists using sorted(). Example: a = [1, 3, 5] b = [2, 4, 6] merged = sorted(a + b) print(merged) # [1, 2, 3, 4, 5, 6]
12
參考答案
def bs(a): # a = name of list b=len(a)-1nbsp; # minus 1 because we always compare 2 adjacent values for x in range(b): for y in range(b-x): a[y]=a[y+1] a=[32,5,3,6,7,54,87] bs(a) Output: [3, 5, 6, 7, 32, 54, 87]
13
參考答案
A lambda function is an anonymous function defined using the lambda keyword. It is useful for short, one-off operations and is often used in situations where a full function definition may seem excessive. add = lambda x, y: x + y result = add(3, 5) # Result: 8
14
參考答案
Answer: b) a b c = 1000 2000 3000 Spaces are not allowed in variable names.
15
參考答案
Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of their dependencies. This means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs. A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify them. The user can modify the session if only it has the secret key Flask.secret_key.
16
參考答案
Pickling is when a Python object converts into a string representation by a pickle module. It is then placed into a file with the dump() function. Unpickling refers to the reverse process, in which the stored string is retrieved and turned back into an object.
17
參考答案
Graphs can be represented using dictionaries (adjacency list). Example: graph = { 'A': ['B', 'C'], 'B': ['A', 'D'], 'C': ['A'], 'D': ['B'] } print(graph)
18
參考答案
Some common strategies for optimizing code include using efficient data structures, minimizing the use of loops and conditional statements, avoiding unnecessary calculations or function calls, and using vectorized operations when possible. It can also be helpful to profile the code to identify performance bottlenecks and optimize those sections of the code.
19
參考答案
Wheels are binary distribution formats, making installations faster. Source distributions contain source code and require compilation.
20
參考答案
list1 = [1, 2, 3, 4] list2 = [3, 4, 5, 6] common = list(set(list1) & set(list2)) print(common) # [3, 4]
21
參考答案
The "is" operator checks if two objects are the same object, while the "==" operator checks if two objects have the same value.
22
參考答案
In Pandas, merge() is used to combine dataframes based on common columns or indices, while join() is used to combine dataframes based on their indices.
23
參考答案
The main difference between a tuple and a list is that tuple is an immutable sequence type and list is mutable. You cannot modify its content, once you define a tuple. This immutability makes tuples suitable for representing fixed collections of items or data structures that shouldn't change, such as keys in a dictionary. A list is mutable. You can add, remove, or change elements in a list after its creation. This flexibility makes lists a choice for tasks where the collection's content can change over time. Memory-wise, tuples can be slightly more efficient than lists due to their static nature. Tuples support all operations that don't modify the content, while lists support a myriad of methods to manipulate their content.
24
參考答案
Dictionary comprehension is one way to create a dictionary in Python. It creates a dictionary by merging two sets of data which are in the form of either lists or arrays. The data of one of the two lists/arrays will act as the keys of the dictionary while the data of the second list/array will act as the values. Each key acts as a unique identifier for each value, hence the size of both lists/arrays should be the same. Here we'll look at simple merging: Simple merging is merging or combining two lists without any restrictions. In other words, it is the unconditional merging. The general syntax is as follows: Example The following example runs for the college's data base and uses simple merging. Imagine that there is a college's database storing lots of data. For example student's address, grades, section, fees, roll number and so on. Now we need to identify each student uniquely and create a new dictionary which stores all students only. Our decision simply depends on two questions: - What should be the key? - What should be the value? Here we will choose roll numbers as key and names as the value because roll numbers are unique and names could be repetitive. So, Alex's roll number is 122 so the tuple will look like 122: Alex. This will be better explained once you try the code attached below. rollNumbers =[122,233,353,456] names = ['alex','bob','can', 'don'] NewDictionary={ i:j for (i,j) in zip (rollNumbers,names)} print(NewDictionary) Output: {456: 'don', 233: 'bob', 122: 'alex', 353: 'can'}
25
參考答案
Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python.
26
參考答案
- A Python Set is an unordered collection data type that is iterable, mutable and has no duplicate elements. Python's set class represents the mathematical notion of a set. - Syntax: Defined using curly braces {} or the set() function. my_set = {1, 2, 3} - Dictionary is a collection of key-value pairs used to store and retrieve data using unique keys. Dictionaries preserve insertion order. - Syntax: Defined using curly braces {} with key-value pairs. my_dict = {"a": 1, "b": 2, "c": 3}
27
參考答案
A shallow copy creates a new object but does not create copies of nested objects. A deep copy creates a completely independent copy of the object and all its nested objects.
28
參考答案
Yes. If the threads happen to execute in the wrong order, a deadlock can occur, where each thread is waiting for the other to release the lock that it needs. To avoid deadlocks, it's important to carefully manage shared resources and ensure that threads are always acquiring locks in the same order. Alternatively, higher-level synchronisation mechanisms such as semaphores and condition variables can be used to avoid deadlocks by allowing threads to communicate and coordinate with each other more effectively.
29
參考答案
Sample Answer: You can expand around each character and its neighbor to check for palindromes to find the longest palindromic substring in a string. This method explores all possible centers of the palindrome. Here's how you can implement this: def longest_palindrome(s): def expand_from_center(left, right): while left >= 0 and right < len(s) and s[left] == s[right]: left -= 1 right += 1 return right - left - 1 start, end = 0, 0 for i in range(len(s)): len1 = expand_from_center(i, i) len2 = expand_from_center(i, i + 1) max_len = max(len1, len2) if max_len > end - start: start = i - (max_len - 1) // 2 end = i + max_len // 2 return s[start:end + 1
30
參考答案
def pyfunc(r): for x in range(r): print(' '*(r-x-1)+'*'*(2*x+1)) pyfunc(9) Output: * *** ***** ******* ********* *********** ************* *************** *****************
31
參考答案
When you write a variable with two underscores like __age, Python changes its name internally to _ClassName__age, this is called name mangling, it is used to avoid accidental override in child classes, it does not make the variable truly private, but it helps prevent mistakes in inheritance. class Person: def __init__(self): self.__age = 20 p = Person() # print(p.__age) # error print(p._Person__age) # works Gotcha: people think this makes it fully private, but you can still access it if you know the mangled name.
32
參考答案
- Functions that create iterators, producing values one at a time instead of storing the entire sequence in memory. - Efficient for iterating over large datasets or situations where generating all elements upfront is unnecessary. - Use yield keyword to return each element sequentially. - Python Example: def my_generator(): yield 1 yield 2
33
參考答案
Yes, Python is a case-sensitive language.
34
參考答案
def longest_common_substring(s1, s2): m, n = len(s1), len(s2) dp = [[0] * (n + 1) for _ in range(m + 1)] result = 0 for i in range(1, m + 1): for j in range(1, n + 1): if s1[i-1] == s2[j-1]: dp[i][j] = dp[i-1][j-1] + 1 result = max(result, dp[i][j]) return result
35
參考答案
Exceptions are handled using try, except, and optionally finally blocks. The finally block is executed regardless of whether an exception is raised.
36
參考答案
Python is popular for web development due to its simplicity, readability, and extensive libraries. Some advantages include rapid development, ease of use, and a large community of developers. Popular Python web frameworks include Django, Flask, and Pyramid.
37
參考答案
Docstrings are not actually comments, but, they are documentation strings. These docstrings are within triple quotes. They are not assigned to any variable and therefore, at times, serve the purpose of comments as well. Example: """ Using docstring as a comment. This code divides 2 numbers """ x=8 y=4 z=x/y print(z) Output: 2.0
38
參考答案
To remove duplicate elements from a list in Python, convert the list to a set (which automatically removes duplicates) and then back to a list, or use a loop with a temporary set for order preservation.
39
參考答案
You can use the max() and min() functions to find the maximum and minimum values in a list, respectively. my_list = [3, 1, 4, 1, 5, 9, 2] max_value = max(my_list) # Result: 9 min_value = min(my_list) # Result: 1
40
參考答案
A module is a file containing Python code that can be reused in other Python programs. It can include functions, classes, and variables.
41
參考答案
These are reserved words with special meanings used to define types of variables. However, they cannot be used for function names or variables. Examples of keywords are: Break, And, Or, If, Elif, For, While, etc.
42
參考答案
def is_armstrong(number): num_str = str(number) num_digits = len(num_str) return number == sum(int(digit) ** num_digits for digit in num_str) print(is_armstrong(153)) # True print(is_armstrong(123)) # False
43
參考答案
Sample Answer: The factorial of a number is defined as the product of all positive integers less than or equal to that number, and it is denoted by 'n!'. A recursive approach is an effective way to calculate the factorial, where the function calls itself with a decremented value until it reaches the base case. Here's how you can write a program to calculate the factorial of a number: def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) The function factorial(n) checks if n is 0 (the base case), returning 1. Otherwise, it multiplies n by the factorial of n−1n – 1n−1, recursively computing the result until it reaches the base case.
44
參考答案
Python web frameworks are evolving to meet modern web development demands. Future trends include: Increased Asynchronous Support: Frameworks like FastAPI and Sanic lead this trend with native support for async/await syntax for handling concurrent connections and improving performance. Integration with Machine Learning and AI: Frameworks will allow developers to easily incorporate intelligent features like personalized recommendations or NLP into web applications. More Robust Security Features: Built-in mechanisms for HTTPS, secure cookies, and CORS policies to protect against vulnerabilities. Enhanced Performance Optimization: Possible JIT compilation or other advanced techniques to reduce response times and resource consumption. Cross-Platform Compatibility and Microservices: Better support for containerization and cloud-native development with platforms like Docker and Kubernetes. Adoption of WebAssembly: Integration with WASM to enable Python applications to run in the browser at near-native speeds, blurring front-end and back-end lines. Progressive Web Applications (PWA) Support: More features for building mobile-friendly web experiences closer to native mobile applications.
45
參考答案
- Utilize NumPy for fast array operations and Scikit-learn for statistical analysis and machine learning tasks.
46
參考答案
This question is quite straightforward but requires special attention to detail. We are provided with an array of positive integers. We have to find the maximum difference between j-i where array[j] > array[i]. Examples: - Input: [20, 70, 40, 50, 12, 38, 98], Output: 6 (j = 6, i = 0) - Input: [10, 3, 2, 4, 5, 6, 7, 8, 18, 0], Output: 8 ( j = 8, i = 0) Solution: - Calculate the length of the array and initiate max difference with -1. - Run two loops. The outer loop picks elements from the left, and the inner loop compares the picked elements with elements starting from the right side. - Stop the inner loop when the element is greater than the picked element and keep updating the maximum difference using j - I. def max_index_diff(array): n = len(array) max_diff = -1 for i in range(0, n): j = n - 1 while(j > i): if array[j] > array[i] and max_diff < (j - i): max_diff = j - i j -= 1 return max_diff array_1 = [20,70,40,50,12,38,98] max_index_diff(array_1) # 6
47
參考答案
A tuple is similar to a list but is immutable, meaning its elements cannot be changed after creation.
48
參考答案
Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.
49
參考答案
You sort each word and use the sorted version as a key in a dictionary, all words with the same sorted form go into the same list, at the end you return all the grouped lists. def group_anagrams(words): groups = {} for w in words: key = "".join(sorted(w)) groups.setdefault(key, []).append(w) return list(groups.values()) print(group_anagrams(["eat","tea","tan","ate","nat","bat"]))
50
參考答案
Use exception handling and retry methods to handle network issues. Example: import requests from time import sleep def fetch_with_retry(url, retries=3): for attempt in range(retries): try: response = requests.get(url, timeout=5) response.raise_for_status() return response.text except requests.RequestException as e: if attempt < retries - 1: sleep(2) else: print(f"Failed after {retries} attempts: {e}") return None data = fetch_with_retry('https://example.com')
51
參考答案
To check if a pandas DataFrame is empty, use the df.empty attribute, which returns True if the DataFrame has no rows or columns. Alternatively, use len(df) == 0 or df.shape[0] == 0.
52
參考答案
Below code helps you create 1D array: import numpy as np & creating the list list = [100, 200, 300, 400] # creating 1-d array n = np.array(list) print(n) Output: [100 200 300 400] Below code helps you create a 2D array: import numpy as np # Create a 2-dimensional array with 3 rows and 4 columns arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # Print the array print(arr) Output: [[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] Below code helps you create a 3D array: import numpy as np # Create a 3D array with shape (2, 3, 4) nested_list = [[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], [[13, 14, 15, 16], [17, 18, 19, 20], [21, 22, 23, 24]]] arr = np.array(nested_list) print(arr) Output: [[[ 1 2 3 4] [ 5 6 7 8] [ 9 10 11 12]] [[13 14 15 16] [17 18 19 20] [21 22 23 24]]]
53
參考答案
Python is interpreted by converting source code into bytecode, which is then executed by the Python Virtual Machine (PVM). This process happens line by line at runtime, making it easier to debug and portable across platforms.
54
參考答案
def count_uppercase(s): return sum(1 for char in s if char.isupper()) print(count_uppercase("Nxtwave")) # 1
55
參考答案
Pychecker can be used to find the bugs in python. Pylint is another tool which can be used to detect errors.
56
參考答案
Yes, in TDD, we often use mocking or stubbing to isolate the code under test. For instance, when testing a service that interacts with a database, we use libraries like unittest.mock to mock database calls and control their behavior during testing.
57
參考答案
Pip is the package installer for Python, used for installing and managing Python packages from the Python Package Index (PyPI). It allows developers to add libraries and tools to their Python environment with ease. For example, to install a package named "flask", one would run the command `pip install flask` in the terminal. For uninstalling a package, the command would be `pip uninstall package_name`. Use `pip list`, to list all installed packages. Pip provides a simple interface to manage dependencies, ensuring that developers can quickly integrate third-party libraries into their projects. Always ensure that pip is updated to its latest version, as it frequently receives improvements and security updates.
58
參考答案
Beautiful Soup is used for web scraping and parsing HTML or XML documents. It allows you to extract data from web pages.
59
參考答案
pandas is a library for data manipulation and analysis. It provides data structures like DataFrame and Series, along with functions for data cleaning, transformation, and analysis.
60
參考答案
A linked list is implemented in Python using node objects and references. Start by defining a `Node` class with two attributes: `data` and `next`. The `data` attribute holds the value of the node, while the `next` attribute serves as a pointer to the subsequent node in the list .The `next` attribute of the last node points to `None`, for an empty list. The linked list itself can be represented using a separate class, named `LinkedList`. This class will have methods such as `insert`, `delete`, and `display`. The `insert` method adds a new node, the `delete` method removes a node, and the `display` method traverses the list, showing each node's data. Linked lists provide advantages like dynamic size and efficient insertions/deletions. They can use more memory due to the storage of references and might have slower access times compared to arrays. Proper understanding of pointers and references is essential for their effective implementation.
61
參考答案
You should understand how import statements work, the difference between absolute and relative imports, and when to use 'from module import function' versus 'import module'. The standard library includes modules like os for interacting with the operating system, sys for accessing system-specific parameters, datetime for handling dates and times, and json for parsing and generating JSON data.
62
參考答案
The `argparse` module simplifies the process of parsing command-line arguments``, allowing you to define options, arguments``, and help messages.
63
參考答案
The pass statement
64
參考答案
Polymorphism means "many forms." It allows the same method name to perform different actions depending on the object that calls it. This is achieved through method overriding, where child classes provide their own implementation of a method defined in a parent class. - The same method name can behave differently for different objects. - Child classes can override methods of parent classes. - It improves code flexibility and reusability. Example: class Animal: def sound(self): print("Some sound") class Dog(Animal): def sound(self): print("Bark") class Cat(Animal): def sound(self): print("Meow") for animal in [Dog(), Cat()]: animal.sound() Output Bark Meow Explanation: - Dog and Cat override the sound() method of Animal. - The same sound() method produces different outputs for different objects. - This demonstrates polymorphism in Python.
65
參考答案
- Answer: Mention containerizing scripts and test environments with Docker, using orchestration tools like Kubernetes, and ensuring secure deployments within containerized environments.
66
參考答案
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 for polymorphism.
67
參考答案
RESTful API communication between different software systems using HTTP methods. Frameworks such as Flask and Django facilitate the creation and management of these APIs. They help developers build, deploy, and scale web services that can interact with databases, perform authentication, and serve data to clients. A client, such as a web browser or mobile application, sends an HTTP request to a server hosting the API. The server processes the request, interacts with the database or other resources, and sends an HTTP response back to the client. Do X, if the API endpoint corresponds to a specific resource or action. Python web applications can interact with other systems, Using RESTful APIs, exchange data in standard formats like JSON, and support CRUD operations. This simplifies the process of building and maintaining scalable web applications.
68
參考答案
def count_vowels(s): return sum(1 for char in s if char.lower() in 'aeiou') print(count_vowels("Hello World")) # 3
69
參考答案
Use libraries like Pandas to fill, interpolate, or drop missing data based on the context of the analysis.
70
參考答案
The `*args` and `**kwargs` syntax in Python allows for passing a variable number of arguments to a function. `*args` is used to pass a non-keyworded, variable-length argument list. It collects additional positional arguments into a tuple. For example, in a function definition `def func(*args)` , call the function with any number of positional arguments. These arguments appear as a tuple, Inside the function. `**kwargs` works similarly but collects additional keyword arguments into a dictionary. In a function definition `def func(**kwargs)` , call the function with any number of keyword arguments. Access these as a dictionary, within the function. It's common to combine both in a function definition. Always put `*args ` before `**kwargs` , when doing so. This order ensures positional arguments are processed first, followed by keyword arguments. The asterisks are the key; any name like `*var` or `**vars` would also work, while `*args` and `**kwargs` are the conventional names. Using the conventional names helps in better readability and understanding. 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.
71
參考答案
- Negative indexes are the indexes from the end of the list or tuple or string. - Arr[-1] means the last element of array Arr[] arr = [1, 2, 3, 4, 5, 6] #get the last element print(arr[-1]) #output 6 #get the second last element print(arr[-2]) #output 5
72
參考答案
The difference between Python 2 and Python 3 lies in their syntax, libraries, and support. Python 2 has more complex syntax than Python 3. Python 3 has more library and community support. Python 2 and Python 3 are two major versions of the Python programming language. Python 2 was the legacy version, while Python 3 introduced significant improvements and changes. The print function in Python 2 is a statement. It's a function that requires parentheses, in Python 3. Python 3 uses Unicode for string representation, while Python 2 uses ASCII by default. Integer division in Python 3 returns a float; It returns the floor value, in Python 2. Libraries developed for Python 2 are not always compatible with Python 3. Python 3 introduced a new syntax for exception handling. Python 2 no longer receives updates as end-of-life for Python 2 was in 2020. Python 3 is the present and future of the language. Transitioning to Python 3 is essential for modern software development. It ensures code is up-to-date with the latest features and best practices.
73
參考答案
import unittest from unittest.mock import patch def fetch_data(api_url): # Function that makes an HTTP request to the provided api_url pass class TestFetchData(unittest.TestCase): @patch('path.to.fetch_data_function') def test_mock_api_call(self, mock_fetch): mock_fetch.return_value = "Mocked Data" response = fetch_data("http://example.com/api") self.assertEqual(response, "Mocked Data") if __name__ == '__main__': unittest.main() Explanation of solution: The unittest.mock module is used to replace the fetch_data function with a mock during the test. @patch decorator is applied to mock the function. mock_fetch.return_value sets a predefined return value for the mock. The test verifies that fetch_data returns the mocked response instead of performing a real API call.
74
參考答案
TDD involves writing tests before code. I've used tools like pytest to follow TDD, ensuring code quality and reliability. For example, in a recent project, I wrote unit tests before implementing new features.
75
參考答案
A global interpreter lock (GIL) is a mechanism used in computer-language interpreters to synchronize the execution of threads so that only one native thread (per process) can execute at a time. GIL is a crucial component of CPython, which is the standard and most widely-used implementation of Python. The GIL ensures that only one thread executes Python bytecode at a time in a given process. This simplifies the design of CPython and avoids potential data corruption due to concurrent access. CPython does not fully exploit multi-core processors when executing Python programs. The presence of the GIL can limit the performance of CPU-bound and multithreaded Python programs on multi-core machines. Not all Python implementations have a GIL. For example, Jython and IronPython do not have a GIL, allowing for true multithreading. The GIL is a unique aspect of CPython that affects threading and performance. When designing systems that need to scale or perform optimally on multi-core architectures, being aware of its implications is crucial for Python developers.
76
參考答案
- Data Validation: Implement checks during data ingestion to identify inconsistencies or missing values early. - Try-Except Blocks: Use Python's try-except to catch exceptions gracefully, allowing the program to continue running or log errors without crashing. - Logging: Maintain detailed logs of errors to monitor and troubleshoot issues efficiently. - Chunk Processing: Process data in smaller chunks to isolate errors and reduce memory load, making it easier to identify problematic segments. - Testing: Perform unit tests and validation checks on a sample of the dataset before full-scale processing.
77
參考答案
The Global Interpreter Lock (GIL) is a mutex in CPython (the reference Python implementation) that ensures only one native thread executes Python bytecode at a time. It simplifies memory management by protecting internal data structures like reference counts, but it also restricts true parallelism in CPU-bound tasks, making multithreading less effective for computational workloads. However, it works well for I/O-bound tasks, where threads spend time waiting on network, file, or database operations. Note: Python 3.13 introduced an experimental no-GIL build (PEP 703), and Python 3.14 adds documented free-threaded support. Some C extensions and libraries may not yet be fully compatible.
78
參考答案
- Break statement: Used to terminate the loop or statement in which it is present. After that, the control will pass to the statements that are present after the break statement, if available. - Continue: is also a loop control statement just like the break statement. continue statement is opposite to that of the break statement, instead of terminating the loop, it forces to execute the next iteration of the loop. - Pass: means performing no operation or in other words, it is a placeholder in the compound statement, where there should be a blank left and nothing has to be written there.
79
參考答案
Global Variables: Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program. Local Variables: Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space. Example: a=2 def add(): b=3 c=a+b print(c) add() Output: 5 When you try to access the local variable outside the function add(), it will throw an error.
80
參考答案
The output would be: llo
81
參考答案
def is_armstrong(num): # Calculate the number of digits in the number num_digits = len(str(num)) # Initialize sum to store the result sum = 0 # Temporary variable to store the original number temp = num # Calculate Armstrong sum while temp > 0: digit = temp % 10 sum += digit ** num_digits temp //= 10 # Check if the number is Armstrong or not if num == sum: return True else: return False # Input from the user number = int(input("Enter a number: ")) # Check if the number is Armstrong or not if is_armstrong(number): print(f"{number} is an Armstrong number.") else: print(f"{number} is not an Armstrong number.") In this program the function is_armstrong() which takes a number as input and returns True if it's an Armstrong number, otherwise False. It will prompt the user to enter a number and calls this function to determine if the entered number is an Armstrong number or not when executed.
82
參考答案
.py file includes the source code while .pyc includes the bytecode (intermediate between source code and machine-level code).
83
參考答案
You use recursion, keep adding parent keys with a dot, when the value is not a dictionary you save it, this is useful in configs and logging systems. def flatten(d, parent=""): res = {} for k, v in d.items(): new_key = f"{parent}.{k}" if parent else k if isinstance(v, dict): res.update(flatten(v, new_key)) else: res[new_key] = v return res print(flatten({"a":{"b":1,"c":{"d":2}}}))
84
參考答案
Python is widely used in major organizations such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify, and many others.
85
參考答案
Exception handling in Python is used to manage runtime errors gracefully without stopping the program abruptly. Python provides three main keywords for handling exceptions: - try: A block of code that is monitored for errors. - except: Executes when an error occurs in the try block. - finally: Executes after the try and except blocks, regardless of whether an error occurred. It's used for cleanup tasks. Example: Trying to divide a number by zero will cause an exception. n = 10 try: res = n / 0 # Raises ZeroDivisionError except ZeroDivisionError: print("Can't be divided by zero!") finally: print("Execution completed.") Output Can't be divided by zero! Execution completed. Explanation: In this example, dividing number by 0 raises a ZeroDivisionError. The try block contains the code that might cause an exception and the except block handles the exception, printing an error message instead of stopping the program.
86
參考答案
The code is missing a colon after the for statement. The fixed code is: squares = [] for i in range(5): squares.append(i ** 2) print(squares)
87
參考答案
Use the min() function: nums = [3, 7, 2, 9, 5] min_num = min(nums) print(min_num) # Output: 2
88
參考答案
The apply() function in Pandas is used to apply a custom function to each element or row of a dataframe. This can be useful for performing complex operations that are unavailable as built-in functions in Pandas.
89
參考答案
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def is_balanced(root): if not root: return True def height(node): if not node: return 0 return 1 + max(height(node.left), height(node.right)) return abs(height(root.left) - height(root.right)) <= 1 # Example usage root = Node(1) root.left = Node(2) root.right = Node(3) print(is_balanced(root)) # True
90
參考答案
- Answer: I'd use Natural Language Processing (NLP) libraries like NLTK or spaCy for tokenization, cleaning, stop word removal, and stemming/lemmatization. TF-IDF or similar techniques could be employed for feature engineering.
91
參考答案
They do so using the return statement. The statement can be used inside a function to refer the result back to the caller. The return statement has the return keyword and the optional return value. This return value can be used on any Python object.
92
參考答案
The GIL is a mutex in CPython that ensures only one thread executes Python bytecode at a time, even on multi-core systems. While this simplifies memory management and prevents race conditions, it also limits performance for CPU-bound tasks. However, for I/O-bound operations like network requests or file reads, the GIL is released during waiting periods, allowing other threads to continue.
93
參考答案
We implemented a retry mechanism with exponential backoff for network-related errors. Additionally, we used proper logging and monitoring to detect and investigate integration failures promptly.
94
參考答案
Method overriding allows a subclass to provide a specific implementation of a method that is already defined in its superclass. Example: In a subclass, redefine a method from the superclass.
95
參考答案
A shallow copy creates a new object but inserts references into the original elements, so changes to nested objects affect both copies. A deep copy creates a completely independent copy, including all nested objects, so changes do not propagate.
96
參考答案
Flask, Django, and Pyramid are three extremely popular Python libraries. Here are a few talking points: - Flask is a micro-framework having fewer requirements, while Django and Pyramid are large-scale Python frameworks. - Flask is typically used to develop small applications whereas Django and Pyramid are used to build more complex applications. - Pyramid is far more configurable than Django. - Django relies on the model-view-controller (MVC) architecture and includes an ORM.
97
參考答案
Chained comparisons are checked from left to right, so a < b < c means a < b and b < c, it does not compare a directly with c, this makes code clean but can confuse beginners who think it is evaluated differently. a = 1 b = 2 c = 3 print(a < b < c) # True print(a < b and b < c) # Same result Gotcha: a < b > c also works and means a < b and b > c.
98
參考答案
You should have used tuple as a return value. If you want more than 1 value as a return value.
99
參考答案
The pass statement serves as a placeholder in Python code. It is used where a statement is syntactically required but no action or code needs to be executed, such as in empty function definitions, loops, or conditional blocks.
100
參考答案
def first_non_repeating_char(s): char_count = {} for char in s: char_count[char] = char_count.get(char, 0) + 1 for char in s: if char_count[char] == 1: return char return None print(first_non_repeating_char("nxtwave")) # n
101
參考答案
Django is a Python web framework that offers an open-source, high-level framework that “encourages rapid development and clean, pragmatic design.” It's fast, secure, and scalable. Django offers strong community support and detailed documentation. The framework is an inclusive package, in which you get an admin panel, database interfaces, and directory structure right when you create the app. Furthermore, it includes many features, so you don't have to add separate libraries and dependencies. Some features it offers are user authentication, templating engine, routing, database schema migration, and much more. The Django framework is incredibly flexible in which you can work with MVPs to larger companies. For some perspective, some of the largest companies that use Django are Instagram, Dropbox, Pinterest, and Spotify. Flask is considered a microframework, which is a minimalistic web framework. It's less “batteries-included,” meaning that it lacks a lot of features and functionality that full-stack frameworks like Django offer, such as a web template engine, account authorization, and authentication. Flask is minimalistic and lightweight, meaning that you add extensions and libraries that you need as you code without automatically being provided with it by the framework. The philosophy behind Flask is that it gives only the components you need to build an app so that you have the flexibility and control. In other words, it's un-opinionated. Some features it offers are a build-int dev server, Restful request dispatching, Http request handling, and much more.
102
參考答案
Metaclasses are classes for classes. You use them to customize the behavior of classes, such as adding class-level methods or enforcing coding standards.
103
參考答案
Sample Answer: A stack is a data structure that follows a last-in, first-out (LIFO) principle. The last item added to the stack is the first one to be removed. You can implement a stack in Python using lists, which allow you to define basic operations such as push (to add an item), pop (to remove the most recently added item), and check if the stack is empty. Here's an example of how to create a stack class using a list: class Stack: def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): return self.stack.pop() if not self.is_empty() else None def is_empty(self): return len(self.stack) == 0
104
參考答案
Interviewers often focus on arguments and return values. A common mistake is using mutable objects as default arguments, which can result in shared state across function calls because the default value is created only once when the function is defined.
105
參考答案
File I/O in Python is handled using the open() function and various file modes. Here's an example of reading and writing to a file: Reading from a file: with open(example.txt', r') as file: content = file.read() print(content) Writing to a file: with open(output.txt', w') as file: file.write(This is some content written to the file.')
106
參考答案
- Modules group related functions and variables. - Packages group modules into hierarchies. - Used for code organization and import for reuse.
107
參考答案
Metaclasses are classes of classes. They define how classes behave and are created. While regular classes create objects, metaclasses create classes. By using metaclasses, you can modify class definitions, enforce rules, or add functionality during class creation. class Meta(type): def __new__(cls, name, bases, dct): print(f"Creating class {name}") return super().__new__(cls, name, bases, dct) class MyClass(metaclass=Meta): pass # Output: Creating class MyClass
108
參考答案
- Arrays (when talking about the array module in Python) are specifically used to store a collection of numeric elements that are all of the same type. This makes them more efficient for storing large amounts of data and performing numerical computations where the type consistency is maintained. - Syntax: Need to import the array module to use arrays. Example: from array import array arr = array('i', [1, 2, 3, 4]) # Array of integers print(arr) Output array('i', [1, 2, 3, 4]) - Lists are more flexible than arrays in that they can hold elements of different types (integers, strings, objects, etc.). They come built-in with Python and do not require importing any additional modules. - Lists support a variety of operations that can modify the list. Example: a = [1, 'hello', 3.14, [1, 2, 3]] print(a) Output [1, 'hello', 3.14, [1, 2, 3]]
109
參考答案
The with statement is used for resource management, ensuring proper acquisition and release of resources like file handling. Example: with open('example.txt', 'w') as f: f.write('Hello, World!') # Automatically closes the file after the block
110
參考答案
Sample Answer: Finding common elements between two lists is a useful operation in data analysis; one efficient way to do this is by using set operations, specifically the intersection. By converting both lists into sets, you can easily identify elements that appear in both. Here's how you can implement this: def common_elements(list1, list2): return list(set(list1) & set(list2))
111
參考答案
The `is` operator is used to test if two variables reference the same object in memory (i.e., they have the same identity).
112
參考答案
AI agents are autonomous systems that can perceive their environment, make decisions, and take actions to achieve goals. Modern AI agents often combine LLMs with tools and memory. Key components of an AI agent: - LLM Core: The reasoning engine that processes inputs and decides actions - Tools: Functions the agent can call (web search, code execution, APIs) - Memory: Short-term (conversation) and long-term (vector store) memory - Planning: Breaking complex tasks into subtasks Example using LangChain: from langchain.agents import create_openai_functions_agent, AgentExecutor from langchain.chat_models import ChatOpenAI from langchain.tools import Tool from langchain import hub # Define tools def search_database(query: str) -> str: return f"Results for: {query}" tools = [ Tool( name="DatabaseSearch", func=search_database, description="Search the company database for information" ) ] # Create agent llm = ChatOpenAI(model="gpt-4") prompt = hub.pull("hwchase17/openai-functions-agent") agent = create_openai_functions_agent(llm, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools) # Run agent result = agent_executor.invoke({"input": "Find sales data for Q4"}) print(result["output"])
113
參考答案
Python list is an ordered and changeable collection that is written within square brackets. The list can be homogenous or heterogeneous. It is one-dimensional by default and can be nested to form N dimensions. They come with benefits like concatenation, item deletion, item insertion, or appending. NumPy or NumPy array is a Python module that supports the use of arrays for advanced mathematical computations. You can use it to create N-dimensional arrays that are homogenous by default. It comes equipped with several functions, methods, and variables in python for effortless matrix computation. While answering this Python interview question, the candidate should display an inclination toward NumPy array as they are far faster and more efficient and utilize minimal code.
114
參考答案
You can rename columns using the `.rename()` method``, passing a dictionary that maps old column names to new names as an argument.
115
參考答案
The following will be the final outputs of A0, A1, … A6 A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary A1 = range(0, 10) A2 = [] A3 = [1, 2, 3, 4, 5] A4 = [1, 2, 3, 4, 5] A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]
116
參考答案
To handle categorical variables with many levels, I use the following strategies: - Frequency Encoding: Replace categories with their frequency counts to reduce dimensionality. - Target Encoding: Encode categories based on the mean of the target variable for each category, which captures useful information. - Dimensionality Reduction: Apply techniques like PCA or clustering to group similar categories and reduce levels. - Grouping Rare Categories: Combine infrequent categories into an "Other" category to simplify the variable. - Use of Dummy Variables: Create binary (one-hot) encoded variables for categories, but limit this to manageable levels to avoid high dimensionality.
117
參考答案
Python interacts with relational databases through specific libraries and modules. One of the tools for this is the Python Database API (DB-API), which provides a standard interface for connecting to relational databases. Developers can perform CRUD operations, manage transactions, and execute stored procedures, with the DB-API, Many popular relational databases have Python adapters compliant with the DB-API. For example, SQLite comes bundled with Python's standard library. Libraries such as MySQLdb, psycopg2, and cx_Oracle are available, For databases like MySQL, PostgreSQL, and Oracle. SQLAlchemy and Django's ORM, offer a higher-level, more abstracted way to interact with databases. They allow developers to work with databases using Python classes instead of writing SQL directly.
118
參考答案
Find indices of two numbers in a list that add up to a target. Example: def two_sum(nums, target): seen = {} for i, num in enumerate(nums): if target - num in seen: return [seen[target - num], i] seen[num] = i return [] print(two_sum([2, 7, 11, 15], 9)) # [0, 1]
119
參考答案
It is used to determine the length of a string, a list, an array, etc. Example: stg='ABCD' len(stg) Output:4
120
參考答案
- Answer: Explain reading data from the CSV, parameterizing test steps with the data, and reporting results based on success/failure for each data point. - Example Code: import csv import pytest @pytest.mark.parametrize('username,password,expected', [ ('user1', 'pass1', True), ('user2', 'pass2', False) ]) def test_login(username, password, expected): # login logic here assert login(username, password) == expected
121
參考答案
Dictionaries in Python are collections of key-value pairs where each key is unique and immutable (e.g., strings, numbers), and values can be of any type. They are mutable, allowing modification, addition, or deletion of elements. Example: person = {"name": "John", "age": 30} print(person["name"]) # Output: John person["city"] = "New York" # Adding a new pair del person["age"] # Deleting a pair print(person) # Output: {'name': 'John', 'city': 'New York'} Key Points: - Mutable: Can be changed after creation. - Efficient: O(1) average lookup time. - Use Cases: Mapping, counting, and lookup tables.
122
參考答案
def max_subarray_sum(arr): max_sum = arr[0] current_sum = arr[0] for i in range(1, len(arr)): current_sum = max(arr[i], current_sum + arr[i]) max_sum = max(max_sum, current_sum) return max_sum Explanation: - The max_subarray_sum function utilizes Kadane's algorithm to find the maximum sum of a subarray. - It starts by initializing max_sum and current_sum to the first element of the array. - Then, it iterates through the array, updating current_sum by either including the current element or starting a new subarray from the current element. - At each iteration, max_sum is updated to store the maximum sum encountered so far. - Finally, the function returns max_sum, which represents the maximum sum of any contiguous subarray within the given array.
123
參考答案
It is an environment variable used for incorporating additional directories during the import of a module or a package. PYTHONPATH is used for checking if the imported packages or modules are available in the existing directories. Not just that, the interpreter uses this environment variable to identify which module needs to be loaded.
124
參考答案
Sample Input: 4 a a c d 2 Sample Output: 0.8333 Explanation: All possible unordered tuples of length 2 comprising of indices from 1 to 4 are: (1, 2) (1, 3) (1, 4) (2, 3) (2, 4) (3, 4) Out of these 6 combinations, 5 of them contain either index 1 or index 2, which are the indices that contain the letter 'a'. Hence, the answer is 5/6.
125
參考答案
The “with” statement in Python is used for resource management, particularly in file I/O operations. It ensures that the file is properly closed after its suite finishes, even if an exception occurs during the operation. It eliminates the need to explicitly close the file, making the code cleaner and less prone to resource leaks.
126
參考答案
To add a vertex to a graph in Python, you can simply append a new element to the adjacency list or add a new row and column to the adjacency matrix.
127
參考答案
The largest element in an array in Python is found using the `max` function. Arrays can be represented using lists or using the `array` module in Python. Regardless of representation, the `max` function can directly obtain the maximum element. For example, given a list `arr`, the expression `max(arr)` returns the largest element. The `max` function iterates over the array to determine the largest element, taking linear time. Ensure the array is not empty before using `max` , as an exception will be raised for empty arrays.
128
參考答案
- An iterator is an object. - It remembers its state i.e., where it is during iteration (see code below to see how) - __iter__() method initializes an iterator. - It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception. - It is also self-iterable. - Iterators are objects with which we can iterate over iterable objects like lists, strings, etc. class ArrayList: def __init__(self, number_list): self.numbers = number_list def __iter__(self): self.pos = 0 return self def __next__(self): if(self.pos < len(self.numbers)): self.pos += 1 return self.numbers[self.pos - 1] else: raise StopIteration array_obj = ArrayList([1, 2, 3]) it = iter(array_obj) print(next(it)) #output: 2 print(next(it)) #output: 3 print(next(it)) #Throws Exception #Traceback (most recent call last): #... #StopIteration
129
參考答案
A number's factorial is the product of all positive integers which are either less than or equal to that number. For this computation, use the factorial function. def factorial(n): if n == 0: return 1 return n * factorial(n - 1) print(factorial(5)) Output: 120
130
參考答案
For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object. This means that xrange doesn't actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you'd like to generate a list for, say one billion, xrange is the function to use. This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It's a memory hungry beast.
131
參考答案
The `to_datetime()` function is used to convert date``-``like or time``-``like strings or numbers into datetime objects in Pandas.
132
參考答案
Sample Answer: Finding the length of a list without using the built-in 'len()' function is a useful exercise to understand iteration and counting in Python. You can achieve this by iterating through the list and incrementing a counter for each element encountered. Here's how you can approach it: def get_length(lst): count = 0 for _ in lst: count += 1 return count
133
參考答案
This can be done as shown in the following: reversed_array = arr[::-1] where arr = original given array, reverse_array is the resultant after reversing all elements in the input.
134
參考答案
| List | Tuples | Dictionaries | Sets | |---|---|---|---| | Ordered collection of items. | Ordered collection of items. | Collection of key-value pairs. And Unordered (no specific order of elements). | Unordered collection of unique elements. | | Mutable (can be modified after creation). | Immutable (cannot be modified after creation). | Mutable | Mutable | | Allows duplicate elements. | Allows duplicate elements. | Keys are unique, and values can be duplicated. | Doesn't allow duplicate elements. | | Elements are enclosed in square brackets [ ]. | Elements are enclosed in parentheses ( ) or can be without any enclosure. | Elements are enclosed in curly braces { }, with each item consisting of a key and its value separated by a colon : | Elements are enclosed in curly braces { }. | | Ex- fruits = [“apple”, “banana”, “orange”, “grape”] | Ex- numbers = (“Twenty”, 20, “Thirty”) | Ex- assassin = {“name”: “John Wick”, “age”: 28, “major”: “Self Defence & Martial Art”} | Ex- numbers = {1, 2, 3, 4, 5} |
135
參考答案
You can create a NumPy array in Python by importing the NumPy module and using the numpy.array() function. For example, import numpy as np and then np.array([1,2,3]).
136
參考答案
Python's ecosystem is rich with libraries that cater to evolving and emerging fields. Below are essential Python libraries for some of the most dynamically growing fields. Data Science and Machine Learning – Pandas: A staple for data manipulation and analysis, providing data structures and operations for manipulating numerical tables and time series. – NumPy: Critical for numerical computing, offering support for arrays and matrices, along with a collection of mathematical functions to operate on these data structures. – SciPy: Builds on NumPy by adding a collection of algorithms and high-level commands for data manipulation and analysis. – Scikit-learn: A key library for machine learning, providing a range of supervised and unsupervised learning algorithms. – TensorFlow and PyTorch: These two libraries are at the forefront of deep learning, providing flexible platforms for building and training neural networks. Artificial Intelligence – Keras: An open-source software library that provides a Python interface for artificial neural networks. Keras acts as an interface for the TensorFlow library. – OpenAI Gym: A toolkit for developing and comparing reinforcement learning algorithms. Computer Vision – OpenCV: A library focused on real-time computer vision applications, with extensive resources for image and video analysis. – Pillow: A user-friendly library for opening, manipulating, and saving many different image file formats. Natural Language Processing – NLTK (Natural Language Toolkit): A leading platform for building Python programs to work with human language data, offering easy-to-use interfaces and lexical resources. – spaCy: Known for its speed and efficiency, spaCy is great for large-scale information extraction tasks with a focus on practical business applications. Internet of Things (IoT) – RPi.GPIO: A library to control Raspberry Pi GPIO channels, which is particularly useful for IoT projects. – MicroPython: A lean and efficient implementation of Python 3 that includes a subset of the Python standard library, optimized to run on microcontrollers and in constrained environments. Quantum Computing – Qiskit: Developed by IBM, this library is designed for composing quantum programs at the level of circuits and pulses. – ProjectQ: An open-source software framework for quantum computing that allows users to implement their quantum programs in Python. Cybersecurity – Scapy: A powerful interactive packet manipulation program that is widely used in networking tasks and security testing. – Cryptography: A package designed to expose cryptographic primitives and recipes to Python developers.
137
參考答案
`pickle` is used to serialize Python objects to binary format, while `json` is used for human-readable data interchange in a portable format.
138
參考答案
You can use the ipaddress module in Python to check if a given IP address is valid.
139
參考答案
A namespace is used for creating unique object names that will not cause a conflict later.
140
參考答案
The __name__ variable is a built-in variable in Python scripts. When a Python script is run directly, the value of __name__ is set to __main__'. This allows you to include code in your script that should only run when the script is executed directly and not when it is imported as a module into another script.
141
參考答案
Profiling Python code involves using tools to measure the execution time and memory consumption of various sections of the code. This helps in identifying bottlenecks or inefficient segments. One popular tool is `cProfile`. It provides a detailed breakdown of function calls and their respective time consumption. Simply import it and run your code with `cProfile.run('your_function()')`, To use `cProfile`. Another tool is `timeit`, which measures the execution time of small code snippets. Use `timeit` by importing it and invoking the `timeit` method with the code segment you want to test. After profiling, analyze the results to pinpoint areas of optimization. Optimize the code segments with the highest execution times, and re-run the profiler to verify improvements.
142
參考答案
To find the strongly connected components (SCCs) of a directed graph in Python, we can use the Kosaraju's algorithm, which is a two-pass algorithm that first does a depth-first search (DFS) of the graph to find the finishing times of all vertices, and then does another DFS on the transpose of the graph (where all edges are reversed) to find the SCCs.