不想錯過任何事?

通過認證考試的技巧

最新考試新聞和折扣資訊

由我們的專家策劃和更新

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

查看其他面試題

1
參考答案
Solution: def fibonacci(n): fib_sequence = [0, 1] # Initialize the sequence with the first two terms for i in range(2, n): next_term = fib_sequence[-1] + fib_sequence[-2] fib_sequence.append(next_term) return fib_sequence # Example usage num_terms = 10 fib_sequence = fibonacci(num_terms) print("Fibonacci sequence up to", num_terms, "terms:", fib_sequence) Output: Fibonacci sequence up to 10 terms: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
2
參考答案
A namespace in python refers to the name which is assigned to each object in python. The objects are variables and functions. As each object is created, its name along with space(the address of the outer function in which the object is), gets created. The namespaces are maintained in python like a dictionary where the key is the namespace and value is the address of the object. There 4 types of namespace in python-
職涯加速

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

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

1 100% 通過率
2 2 週題庫練習
3 通過認證考試
3
參考答案
You can verify whether the given number is a prime factor of another number by utilizing the is_prime_factor function and determining whether the number is prime (is_prime), followed by checking if even the number you would like to verify the properties of can be evenly divided. 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 is_prime_factor(number, potential_factor): return is_prime(potential_factor) and number % potential_factor == 0 print(is_prime_factor(15, 3)) # Output: True print(is_prime_factor(15, 4)) # Output: False
4
參考答案
Assertions in Python are a debugging aid that tests a condition as an internal self-check in your program. They are implemented by the "assert" statement. Python uses "AssertionError" to raise an exception, if the assert statement fails. Assertions are not intended to signal expected error conditions, like a "File not found" error, but to detect bugs. Use them when you're confident the assertion will hold true, because it's a way to communicate to other developers about the assumptions in your code. Avoid using assertions for data validation or to handle runtime errors. Disable them globally in production code using the "-O" (optimize) command line switch.
5
參考答案
Packages in Python are installed using the package manager called pip. Pip comes bundled with Python installations from version 3.4 onwards. Simply use the command `pip install package-name` in your terminal or command prompt to install a package. For example, you'd run `pip install requests`, to install the popular requests library. It's advisable to use virtual environments, such as `venv` or `virtualenv`, when working on different projects. This way, dependencies are managed for each project separately, preventing potential conflicts. Activate the virtual environment before installing packages, ensuring they are confined to that specific environment.
6
參考答案
- Use browser-specific methods like accept_alert() or dismiss_alert() to handle alerts. - Utilize WebDriverWait for JavaScript execution with execute_script() method.
7
參考答案
- Allows creating new classes (subclasses) by inheriting attributes and methods from existing classes (superclasses). - Promotes code reuse and simplifies building complex object hierarchies. - Python Example: class Parent: pass class Child(Parent): pass
8
參考答案
Monkey patching is the practice of dynamically modifying or extending code at runtime, such as changing the behavior of classes or modules. In Python, it involves reassigning attributes or methods, which can be useful for testing or quick fixes.
9
參考答案
You can use the type() function, like this: x = 10 print(type(x)) # Output:
10
參考答案
def calculate_simple_interest(principal, rate, time): # Simple interest formula: SI = (P * R * T) / 100 simple_interest = (principal * rate * time) / 100 return simple_interest # Input from the user principal = float(input("Enter the principal amount: ")) rate = float(input("Enter the annual interest rate (in percentage): ")) time = float(input("Enter the time period (in years): ")) # Calculate simple interest interest = calculate_simple_interest(principal, rate, time) # Display the result print(f"The simple interest for the principal amount ${principal}, annual interest rate of {rate}%, and time period of {time} years is ${interest}.") The function calculate_simple_interest() takes the principal amount, annual interest rate, and time period as input and returns the simple interest. Then, it prompts the user to enter these values and calls the function to calculate the simple interest, finally displaying the result.
11
參考答案
Functional programming languages rely on immutable objects. On the contrary, object-oriented programming supports mutable states and allows object modifications. Functional programming relies on the concept of function, using inputs in computations to return the desired output. On the other hand, OOP is class-focused, allowing developers to create variables that can be manipulated using methods or functions, inherited, or extended.
12
參考答案
__str__ returns a human-readable string representation of an object, used by print(). __repr__ returns an unambiguous string representation used for debugging.
13
參考答案
Python's threading module lets you run multiple threads within a single process, all sharing the same memory space. But there's a catch - the Global Interpreter Lock (GIL). This lock restricts threads from executing Python bytecode simultaneously, which means threading is best suited for I/O-bound tasks like reading files or handling network requests, rather than heavy computations. On the flip side, multiprocessing takes a different approach. It spins up separate processes, each with its own memory space. This allows true parallel execution by leveraging multiple CPU cores, making it a great choice for CPU-bound tasks such as complex calculations or intensive data processing. However, this comes at a cost - multiprocessing typically uses more memory and requires a bit more setup compared to threading.
14
參考答案
We need to create a function that takes a list of coin denominations and a total amount and returns the number of ways we can make the change. In the example, we have provided coin denominations [1, 2, 5] and the total amount of 5. In return, we get four ways to make the change. Solution: - We will create the list of size amount + 1. Additional space is added to store the solution for a zero amount. - We will initiate a solution list with solution[0] = 1. - We will run two loops. The outer loop iterates over the denominations, and the inner loop runs from the current denomination value to amount + 1. - The results of different denominations are stored in the array solution. solution[i] = solution[i] + solution[i - den]. The process will be repeated for all the elements in the denomination list, and at the last element of the solution list, we will have our number. def solve_coin_change(denominations, amount): solution = [0] * (amount + 1) solution[0] = 1 for den in denominations: for i in range(den, amount + 1): solution[i] += solution[i - den] return solution[amount] denominations = [1, 2, 5] amount = 5 solve_coin_change(denominations, amount) # 4
15
參考答案
The common built-in data types in python are- Numbers– They include integers, floating-point numbers, and complex numbers. eg. 1, 7.9,3+4i List– An ordered sequence of items is called a list. The elements of a list may belong to different data types. Eg. [5,'market',2.4] Tuple– It is also an ordered sequence of elements. Unlike lists , tuples are immutable, which means they can't be changed. Eg. (3,'tool',1) String– A sequence of characters is called a string. They are declared within single or double-quotes. Eg. "Sana" , 'She is going to the market' , etc. Set– Sets are a collection of unique items that are not in order. Eg. {7,6,8} Dictionary– A dictionary stores values in key and value pairs where each value can be accessed through its key. The order of items is not important. Eg. {1:'apple',2:'mango} Boolean– There are 2 boolean values- True and False.
16
參考答案
A rolling window calculation can be performed on a Pandas dataframe column using the rolling() function, which allows you to specify the window size and the function to apply to each window.
17
參考答案
Profiling (e.g. cProfile) or looking into network delay or a long parsing time can help you find performance issues. You could reduce duplicated requests, use a session to persist cookies, or restrict parsing to some of the data to optimize processing. Example: import requests from bs4 import BeautifulSoup session = requests.Session() response = session.get('https://example.com') soup = BeautifulSoup(response.text, 'html.parser') titles = [tag.text for tag in soup.select('h1, h2')]
18
參考答案
We can use the method numpy.loadtxt() which can automatically read the file's header and footer lines and the comments if any. This method is highly efficient and even if this method feels less efficient, then the data should be represented in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of NumPy used. Following are the file formats that are supported: - Text files: These files are generally very slow, huge but portable and are human-readable. - Raw binary: This file does not have any metadata and is not portable. But they are fast. - Pickle: These are borderline slow and portable but depends on the NumPy versions. - HDF5: This is known as the High-Powered Kitchen Sink format which supports both PyTables and h5py format. - .npy: This is NumPy's native binary data format which is extremely simple, efficient and portable.
19
參考答案
Depth-first search (DFS) is implemented in Python using recursion or an explicit stack. You start from a source node, represented as an adjacency list or matrix, for a given graph. You explore as far as possible along each branch before backtracking. The process ensures every vertex gets visited. The function calls itself for every unvisited neighboring node. Using recursion, for an iterative approach you use a stack. Push the source node onto the stack. Pop a node, process it, and push its unvisited neighbors onto the stack, while the stack isn't empty. Mark nodes as visited to avoid infinite loops and redundant operations. It's crucial to maintain a record of visited nodes, to ensure the algorithm works correctly. Ensuring efficient traversal of the graph, the algorithm doesn't revisit nodes.
20
參考答案
Optimizations include using efficient libraries like pandas and NumPy for vectorized computations, avoiding loops with built-in functions, minimizing data copying, selecting appropriate data structures, and leveraging parallelism or chunk-based processing where appropriate.
21
參考答案
try: and except: are commonly known for exceptional handling in Python, so where does else: come in handy? else: will be triggered when no exception is raised. Let's learn more about else: with a couple of examples. - On the first try, we entered 2 as the numerator and d as the denominator. Which is incorrect, and except: was triggered with “Invalid input!”. - On the second try, we entered 2 as the numerator and 1 as the denominator and got the result 2. No exception was raised, so it triggered the else: printing the message Division is successful. try: num1 = int(input('Enter Numerator: ')) num2 = int(input('Enter Denominator: ')) division = num1/num2 print(f'Result is: {division}') except: print('Invalid input!') else: print('Division is successful.') ## Try 1 ## # Enter Numerator: 2 # Enter Denominator: d # Invalid input! ## Try 2 ## # Enter Numerator: 2 # Enter Denominator: 1 # Result is: 2.0 # Division is successful.
22
參考答案
It is a constructor method automatically called to allocate memory when a new instance or object is created, and classes in Python have an init associated with them which initializes attributes declared in the class when an object of that class is created.
23
參考答案
You can use the `.pct_change()` method to calculate the percentage change between rows in a DataFrame, which is useful for time series data.
24
參考答案
- Arrays in python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists. - Lists in python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory. import array a = array.array('i', [1, 2, 3]) for i in a: print(i, end=' ') #OUTPUT: 1 2 3 a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str) a = [1, 2, 'string'] for i in a: print(i, end=' ') #OUTPUT: 1 2 string
25
參考答案
Following are the ways using which you can access parent class members within a child class: - By using Parent class name: You can use the name of the parent class to access the attributes as shown in the example below: class Parent(object): # Constructor def __init__(self, name): self.name = name class Child(Parent): # Constructor def __init__(self, name, age): Parent.name = name self.age = age def display(self): print(Parent.name, self.age) # Driver Code obj = Child("Interviewbit", 6) obj.display() - By using super(): The parent class members can be accessed in child class using the super keyword. class Parent(object): # Constructor def __init__(self, name): self.name = name class Child(Parent): # Constructor def __init__(self, name, age): ''' In Python 3.x, we can also use super().__init__(name) ''' super(Child, self).__init__(name) self.age = age def display(self): # Note that Parent.name cant be used # here since super() is used in the constructor print(self.name, self.age) # Driver Code obj = Child("Interviewbit", 6) obj.display()
26
參考答案
When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case. Python does support multiple inheritances, unlike some programming languages that restrict multiple inheritance of classes. For example: class A: def method_a(self): print("Method from class A") class B: def method_b(self): print("Method from class B") class C(A, B): pass obj = C() obj.method_a() obj.method_b() Output Method from class A Method from class B Explanation: - A and B are parent classes, each defining one method. - C(A, B) inherits from both parent classes. - obj = C() creates an object of class C. - The object obj can call methods from both A and B.
27
參考答案
OS.unlink(filename) or OS.remove(filename)
28
參考答案
The purpose of Python's built-in function `dir()` is to return a list of names in the current local scope or a list of attributes of a specified object. `dir()` provides a list of names in the current local scope, when used without an argument. This includes functions, classes, and variables available in the immediate environment. `dir()` lists the attributes, methods, and properties associated with that object, when provided with an object as an argument. This function is valuable for introspection, allowing developers to understand the capabilities and structure of objects in Python.
29
參考答案
A list is mutable and can be changed after creation, while a tuple is immutable and cannot be modified. Lists are used when you need a collection that may change, such as dynamic data, whereas tuples are used for fixed data, such as function arguments or return values where immutability ensures safety.
30
參考答案
In Python 2, xrange returns an iterator that generates numbers lazily, while range returns a list. In Python 3, xrange is removed, and range behaves like xrange, returning a range object that is memory-efficient.
31
參考答案
The `json` module provides methods to serialize and deserialize JSON data. You can use `json.loads()` to parse JSON strings and `json.dumps()` to serialize Python objects to JSON``.
32
參考答案
- Simple and Easy to Learn: Python's syntax is clean and easy to understand. - Interpreted Language: Python code is executed line-by-line without prior compilation. - Dynamically Typed: You don't need to declare data types explicitly. - Extensive Libraries: Python offers a vast standard library and external modules for tasks like web development (Django, Flask), data manipulation (NumPy, Pandas), and machine learning (scikit-learn, TensorFlow). - Cross-Platform Compatibility: Python programs can run on different platforms with little to no modification. - Object-Oriented Programming Support: Python supports OOP principles like inheritance, encapsulation, and polymorphism.
33
參考答案
Python is considered both a compiled and an interpreted language. First, Python source code (.py files) is compiled into bytecode (.pyc files). Then, the Python Virtual Machine (PVM) interprets and executes this bytecode line by line. - Python code is first compiled into bytecode. - The Python Virtual Machine (PVM) executes the bytecode. - CPython, the most common Python implementation, both compiles and interprets code. - Some implementations like PyPy use Just-In-Time (JIT) compilation for improved performance. Therefore, Python combines features of both compiled and interpreted languages.
34
參考答案
You can use the `.astype()` method to change the data type of a column. For example: ` ```df['column_name'] = df['column_name'].astype('new_data_type'```)`.``
35
參考答案
PYTHONPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location.
36
參考答案
The `.nunique()` method is used to count the number of unique values in a column of a Pandas DataFrame.
37
參考答案
Advanced techniques include multi-indexing for hierarchical data, groupby-apply patterns, pivoting and melting data frames, handling time-series data, efficient merging and joining of large datasets, and optimizing with categorical types.
38
參考答案
Sample Input: 2 Sun 10 May 2015 13:54:36 -0700 Sun 10 May 2015 13:54:36 -0000 Sat 02 May 2015 19:54:36 +0530 Fri 01 May 2015 13:54:36 -0000 Sample Output: 25200 88200 Explanation: In the first query, when we compare the time in UTC for both the time stamps, we see a difference of 7 hours, which is 7 x 3,600 seconds or 25,200 seconds. Similarly, in the second query, the time difference is 5 hours and 30 minutes for time zone. Adjusting for that, we have a difference of 1 day and 30 minutes. Or 24 x 3600 + 30 x 60 = 88200.
39
參考答案
- Answer: Highlight sending API requests, validating responses with assertions, handling different status codes, and using data-driven approaches for API test cases. - Example Code: import requests response = requests.get('https://api.example.com/data') assert response.status_code == 200 assert 'key' in response.json()
40
參考答案
A thread is a lightweight subprocess that shares memory with the parent process, while a process is a separate instance of a program that has its own memory space.
41
參考答案
Type hints provide static type checking and improved code documentation, making it easier to understand and maintain code. You can use type hints for variables``, function parameters, and return values.
42
參考答案
The differences between `range` and `xrange` in Python lie in their working speed and return values. Both `range` and `xrange ` exist In Python 2,. `range` produces a list of numbers, consuming memory in proportion to the size of the range. This becomes memory-inefficient, for large ranges..`xrange` returns an iterator, generating numbers on-the-fly. It uses a consistent amount of memory, no matter the size of the range. Only `range` exists, in Python 3, but it behaves like `xrange` from Python 2. It returns an immutable sequence type, not a list, and generates numbers on demand. The memory concern associated with `range` in Python 2 does not exist in Python 3. You must replace `xrange` with `range` when transitioning code from Python 2 to 3. Developers often use conditionals to determine the Python version and use the appropriate function, if backward compatibility is essential. The primary distinction between the two is their memory consumption and iteration mechanism in Python 2. With Python 3's evolution, `xrange` became obsolete, and `range` adopted its characteristics. Understanding this change is crucial for Python developers, especially when working with older codebases or aiming for cross-version compatibility.
43
參考答案
Memoization is a technique to cache expensive function calls and reuse results. Example (Fibonacci with memoization): def fib(n, memo={}): if n in memo: return memo[n] if n <= 2: return 1 memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n] print(fib(10)) # 55
44
參考答案
To reverse a numpy array, we can use the flip() function in NumPy.
45
參考答案
Use the count() method to count specific characters. s = "banana" count_a = s.count('a') print(count_a) # Output: 3
46
參考答案
Performance optimization in Python is critical for efficient programs. Strategies include: - Utilize Built-in Data Types: Lists, sets, and dictionaries are implemented in C and optimized for performance. - Use List Comprehensions: Often faster than map, filter, or manual loops. - Take Advantage of Local Variables: Accessing local variables is faster than global variables. - Minimize the Use of Global Variables: Global variables slow down code due to longer lookup times. - Utilize Generators: Allow lazy evaluation, using less memory with large data sets. - Avoid Unnecessary Loops: Use built-in functions and libraries optimized with C-level code. - Profile Before Optimizing: Use profiling tools to identify bottlenecks. - Caching Results with functools.lru_cache: Improves performance for expensive functions called repeatedly with the same arguments. - Use Compiled Extensions: Write performance-critical parts in Cython or use PyPy as an alternative interpreter. - Optimize Algorithm Complexity: Using a more efficient algorithm often yields the biggest gains. - Keep Your Code Base Updated: Newer Python versions and libraries include performance improvements. - Multi-threading and Multi-processing: For CPU-bound tasks, use multi-processing; for I/O-bound tasks, use multi-threading.
47
參考答案
The dataframes can be combines using the below approaches: - append() method: This is used to stack the dataframes horizontally. Syntax: df1.append(df2) - concat() method: This is used to stack dataframes vertically. This is best used when the dataframes have the same columns and similar fields. Syntax: pd.concat([df1, df2]) - join() method: This is used for extracting data from various dataframes having one or more common columns. df1.join(df2)
48
參考答案
A dynamically typed language, like Python, does not require explicit declaration of variable types. The type is determined at runtime based on the assigned value, allowing for more flexibility but potentially leading to runtime errors.
49
參考答案
Read test data from external sources (like CSV or Excel) and run tests with different data sets. Example (using pytest): import pytest @pytest.mark.parametrize( "a, b, expected", [ (1, 2, 3), (4, 5, 9) ] ) def test_add(a, b, expected): assert a + b == expected
50
參考答案
- Answer: I'd use Selenium with WebDriverWait and ExpectedConditions to handle dynamic elements. For access blocks, I'd try user-agent rotation, headless browsing, and changing IP addresses to evade detection. If that fails, I'd consider alternative data sources or APIs.
51
參考答案
Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages - - Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone. - Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program. - Reusability: Functions defined in a module can be easily reused by other parts of the application. - Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program. Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar. Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names. Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot. Note: You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless.
52
參考答案
To remove duplicates from a list, you can convert the list to a set and then back to a list. The set automatically removes duplicates as it only stores unique elements. For example: original_list = [1, 2, 2, 3, 4, 4, 5] unique_list = list(set(original_list))
53
參考答案
Lists are mutable (can be modified after creation) and are defined with square brackets []. Tuples are immutable (cannot be changed after creation) and are defined with parentheses (). Tuples are often used for fixed collections of items, while lists are for variable-length sequences.
54
參考答案
Re is a Python module developers use to execute operations that involve expression matching. In particular, it contains three modules to allow editing strings – subn(), sub(), and split(). Here are the differences between these methods: | Method name | Application | | subn() | Defines all strings with a matching regex pattern, replaces them with a new one, and returns the number of replacements. | | sub() | Defines all strings with a matching regex pattern and replaces them with a new one. | | split() | Splits strings into lists using regex patterns. |
55
參考答案
A context manager is used to manage resources like files, database connections, or locks. It makes sure things are properly opened and closed.You use it with the with keyword. It runs setup code when entering and cleanup code when exiting. This avoids bugs like forgetting to close a file.It keeps code clean and safe. with open("data.txt", "w") as f: f.write("Hello World") # File is automatically closed here
56
參考答案
You can modify a DataFrame's row and column index using reindexing in Pandas. Indexes can be used with reference to many index DataStructure associated with several pandas series or pandas DataFrame.
57
參考答案
You can rename the index of a DataFrame using the `.rename_axis()` method, specifying the new name for the index.
58
參考答案
Class methods (using cls) modify the class state, while static methods act as regular functions scoped within a class. Knowing when to use these decorators showcases thoughtful design skills.
59
參考答案
The keyword self defines an instance or object of a class and helps to differentiate between methods and attributes of a class.
60
參考答案
To check if a string is a palindrome in Python, you compare the original string to its reverse. A straightforward way is to use slicing. Reverse the string with `[::-1]` and check if it matches the original string. If they are the same, the string is a palindrome. # function which return reverse of a string def isPalindrome(s): return s == s[::-1] # Driver code s = "mom" ans = isPalindrome(s) if ans: print("Yes") else: print("No") Considerations like case sensitivity and whitespace can affect the result. Normalize the string by converting it to lowercase and removing spaces, if a precise check is required. Remember, accuracy is paramount in determining palindromes, especially when evaluating strings with varying formats or cases.
61
參考答案
Wheels are binary distribution formats that make installations faster. Source distributions (sdist) contain source code and require compilation during installation.
62
參考答案
- Python's argument-passing model is neither "Pass by Value" nor "Pass by Reference" but it is "Pass by Object Reference". - Function arguments are passed as references to objects. - Mutable objects (such as lists and dictionaries) can be modified inside a function. - Immutable objects (such as integers, strings and tuples) cannot be changed in place. You can check the difference between pass-by-value and pass-by-reference in the example below: def call_by_val(x): x = x * 2 return x def call_by_ref(b): b.append("D") return b a = ["E"] num = 6 # Call functions updated_num = call_by_val(num) updated_list = call_by_ref(a) # Print after function calls print("Updated value after call_by_val:", updated_num) print("Updated list after call_by_ref:", updated_list) Output Updated value after call_by_val: 12 Updated list after call_by_ref: ['E', 'D']
63
參考答案
Python uses automatic memory management with a private heap and a garbage collector that uses reference counting and cycle detection. The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes simultaneously in one process, which simplifies memory management but limits multi-threaded performance.
64
參考答案
Scope resolution in Python follows the LEGB rule: Local, Enclosing, Global, and Built-in scopes. When a variable is referenced, Python searches in this order to find its value, ensuring correct variable access based on the context.
65
參考答案
Identifying missing values We can identify missing values in the DataFrame by using the isnull() function and then applying sum(). Isnull() will return boolean values, and the sum will give you the number of missing values in each column. In the example, we have created a dictionary of lists and converted it into a pandas DataFrame. After that, we used isnull().sum() to get the number of missing values in each column. import pandas as pd import numpy as np # dictionary of lists dict = {'id':[1, 4, np.nan, 9], 'Age': [30, 45, np.nan, np.nan], 'Score':[np.nan, 140, 180, 198]} # creating a DataFrame df = pd.DataFrame(dict) df.isnull().sum() # id 1 # Age 2 # Score 1 Dealing with missing values There are various ways of dealing with missing values in Python. - Drop the entire row or the columns if it consists of missing values using dropna(). This method is not recommended, as you will lose important information. - Fill the missing values with the constant, average, backward fill, and forward fill using the fillna() function. - Replace missing values with a constant String, Integer, or Float using the replace() function. - Fill in the missing values using an interpolation method. Note: Make sure you are working with a larger dataset while using the dropna() function. # drop missing values df.dropna(axis = 0, how ='any') #fillna df.fillna(method ='bfill') #replace null values with -999 df.replace(to_replace = np.nan, value = -999) # Interpolate df.interpolate(method ='linear', limit_direction ='forward')
66
參考答案
In Python, a module is a single file containing Python code that can be imported and used in other Python programs. A package, on the other hand, is a collection of modules organized in a directory with a special file named __init__.py. The __init__.py file marks the directory as a package and allows it to be imported as a whole.
67
參考答案
def is_symmetrical(input_string): # Check if the string is symmetrical return input_string == input_string[::-1] def is_palindrome(input_string): # Remove spaces and convert to lowercase input_string = input_string.replace(" ", "").lower() # Check if the string is a palindrome return input_string == input_string[::-1] # Input from the user string = input("Enter a string: ") # Check if the string is symmetrical if is_symmetrical(string): print(f"{string} is symmetrical.") else: print(f"{string} is not symmetrical.") # Check if the string is a palindrome if is_palindrome(string): print(f"{string} is a palindrome.") else: print(f"{string} is not a palindrome.") This program defines two functions is_symmetrical() and is_palindrome(). The is_symmetrical() function checks if the string is symmetrical, and the is_palindrome() function checks if the string is a palindrome. Then, it prompts the user to enter a string and calls these functions to determine whether the entered string is symmetrical or a palindrome, and prints the result accordingly.
68
參考答案
import pandas as pd def filter_dataframe(df, column, threshold): return df[df[column] >= threshold] # Example usage # df = pd.DataFrame({'Age': [25, 30, 45, 20]}) # filtered_df = filter_dataframe(df, 'Age', 30) Explanation of solution: The function filter_dataframe filters rows in a DataFrame based on a column value threshold. It uses boolean indexing (df[column] >= threshold) to select rows where the column value meets the condition.
69
參考答案
Solution: Using User-defined: def find_min_element(lst): if not lst: # If the list is empty return None # Return None since there is no minimum element min_element = lst[0] # Initialize min_element with the first element of the list for num in lst: if num < min_element: min_element = num return min_element # Example usage my_list = [10, 23, 45, 67, 12, 89, 34] min_element = find_min_element(my_list) print("Minimum element in the list:", min_element) Output: Minimum element in the list: 10 Using Built-in Function: my_list = [10, 23, 45, 67, 12, 89, 34] min_element = min(my_list) print("Minimum element in the list:", min_element) Output: Minimum element in the list: 10
70
參考答案
def is_perfect_number(number): if number <= 0: return False divisor_sum = sum(i for i in range(1, number) if number % i == 0) return divisor_sum == number print(is_perfect_number(28)) # True print(is_perfect_number(12)) # False
71
參考答案
A closure is a function that retains the values of variables in the enclosing scope even after that scope has finished executing. Closures are used to create function factories and decorators, among other things.
72
參考答案
Sample Answer: When merging two dictionaries, if both dictionaries have the same key, the value from the second dictionary will overwrite the value from the first. Here is how you can merge two dictionaries in Python: dict1 = {'a': 1, 'b': 2} dict2 = {'b': 3, 'c': 4} merged = {**dict1, **dict2}
73
參考答案
`requests` is a popular library for making HTTP requests with a user-friendly API. `urllib` is a built-``in library with a lower-level interface``.
74
參考答案
Python documentation strings (or docstrings) are essentially comments assigned to modules, classes, functions, and methods. They make use of triple quotes rather than hashtags and are not executed. The use of Python documentation strings indicates adherence to the best Python development practices.
75
參考答案
- Memory management in python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The python interpreter takes care of this instead. - The allocation of heap space for Python objects is done by Python's memory manager. The core API gives access to some tools for the programmer to code. - Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space.
76
參考答案
The re.split() function splits a string by occurrences of a pattern. re.sub() replaces all occurrences of a pattern with a replacement string. re.subn() does the same but also returns the number of replacements made.
77
參考答案
The process of memory management in Python is powered by the involvement of a private heap containing all Python objects and data structures. The internal Python memory manager ensures the management of this private heap.
78
參考答案
You can use the sorted() function or the sort() method of a list in Python to sort a list of objects based on a specific attribute. You can provide a key parameter to specify the attribute by which to sort the objects. For example: class Person: def __init__(self, name, age): self.name = name self.age = age people = [Person(John', 30), Person(Alice', 25), Person(Bob', 35)] # Sort by age sorted_people = sorted(people, key=lambda person: person.age) print(sorted_people)
79
參考答案
Functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions. It avoids mutable state and side effects, emphasizing pure functions, higher-order functions, and immutability. Python supports functional features like lambda, map, and filter.
80
參考答案
def binarySearch(a, item, curr): first = 0 last = len(a) - 1 found = False index = -1 while first <= last and not found: mid = (first + last) // 2 if a[mid] == item: index = mid found = True else: if item < a[mid]: last = mid - 1 else: first = mid + 1 if found: return index else: return -1 def findSum(lst, k): lst.sort() for j in range(len(lst)): # find the difference in list through binary search # return the only if we find an index index = binarySearch(lst, k -lst[j], j) if index is not -1 and index is not j: return [lst[j], k -lst[j]] print(findSum([1, 5, 3], 2)) print(findSum([1, 2, 3, 4], 5)) Output: None [1,4] You can solve this problem by first sorting the list. Then for each element in the list, use a binary search to look for the difference between that element and the intended sum. In other words, if the intended sum is k and the first element of the sorted list is we will do a binary search for The search is repeated until one is found. You can implement the binarySearch() function however you like, recursively or iteratively. Time Complexity Since most optimal comparison-based sorting functions take O(nlogn), let's assume that the Python .sort() function takes the same. Moreover, since binary search takes O(logn) time for finding a single element, therefore a binary search for all n elements will take O(nlogn) time.
81
參考答案
Local variables are defined inside a function and are only accessible within that function. Global variables are defined outside any function and are accessible throughout the program. The 'global' keyword is used to modify global variables inside a function.
82
參考答案
You can drop a column using the `.```drop```()` method``, specifying the column name and `axis=```1``` ` as arguments. For example: `df.drop(```'column_name', axis=1, inplace=True```)`.
83
參考答案
Pandas is an open-source library in Python used for data manipulation and analysis. It provides data structures and functions for efficiently handling large datasets.
84
參考答案
Pickling in python is the process of converting python objects into bytes stream whereas unpickling is the reverse operation of pickling.
85
參考答案
To check for missing values in a Pandas dataframe, we use isnull() and notnull() functions. Both the functions help in checking whether a value is NaN or not. These functions can also be used with Panda series to identify null value in the series.
86
參考答案
Decorators are a way to modify the behavior of a function or class in Python without changing its source code. They are implemented as callable objects that take another function or class as an argument and return a modified version of it.
87
參考答案
The print() function is used to display output in the console. You can print text, variables, and formatted strings. Example: name = "Python" print("Welcome to", name) # Output: Welcome to Python
88
參考答案
The try block is used to check some code for errors i.e the code inside the try block will execute when there is no error in the program. Whereas the code inside the except block will execute whenever the program encounters some error in the preceding try block. Syntax: try: #Code 1 except: #Code 2 The try clause is executed first i.e. the code between try. If there is no exception, then only the try clause will run, except clause is finished. If any exception occurs, the try clause will be skipped and except clause will run. If any exception occurs, but the except clause within the code doesn't handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops. A try statement can have more than one except clause.
89
參考答案
Python can be used to create software, games, and web applications using several frameworks.
90
參考答案
a, b = b, a
91
參考答案
The / operator performs true division in Python, returning a float result. The // operator performs floor division, returning an integer result (or float if one operand is float) by rounding down to the nearest whole number.
92
參考答案
Memory isn't freed because python did not try to destroy every single of its objects. Also, certain bits of memory are distributed by the C library which is impossible to get free.
93
參考答案
Object-oriented, imperative, functional, and procedural is the programming paradigm that Python includes.
94
參考答案
A Python module is a file containing Python code (functions, classes, and variables) that can be imported into other programs. Modules help organize code and promote reusability. Example: # my_module.py def greet(): return "Hello, Python!" # importing the module import my_module print(my_module.greet()) # Output: Hello, Python!
95
參考答案
['!!Python!! ', '!!Python!!']
96
參考答案
Help() function displays all the documentation and information about modules, attributes, and so on. Dir() function displays defined symbols.
97
參考答案
str1 = "Hello" str2 = "World" result = str1 + " " + str2 print(result) #Hello World
98
參考答案
Web based applications are typically tested with Selenium which is an automated tool for browser applications. Example: from selenium import webdriver # Initialize the Chrome WebDriver driver = webdriver.Chrome() # Open the website driver.get('https://www.example.com') # Print the page title print(driver.title) # Close the browser driver.quit()
99
參考答案
You can swap the values of two variables in Python using a tuple assignment. Here's an example: x = 10 y = 20 x, y = y, x print(x) # Output: 20 print(y) # Output: 10
100
參考答案
xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a Python list, whereas, xrange() returns an xrange object. So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object-type generator and has been termed as "yielding". Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison). for i in xrange(10): # numbers from o to 9 print i # output => 0 1 2 3 4 5 6 7 8 9 for i in xrange(1,10): # numbers from 1 to 9 print i # output => 1 2 3 4 5 6 7 8 9 for i in xrange(1, 10, 2): # skip by two for next print i # output => 1 3 5 7 9 Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same as what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x.
101
參考答案
- Vectorized operations, data type optimizations, caching results, using appropriate indexing methods.
102
參考答案
A future is a container that represents the result of a computation that has not yet completed. It can be used to check the status of a computation, or to wait for it to complete.
103
參考答案
The code is correct, but it should include a newline character at the end of the string to properly format the output in the file. with open('output.txt', 'w') as f: f.write('hello, worldn')
104
參考答案
- is compares whether two objects reference the same memory location. - == compares the values of the objects. Example: a = [1, 2, 3] print(a == b) # True (values are equal) b = [1, 2, 3] print(a is b) # False (different memory locations)
105
參考答案
PEP stands for Python Enhancement Proposal. A PEP is an official design document providing information to the Python community, or describing a new feature for Python or its processes. PEP 8 is especially important since it documents the style guidelines for Python Code. Apparently contributing to the Python open-source community requires you to follow these style guidelines sincerely and strictly.
106
參考答案
- Shallow copy does the task of creating new objects storing references of original elements. This does not undergo recursion to create copies of nested objects. It just copies the reference details of nested objects. - Deep copy creates an independent and new copy of an object and even copies all the nested objects of the original element recursively.
107
參考答案
Solution: With User-defined Function: def check_even_odd(number): if number % 2 == 0: return "Even" else: return "Odd" # Example usage input_number = 7 result = check_even_odd(input_number) print(input_number, "is", result) Output: 7 is Odd Without Function: number = 7 if number % 2 == 0: print(number, "is Even") else: print(number, "is Odd") Output: 7 is Odd
108
參考答案
The whereis command can be implemented by searching standard directories (e.g., /bin, /usr/bin, /usr/share/man) for files matching the command name with common extensions (e.g., no extension for binaries, .c for source, and section numbers for man pages). It returns paths to all found files.
109
參考答案
- Use explicit waits with WebDriverWait and ExpectedConditions to avoid timing issues. - Consider implicit waits as a fallback mechanism for elements that appear consistently.
110
參考答案
A lambda function is a small anonymous function, which returns an object. The object returned by lambda is usually assigned to a variable or used as a part of other bigger functions. Instead of the conventional def keyword used for creating functions, a lambda function is defined by using the lambda keyword. The structure of lambda can be seen below: The purpose of lambdas A lambda is much more readable than a full function since it can be written in-line. Hence, it is a good practice to use lambdas when the function expression is small. The beauty of lambda functions lies in the fact that they return function objects. This makes them helpful when used with functions like map or filter which require function objects as arguments. Lambdas aren't useful when the expression exceeds a single line.
111
參考答案
The Pandas library supplies instances of data structures (Series and DataFrame) which provide a way to manage and manipulate data. Example: import pandas as pd # Create a DataFrame data = {'name': ['Alice', 'Bob'], 'age': [25, 30]} df = pd.DataFrame(data) # Add a new column with age incremented by 1 df['age_plus_one'] = df['age'] + 1 print(df) # Output: # name age age_plus_one # 0 Alice 25 26 # 1 Bob 30 31
112
參考答案
To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function. Example: import os os.remove("xyz.txt")
113
參考答案
def check_odd_even(number): if number % 2 == 0: print(f"{number} is even.") else: print(f"{number} is odd.") # Input from the user num = int(input("Enter a number: ")) # Checking if the number is odd or even check_odd_even(num) In this program a function named check_odd_even() is defined which takes a number as input and prints whether it's odd or even. After the program is executed, it will prompt the user to enter a number and calls this function to determine if the entered number is odd or even.
114
參考答案
matplotlib is a library for creating static, animated, and interactive visualizations in Python. It is often used for data plotting and charting.
115
參考答案
class Queue: def __init__(self): self.in_stack = Stack() self.out_stack = Stack() def enqueue(self, item): self.in_stack.push(item) def dequeue(self): if self.out_stack.is_empty(): while not self.in_stack.is_empty(): self.out_stack.push(self.in_stack.pop()) return self.out_stack.pop() Explanation of solution: The Queue class uses two instances of the Stack class. One stack (in_stack) is used for enqueue operations, and the other (out_stack) for dequeue operations. For dequeue, if out_stack is empty, all elements from in_stack are popped and pushed into out_stack. This reverses the order of elements, making the earliest enqueued element available for dequeue.
116
參考答案
- Answer: I'd use libraries like Flask or Dash to build the interactive dashboard. For real-time updates, I'd consider WebSockets or SSE (Server-Sent Events) for server-to-client communication. To minimize latency, I'd cache frequently accessed data, optimize queries, and leverage asynchronous tasks.
117
參考答案
Lambda expressions are a way to quickly create what are known as anonymous functions, basically just, one-time-use functions that you don't even really name. You just use them one time and then never reference them again. Code Ex- add = lambda x, y: x + y result = add(20,15) print(result) #Output: 35
118
參考答案
Sample Answer: The mode of a list is defined as the element that appears most frequently within that list. To find the mode efficiently, you can use the Counter class from the collections module, which counts the frequency of each element. Here's how you can implement a Python function to find the mode of a list: from collections import Counter def find_mode(numbers): count = Counter(numbers) mode_data = count.most_common() return mode_data[0][0]
119
參考答案
*args (pronounced “star args”) allows you to pass multiple number of arguments to a function without specifying their names in advance. It collects all the arguments into a tuple, which you can access within the function. def prac_function(*args): for ARG in args: print(ARG) prac_function(1,2,3,4,5,6) #Output: 1 2 3 4 5 6 def prac_function(**kwargs): for key, value in kwargs.items(): print(key, value) prac_function(Name='Viraj', Age=22, City='Lucknow')
120
參考答案
You can use the `.groupby()` method to group data based on one or more columns and then apply aggregation functions to the groups.
121
參考答案
A class method is a method that is bound to the class and not the instance of the class. It can be called on the class itself, without the need to create an instance of the class. An instance method, on the other hand, is bound to the instance of the class and can only be called on an instance of the class.
122
參考答案
Environment variables are used to store things like API keys, paths, and config values, in Python you read them using the os module, this keeps secrets out of code, it is very common in deployment and automation scripts, and you can also set default values if the variable is missing. import os db = os.getenv("DB_NAME", "default_db") print(db) export DB_NAME=mydb python script.py
123
參考答案
Python provides several ways to delete files, some of them are as following: - os.remove() deletes a file permanently. - send2trash.send2trash() moves a file to the recycle bin or trash. - os.rmdir is used to remove empty directories, not files.
124
參考答案
Dict and List comprehensions are concise syntax in Python for creating dictionaries and lists. They allow for generating collections by applying an expression to each item in an iterable, optionally with filtering conditions, in a single line.
125
參考答案
*args - *args is a special syntax used in the function definition to pass variable-length arguments. - "*" means variable length and "args" is the name used by convention. You can use any other. def multiply(a, b, *argv): mul = a * b for num in argv: mul *= num return mul print(multiply(1, 2, 3, 4, 5)) #output: 120 **kwargs - **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments. - Here, also, "kwargs" is used just by convention. You can use any other name. - Keyworded argument means a variable that has a name when passed to a function. - It is actually a dictionary of the variable names and its value. def tellArguments(**kwargs): for key, value in kwargs.items(): print(key + ": " + value) tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3") #output: # arg1: argument 1 # arg2: argument 2 # arg3: argument 3
126
參考答案
`__init__` is a special method in Python classes known as the constructor. It is automatically called when an object of the class is created and is used to initialize the object's attributes or state.
127
參考答案
You can use the join() method of strings to concatenate the elements of a list into a single string. For example: my_list = [Hello', , World'] concatenated_string = ;.join(my_list) print(concatenated_string) # Output: Hello World;
128
參考答案
You can create a virtual environment using the venv module. For example: python3 -m venv myenv creates a virtual environment named "myenv."
129
參考答案
Asynchronous code is created using the ` ```async``` ` and ` ```await``` ` keywords. ` ```await``` ` is used to pause the execution of a coroutine until the awaited task is complete.
130
參考答案
A Python module is created by saving a .py file where the filename (without extension) serves as the module name. For organizing multiple modules into a package, place an __init__.py file inside the directory. Use the import statement to access the module's functionality: import module_name accesses functions using the module prefix (e.g., module_name.function()). Alternatively, use from module_name import specific_members to import directly into the local namespace. Best practices include: avoiding 'from module import *' to prevent name collisions, using the __name__ global variable with an execution guard (if __name__ == '__main__':) to prevent code from running during import, and including type hints for modern Python modules.
131
參考答案
Dictionaries are used when there is a need for a logical association between a key:pair. Example: Counting frequency of elements, where elements are keys and counts are values.
132
參考答案
| List | Array | |---|---| | Python lists are very flexible and can hold arbitrary data. | Python arrays are just a thin wrapper on C arrays. | | Lists are a part of Python's syntax, so they do not need to be declared first. | Arrays need to first be imported, or declared, from other libraries (i.e. numpy). | | Lists can also be re-sized quickly in a time-efficient manner. This is because Python initializes some extra elements in the list at initialization. | Arrays cannot be resized. Instead, an array's values would need to be copied to another larger array. | | Lists can hold heterogeneous data. | Arrays can only store homogenous data. They have values with uniform data types. | | Mathematical functions cannot be directly applied to lists. Instead, they have to be individually applied to each element. | Arrays are specially optimized for arithmetic computations. | | Lists consume more memory as they are allocated a few extra elements to allow for quicker appending of items. | Since arrays stay the size that they were when they were first initialized, they are compact. |
133
參考答案
Operators are special functions. They take one or more values and produce a corresponding result. is: returns true when 2 operands are true (Example: “a” is ‘a') not: returns the inverse of the boolean value in: checks if some element is present in some sequence
134
參考答案
Python uses the Tim Sort algorithm for sorting. It's a stable sorting whose worst case is O(N log N). It's a hybrid sorting algorithm, derived from merge sort and insertion sort, designed to perform well on many kinds of real-world data.
135
參考答案
Output : 5! = 120
136
參考答案
An object's identity never changes once it has been created; you may think of it as the object's address in memory. For instance, placing a list inside a tuple means the tuple holds a reference to that list. While the tuple itself remains unchanged, the mutable object it contains can be modified. Example: person = (['Ayaan', 5, 'Male'], ['Aaradhya', 8, 'Female']) person[0][1] = 4 In this case, altering the inner list doesn't affect the tuple's overall identity.
137
參考答案
Indentation is more than a cosmetic or readability feature of Python, it is a core concept that will return a failure statement when not followed. It utilizes four spaces to separate blocks of code and helps developers specify a block within a class, function, or loop.
138
參考答案
The shebang tells the system which program should run the file, so when you write #!/usr/bin/env python3 it means use whatever python3 is available in the user's environment, this makes the script more portable across systems, without a shebang you would always have to type python script.py, but with it you can run the file directly. #!/usr/bin/env python3 print("Running with system python3")
139
參考答案
import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Flatten from tensorflow.keras.optimizers import SGD # Load the MNIST dataset (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # Normalize the images train_images = train_images / 255.0 test_images = test_images / 255.0 # Building the model model = Sequential([ Flatten(input_shape=(28, 28)), Dense(128, activation='relu'), Dense(10, activation='softmax') ]) # Compiling the model model.compile(optimizer=SGD(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Training the model model.fit(train_images, train_labels, epochs=5) # Evaluate the model model.evaluate(test_images, test_labels) Explanation of solution: The solution involves loading the MNIST dataset and normalizing the image data. A sequential model is built using Dense layers, including a flatten layer for the input and a softmax activation for the output. The model is compiled with the SGD optimizer and sparse categorical cross-entropy loss function. The model is trained using the fit method and evaluated on test data.
140
參考答案
Sample Answer: A trie is a tree-like structure that helps store strings efficiently, where each node represents a single character. Below is an example of how to implement a trie: class TrieNode: def __init__(self): self.children = {} self.is_end_of_word = False class Trie: def __init__(self): self.root = TrieNode() def insert(self, word): node = self.root for char in word: if char not in node.children: node.children[char] = TrieNode() node = node.children[char] node.is_end_of_word = True def search(self, word): node = self.root for char in word: if char not in node.children: return False node = node.children[char] return node.is_end_of_word def starts_with(self, prefix): node = self.root for char in prefix: if char not in node.children: return False node = node.children[char] return True
141
參考答案
Re (Regular Expression or RegEx) is a built-in module that helps with expression matching and contains three main functions. These are: - sub(): It evaluates patterns and calls a method for every regex match to replace it. - subn(): It functions like sub() but returns a tuple having a count of a total of all substitutions, along with the new string. - split(): It generates regex matches after breaking down the string along the defined separator.
142
參考答案
`unittest` is Python```'s built-in library for writing unit tests. You create test cases by subclassing unittest.TestCase` and defining test methods.``
143
參考答案
We will be using either help() or dir() method.
144
參考答案
You will use some of these modules that are included in the Python standard library often when programming in Python: • Email: Used to parse, handle, and generate email messages. • String: An index of types of strings, such as all capital or lowercase letters. • Sqlite3: Used to deal with the SQLite database. • XML: Provides XML support. • Logging: Creates logging classes to log system details. • Traceback: Allows you to extract and print stack trace details.
145
參考答案
- Shallow copy: Copies reference to the original data structure, modifying the copy changes the original. - Deep copy: Creates a new, independent copy of the data structure, modifying the copy does not affect the original.
146
參考答案
A metaclass is a class that defines the behavior of other classes. It is used to customize the creation of classes and their instances, and can be used to enforce certain constraints or provide additional functionality to classes. The main difference between a metaclass and a regular class is that a metaclass is used to define the behavior of other classes, whereas a regular class is used to define objects that can be instantiated and used in a program.
147
參考答案
Unlike Java, Python allows developers to see an error in the code without terminating the execution of the program. This mechanism is called try-except. Sometimes, the system suggests a way to solve the problem along with the error description. There are two types of try-except clauses in Python: - Try-except-finally. - Try-except-else.
148
參考答案
To create a pandas Series from a list, use pd.Series(list). From a NumPy array, use pd.Series(array). From a dictionary, use pd.Series(dict), where dictionary keys become the index and values become the series data.
149
參考答案
In Python, the memory is managed using the Python Memory Manager. The manager allocates memory in the form of a private heap space dedicated to Python. All objects are now stored in this Hype and due to its private feature, it is restricted from the programmer.
150
參考答案
Matplotlib is used in Python for creating static, interactive, and animated visualizations. It's a comprehensive library that offers various plotting styles, including line plots, scatter plots, bar charts, and histograms. Users can customize virtually every element of a plot, from its colors to its labels. Import the `pyplot` module to start with Matplotlip, commonly aliased as `plt`. Visualizations are generated by calling functions from `plt`, such as `plt.plot()` or `plt.scatter()`. The `plt.show()` function displays the complete visualization, after setting up the plot elements. Fine-tuning the appearance and adding details to the plot, like titles or legends, becomes easy with Matplotlib's extensive functionality. Libraries like Pandas, Matplotlib integrates seamlessly, offering a cohesive data visualization workflow, when working with data analysis
151
參考答案
Solution: def count_words(sentence): # Split the sentence into words using whitespace as the delimiter words = sentence.split() # Count the number of words return len(words) # Example usage input_sentence = "This is a sample sentence." word_count = count_words(input_sentence) print("Number of words in the sentence:", word_count) Output: Number of words in the sentence: 5 With Built-in Fucntion: sentence = "This is a sample sentence." word_count = len(sentence.split()) print("Number of words in the sentence:", word_count) Output: Number of words in the sentence: 5 Without Built-in Function: sentence = "This is a sample sentence." word_count = 0 # Flag to indicate if the current character is part of a word in_word = False # Iterate through each character in the sentence for char in sentence: # If the character is not a space and we are not already in a word if char != ' ' and not in_word: # Increment word count and set the flag to indicate we are in a word word_count += 1 in_word = True # If the character is a space and we are in a word elif char == ' ' and in_word: # Set the flag to indicate we are not in a word in_word = False print("Number of words in the sentence:", word_count) Output: Number of words in the sentence: 5
152
參考答案
Using pass , For example Loading...
153
參考答案
A new column can be added to a pandas dataframe as follows: import pandas as pd data_info = {'first' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'second' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(data_info) #To add new column third df['third']=pd.Series([10,20,30],index=['a','b','c']) print (df) #To add new column fourth df['fourth']=df['first']+info['third'] print (df)
154
參考答案
- is: Compares memory locations of objects. - ==: Compares the values of objects. Example: a = [1, 2, 3] b = [1, 2, 3] print(a == b) # True (values are the same) print(a is b) # False (different memory locations)
155
參考答案
Virtual environments provide isolation, ensuring that project dependencies don't interfere with system-level packages. However, they can consume extra disk space and require additional setup. It's a trade-off between isolation and convenience.
156
參考答案
def reverse_string(s): return s[::-1] Explanation of solution: The solution uses Python's slicing mechanism. The slice [::-1] is a common Python idiom for reversing a string (or a list). It starts from the end towards the first character, stepping backwards. s[::-1] takes the entire string s and reverses it.
157
參考答案
A literal is a direct and simple form of expressing a value. Some common Python literals include: - String literals: A series of characters or text wrapped in a set of single, double, or triple quotes. Eg: “Hello” - Numeric literals: Unchangeable numbers that can be categorized as integer, complex, or float. Eg: 5 (integer), 8i (complex), 3.14 (float) - Boolean literals: Indicating “0” (false) or “1” (true) - Special literals: Signifies that a particular field is not created. Eg: “None”
158
參考答案
You can flatten a matrix in NumPy using the numpy.flatten() function or the .flatten() method of a NumPy array. For example, numpy.flatten(matrix) or matrix.flatten().
159
參考答案
The __init__.py file is used to indicate that a directory should be treated as a Python package. It can contain initialization code for the package.
160
參考答案
The `break` statement is used to exit a loop prematurely. The `continue` statement is used to skip the rest of the current iteration and continue to the next.
161
參考答案
Some of its features are: - Dynamically typed - An interpreted language - Object-oriented - Coding is quick
162
參考答案
In Python, a closure is a function that retains access to variables from its containing (enclosing) scope even after the scope has finished executing. It allows a function to remember and access its lexical scope's variables. Here's an example: def outer_function(x): def inner_function(y): return x + y return inner_function closure_example = outer_function(10) print(closure_example(5)) # Output: 15 In this example, inner_function is a closure that remembers the value of x from the enclosing outer_function, even after outer_function has finished executing.
163
參考答案
Python docstrings are specific string literals that appear right after the definition of a module, function, class, or method. Python docstrings provide a concise summary or explanation of the enclosed code's purpose. Docstrings are retained throughout the runtime of the program, making them accessible via the `__doc__` attribute or through Python's built-in `help()` function. Docstrings are enclosed in triple quotes, either single (`'''`) or double (`"""`). They serve as the primary source of documentation for many Python tools and libraries. For example, The displayed information typically originates from the associated docstring, when you use the `help()` function on a Python object or method. This means that well-documented code can offer direct assistance to developers without requiring external documentation. The Python community has established conventions for docstring formats, To promote consistent documentation. Popular choices include reStructuredText and Google style. Adopting a consistent format ensures readability and makes it easier for tools to parse and display the documentation.
164
參考答案
Shallow copy and deep copy are used to duplicate objects in Python. A shallow copy creates a new object, but it only copies the references to the original elements, not the elements themselves. On the other hand, a deep copy creates a new object and recursively copies all the elements and their contents.
165
參考答案
Reindexing in pandas is the process of conforming a DataFrame or Series to a new index, potentially introducing NaN values for missing labels. It is used to align data to a desired index order or to handle missing data.
166
參考答案
.py files contain human-readable Python source code. .pyc files contain compiled bytecode generated by the Python interpreter, which is executed faster. .pyc files are automatically created when a module is imported.
167
參考答案
Sample Answer: To find the largest number in a list, you can define the function find_largest(numbers) to take a list as input and use the max() function to return the largest number from the list. Here is an example of how you can do it: def find_largest(numbers): return max(numbers) In this code, max(numbers) scans through the list and returns the highest value, making it an effective solution for this problem.
168
參考答案
A string is a palindrome if it reads the same forward and backward. Example: def is_palindrome(s): s = ''.join(e for e in s if e.isalnum()).lower() # Remove non-alphanumeric and convert to lowercase return s == s[::-1] print(is_palindrome("A man, a plan, a canal: Panama")) # Output: True print(is_palindrome("hello")) # Output: False
169
參考答案
Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. For example: # decorator function to convert to lowercase def lowercase_decorator(function): def wrapper(): func = function() string_lowercase = func.lower() return string_lowercase return wrapper # decorator function to split words def splitter_decorator(function): def wrapper(): func = function() string_split = func.split() return string_split return wrapper @splitter_decorator # this is executed next @lowercase_decorator # this is executed first def hello(): return 'Hello World' hello() # output => [ 'hello' , 'world' ] The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope. # decorator function to capitalize names def names_decorator(function): def wrapper(arg1, arg2): arg1 = arg1.capitalize() arg2 = arg2.capitalize() string_hello = function(arg1, arg2) return string_hello return wrapper @names_decorator def say_hello(name1, name2): return 'Hello ' + name1 + '! Hello ' + name2 + '!' say_hello('sara', 'ansh') # output => 'Hello Sara! Hello Ansh!'
170
參考答案
A virtual environment is an isolated runtime environment that allows users to run specific versions of Python and its libraries, preventing conflicts between versions.
171
參考答案
You can use the command edit mysite/setting.py, it is a normal python module with module level representing Django settings. Django uses SQLite by default; it is easy for Django users as such it won't require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default' item to match your database connection settings. Engines: you can change the database by using ‘django.db.backends.sqlite3' , ‘django.db.backeneds.mysql', ‘django.db.backends.postgresql_psycopg2', ‘django.db.backends.oracle' and so on. Name: The name of your database. In the case if you are using SQLite as your database, in that case, database will be a file on your computer, Name should be a full absolute path, including the file name of that file. Django uses SQLite as a default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database's administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project's settings.py file comes in. We will add the following lines of code to the setting.py file: DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.sqlite3', 'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'), } }
172
參考答案
To schedule scripts, on Linux and macOS you use cron, and on Windows you use Task Scheduler, this is used for daily backups, reports, or cleanup jobs, you just tell the system when to run your script, and it runs automatically without you opening it. crontab -e 0 9 * * * /usr/bin/python3 /home/user/script.py
173
參考答案
You can create a sparse matrix in Python using the scipy.sparse module. For example, scipy.sparse.csr_matrix(matrix) creates a compressed sparse row matrix from a dense matrix.
174
參考答案
A set is an unordered collection of unique elements. Example: my_set = {1, 2, 3, 2} print(my_set) # {1, 2, 3}
175
參考答案
Output : (No output provided in the source content)
176
參考答案
Instance, are different types of methods that can be defined in a Python class. An instance method is the most common type of method. It takes `self` as its first parameter, which refers to the instance of the class. This allows it to access and modify object attributes and call other instance methods. The behavior of an instance method is specific to the instance, making it the most used method type. A static method, defined using the `@staticmethod` decorator, doesn't take a special first parameter like `self` or `cls` . It acts like a regular function but belongs to the class's namespace. Static methods cannot access or modify class-specific or instance-specific data. Use them, if you don't need to access any instance or class-specific data. A class method, marked with the `@classmethod` decorator, takes a reference to the class, `cls` , as its first parameter. It can't access instance-specific data, but it can access and modify class-level data. Class methods are often used for factory methods which can create class instances in diverse ways. Instance methods focus on the individual object, static methods are independent, and class methods center on the class itself.
177
參考答案
Python comes with a variety of techniques to generate random numbers using its Random library: https://docs.python.org/3/library/random.html • Random(): This command returns a floating-point number between 0 and 1. • Uniform(x, y): This command returns a floating-point number between the values given for x and y. • Randint(x, y): This command returns a random integer between the values given for x and y.
178
參考答案
The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution. def myEmptyFunc(): # do nothing pass myEmptyFunc() # nothing happens ## Without the pass keyword # File "", line 3 # IndentationError: expected an indented block
179
參考答案
You can find the current date and time in Python using the “datetime” module. Here's an example: Import datetime current_date = datetime.date.today() current_time = datetime.datetime.now() print(current_date) # Output: 2023-07-26 print(current_time) # Output: 2023-07-26 12:34:56.789012
180
參考答案
In order to comment in Python, you need to put this character # in front of the comment. In order to comment on more than one line, you should press Ctrl and left-click all the lines that this comment is about.
181
參考答案
NumPy: It provides operations on multi-dimensional arrays, mathematical functions, and tools for working with large datasets. In simple words it enables us to perform complex mathematical operations. NumPy is mainly used in data analysis, scientific calculations, and machine learning. Pandas: This library is used for data manipulation and analysis. Pandas offers data structures (such as DataFrames) and functions for cleaning, transforming and exploring structured data. Matplotlib: This library for creating static, animated, and interactive visualizations in Python from the data provided by the user. Matplotlib enables the creation of various plots, charts, and graphs, making it a go-to choice for data visualization tasks. TensorFlow: An open-source library for machine learning and deep learning. TensorFlow provides a flexible ecosystem for building and deploying machine learning models, especially neural networks. It is widely used in research, production-grade applications, and AI development. Scikit-learn: A machine learning library that offers a range of algorithms and tools for data mining, classification, regression, clustering, and dimensionality reduction. Scikit-learn simplifies the implementation of machine learning models and pipelines. Beautiful Soup: A library for web scraping and parsing HTML/XML documents. Beautiful Soup makes it easy to extract data from web pages, navigate the HTML/XML structure, and scrape information for various applications. PyTorch: PyTorch is designed to take advantage of GPUs for fast computation in deep learning tasks. It provides a tensor library that enables efficient data storage and manipulation on GPUs. PyTorch is widely used in developing and training neural networks.
182
參考答案
The __init__ method is a special method in Python classes that is called when an object is created. It is used to initialize the attributes of the object. class MyClass: def __init__(self, x, y): self.x = x self.y = y # Usage obj = MyClass(10, 20)
183
參考答案
Data Abstraction means providing only the essential details while hiding the implementation. It allows users to interact with an object through a simple interface without needing to understand its internal working. It's achieved using abstract base classes provided by the abc module. These classes define abstract methods that must be implemented by derived classes. Example: from abc import ABC, abstractmethod class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def area(self): return 3.14 * 5 * 5 c = Circle() print(c.area()) Output 78.5 Explanation: - Shape defines an abstract method area(). - Circle implements the area() method and Circle objects can usearea() normally. - The implementation details are hidden behind a common interface.
184
參考答案
A generator function is a special type of function that can be used to generate a sequence of values on-the-fly. It is different from a regular function in that it uses the "yield" keyword to return values one-at-a-time instead of returning a list of all values at once.
185
參考答案
Use profiling tools like cProfile or timeit to measure performance and find slow-running pieces of the code. Example: import cProfile def slow_function(): # Some code to profile pass # Run the profiler on the function cProfile.run('slow_function()')
186
參考答案
You can use a secure connection with the extensions SMTP_SSL() and .starttls(). Following this step, use the built-in smtplib library module to define the SMTP client session object. This object can then be used to send the email message using Python Script. To send the emails you can use HTML content, as well as, the attachments with the email package. If you use a CSV file that contains contact data, you can even send a number of personalized emails. If you add a few lines of code to your Gmail account, you can configure the Yagmail package to send emails.
187
參考答案
The __init__ method is run as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.
188
參考答案
There are several idiomatic ways to create dictionaries in Python: 1) Literal Syntax using curly braces {} with key:value pairs. 2) dict() Constructor using keyword arguments or a sequence of key-value pairs. 3) Dictionary Comprehension using an iterable and logic (e.g., {x: x**2 for x in range(1,6)}). 4) zip() Function mapping two separate iterables into a dictionary (e.g., dict(zip(keys, values))). 5) fromkeys() Method creating a dictionary with predefined keys and an optional shared default value (e.g., dict.fromkeys(keys, 'Pending')). Since Python 3.7+, dictionaries maintain insertion order and provide O(1) average time complexity for lookups, insertions, and deletions.
189
參考答案
The Python Path environment variable (PYTHONPATH) is a list of directories that Python searches for modules and packages when importing. It extends the default search path and can be set to include custom directories.
190
參考答案
A variable created inside a function belongs to the local scope of that function, and can only be used inside that function. A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
191
參考答案
Solution: Using Built-in Function: # Example list my_list = [10, 23, 45, 67, 12, 89, 34] # Find maximum element max_element = max(my_list) print("Maximum element in the list:", max_element) Output: Maximum element in the list: 89 Using User-defined Function: def find_max_element(lst): if not lst: # If the list is empty return None # Return None since there is no maximum element max_element = lst[0] # Initialize max_element with the first element of the list for num in lst: if num > max_element: max_element = num return max_element # Example usage my_list = [10, 23, 45, 67, 12, 89, 34] max_element = find_max_element(my_list) print("Maximum element in the list:", max_element) Output: Maximum element in the list: 89
192
參考答案
Sample Answer: A palindrome is a word or phrase that reads the same forwards and backward, ignoring spaces, punctuation, and capitalization. To check if a string is a palindrome, you can compare the original string with its reversed version. For example: def is_palindrome(s): return s == s[::-1] The function 'is_palindrome(s)' checks if the input string s is equal to its reverse, 's[::-1]'. If they are the same, the function returns 'True', indicating that the string is a palindrome. Otherwise, it returns 'False'.
193
參考答案
Strategies involve structuring code for testability (separation of concerns), using frameworks like pytest or unittest, mocking external dependencies, writing comprehensive test suites, integrating continuous integration systems, and ensuring good test coverage metrics.
194
參考答案
- init: This is the constructor method called when an object is created. It's used to initialize the object's attributes with specific values or perform necessary setup. - Example: class MyClass: def __init__(self, value): self.value = value - str: This method defines how the object is represented when printed or converted to a string. It allows you to customize the object's representation for better readability or information display. Python Example Code: class MyClass: def __str__(self): return f'MyClass with value: {self.value}'
195
參考答案
PEP 703, accepted in 2023, introduces the option to disable the GIL in CPython via a --disable-gil build configuration. While the GIL remains the default for standard builds, this development highlights Python's evolving capabilities.
196
參考答案
In pandas, the groupby() method can use aggregation functions such as sum(), mean(), count(), min(), max(), std(), and apply() for custom operations. These functions are applied to groups defined by one or more columns.
197
參考答案
| NumPy | SciPy | | It refers to Numerical python. | It refers to Scientific python. | | It has fewer new scientific computing features. | Most new scientific computing features belong in SciPy. | | It contains less linear algebra functions. | It has more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. | | NumPy has a faster processing speed. | SciPy on the other hand has slower computational speed. |
198
參考答案
The `datetime` module provides classes for working with dates and times, including parsing, formatting, and arithmetic operations.
199
參考答案
- Read data from external files or APIs, utilize libraries like pandas for data manipulation. Use assertion libraries like pytest or unittest to verify successful test execution and expected outcomes.
200
參考答案
While the = operator will copy many things in Python, it will not copy a Python object. It only creates a reference to the object. To create a copy of an object in Python, you need to use the copy module. The copy module offers two ways of copying an object. • Shallow copy: Copies an object and re-use references from the old object • Deep copy: Copies all the values in an object recursively. from copy import copy, deepcopy list_1 = [1, 2, [3, 5], 4] ## shallow list_2 = copy(list_1) list_2[3] = 11 list_2[2].append(12) list_2 # output => [1, 2, [3, 5, 12], 11] list_1 # output => [1, 2, [3, 5, 12], 4] ## deep list_3 = deepcopy(list_1) list_3[3] = 10 list_3[2].append(13) list_3 # output => [1, 2, [3, 5, 6, 13], 10] list_1 # output => [1, 2, [3, 5, 6], 4]