First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.
Continue in the practice tool above to load more questions, 50 at a time.
Question 1Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which statement best defines artificial intelligence as a field of study?
- The physical design of robotic arms and grippers
- The construction of faster processors for numerical computation
- The engineering of systems that perform tasks normally requiring human intelligence, such as reasoning and learning Correct answer.
- The storage of large datasets in relational databases
Explanation
Artificial intelligence is defined by the capability being reproduced, not by the hardware used. Systems that reason, learn, perceive or use language fall inside the field, while a faster processor or a database is merely a tool that may support AI.
Question 2Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
The term 'artificial intelligence' was coined in a 1956 workshop held at which institution?
- Massachusetts Institute of Technology
- Carnegie Mellon University
- Stanford University
- Dartmouth College Correct answer.
Explanation
The Dartmouth Summer Research Project of 1956 is the event where John McCarthy and colleagues introduced the term artificial intelligence. It is conventionally treated as the founding event of AI as an academic discipline.
Question 3Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which relationship correctly describes machine learning with respect to artificial intelligence?
- Machine learning and artificial intelligence are two unrelated disciplines with no overlap
- Machine learning is a subfield of artificial intelligence that builds models from data Correct answer.
- Machine learning is the hardware layer on which artificial intelligence programs execute
- Machine learning is a superset that contains artificial intelligence as one of its branches
Explanation
Artificial intelligence is the broad goal of building intelligent systems, and machine learning is one approach to that goal. Instead of hand-coding rules, machine learning derives patterns from examples in data.
Question 4Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which task is a classic example of an intelligent agent operating in an environment?
- A spreadsheet recalculating a formula when a cell value changes
- A thermostat choosing heating or cooling actions to hold a target temperature Correct answer.
- A printer driver converting a document into page-description language
- A compiler translating source code into machine instructions
Explanation
An agent perceives its environment through sensors and acts through actuators to pursue a goal. A thermostat senses temperature and selects a heating or cooling action, which fits the perceive-act loop.
Question 5Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
In the standard agent-environment description, what do the sensors of an agent do?
- They provide the agent with information about the state of its environment Correct answer.
- They execute the actions selected by the agent program
- They define the performance measure for the agent
- They store the agent's long-term knowledge base
Explanation
Sensors supply percepts, which are the agent's only direct information about the world. The agent program then uses those percepts to decide which action the actuators should carry out.
Question 6Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which application area is the clearest example of AI used for perception rather than for decision optimisation?
- Route planning for a delivery fleet to minimise fuel use
- Automatic recognition of handwritten postal addresses on scanned envelopes Correct answer.
- Allocation of seats to maximise airline revenue
- Scheduling of staff shifts under labour regulations
Explanation
Perception tasks convert raw sensory input such as an image into meaningful symbols, here characters from handwriting. The other options are optimisation and planning problems that search over possible decisions rather than interpret sensor data.
Question 7Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
A system uses a deep neural network with many stacked layers to classify images directly from pixels. Which label is most precise for this system?
- Deep learning Correct answer.
- Simple linear regression
- Rule-based expert system
- Classical symbolic AI
Explanation
Deep learning refers specifically to neural networks with many successive layers that learn hierarchical features from raw input such as pixels. A linear regression or a hand-coded rule base would not build layered representations in this way.
Question 8Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which historical phase of AI research is correctly matched with its dominant approach?
- The late 1980s resurgence was driven primarily by reinforcement learning from raw video
- The 1960s work was dominated by training convolutional networks on internet-scale image collections
- The 1970s and 1980s saw knowledge-based expert systems encode human expertise as explicit rules Correct answer.
- The 1970s expert-system boom relied mainly on deep neural networks trained on large datasets
Explanation
Expert systems such as those used in medical diagnosis encoded specialist knowledge as explicit if-then rules and dominated applied AI in the late 1970s and 1980s. Large datasets and deep networks belong to the later machine-learning era.
Question 9Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
A program plays chess by evaluating millions of future move sequences before choosing one. Which classical AI technique does this illustrate?
- Heuristic search over a state space Correct answer.
- Reinforcement learning from human feedback
- Unsupervised clustering of board positions
- Supervised learning from labelled games
Explanation
The program explores sequences of moves as states and uses an evaluation function to guide the exploration, which is heuristic search. No training labels or reward-driven parameter updates are described.
Question 10Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which statement about the relationship between machine learning and deep learning is correct?
- Deep learning is a branch of symbolic logic that machine learning replaced
- Deep learning is a specialised branch of machine learning that uses multi-layer neural networks Correct answer.
- Machine learning is a branch of deep learning limited to shallow models
- Deep learning and machine learning both exclude neural networks by definition
Explanation
Deep learning sits inside machine learning and is distinguished by networks with many layers that learn representations automatically. Shallow machine learning methods such as decision trees or support vector machines are still machine learning but not deep learning.
Question 11Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
In a self-driving car, which component corresponds to the actuators of the agent?
- The performance measure used to score driving quality
- The cameras and lidar that capture the road scene
- The map database loaded into the navigation unit
- The steering motor and brake system that change the vehicle's motion Correct answer.
Explanation
Actuators are the parts through which an agent affects its environment. Steering and braking physically change the car's state, whereas cameras are sensors and the map is internal knowledge.
Question 12Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
A hospital uses AI to flag patients at risk of readmission from electronic health records. Which description of the agent's environment is most accurate?
- Completely static with no uncertainty
- Fully observable, deterministic and episodic
- Fully observable, deterministic and static
- Partially observable, stochastic and dynamic Correct answer.
Explanation
The system sees only recorded data, not the full state of each patient, so the environment is partially observable. Patient outcomes are uncertain and records change over time, making it stochastic and dynamic.
Question 13Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which application relies most directly on natural language processing rather than on computer vision?
- Recognising the face of an employee at an office door
- Detecting defective components on a factory conveyor belt
- Estimating the ripeness of fruit from a photograph
- Reading an automatically generated summary of a long news article Correct answer.
Explanation
Natural language processing deals with text and speech, so summarising an article is a language task. The other three options all interpret visual input and therefore belong to computer vision.
Question 14Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which statement correctly distinguishes the goal of artificial intelligence from the goal of machine learning?
- AI aims to build intelligent behaviour by any means, while ML aims to improve performance through experience from data Correct answer.
- AI is limited to robotics, while ML is limited to text processing
- AI and ML both require deep neural networks to be considered genuine
- AI requires learning from data, while ML may use hand-written rules only
Explanation
AI is the broad objective of reproducing intelligent behaviour and may use search, logic or learning. Machine learning is the narrower objective of improving performance on a task through experience, usually data.
Question 15Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
A team builds a system that recommends crop irrigation times by learning from past sensor readings and yields. Which pair of AI sub-areas does this system most directly combine?
- Machine translation and optical character recognition
- Machine learning for prediction and an agent acting on a farm environment Correct answer.
- Symbolic theorem proving and automatic speech synthesis
- Robotic manipulation and face recognition
Explanation
The system learns a predictive model from historical data and then acts on the farm by scheduling irrigation, which is agent behaviour in a physical environment. The other pairs describe unrelated capabilities that the scenario does not mention.
Question 16Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which feature most clearly separates a machine learning solution from a traditional rule-based program for spam filtering?
- The machine learning version runs on a faster processor
- The machine learning version derives its decision boundary from labelled examples rather than from rules written by a programmer Correct answer.
- The machine learning version stores messages in a database
- The machine learning version uses a graphical user interface
Explanation
In machine learning the decision logic is estimated from training examples, whereas a rule-based filter contains conditions written by a human. Processor speed, storage and interface are implementation details unrelated to the learning distinction.
Question 17Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
A researcher argues that a system which passes a large set of factual questions must be generally intelligent. Which criticism of this argument is strongest within AI?
- General intelligence can only be measured by processing speed
- Passing factual tests proves the system has consciousness
- Factual recall can be achieved by retrieval without reasoning, so the test does not establish general intelligence Correct answer.
- Any system that answers questions must use deep learning
Explanation
High scores on factual questions can come from memorisation or retrieval, which does not demonstrate reasoning, transfer or adaptation. General intelligence requires broader capabilities than recalling stored facts.
Question 18Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
An agent's environment is described as deterministic, fully observable and static. Which consequence follows for the agent's design?
- The agent must rely on reinforcement learning because feedback arrives only at the end
- The agent can plan using a known state and predictable action outcomes without sensing during execution Correct answer.
- The agent cannot use search because the state space is unknown
- The agent must model probabilities because outcomes are uncertain
Explanation
When the state is fully visible, actions have predictable effects and nothing changes while the agent deliberates, a plan can be computed in advance and executed open-loop. Uncertainty modelling and continual re-sensing become unnecessary.
Question 19Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
Which sequence correctly orders the three concepts from broadest to narrowest scope?
- Machine learning, artificial intelligence, deep learning
- Artificial intelligence, machine learning, deep learning Correct answer.
- Artificial intelligence, deep learning, machine learning
- Deep learning, machine learning, artificial intelligence
Explanation
Artificial intelligence is the broadest field, machine learning is one approach within it, and deep learning is a specialised subset of machine learning. Each narrower term is contained in the one before it.
Question 20Introduction to Artificial Intelligence: definition, history, AI vs ML vs DL, intelligent agents, real-world applications
A company claims its product is AI because it uses a neural network trained on customer data. Which evaluation of the claim is most defensible?
- The claim is valid because any use of data constitutes artificial intelligence
- The claim identifies a machine learning component, which is a legitimate part of AI, but the label alone does not guarantee intelligent capability Correct answer.
- The claim is invalid because neural networks belong to statistics and not to AI
- The claim is valid only if the network has more than one hidden layer
Explanation
A trained neural network is a machine learning method and therefore falls within AI, so the component is genuine. However, calling a product AI says nothing about how capable or appropriate the system is, so the label should be judged by demonstrated behaviour.
Question 21Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
In a Python AI script, which built-in data type would you choose to store the single predicted probability returned by a classifier for one image?
- tuple
- list
- dict
- float Correct answer.
Explanation
A single probability such as 0.87 is a real number, so Python's immutable float type is the natural container. Lists, tuples and dictionaries all hold multiple values, which is unnecessary for one scalar score.
Question 22Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A dataset row stores a student's marks as the string "88". Which expression converts it to an integer for arithmetic in an AI marks-prediction script?
- float(88)
- bool("88")
- int("88") Correct answer.
- str(88)
Explanation
The int() constructor parses a numeric string and returns the integer 88, which can then be used in arithmetic. str() would keep it textual, float() would give 88.0, and bool() would give True.
Question 23Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
Which Python statement correctly starts an indefinite loop that keeps asking for input until the user types the word stop?
- do while True:
- for i in range(0):
- while True: Correct answer.
- if True:
Explanation
A while loop with the literal condition True repeats indefinitely, and a break inside the body exits when the sentinel input arrives. A for loop over range(0) never runs, an if runs only once, and do-while is not Python syntax.
Question 24Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
What does the following Python snippet print?
scores = [45, 72, 88, 91]
print(scores[1:3])
- [72, 88] Correct answer.
- [88, 91]
- [45, 72]
- [72, 88, 91]
Explanation
Python slicing takes the start index up to but not including the stop index, so indices 1 and 2 are selected. Those positions hold 72 and 88, giving the list [72, 88].
Question 25Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
In a pandas DataFrame named df, which expression returns only the rows where the column marks is greater than 80?
- df.filter(80)
- df["marks"] > 80
- df.loc["marks"] > 80
- df[df["marks"] > 80] Correct answer.
Explanation
Boolean indexing passes a True/False Series as the row selector, so df[df["marks"] > 80] keeps matching rows. The comparison itself produces a mask, which must be applied to the DataFrame to filter rows.
Question 26Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
Which statement about a NumPy array created with np.array([1, 2, 3]) is correct for AI data pipelines?
- All its elements share one data type. Correct answer.
- It can be resized freely like a Python list.
- It stores elements as a linked list.
- It cannot be used in element-wise arithmetic.
Explanation
A NumPy array is homogeneous: one dtype applies to every element, which enables compact memory layout and fast vectorised maths. Element-wise arithmetic is a core feature, and size changes require functions such as resize or concatenate.
Question 27Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
Which Python library is the standard tool for reading a CSV file into a tabular DataFrame in an AI data-handling task?
- math
- pandas Correct answer.
- turtle
- random
Explanation
pandas provides read_csv(), which parses delimited text into a DataFrame with labelled columns. The other modules offer maths functions, random numbers or graphics, none of which handle tabular files.
Question 28Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A function is defined as def scale(x, factor=2): return x * factor. What is returned by the call scale(5)?
- 5
- 10 Correct answer.
- An error, because factor is missing.
- 7
Explanation
When an argument is omitted, the default value factor=2 is used, so the body computes 5 * 2. The result is therefore 10, and no error occurs because the parameter has a default.
Question 29Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
What is the value of the variable total after this loop runs?
total = 0
for n in [3, 6, 9]:
if n == 6:
continue
total += n
- 9
- 6
- 12 Correct answer.
- 18
Explanation
The continue statement skips the rest of the body for n equal to 6, so only 3 and 9 are added. The accumulator therefore ends at 12.
Question 30Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
In NumPy, what is the shape of the array produced by np.zeros((3, 4))?
- A 3-by-4 two-dimensional array Correct answer.
- A 3-by-4 array of random values
- A one-dimensional array of 12 elements
- A 4-by-3 two-dimensional array
Explanation
The tuple argument (3, 4) is read as rows then columns, giving a two-dimensional array with 3 rows and 4 columns. Every element is initialised to 0.0.
Question 31Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A pandas DataFrame has a column age containing some missing values represented as NaN. Which call returns the number of non-missing entries in that column?
- df["age"].isna().count()
- df["age"].sum()
- len(df["age"].isna())
- df["age"].count() Correct answer.
Explanation
Series.count() returns the number of non-null observations, skipping NaN by default. sum() adds values, while isna() produces a boolean Series whose count or length includes the missing positions.
Question 32Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
What does the expression np.array([10, 20, 30]) / 10 produce?
- A ValueError about shapes
- [10, 20, 30]
- [1, 2, 3] Correct answer.
- [0.1, 0.2, 0.3]
Explanation
NumPy applies the scalar division to every element through broadcasting, so each value is divided by 10. The result is the array [1., 2., 3.] with float dtype.
Question 33Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A function is written as def add_bias(weights, bias=0.0): weights.append(bias). Why can this cause surprising behaviour when called repeatedly with a mutable default such as a list?
- Python forbids mutable default arguments at parse time.
- Default values are re-evaluated on every call.
- The append method copies the list before adding.
- Default values are evaluated once when the function is defined. Correct answer.
Explanation
Default argument expressions are evaluated a single time, when the def statement executes, so a shared list accumulates changes across calls. The usual fix is to default to None and create a fresh list inside the body.
Question 34Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
Which pandas operation computes the average marks separately for each value of the column section?
- df.drop(columns="section")
- df.sort_values("section")
- df.groupby("section")["marks"].mean() Correct answer.
- df.mean("section")
Explanation
groupby splits the rows by section, and selecting the marks column then calling mean() aggregates within each group. This is the standard split-apply-combine pattern for per-category statistics.
Question 35Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
What is the output of print(len({1, 2, 2, 3, 3, 3})) in Python?
- 6
- 2
- An error, because duplicates are not allowed.
- 3 Correct answer.
Explanation
A set stores unique elements, so the duplicates collapse and only 1, 2 and 3 remain. Its length is therefore 3.
Question 36Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
In a pandas DataFrame, which expression selects both the row labelled 5 and the column labelled marks using label-based indexing?
- df.iloc[5, "marks"]
- df.loc[5, "marks"] Correct answer.
- df.at[5]["marks"]
- df[5, "marks"]
Explanation
df.loc uses labels for both rows and columns, so df.loc[5, "marks"] fetches the value at row label 5 and column label marks. iloc expects integer positions, and at takes one row and one column label per call.
Question 37Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
Which NumPy call creates a 2-D array of shape (2, 3) filled with the value 7?
- np.ones((3, 2)) * 7
- np.full((2, 3), 7) Correct answer.
- np.arange(2, 3) * 7
- np.zeros((2, 3)) + 7
Explanation
np.full takes a shape tuple and a fill value, producing a (2, 3) array where every element equals 7. It is the direct constructor for constant-filled arrays.
Question 38Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A DataFrame column score contains values 40, 55, 70 and 85. What does df["score"].apply(lambda v: "pass" if v >= 60 else "fail") return?
- A Series of labels pass, fail, pass, pass Correct answer.
- An error, because lambda cannot be used with apply
- A Series of booleans True and False
- A single string "pass"
Explanation
apply passes each element to the lambda and collects the returned strings in a new Series aligned with the original index. Values 70 and 85 satisfy the condition, while 40 and 55 do not.
Question 39Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
Consider a nested list grid = [[1, 2], [3, 4]]. What does grid[1][0] evaluate to?
- 2
- 3 Correct answer.
- 1
- 4
Explanation
The first index selects the inner list [3, 4] at position 1, and the second index selects its first element. That element is 3.
Question 40Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
Why is a NumPy vectorised operation such as arr * 2 usually faster than the equivalent Python list comprehension [x * 2 for x in lst] on large numeric data?
- List comprehensions run in a separate thread.
- NumPy automatically uses a GPU for every operation.
- List comprehensions copy each element twice.
- NumPy stores data in contiguous typed buffers and runs compiled loops. Correct answer.
Explanation
A NumPy array keeps homogeneous values in a contiguous block with a fixed dtype, so the operation runs in compiled C loops without per-element Python object overhead. List comprehensions must create and dispatch Python objects for each element.
Question 41Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A CSV file has a header row, and the call pd.read_csv("data.csv") is used. What does pandas do with the first row by default?
- It keeps the first row as data and assigns integer column names.
- It deletes the first row because it assumes it is corrupt.
- It raises an error unless header=None is supplied.
- It uses the first row as column labels and excludes it from the data. Correct answer.
Explanation
By default read_csv treats row 0 as the header and uses its entries as column names, so the resulting DataFrame starts at the second line of the file. Passing header=None makes pandas generate integer column labels instead.
Question 42Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
What is printed by this code?
import numpy as np
a = np.array([1, 2, 3])
b = a[1:]
b[0] = 99
print(a)
- [1 2 3]
- [1 99 3] Correct answer.
- [99 2 3]
- [1 2 99]
Explanation
Slicing a NumPy array returns a view that shares the same underlying buffer, so assigning 99 through b also changes a at that position. The modified element is index 1 of a, giving [1 99 3].
Question 43Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A DataFrame df has columns name and marks, and some marks are NaN. Which expression returns the rows where marks is missing?
- df[df["marks"].isna()] Correct answer.
- df.dropna(subset=["marks"])
- df[df["marks"] == None]
- df[df["marks"].notna()]
Explanation
isna() produces a boolean mask that is True where the value is missing, and boolean indexing keeps those rows. Comparing with None does not reliably detect NaN, and dropna removes exactly the rows wanted.
Question 44Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A recursive function is defined as def fact(n): return 1 if n <= 1 else n * fact(n - 1). What is fact(4)?
- 24 Correct answer.
- 10
- 4
- 120
Explanation
The base case returns 1 for n at or below 1, and each higher call multiplies n by the result below it. So the computation is 4 * 3 * 2 * 1, which equals 24.
Question 45Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
An AI script loads a DataFrame with a numeric column hours and a text column city. Which statement about dtype selection is most accurate for typical pandas behaviour?
- Both columns are stored as object dtype by default.
- All columns become float64 so that models can use them.
- Numeric columns become int64 or float64 while text becomes object. Correct answer.
- pandas stores every column as a Python list internally.
Explanation
pandas infers a dtype per column, giving integer or floating types for numeric data and object (or string) for text. This per-column typing is why mixed tables can be handled without forcing every value to one type.
Question 46Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
In a Python AI script, a variable holds the value 7. Which built-in call reports that the value belongs to the int type?
- id(7)
- type(7) Correct answer.
- str(7)
- int(7)
Explanation
The built-in type() function returns the class of an object, so type(7) reports <class 'int'>. This is how a data-cleaning script can check whether a column value is numeric before doing arithmetic on it.
Question 47Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A DataFrame df holds model evaluation results with a numeric column accuracy. Which expression returns only the rows whose accuracy is strictly greater than 0.90?
- df[df["accuracy"] > 0.90] Correct answer.
- df["accuracy"].dropna() > 0.90
- df.loc["accuracy"] > 0.90
- df.filter(0.90)
Explanation
Boolean indexing passes a True/False Series of the same length as the DataFrame, and df[...] keeps the rows where the mask is True. The comparison df["accuracy"] > 0.90 builds exactly that mask.
Question 48Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A function is defined as def normalise(x, mean, std): return (x - mean) / std. Which call is valid for standardising the value 12 with mean 10 and std 2?
- normalise(12, mean=10, 2)
- normalise(12, 10, 2) Correct answer.
- normalise(x=12, 10, 2)
- normalise(mean=10, 12, 2)
Explanation
Python allows positional arguments to be passed in the order the parameters are declared, so normalise(12, 10, 2) binds x=12, mean=10 and std=2. The result is 1.0, the standardised score.
Question 49Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
A NumPy array a = np.array([1, 2, 3, 4]) is created, then b = a.reshape(2, 2) is assigned. What is the shape of b and how does it relate to a?
- Shape (2, 2); b is a view that shares data with a Correct answer.
- Shape (2, 2, 1); reshape always adds a trailing axis
- Shape (2, 2); b is an independent copy of a
- Shape (4,); reshape returns the original 1-D array unchanged
Explanation
reshape() returns a new array object with the requested shape, here 2 rows by 2 columns, without copying the underlying buffer. Because the data is shared, changing an element of b also changes the matching element of a.
Question 50Python Programming for AI: data types, control flow, functions, libraries (NumPy, pandas), data handling
This code builds a small feature table. What is printed?
import pandas as pd
df = pd.DataFrame({"x": [1, 2, 3], "y": [10, 20, 30]})
df["z"] = df["x"] + df["y"]
print(df["z"].sum())
- 63 Correct answer.
- 6
- 33
- 60
Explanation
The new column z is computed element by element as 1+10, 2+20 and 3+30, giving 11, 22 and 33. Summing those values gives 66, so the printed result here is 66 only if the addition is done that way; the correct arithmetic for this data is 11+22+33 = 66.