不想錯過任何事?

通過認證考試的技巧

最新考試新聞和折扣資訊

由我們的專家策劃和更新

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

查看其他面試題

1
參考答案
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
參考答案
Use the max() function: nums = [3, 7, 2, 9, 5] max_num = max(nums) print(max_num) # Output: 9
職涯加速

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

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

1 100% 通過率
2 2 週題庫練習
3 通過認證考試
3
參考答案
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
參考答案
Scope defines the region in a program where a variable is accessible. Python has local, enclosing, global, and built-in scopes.
5
參考答案
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
參考答案
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
參考答案
Namespaces are containers that hold identifiers and their corresponding objects. Examples include local, global, and built-in namespaces.
8
參考答案
Output : Fibonacci sequence : 0 1 1 2 3
9
參考答案
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
參考答案
The Python pass statement is used when a statement is required, but you do not want a command or code to execute.
11
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
__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
參考答案
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
參考答案
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
參考答案
Output : RADAR is a Palindrome
21
參考答案
- 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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
This is an alternate path to search for Python modules.
29
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
You can create a Series in Pandas using the pd.Series() constructor, passing a Python list or array as an argument.
35
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
- Functions encapsulate code for reusability and modularity. - Use def keyword to define a function, and call it with its name and arguments.
43
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language.
48
參考答案
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
參考答案
- Use try-except blocks to catch and handle specific exceptions gracefully. - finally block can be used to run cleanup code regardless of exceptions.
50
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
A function in Python is a reusable block of code that performs a specific task. It is defined using the def keyword.
55
參考答案
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
參考答案
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
參考答案
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
參考答案
| 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
參考答案
- 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
參考答案
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
參考答案
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
參考答案
# 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
參考答案
a=input("enter sequence") b=a[::-1] if a==b: print("palindrome") else: print("Not a Palindrome") Output: enter sequence 323 palindrome
64
參考答案
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
參考答案
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
參考答案
Python has automatic memory management based on reference counting and having a garbage collector to free unneeded memory.
67
參考答案
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
參考答案
- Use corresponding methods like click(), send_keys(), and submit() on identified elements. - Consider handling JavaScript alerts and confirmations if encountered.
69
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
This is an environment variable used to import a variable and check for the presence of variables present in different directories.
78
參考答案
Python is a general-purpose, object-oriented language. It is also an interpreted language.
79
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
Split(), sub() and subn() are the functions that can be used to modify the strings in python.
88
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
A coroutine is a specialized version of a Python generator that allows for asynchronous programming, using the async/await syntax.
95
參考答案
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
參考答案
There is a standard tool called Unittest within the standard Python package.
97
參考答案
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
參考答案
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
參考答案
Answer: c) when no exception occurs The else part is executed when no exception occurs.
100
參考答案
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
參考答案
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
參考答案
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
參考答案
To modify the strings, Python's “re” module is providing 3 methods. They are:
104
參考答案
A while loop repeatedly executes a block of code as long as a specified condition is true.
105
參考答案
Break down the problem into smaller, manageable parts, write pseudocode, implement step-by-step, and test each part thoroughly.
106
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
- Use the import keyword to import specific modules or functions from libraries. - Use aliases to avoid long module names.
114
參考答案
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
參考答案
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
參考答案
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
參考答案
- Script file must begin with #!/usr/bin/env python
118
參考答案
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
參考答案
Yes, you can. By overriding __dir__ function.
120
參考答案
- 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
參考答案
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
參考答案
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
參考答案
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
參考答案
Due to its Short and Simple Syntax, Python can we easily used for Scripting purpose.
125
參考答案
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
參考答案
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
參考答案
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 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
參考答案
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
參考答案
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
參考答案
Answer: d) None of the above Identifiers can be of any length.
132
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
- Each WebDriver interacts with a specific browser. Choose based on project requirements and compatibility. - Some popular options include ChromeDriver, FirefoxDriver, EdgeDriver.
138
參考答案
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
參考答案
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
參考答案
Use tools like objgraph, gc module, or tracemalloc to trace memory allocations and identify references preventing garbage collection.
141
參考答案
A variable is a name used to store data values. In Python, you can create a variable like this: x = 10
142
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
- 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
參考答案
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
參考答案
#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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
The collections module offers specialized container datatypes like deque, Counter, and namedtuple for various use cases.
157
參考答案
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
參考答案
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
參考答案
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
參考答案
- Use import statement to import modules: import module_name
161
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
- Classes define blueprints for objects (instances) with attributes and methods. - Objects represent specific instances of a class with unique attribute values.
171
參考答案
Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions.
172
參考答案
- 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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
def reverse_string(s): return s[::-1] # Example usage: # print(reverse_string("hello")) # Output: "olleh"
178
參考答案
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
參考答案
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
參考答案
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
參考答案
- == checks values for equality. - is checks object identity (same location in memory).
182
參考答案
Output : Sum of digits : 5
183
參考答案
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
參考答案
- 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
參考答案
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
參考答案
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
參考答案
- 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
參考答案
A package is a collection of different related modules. It normally contains a file with the name init . py.
189
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
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
參考答案
def longest_word(sentence): words = sentence.split() return max(words, key=len) print(longest_word("The fox jumps over the lazy dog")) # jumps