不想錯過任何事?

通過認證考試的技巧

最新考試新聞和折扣資訊

由我們的專家策劃和更新

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

查看其他面試題

1
參考答案
PEP 8 is the official style guide for Python. Therefore, it promotes code readability and consistency for any Python project.
2
參考答案
The `.merge()` method is used to combine two DataFrames into a single DataFrame based on common columns or indices. It is similar to SQL JOIN operations.
職涯加速

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

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

1 100% 通過率
2 2 週題庫練習
3 通過認證考試
3
參考答案
NumPy uses less storage, is faster, and has many vector and matrix operations that eliminate the need for oftentimes unnecessary work. Its slicing and broadcasting functionality are more powerful than those of regular Python lists.
4
參考答案
a = int(input("Enter a number = ")) if a == 1: print("Not a prime number.") else: for x in range(2, a): if (a % x) == 0: print("Not a prime number.") break else: print("Prime Number.")
5
參考答案
Namespaces in Python ensure that Python variables, functions, and other names don't clash.
6
參考答案
def celsius_to_fahrenheit(temps): return [(temp * 9/5) + 32 for temp in temps] print(celsius_to_fahrenheit([0, 20, 37])) # [32.0, 68.0, 98.6]
7
參考答案
Metaclasses are classes of classes that define how classes behave. They are used to create APIs, enforce coding standards, or modify class creation.
8
參考答案
Lambda functions are used to create small, anonymous functions that can be used in place of regular functions. They are different from regular functions in that they do not have a name and can only contain a single expression.
9
參考答案
Pickling is the process of converting a Python object into a byte stream, and unpickling is the reverse operation. The pickle module provides this functionality.
10
參考答案
The indentation may be just for easier reading in other languages but it is essential in Python. It indicates a block of code, and without it, you will face the error message and the code will not be compiled.
11
參考答案
The below program will help you in identifying items in series A but no in series B: import pandas as pd # Creating 2 pandas Series ps1 = pd.Series([2, 4, 8, 20, 10, 47, 99]) ps2 = pd.Series([1, 3, 6, 4, 10, 99, 50]) print("Series 1:") print(ps1) print("nSeries 2:") print(ps2) # Using Bitwise NOT operator along # with pandas.isin() print("nItems of Series 1 not present in Series 2:") res = ps1[~ps1.isin(ps2)] print(res)
12
參考答案
They can be removed using the remove() or pop() function.
13
參考答案
Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code. Some of the commonly used built-in modules are:
14
參考答案
pass is a null statement in Python. It does nothing when executed and is used as a placeholder.
15
參考答案
Data types define the type of data a variable can hold. Common data types include int, float, str, bool, and more.
16
參考答案
Indentation is necessary for Python. It specifies a block of code. All code within loops, classes, functions, etc is specified within an indented block. It is usually done using four space characters. If your code is not indented necessarily, it will not execute accurately and will throw errors as well.
17
參考答案
List comprehension is a concise way to create lists in Python. It allows you to generate a list by specifying the elements you want to include and the conditions they must satisfy. squares = [x**2 for x in range(5)] # Result: [0, 1, 4, 9, 16]
18
參考答案
PEP 8 is a guide that helps in writing clean, consistent, and maintainable Python code that is easy to read and understand. It stands for Python Enhancement Proposal, it specifically provides guidelines and recommendations on how to format and structure Python code to enhance readability and reliability of the code. Some key points of PEP 8 include: - Indentation: Use 4 spaces for indentation to improve code readability. - Line Length: Limit lines to a maximum of 79 characters to ensure readability, although it can be extended up to 120 characters in certain cases. - Naming Conventions - Function and Variable Names - Imports: Import modules on separate lines and follow a specific ordering convention (standard library modules, third-party modules, local modules). - It also provides numerous other guidelines covering various aspects of coding style, including whitespace, blank lines, operator spacing, and more.
19
參考答案
Dictionary in python are used for mapping of unique keys to values.
20
參考答案
Those are Django, Flask, and Pyramid. Flask aims at small applications while Django and Pyramid were created for larger projects. Pyramid is very flexible, developers can choose all the tools they want from database to templating style. Django has ORM and many other tools out of the box.
21
參考答案
Decorators allow developers to modify or extend the behavior of callable objects (like functions or methods) without permanently modifying the callable itself.
22
參考答案
API versioning is important for maintaining compatibility. We would typically include the version in the URL, such as /api/v1/resource, and use URL routing or middleware to handle requests to the appropriate version.
23
參考答案
In general, variables defined outside of functions are global. Variables defined inside a function can also be made global by using the command global x, for example, to create a global variable called x.
24
參考答案
Version control systems like Git help track changes, collaborate with team members, manage branches, and handle code merges and conflicts.
25
參考答案
Encapsulation means binding the code and the data together. A Python class in an example of encapsulation.
26
參考答案
The `.loc[]` method is used for label-based indexing. It allows you to select rows and columns by labels, rather than by their integer position.
27
參考答案
Infinite loops occur when a loop's condition never becomes False, causing it to run indefinitely. To avoid infinite loops, you need to ensure that the loop's condition eventually evaluates to False. Common techniques to handle infinite loops include using a loop control variable, using a break statement within the loop, or using conditional checks to exit the loop based on certain conditions. Additionally, using a timeout mechanism or Keyboard Interrupt exception handling can be used to interrupt infinite loops during development and testing.
28
參考答案
Docstring is a string literal used to document modules, classes, functions, and methods. It serves as a documentation tool to describe the purpose, behavior, parameters, return values, and other important details of the code. A docstring is enclosed in triple quotes (single or double) and is typically placed as the first line after the definition of a module, class, function, or method. It can span multiple lines and supports both single-line and multi-line docstrings. def hello(name): """ This function says hello to the person with the given name. Parameters: name (str): The name of the person to be greeted. Returns: str: A greeting message. """ return "Hello, " + name + " !!!!!" print(hello("Isabelle"))
29
參考答案
Breadth-first search (BFS) is implemented in Python using a queue data structure. Start by initializing a queue and adding the starting node to it. Make sure the queue is not empty, remove the first node and process it and add all its unvisited neighbors to the queue. Mark nodes as visited once they're processed, ensuring they aren't revisited. The process continues until the queue is empty or the desired node is found. You can use an adjacency list or matrix, to represent the graph. Python's built-in list or the `collections.deque` can be used for the queue operations. Check if a node has been visited before adding it to the queue, preventing infinite loops in cyclic graphs.
30
參考答案
Sample Input: aaadaa aa Sample Output: (0, 1) (1, 2) (4, 5) Task: Find the indices of the start and end of string k in S. If no match is found, print (-1, -1).
31
參考答案
Python allows software developers to change the behavior of a module at runtime. To make these dynamic edits, programmers use monkey-patching.
32
參考答案
Pandas dataframes can be merged using multiple keys by passing a list of columns to the on parameter of the merge() function. This allows you to merge dataframes based on more than one common column.
33
參考答案
By using the decorators we can alter the functions easily.
34
參考答案
Lists are mutable sequences that allow elements to be added, removed, or modified after creation. Tuples are immutable; their structure and references cannot be changed once instantiated. Tuples have a lower memory footprint and are faster to create and iterate over because they are allocated exact memory, while lists over-allocate for O(1) amortized append() operations. Tuples (containing only hashable elements) are hashable and can be used as dictionary keys or set elements; lists are unhashable. Lists are ideal for collections requiring frequent updates or resizing, while tuples are preferred for fixed data structures, protecting data from accidental modification, and serving as constant keys in mapping types.
35
參考答案
A syntax error is a type of error that occurs when Python cannot parse the code due to a violation of the language grammar rules, such as a missing parenthesis or a typo in a keyword. A runtime error, on the other hand, occurs when Python is able to parse the code but encounters an error while running it, such as a division by zero or an undefined variable.
36
參考答案
| Break | The break statement terminates the loop immediately and the control flows to the statement after the body of the loop. | | Continue | The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop. | | Pass | As explained above, the pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript, etc. | pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] for p in pat: pass if (p == 0): current = p break elif (p % 2 == 0): continue print(p) # output => 1 3 1 3 1 print(current) # output => 0
37
參考答案
Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use. Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable. Django can also be used for larger applications just like Pyramid. It includes an ORM.
38
參考答案
Both lists and tuples can store an ordered array of objects, however, a tuple is immutable. This means that once a tuple is created with objects in it, the objects can not be swapped out (mutating). A list still allows for objects to be reassigned within the list.
39
參考答案
Dictionary Comprehension is a concise way to create dictionaries from existing iterables. It allows you to generate key-value pairs in a single line of code, making the code more readable and efficient. keys = ['a', 'b', 'c', 'd', 'e'] values = [1, 2, 3, 4, 5] # Dictionary comprehension d = {k: v for k, v in zip(keys, values)} print(d) Output {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
40
參考答案
Although both lists and tuples are data collections, there are fundamental differences between the two. Knowing them helps developers choose which collection type they want to use. | Lists | Tuples | | Mutability: items on the list can be changed | Immutability: there's no way to edit a tuple | | Lower speed than that of tuples | Higher speed than that of lists | | Uses square brackets: mylist=[1, "Python", 1.5] | Uses round brackets: mytuple=(1, "Python", 1.5) |
41
參考答案
Python uses automatic memory management, employing techniques such as: - Reference Counting: Tracks the number of references to objects. - Garbage Collection: Frees up memory for objects no longer in use, using algorithms like generational garbage collection.
42
參考答案
An iterator is any object that you can loop over using for, like a list or a tuple. It has two methods: __iter__() and __next__(). A generator is a special kind of iterator made using a function and the yield keyword. Generators don't store all values in memory at once; they give values one by one. This saves memory and is useful for large data or streams. So, every generator is an iterator, but not every iterator is a generator. # Iterator example nums = [1, 2, 3] it = iter(nums) print(next(it)) # 1 print(next(it)) # 2 # Generator example def count_up(n): for i in range(n): yield i gen = count_up(3) print(next(gen)) # 0 print(next(gen)) # 1
43
參考答案
Here is the code for merge sort in Python: def mergeSort(myList): if len(myList) > 1: mid = len(myList) // 2 left = myList[:mid] right = myList[mid:] # Recursive call on each half mergeSort(left) mergeSort(right) # Two iterators for traversing the two halves i = 0 j = 0 # Iterator for the main list k = 0 while i < len(left) and j < len(right): if left[i] < right[j]: # The value from the left half has been used myList[k] = left[i] # Move the iterator forward i += 1 else: myList[k] = right[j] j += 1 # Move to the next slot k += 1 # For all the remaining values while i < len(left): myList[k] = left[i] i += 1 k += 1 while j < len(right): myList[k]=right[j] j += 1 k += 1 myList = [54,26,93,17,77,31,44,55,20] mergeSort(myList) print(myList) Output: [17, 20, 26, 31, 44, 54, 55, 77, 93] Explanation This is the recursive approach for implementing merge sort. The steps needed to obtain the sorted array through this method can be found below: The list is divided into left andright in each recursive call until two adjacent elements are obtained.Now begins the sorting process. The i andj iterators traverse the two halves in each call. Thek iterator traverses the whole lists and makes changes along the way.If the value at i is smaller than the value atj ,left[i] is assigned to themyList[k] slot andi is incremented. If not, thenright[j] is chosen.This way, the values being assigned through k are all sorted.At the end of this loop, one of the halves may not have been traversed completely. Its values are simply assigned to the remaining slots in the list. Time complexity The algorithm works in O(n.logn). This is because the list is being split in log(n) calls and the merging process takes linear time in each call.
44
參考答案
- Create basic plots like histograms, bar charts, line charts, and boxplots.
45
參考答案
PYTHONPATH is an environment variable that developers use to add (and maintain) additional directories without installing them in the global default location. It achieves this by creating additional folders to the sys.path directory list of program in Python where it can look for modules and packages.
46
參考答案
A variable which you define inside the function is known as local variable, you can not use local variable outside the function.
47
參考答案
- Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally. - Source code is a file with .py extension. - Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called "bytecode". - .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy.
48
參考答案
Use the assert statement to check conditions during development or tests. Example: def divide(a, b): assert b != 0, "Denominator cannot be zero" return a / b print(divide(10, 2)) # 5.0
49
參考答案
A Large Language Model (LLM) is a deep learning model trained on massive text datasets to understand and generate human-like text. Popular LLMs include GPT-5, Claude, Llama, and Gemini. In Python, you can interact with LLMs through APIs or run them locally. Example using OpenAI's API: from openai import OpenAI client = OpenAI(api_key="your-api-key") response = client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": "You are a helpful assistant."}, {"role": "user", "content": "Explain Python decorators in simple terms."} ] ) print(response.choices[0].message.content)
50
參考答案
Vectorization is the process of performing mathematical operations on arrays of data rather than using loops to perform these operations on each individual element of the array. Vectorization in NumPy is important because it allows for faster and more efficient computation of numerical operations, making it a crucial tool for scientific computing and data analysis.
51
參考答案
ABCs define abstract methods that must be implemented by subclasses. They're used to enforce interfaces and create extensible frameworks.
52
參考答案
Python developers are able to make dynamic edits, edits of the module during the runtime. Monkey-patching helps them do so.
53
參考答案
Keep sensitive information out of code by accessing environment variables via the OS module. Example: import os # Get the API key from environment variables api_key = os.environ.get('API_KEY') print(api_key) # Prints None if 'API_KEY' is not set
54
參考答案
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
55
參考答案
You can create a list of unique random numbers by using the `random.sample()` function, specifying the range and the number of unique numbers you want.
56
參考答案
A decorator is a design pattern and language feature that allows dynamically modifying or extending the behavior of functions or classes without changing their source code. Decorators are higher-order functions that take another function as an argument and return a new function. They leverage closures to 'wrap' the original function, allowing code execution both before and after the target function runs. Common use cases include authorization, logging/profiling, caching/memoization, validation, and rate limiting. The @decorator syntax is syntactic sugar for func = decorator(func). Modern Python development requires functools.wraps to preserve the original function's metadata (__name__, __doc__, type annotations). Decorator factories (additional nesting) allow passing arguments to decorators.
57
參考答案
A generator is a special type of iterable that yields values one at a time, allowing for efficient memory usage. Generators are created using functions with `yield` statements and save and resume state between calls.
58
參考答案
Use the # symbol for single-line comments, like this: # This is a comment
59
參考答案
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.
60
參考答案
RAG combines retrieval systems with generative AI to produce more accurate, grounded responses. Instead of relying solely on the LLM's training data, RAG retrieves relevant documents from a knowledge base and uses them as context for generation. Key components of a RAG system: - Document Store: A vector database (like Pinecone, Chroma, or FAISS) storing embedded documents - Retriever: Finds relevant documents based on query similarity - Generator: An LLM that produces responses using retrieved context Example RAG workflow: from langchain.vectorstores import Chroma from langchain.embeddings import OpenAIEmbeddings from langchain.chat_models import ChatOpenAI from langchain.chains import RetrievalQA # Create vector store from documents embeddings = OpenAIEmbeddings() vectorstore = Chroma.from_documents(documents, embeddings) # Create RAG chain llm = ChatOpenAI(model="gpt-4") qa_chain = RetrievalQA.from_chain_type( llm=llm, retriever=vectorstore.as_retriever() ) # Query the system result = qa_chain.invoke("What are Python best practices?") print(result)
61
參考答案
Yes, it is a case-sensitive language.
62
參考答案
The finally block in a try statement in Python is executed regardless of whether an exception is raised or not. It is typically used to perform cleanup tasks, such as closing a file or releasing a resource.
63
參考答案
Modules can be imported using the import keyword. You can import modules in three ways- Example: import array #importing using the original module name import array as arr # importing using an alias name from array import * #imports everything present in the array module
64
參考答案
To write a Python script to merge two Python dictionaries, use the `update()` method or the `**` unpacking operator. Using the `update()` method, the second dictionary's keys and values get added to the first dictionary. Keys value gets updated, If the key already exists in the first dictionary. For example, `dict1.update(dict2)` will merge `dict2` into `dict1`. With Python 3.5 and later, you can use the `**` unpacking operator. A merged dictionary can be created as `merged_dict = {**dict1, **dict2}`. This method creates a new dictionary without modifying the original ones. Both approaches effectively merge dictionaries, the choice between them depends on whether you want to modify an existing dictionary or produce a new merged one.
65
參考答案
Python files that end in the py extension are text-based source files. These are the files you create when writing Python code. Python files with the pyc extension are compiled bytecode files. When a Python application runs, the interpreter looks for existing pyc files. If those do not exist, it then compiles the py source files to bytecode and runs the resulting pyc files.
66
參考答案
- For loop: Used when we know how many times to repeat, often with lists, tuples, sets or dictionaries. - While loop: Used when we only have an end condition and don't know exactly how many times it will repeat. for i in range(5): print(i) c = 0 while c < 5: print(c) c += 1 Output 0 1 2 3 4 0 1 2 3 4
67
參考答案
Yes, several arguments can be passed to a function, including objects, variables (of the same or distinct data types) and functions. Functions can be passed as parameters to other functions because they are objects. Higher-order functions are functions that can take other functions as arguments. def add(x, y): return x + y def apply_func(func, a, b): return func(a, b) print(apply_func(add, 3, 5)) Output 8 The add function is passed as an argument to apply_func, which applies it to 3 and 5.
68
參考答案
Memory is managed in Python in the following ways:
69
參考答案
You can remove duplicates from a list using various methods, including converting it to a set or using list comprehensions. For example: my_list = list(set(my_list)).
70
參考答案
Quicksort is a sorting algorithm which works on divide and conquer principle. Quicksort algorithm selects a "pivot" element from the list and partitions the remaining elements into two sublists - those less than the pivot and those greater than the pivot. This process continues recursively on each sublist until the entire list is sorted. Quicksort excels at efficiently sorting the sublists because it has an average time complexity of O (n log n). It can degrade to O(n^2), in the worst case, so it's crucial to choose a good pivot strategy to optimize performance.
71
參考答案
The code is correct, but the print() statement is printing the generator object instead of the sequence of numbers. To print the sequence of numbers, you can convert the generator to a list: def fibonacci(n): a, b = 0, 1 for i in range(n): yield b a, b = b, a+b print(list(fibonacci(5)))
72
參考答案
Class in Python is created using the class keyword. Example: class Employee: def __init__(self, name): self.name = name E1=Employee("abc") print(E1.name) Output: abc
73
參考答案
Context managers allow for resource management (e.g., file I/O) using __enter__ and __exit__ methods. The with statement ensures resources are properly managed.
74
參考答案
A global variable is the one declared outside of a function, in a so-called global space. All functions within the code can access such a variable. Local variables, on the other hand, are those you create within a function. Trying to access them outside the function will return a system failure.
75
參考答案
import numpy as np def multiply_arrays(a, b): # Element-wise multiplication using broadcasting return a * b # Example: Multiplying arrays of different lengths array1 = np.array([1, 2, 3]) array2 = np.array([4]) # Broadcasting rules allow this operation by 'stretching' array2 # to [4, 4, 3] before performing element-wise multiplication. result = multiply_arrays(array1, array2) # Broadcasting is a powerful concept in NumPy that allows vectorized operations # on arrays of different sizes, making code efficient and concise. Explanation of solution: The function multiply_arrays performs element-wise multiplication, showcasing NumPy's broadcasting capabilities. Broadcasting automatically 'expands' smaller arrays for vectorized operations, avoiding explicit data replication and thus enhancing performance. The example illustrates how an array of length 1 (array2) is 'stretched' to match the size of array1 for multiplication, demonstrating the utility and power of broadcasting in NumPy.
76
參考答案
| Shallow Copy | Deep Copy | |---|---| | Shallow Copy stores the references of objects to the original memory address. | Deep copy stores copies of the object's value. | | Shallow Copy reflects changes made to the new/copied object in the original object. | Deep copy doesn't reflect changes made to the new/copied object in the original object. | | Shallow Copy stores the copy of the original object and points the references to the objects. | Deep copy stores the copy of the original object and recursively copies the objects as well. | | A shallow copy is faster. | Deep copy is comparatively slower. |
77
參考答案
To read a CSV file into a dataframe, use pd.read_csv('filename.csv') Example: import pandas as pd # Read a CSV file into a DataFrame df = pd.read_csv('data.csv') # Display the first 5 rows print(df.head())
78
參考答案
What is any() ? any() is a function that takes in an iterable (such as a list, tuple, set, etc.) and returns True if any of the elements evaluate to True , but it returns False if all elements evaluate to False . Passing an iterable to any() to check if any of the elements are True can be done like this: one_truth = [True, False, False] three_lies = [0, '', None] print(any(one_truth)) print(any(three_lies)) Output: True False The first print statement prints True because one of the elements in one_truth is True . On the other hand, the second print statement prints False because none of the elements are True , i.e., all elements are False . Use any() when you need to check a long series ofor conditions. What is all() ? all() is another Python function that takes in an iterable and returns True if all of the elements evaluate to True , but returns False if otherwise. Similar to any() , all() takes in a list, tuple, set, or any iterable, like so: all_true = [True, 1, 'a', object()] one_true = [True, False, False, 0] all_false = [None, '', False, 0] print(all(all_true)) print(all(one_true)) print(all(all_false)) Output: True False False The first function call returned True because all_true was filled with truthy values. Passing one_true to all() returned False because the list contained one or more falsy values. Finally, passing all_false to all() returns False because it also contained one or more falsy values. Use all() when you need to check a long series ofand conditions.
79
參考答案
Key optimization techniques include caching results with functools.lru_cache to avoid redundant computations. For CPU-intensive tasks, you can offload computations to C extensions or libraries like NumPy and Pandas. These libraries release the GIL during heavy operations, which can significantly improve performance.
80
參考答案
Class is a blueprint or a template that defines the structure and behavior of objects. It is like a blueprint for creating multiple instances of similar objects with shared characteristics and functionalities. It contains data (in the form of attributes or properties) and behaviors (in the form of methods or functions) that define the objects' characteristics and actions. It provides a way to organize related data and functions into a single unit. An object, on the other hand, is an instance of a class. It represents a specific entity or item created based on the class definition. Objects have their own unique state and can interact with other objects or perform operations defined within the class.
81
參考答案
Some of the reasons you'll likely want to highlight include Python's versatility and diversity of applications, its intuitive nature, and ease of use, or the use of Python by top companies including Google, YouTube, Dropbox, Quora, Mozilla, Spotify, and more. You've already proven your technical know-how when it comes to Python, so treat this as an opportunity to discuss why Python specifically interests you.
82
參考答案
You can call a function by using its name followed by parentheses, like this: def greet(name): print("Hello, " + name) greet("Alice")
83
參考答案
NumPy provides support for large, multi-dimensional arrays and matrices, along with mathematical functions for array operations. SciPy builds on NumPy and offers additional modules for scientific computing, such as optimization, integration, and signal processing.
84
參考答案
A dictionary in Python is an unordered collection of key-value pairs, where each key is unique and used to access its corresponding value. Dictionaries are mutable and defined using curly braces {}.
85
參考答案
Python is a popular computer programming language used to build softwares and web applications. Python is a general purpose programming language. It has various types of applications and is not specialized for specific problems. It's popular because of its simple syntax which makes it easy for developers to build applications. Python boasts a vast and active community that contributes to its rich library ecosystem. Python is versatile across different domains because of libraries like NumPy for numerical computations, Django for web development, and TensorFlow for machine learning. Python is a preferred language for startups and tech giants alike due to its adaptability, combined with its efficiency in rapid application development. Python's popularity is also fueled by its application in emerging fields such as data science, artificial intelligence, and automation. Python is the top preferred language for data science and research. The demand for Python developers continues to grow, making Python a sought-after skill in developer interviews, as businesses increasingly rely on data-driven insights and automation.
86
參考答案
The `global` keyword is used to indicate that a variable inside a function should be treated as a global variable (i.e., it should reference the global scope). This allows you to modify global variables within a function.
87
參考答案
try: with open('filename','r') as file: print(file.read()) except IOError: print(“no such file exists”)
88
參考答案
- In a dynamically typed language, the data type of a variable is determined at runtime, not at compile time. - No need to declare data types manually; Python automatically detects it based on the assigned value. - Examples of dynamically typed languages: Python, JavaScript. - Examples of statically typed languages: C, C++, Java. - Dynamically typed languages are easier and faster to code. - Statically typed languages are usually faster to execute due to type checking at compile time. Example: x = 10 # x is an integer x = "Hello" # Now x is a string Here, the type of x changes at runtime based on the assigned value hence it shows dynamic nature of Python.
89
參考答案
Data visualization is the most important part of data analysis. You get to see your data in action, and it helps you find hidden patterns. The most popular Python data visualization libraries are: - Matplotlib - Seaborn - Plotly - Bokeh Matplotlib and Seaborn are the most common. For interactive and more complex applications, we use Plotly, which can be used to create a web application or a dashboard. Bokeh is used for detailed graphics with a high level of interactivity across large datasets.
90
參考答案
- Tools like pip and virtual environments help manage dependencies and versions of libraries.
91
參考答案
Tuple comprehensions are not directly supported, Python's existing features like generator expressions and the tuple() function provide flexible alternatives for creating tuples from iterable data. (i for i in (1, 2, 3)) Explanation: In Python, expressions enclosed in parentheses with a for loop produce a generator expression, which generates values lazily one at a time. Since tuples are immutable sequences, Python does not provide a separate tuple comprehension syntax. Instead, the recommended approach is to use a generator expression and convert it into a tuple using tuple().
92
參考答案
Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor.
93
參考答案
Data cleaning is indeed a significant part. I've used libraries like Pandas and regular expressions for data cleaning and preprocessing. Additionally, visualization tools like Matplotlib and Seaborn help identify outliers and anomalies.
94
參考答案
Python uses the '_' symbol to determine the access control for a specific data member or a member function of a class. A Class in Python has three types of Python access modifiers: - Public Access Modifier: Members declared normally (without any underscore) are public and can be accessed from anywhere. - Protected Access Modifier: Members prefixed with a single underscore (_) are intended for internal use within the class and its subclasses. They can still be accessed from outside the class, but this is discouraged by convention. - Private Access Modifier: Members prefixed with double underscores (__) are name-mangled by Python to make accidental access from outside the class more difficult. Example: class Student: def __init__(self): # Public self.name = "Mike" # Protected self._roll_no = 101 # Private self.__marks = 95 obj = Student() print(obj.name) print(obj._roll_no) print(obj._Student__marks) Output Mike 101 95 Explanation: - name is a public attribute and can be accessed directly. - _roll_no is a protected attribute, it is accessible outside the class but intended for internal use. - __marks is a private attribute and is automatically renamed internally. - obj._Student__marks accesses the private attribute using Python's name mangling mechanism.
95
參考答案
A metaclass is a type of class that defines how classes will behave. Classes are instances of a metaclass, and metaclasses can define a method of creating classes that can, for instance, alter class attributes or constrain the class to a particular design pattern. Example: class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class MyClass(metaclass=Singleton): pass a = MyClass() b = MyClass() print(a is b) # True
96
參考答案
We can identify if a dataframe has missing values by using the isnull() and isna() methods. missing_data_count=df.isnull().sum() We can handle missing values by either replacing the values in the column with 0 as follows: df['column_name'].fillna(0) Or by replacing it with the mean value of the column df['column_name'] = df['column_name'].fillna((df['column_name'].mean()))
97
參考答案
Elements can be added to an array using the append(), extend() and the insert (i,x) functions. Example: a=arr.array('d', [1.1 , 2.1 ,3.1] ) a.append(3.4) print(a) a.extend([4.5,6.3,6.8]) print(a) a.insert(2,3.8) print(a) Output: array(‘d', [1.1, 2.1, 3.1, 3.4]) array(‘d', [1.1, 2.1, 3.1, 3.4, 4.5, 6.3, 6.8]) array(‘d', [1.1, 2.1, 3.8, 3.1, 3.4, 4.5, 6.3, 6.8])
98
參考答案
Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result. Type-checking can be done at two stages - - Static - Data Types are checked before execution. - Dynamic - Data Types are checked during execution. Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language.
99
參考答案
The __init__() method is known as a constructor in object-oriented programming (OOP) terminology. It is used to initialize an object's state when it is created. This method is automatically called when a new instance of a class is instantiated. Purpose: - Assign values to object properties. - Perform any initialization operations. Example: We have created a book_shop class and added the constructor and book() function. The constructor will store the book title name and the book() function will print the book name. To test our code we have initialized the b object with “Sandman” and executed the book() function. class book_shop: # constructor def __init__(self, title): self.title = title # Sample method def book(self): print('The title of the book is', self.title) b = book_shop('Sandman') b.book() # The title of the book is Sandman
100
參考答案
- Interpreted language. Unlike C, there's no need to compile Python code before running it. - Object-oriented language. Like Java and other OOP technologies, Python supports inheritance and class definition. On the other hand, there's no support for access specifiers (e.g., public, private in C++). - Code execution is slower than that of compiled languages. To find their way around the issue, developers use packages like NumPy.
101
參考答案
We can use the argmin() method of numpy as shown below: import numpy as np def find_nearest_value(arr, value): arr = np.asarray(arr) idx = (np.abs(arr - value)).argmin() return arr[idx] #Driver code arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742]) value = 0.52 print(find_nearest_value(arr, value)) # Prints 0.5645
102
參考答案
Microservices are a popular architectural style for building scalable systems, and Python is an excellent choice for developing them. Key aspects include: Choosing the Right Framework: Python offers frameworks like Flask (lightweight for small services), FastAPI (designed for performance with modern features), and Django REST framework (powerful with admin interface and ORM). Containerization: Docker is common for containerizing Python microservices, ensuring consistent environments across development stages and reducing 'it works on my machine' issues. Asynchronous Programming: Using asyncio and frameworks like Tornado can greatly enhance performance of I/O-bound microservices by handling concurrent connections efficiently. Testing: Automated testing with Pytest or Unittest is crucial to ensure each service functions correctly in isolation and when interacting with others. Inter-service Communication: Use HTTP/REST, gRPC, or messaging queues like RabbitMQ. Libraries like requests or httpx for HTTP, and pika for RabbitMQ. Monitoring and Logging: Use Python's logging module and comprehensive solutions like Prometheus or Elastic Stack. Deployment and Scaling: Use Kubernetes for orchestrating containerized applications. Security: Leverage built-in security features, use HTTPS, secure inter-service communications, and manage sensitive data securely.
103
參考答案
Big O notation is a mathematical notation used to describe the time complexity of algorithms. Big O notation gives insights into which solution is more scalable or efficient in the worst-case scenario, when comparing different algorithms for a problem. For example, a solution with a complexity of O(n^2) will perform worse than one with O(n) for large datasets. Recognizing and optimizing the complexity of algorithms is vital, especially when handling large amounts of data in Python applications. Big O notation is fundamental in assessing algorithm performance. For Python developers, mastering this concept ensures optimal code design, making it a frequent topic in technical interviews.
104
參考答案
class Graph: def __init__(self): self.vertices = {} def add_vertex(self, vertex): if vertex not in self.vertices: self.vertices[vertex] = [] def add_edge(self, u, v): if u in self.vertices and v in self.vertices: self.vertices[u].append(v) self.vertices[v].append(u) def display(self): for vertex in self.vertices: print(f'{vertex}: {self.vertices[vertex]}')
105
參考答案
- Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, python does provide some core API functions to work upon the private heap space. - Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space.
106
參考答案
- Use DatetimeIndex, resampling, rolling statistics, and specialized plotting functions.
107
參考答案
You can reverse a string using slicing: s = "Python" reversed_s = s[::-1] print(reversed_s) # Output: 'nohtyP'
108
參考答案
Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways: - Assigning lambda functions to a variable: mul = lambda a, b : a * b print(mul(2, 5)) # output => 10 - Wrapping lambda functions inside another function: def myWrapper(n): return lambda a : a * n mulFive = myWrapper(5) print(mulFive(2)) # output => 10
109
參考答案
All programming languages use positive indexing in the arrays to locate and access elements. Python is the only language that allows both positive and negative indexing in arrays. A positive index would start from the first element of an array and go forward i.e. the first element would be 0, the second element would be 1, and so on. In negative indexing, the last element of the array would have the index -1, the penultimate element would be -2, and so on. For example, arr = [a, b, c, d, e] print(arr[-1]) print(arr[-2]) Output e d
110
參考答案
- __init__() is Python's equivalent of constructors in OOP, called automatically when a new object is created. It initializes the object's attributes with values but doesn't handle memory allocation. - Memory allocation is handled by the __new__() method, which is called before __init__(). - The self parameter in __init__() refers to the instance of the class, allowing access to its attributes and methods. - self must be the first parameter in all instance methods, including __init__() class MyClass: def __init__(self, value): self.value = value # Initialize object attribute def display(self): print(f"Value: {self.value}") obj = MyClass(10) obj.display() Output Value: 10
111
參考答案
Unit testing in Python refers to the process of testing individual units or components of a software. These units are the smallest testable parts of an application, isolated from the rest of the code. The `unittest` module provides tools to create and run tests. Writing tests involves creating test cases that assert certain conditions. The tested unit functions as expected, When these assertions pass. For example, testing a function that adds two numbers would involve writing a test that checks if the function returns the correct sum. Failures indicate defects in the code or the test itself. Conducting unit tests aids developers in ensuring code quality. It identifies bugs early, simplifies integration, and facilitates refactoring. Proper unit testing increases the reliability of the software and reduces the likelihood of errors in production.
112
參考答案
Consider this computationally expensive code: # Fibonacci Numbers def fib(num): if num == 0: return 0 elif num == 1: return 1 return fib(num - 1) + fib(n - 2) Memoization can be achieved through Python decorators Here's the full implementation. import timeit def memoize_fib(func): cache = {} def inner(arg): if arg not in cache: cache[arg] = func(arg) return cache[arg] return inner def fib(num): if num == 0: return 0 elif num == 1: return 1 else: return fib(num-1) + fib(num-2) fib = memoize_fib(fib) print(timeit.timeit('fib(30)', globals=globals(), number=1)) print(timeit.timeit('fib(30)', globals=globals(), number=1)) print(timeit.timeit('fib(30)', globals=globals(), number=1)) Output: 4.9035000301955733e-05 1.374000021314714e-06 1.2790005712304264e-06
113
參考答案
Non-local statements allow assigning variables to outer-scope statements that are not global. The most common application of the keyword is in nested functions, where there's a need to make sure a variable isn't accessible by the inner function.
114
參考答案
The code is correct.
115
參考答案
This is the small anonymous function used in Python as an inline function. An example of lambda function is: lambda arguments : expression
116
參考答案
Output : Permutations of "ABC" is as below, ABC ACB BAC BCA CAB CBA
117
參考答案
Lists are built-in Python data structures that can hold elements of different data types, while NumPy arrays are homogeneous arrays of fixed size and contiguous memory. NumPy arrays also support vectorized operations and mathematical functions, making them more efficient for numerical operations.
118
參考答案
Consider the graph which is implemented in the code below: graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] } visited = [] # List to keep track of visited nodes. queue = [] #Initialize a queue def bfs(visited, graph, node): visited.append(node) queue.append(node) while queue: s = queue.pop(0) print (s, end = " ") for neighbour in graph[s]: if neighbour not in visited: visited.append(neighbour) queue.append(neighbour) # Driver Code bfs(visited, graph, 'A') Output: A B C D E F Explanation Lines 3-10: The illustrated graph is represented using an adjacency list. An easy way to do this in Python is to use a dictionary data structure, where each vertex has a stored list of its adjacent nodes. Line 12: visited is a list that is used to keep track of visited nodes. Line 13: queue is a list that is used to keep track of nodes currently in the queue. Line 29: The arguments of the bfs function are the visited list, the graph in the form of a dictionary, and the starting node A . Lines 15-26: bfs follows the algorithm described above: - It checks and appends the starting node to the visited list and thequeue . - Then, while the queue contains elements, it keeps taking out nodes from the queue, appends the neighbors of that node to the queue if they are unvisited, and marks them as visited. - This continues until the queue is empty. Time Complexity Since all of the nodes and vertices are visited, the time complexity for BFS on a graph is O(V + E); where V is the number of vertices and E is the number of edges.
119
參考答案
PEP 8 is Python's style guide for writing clean and readable code. It includes conventions such as indentation (4 spaces per level), naming variables in snake_case, and avoiding line length exceeding 79 characters. It ensures consistency across Python projects.
120
參考答案
Output : Using String slicing : DASARP Using for loop : DASARP
121
參考答案
The Python int function will convert a string to an integer. The second parameter is for the base of the number, so 10 for decimal numbers. x = '100' int(x, 10)
122
參考答案
Sample Answer: To convert a list of strings to uppercase, you can iterate through the list and convert each string to uppercase using Python's str.upper() method. For example: def to_uppercase(strings): return [s.upper() for s in strings]
123
參考答案
A binary search algorithm in Python is implemented by repeatedly dividing the sorted list in half until the desired element is found or the whole list is exhausted. To begin with, define three pointers: `low` , `high` , and `mid` . Set `low` to 0 and `high` to the length of the list minus one. In each iteration, calculate `mid` as the average of `low` and `high` . Compare the mid-value with the target. If the target is equal to the mid-value, return `mid` . If the target is less than the mid-value, update `high` to `mid - 1` . If the target is greater, set `low` to `mid + 1` . Continue the process until `low` exceeds `high` or the target is found. If the list does not contain the target, return an indication of failure, such as -1. This algorithm works efficiently for sorted lists, reducing the search space by half in each step.
124
參考答案
- df.pivot() reshapes the DataFrame by setting date as the index, category as columns, and value as the data to fill the new table. import pandas as pd # Sample data data = { 'date': ['2023-01-01', '2023-01-01', '2023-01-02', '2023-01-02'], 'category': ['A', 'B', 'A', 'B'], 'value': [10, 20, 15, 25] } # Creating DataFrame df = pd.DataFrame(data) # Pivoting the DataFrame pivot_df = df.pivot(index='date', columns='category', values='value') # Display the pivoted DataFrame print(pivot_df)
125
參考答案
print("Hello, World!") Output Hello, World!
126
參考答案
The `contextlib` module provides utilities for creating and working with context managers using the `with` statement.
127
參考答案
we first have to convert all the IP addresses and the netmask to integers using the ip_to_int function from earlier. Then, we have to use the bitwise AND operator (&) to mask out the subnet portion of the IP addresses, and compare the results. If they are equal, the two IP addresses are in the same subnet.
128
參考答案
There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories- - None Type: None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects. | Class Name | Description | |---|---| | NoneType | Represents the NULL values in Python. | - Numeric Types: There are three distinct numeric types - integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers. | Class Name | Description | |---|---| | int | Stores integer literals including hex, octal and binary numbers as integers | | float | Stores literals containing decimal values and/or exponent signs as floating-point numbers | | complex | Stores complex numbers in the form (A + Bj) and has attributes: real and imag | | bool | Stores boolean value (True or False). | Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision. - Sequence Types: According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations. | Class Name | Description | |---|---| | list | Mutable sequence used to store collection of items. | | tuple | Immutable sequence used to store collection of items. | | range | Represents an immutable sequence of numbers generated during execution. | | str | Immutable sequence of Unicode code points to store textual data. | Note: The standard library also includes additional types for processing: 1. Binary data such as bytearray bytes memoryview, and 2. Text strings such as str. - Mapping Types: A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary. | Class Name | Description | |---|---| | dict | Stores comma-separated list of key: value pairs | - Set Types: Currently, Python has two built-in set types - set and frozenset. set type is mutable and supports methods like add() and remove(). frozenset type is immutable and can't be modified after creation. | Class Name | Description | |---|---| | set | Mutable unordered collection of distinct hashable objects. | | frozenset | Immutable collection of distinct hashable objects. | Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set. - Modules: Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a name defined in m's symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended. - Callable Types: Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes. Refer to the documentation at docs.python.org for a detailed view of the callable types.
129
參考答案
`zip` combines iterables element-wise, and `map` applies a function to elements of iterables. For example, `zip([1, 2], [3, 4])` returns `[(1, 3), (2, 4)]` ```, and` map(lambda x: x*2, [1, 2, 3]) `returns` [2, 4, 6] ```.
130
參考答案
To create a class in python, we use the keyword "class" as shown in the example below: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name To instantiate or create an object from the class created above, we do the following: emp_1=InterviewbitEmployee("Mr. Employee") To access the name attribute, we just call the attribute using the dot operator as shown below: print(emp_1.emp_name) # Prints Mr. Employee To create methods inside the class, we include the methods under the scope of the class as shown below: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name) The self parameter in the init and introduce functions represent the reference to the current class instance which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown below: emp_1.introduce() The overall program would look like this: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name) # create an object of InterviewbitEmployee class emp_1 = InterviewbitEmployee("Mr Employee") print(emp_1.emp_name) #print employee name emp_1.introduce() #introduce the employee
131
參考答案
The lambda function inside the filter() function is missing the argument nums in the expression. The corrected code is: def get_odd_numbers(nums): odd_nums = filter(lambda num: num % 2, nums) return list(odd_nums) nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(get_odd_numbers(nums))
132
參考答案
Python offers various database libraries like SQLAlchemy and Django ORM. You can connect to databases, execute queries, and perform CRUD operations.
133
參考答案
A closure is a lambda (or nested function) that captures variables from its enclosing scope, even after that scope has finished executing. For example, lambda x: x + y forms a closure if y is defined in an outer scope and the lambda retains access to it.
134
參考答案
Use lambda functions when an anonymous function is required for a short period of time.
135
參考答案
The if __name__ == "__main__": statement checks whether the Python script is being run as the main program. It allows you to separate the code that should only run when the script is executed directly from the code that should be used when the script is imported as a module. if __name__ == "__main__": # Code here will only run if the script is executed directly print("Hello, world!")
136
參考答案
Data frames are two-dimensional, labeled data structures in Python, commonly used in the pandas library. They resemble spreadsheets or SQL tables and allow for efficient data manipulation, analysis, and storage.
137
參考答案
Solution: def is_prime_factor(number, potential_factor): if number <= 1 or potential_factor <= 1: return False # Numbers less than or equal to 1 are not considered prime factors return number % potential_factor == 0 # Example usage number = 15 potential_factor = 3 if is_prime_factor(number, potential_factor): print(potential_factor, "is a prime factor of", number) else: print(potential_factor, "is not a prime factor of", number) Output: 3 is a prime factor of 15
138
參考答案
In Python, ‘return' sends a value and terminates a function, while ‘yield' produces a value but retains the function's state, allowing it to resume from where it left off. | YIELD | RETURN | | It replace the return of a function to suspend its execution without destroying local variables. | It exits from a function and handing back a value to its caller. | | It is used when the generator returns an intermediate result to the caller. | It is used when a function is ready to send a value. | | Code written after yield statement execute in next function call. | while, code written after return statement wont execute. | | It can run multiple times. | It only runs single time. | | Yield statement function is executed from the last state from where the function get paused. | Every function calls run the function from the start.
139
參考答案
The time complexity of recursion depends on the number of times the function calls itself. If a function calls itself two times then its time complexity is O(2 ^ N). if it calls three times, then its time complexity is O(3 ^ N) and so on.
140
參考答案
The join method in Python takes elements of an iterable data structure and connects them together using a particular string connector value. How does join work? The join method in Python is a string method, which connects elements of a string iterable structure, which also contains strings or characters (array, list, etc.) by using a particular string as the connector. Example: Connecting elements using an empty string This will join the elements in an array using an empty string between each element. array = ['H','E','L','L','O'] connector = "" joined_string = connector.join(array) print(joined_string) Output: HELLO
141
參考答案
Slicing in Python is about dividing a given string to obtain sub-strings. If you wish to access sequences such as lists, tuples, and strings, slicing is the feature that will help you do so. You can select a specific range or part of these sequences using slicing. You can change or delete parts of sequences like lists that can be changed. Slicing in Python helps you write clean, precise, and readable code. You can perform slicing in Python by either extending indexing or using the slice() Constructor.
142
參考答案
Python documentation strings (or docstrings) provide a convenient way of associating documentation with Python modules, functions, classes, and methods.
143
參考答案
`map` applies a function to elements of an iterable, `filter` filters elements based on a function```'s result, and reduce` applies a function cumulatively to elements of an iterable.``
144
參考答案
In Python, you can handle exceptions using the try, except, else, and finally blocks. The try block contains the code that may raise an exception. If an exception occurs, it is caught by the corresponding except block. The else block is executed if no exception occurs, and the finally block is executed regardless of whether an exception occurred or not.
145
參考答案
x = x + [1] creates a new list and assigns it to x, while x += [1] changes the same list in place, this matters when other variables point to the same list, because one keeps the old list and the other sees the change. a = [1, 2] b = a a = a + [3] print(b) # [1, 2] a = [1, 2] b = a a += [3] print(b) # [1, 2, 3]
146
參考答案
Session management is the process of tracking and managing the state of a user's interaction with a web application. Session management includes the user's login status, preferences, etc. Session management in Python web applications refers to the process of preserving user data across multiple requests. This mechanism ensures that a user does not need to re-authenticate or re-enter data on every page or action. Flask and Django, offer built-in tools for this purpose. Flask uses a secure cookie-based session system by default. Django employs a database-driven session system. A unique session ID is generated and sent to the client's browser, when a user logs in. This ID serves as a reference to the user's stored data on the server. Session management facilitates a seamless user experience. Web applications would not provide continuity or remember individual user interactions across pages.
147
參考答案
You can install Pandas using pip by running the command pip install pandas.
148
參考答案
This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below. import pandas as pd df1 = pd.Series([2, 4, 8, 10, 12]) df2 = pd.Series([8, 12, 10, 15, 16]) df1=df1[~df1.isin(df2)] print(df1) """ Output: 0 2 1 4 dtype: int64 """
149
參考答案
Pandas aggregation is the process of summarizing data by computing statistical measures like mean, median, mode, standard deviation, etc., on a group of rows in a dataframe.
150
參考答案
Object-Oriented Programming (OOP) is a programming paradigm that uses objects and classes to design and structure code. Objects represent real-world entities and the interactions between them in OOP. Python fully supports Object-Oriented Programming (OOP). It allows developers to define classes, create objects, and work with inheritance, polymorphism, and encapsulation. Everything is an object in Python, even basic data types like integers and strings. A class in Python is defined using the `class` keyword. Objects of that class can be instantiated once it is defined. Inheritance allows a class to inherit attributes and methods from another class, enabling code reuse and establishing relationships between classes. Methods in Python can be overridden in derived classes, showcasing polymorphism. Encapsulation is achieved by using private and protected access specifiers, though it's more of a convention in Python. Python offers a rich set of tools and constructs for OOP, making it easy for developers to model and solve complex problems using objects and classes.
151
參考答案
Python zip() function returns a zip object, which maps a similar index of multiple containers. It takes an iterable, converts it into an iterator and aggregates the elements based on iterables passed. It returns an iterator of tuples. Syntax: zip(*iterables)
152
參考答案
- Reusable blocks of code that take arguments and perform specific tasks. - Defined with def: def function_name(parameters): # code block return value
153
參考答案
Lambda functions are generally inline, anonymous functions represented by a single expression. They are used for creating function objects during runtime. They can accept any number of parameters. They are usually used where functions are required only for a short period. They can be used as: mul_func = lambda x,y : x*y print(mul_func(6, 4)) # Output: 24
154
參考答案
Membership operators are used to test if a sequence is present in an object. The in and not in operators are examples of these: x = ["apple", "banana"] print("banana" in x) # returns True x = ["apple", "banana"] print("pineapple" not in x) # returns True
155
參考答案
Use the split() method, which divides a string by whitespace by default: sentence = "Hello World" words = sentence.split() print(words) # Output: ['Hello', 'World']
156
參考答案
Python does not have a traditional switch statement like languages such as C, C++ or Java. Starting with Python 3.10, however, Python introduced structural pattern matching using the match and case keywords, which provides similar functionality. match term: case pattern-1: action-1 case pattern-2: action-2 case pattern-3: action-3 case _: action-default
157
參考答案
Python is widely used for the following fields: - Web Scraping Applications. - Data Science. - Artificial Intelligence and Machine Learning. - Game Development. - Software Development - Web Development, etc.
158
參考答案
To see the code solution in action, visit the original post. Explanation Iterate over the whole linked list and add each visited node to a visited_nodes set. At every node, we check whether it has been visited or not. By principle, if a node is revisited, a cycle exists! Time Complexity We iterate the list once. On average, lookup in a set takes O(1) time. Hence, the average runtime of this algorithm is O(n). However, in the worst case, lookup can increase up to O(n), which would cause the algorithm to work in
159
參考答案
- Documentation string or docstring is a multiline string used to document a specific code segment. - The docstring should describe what the function or method does.
160
參考答案
`MultiIndex` is a feature in Pandas that allows you to have multiple levels of row and column labels in a DataFrame. It is used when dealing with complex, hierarchical data.
161
參考答案
Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class. They are different types of inheritance supported by Python: - Single Inheritance – where a derived class acquires the members of a single super class. - Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2. - Hierarchical inheritance – from one base class you can inherit any number of child classes - Multiple inheritance – a derived class is inherited from more than one base class.
162
參考答案
Use try-except blocks for handling exceptions. Example: try: result = 10 / 0 except ZeroDivisionError as e: print(f"Error: {e}") finally: print("This always executes.")
163
參考答案
Random module is the standard module that is used to generate a random number. The method is defined as: import random random.random The statement random.random() method return the floating-point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are:
164
參考答案
You can specify default values for parameters in the function definition, like this: def greet(name="Guest"): print("Hello, " + name)
165
參考答案
Late binding means variables in a function are looked up when the function is called, not when it is created, so in a loop, all lambdas end up using the last value of the loop variable, which gives wrong results, the fix is to pass the value as a default argument. funcs = [] for i in range(3): funcs.append(lambda: i) for f in funcs: print(f()) # 2 2 2 funcs = [] for i in range(3): funcs.append(lambda i=i: i) for f in funcs: print(f()) # 0 1 2
166
參考答案
The idea is to use collections and pprint module as shown below: import collections import pprint with open("sample_file.txt", 'r') as data: count_data = collections.Counter(data.read().upper()) count_value = pprint.pformat(count_data) print(count_value)
167
參考答案
from django.db import models class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) publication_date = models.DateField() # Creating an instance in the Django shell # from myapp.models import Book # book = Book(title='Sample Book', author='Author Name', publication_date='2023-01-01') # book.save() Explanation of solution: The Book model is defined with three fields: title, author, and publication_date. The model is a subclass of django.db.models.Model. An example is provided for creating an instance of Book in the Django shell, including saving it to the database.
168
參考答案
- Lists: Mutable -- elements can be changed after creation. Use square brackets ([]). - Tuples: Immutable -- elements cannot be changed after creation. Use parentheses (()).
169
參考答案
Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in python source code files and raises alerts for code issues and their complexity. Pylint checks for the module's coding standards and supports different plugins to enable custom features to meet this requirement.
170
參考答案
Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object. Here, the pickle module comes into play. Pickling: - Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions. - The function used for the above process is pickle.dump(). Unpickling: - Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory. - The function used for the above process is pickle.load(). Note: Python has another, more primitive, serialization module called marshall, which exists primarily to support .pyc files in Python and differs significantly from the pickle.
171
參考答案
Duplicates from a list in Python are removed using the set data structure. Transform the list into a set, which inherently doesn't allow duplicate values. Once the duplicates are removed, convert the set back to a list. For example, if you have a list named `my_list`, you can obtain a duplicate-free list with `list(set(my_list))`. It will not preserve the original order of the list, using this method. You can use list comprehensions,to retain the order, Iterate over the list and add each item to the new list only if it hasn't been added before. Opt for the method that best suits the requirements of your application, be it order preservation or computational efficiency.
172
參考答案
One dimensional array capable of storing different data types is called a series. We can create pandas series from a dictionary object as shown below: import pandas as pd dict_info = {'key1' : 2.0, 'key2' : 3.1, 'key3' : 2.2} series_obj = pd.Series(dict_info) print (series_obj) Output: x 2.0 y 3.1 z 2.2 dtype: float64 If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order for constructing the index. In case the index is passed, then values of the index label will be extracted from the dictionary.
173
參考答案
Dependencies can be managed using: - pip: For installing and managing packages. - requirements.txt: Lists all dependencies for a project. - Virtual environments: Tools like venv or virtualenv isolate dependencies. Example: bash pip install -r requirements.txt
174
參考答案
To see the code solution in action, go to the original post. Here you can use two pointers which will work simultaneously. Think of it this way: - The fast pointer moves two steps at a time till the end of the list - The slow pointer moves one step at a time - When the fast pointer reaches the end, the slow pointer will be at the middle Using this algorithm, you can make the process faster because the calculation of the length and the traversal until the middle are happening side-by-side. Time Complexity You are traversing the linked list at twice the speed, so it is certainly faster. However, the bottleneck complexity is still O(n).
175
參考答案
You can download Python from the official website (python.org) and follow the installation instructions for your operating system.
176
參考答案
Sample Answer: Finding the intersection of two sorted arrays involves identifying the common elements that appear in both arrays. This can be efficiently achieved using a two-pointer technique, where you maintain a pointer for each array and move them based on the comparison of the elements. Here's the code to find the intersection of two sorted arrays: def intersection_sorted(arr1, arr2): result = [] i, j = 0, 0 while i < len(arr1) and j < len(arr2): if arr1[i] < arr2[j]: i += 1 elif arr1[i] > arr2[j]: j += 1 else: result.append(arr1[i]) i += 1 j += 1 return result
177
參考答案
You move one pointer one step at a time and another two steps at a time, if there is a cycle they will meet, if the fast pointer reaches the end then there is no cycle, this uses no extra memory and is very efficient. def has_cycle(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False
178
參考答案
The with statement is used for exception handling to make code cleaner and simpler. It is generally used for the management of common resources like creating, editing, and saving a file. Example: Instead of writing multiple lines of open, try, finally, and close, you can create and write a text file using the with statement. It is simple. # using with statement with open('myfile.txt', 'w') as file: file.write('DataCamp Black Friday Sale!!!')
179
參考答案
Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicing is-[start:end:step]. The step can be omitted as well. When we write [start:end] this returns all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or end element is negative i, it means the ith element from the end. The step indicates the jump or how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] will return elements starting from the last element till the third element by printing every second element.i.e. [8,6,4].
180
參考答案
__str__ returns a user-friendly string representation of an object, while __repr__ returns an unambiguous string representation, typically one that could recreate the object.
181
參考答案
A list in python is an ordered collection of items. It can hold elements of different data types.
182
參考答案
The Global Interpreter Lock (GIL) is a mechanism in CPython (the standard implementation of Python) that allows only one thread to execute Python bytecode at a time. This means that even on multi-core systems, Python threads cannot fully utilize multiple CPU cores for CPU-bound tasks. However, the GIL doesn't impact performance much for I/O-bound tasks, making multithreading beneficial in such scenarios.
183
參考答案
In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string.
184
參考答案
- Numeric types: int, float, complex - Sequence types: list, tuple, range - Text type: str - Set types: set, frozenset - Mapping type: dict - Boolean type: bool - Binary types: bytes, bytearray, memoryview
185
參考答案
To open and read a file in Python, you can use the open() function with the appropriate file mode (e.g., r' for reading). For example: with open(example.txt', r') as file: content = file.read()
186
參考答案
An empty class does not have any members defined in it. It is created by using the pass keyword (the pass command does nothing in python). We can create objects for this class outside the class. For example- class EmptyClassDemo: pass obj=EmptyClassDemo() obj.name="Interviewbit" print("Name created= ",obj.name) Output: Name created = Interviewbit
187
參考答案
Cookies are small pieces of data stored on a user's browser by websites. They help websites remember user preferences, login details, and other information to improve user experience. The `http.cookies` module provides tools for working with cookies. Python web frameworks like Flask and Django have built-in mechanisms for handling cookies. For instance, you use `request.cookies` to read cookies and `response.set_cookie` to set them in Flask. Django provides a similar interface through its `request.COOKIES` attribute and the `set_cookie` method on its HttpResponse object. Cookies play a crucial role in maintaining session states and personalizing user interactions in web development. Python, with its rich ecosystem, facilitates smooth cookie management in web applications.
188
參考答案
Use the re module to compile and search patterns. Example: re.findall(r'\b\w{3}\b', text) finds all three-letter words in a text.
189
參考答案
To reverse the rows of a pandas DataFrame, use the iloc[] indexer with [::-1] to reverse row order, e.g., df_reversed = df.iloc[::-1]. Alternatively, use df.sort_index(ascending=False) or df.reindex(index=df.index[::-1]).
190
參考答案
Context managers, implemented with ` ```with``` ` statements, manage resources like files and database connections, ensuring they``'re properly acquired and released.
191
參考答案
Always check the status_code member variable on the response object and handle things according to the code. Example: import requests response = requests.get('https://api.example.com/data') if response.status_code == 200: print("Success") elif response.status_code == 404: print("Not Found") else: print(f"Error: {response.status_code}")
192
參考答案
Answer: a) True The WITH statement when used with open file guarantees that the file object is closed when the with block exits.
193
參考答案
- Pandas is an open-source, python-based library used in data manipulation applications requiring high performance. The name is derived from "Panel Data" having multidimensional data. This was developed in 2008 by Wes McKinney and was developed for data analysis. - Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it, model it, and analyze the data.
194
參考答案
An iterator is an object that implements __iter__() and __next__(), whereas a generator is a special type of iterator that is defined using a regular function and the yield keyword.
195
參考答案
Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are: - Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them - log10(), acos(), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp(). - Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities. temp = 10 # global-scope variable def func(): temp = 20 # local-scope variable print(temp) print(temp) # output => 10 func() # output => 20 print(temp) # output => 10 This behavior can be overridden using the global keyword inside the function, as shown in the following example: temp = 10 # global-scope variable def func(): global temp temp = 20 # local-scope variable print(temp) print(temp) # output => 10 func() # output => 20 print(temp) # output => 20
196
參考答案
Conditional statements control the flow of execution using if, elif, and else. Example: x = 5 if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative")
197
參考答案
import pandas as pd def fill_missing_values(df, column): mean_val = df[column].mean() df[column].fillna(mean_val, inplace=True) return df # Example usage # df = pd.DataFrame({'Values': [1, 2, None, 4]}) # df_filled = fill_missing_values(df, 'Values') Explanation of solution: The function fill_missing_values calculates the mean of the specified column and fills missing values with this mean. fillna is used with inplace=True to modify the original DataFrame. This is a common approach to handle NaN values in datasets.
198
參考答案
Use openpyxl for reading/writing Excel files. Example: import openpyxl # Create a new workbook wb = openpyxl.Workbook() ws = wb.active # Write to a cell ws['A1'] = 'Hello' # Save the workbook wb.save('example.xlsx')
199
參考答案
As the name suggests, polymorphism is the ability of a thing to assume many forms. In Python, it refers to using a function for different data types (strings, integers, booleans, or floats). While two functions will have identical names, they will differ by signatures.
200
參考答案
Shallow Copy: - Shallow copy creates a new object and then copies the references of the original object's elements into the new object. - The new object and the original object share the same elements (references), so changes made to one object may affect the other. - In a shallow copy, the top-level elements are copied, but the nested objects within them are not duplicated. - Shallow copies are created using methods like slicing, the `copy()` method, or the `copy` module. Deep Copy: - Deep copy creates a new object and recursively copies all the elements and nested objects of the original object. - The new object is completely independent of the original object, and any changes made to one object do not affect the other. - Deep copies ensure that all levels of the object hierarchy are duplicated, including nested objects and their references. - Deep copies are created using the `copy.deepcopy()` function from the `copy` module.