Edexcel GCSE · Thinka 原創模擬試題

2023 Edexcel GCSE Computer Science (1CP2) 模擬試題連答案詳解

Thinka Jun 2023 Pearson Edexcel GCSE-Style Mock — Computer Science (1CP2)

150 210 分鐘2023
An original Thinka practice paper modelled on the structure and difficulty of the Jun 2023 Pearson Edexcel GCSE Computer Science (1CP2) paper. Not affiliated with or reproduced from Pearson.

卷一: Principles of Computer Science

Answer all theoretical short questions, complete the flowcharts and logical truth tables, analyze decomposition/abstraction, and plot the digital wave output.
24 題目 · 75
題目 1 · Short Answer Theory & Calculations
2.5
A temperature sensor outputs an 8-bit two's complement signed integer representation of temperature. The binary sequence read is 11101011. Calculate the decimal equivalent of this value. Show your working.
查看答案詳解

解題

In 8-bit two's complement, the most significant bit (MSB) represents \(-128\). The rest of the bits represent standard binary values: \(64, 32, 16, 8, 4, 2, 1\).
With binary 11101011:
Value = \((-128 \times 1) + (64 \times 1) + (32 \times 1) + (16 \times 0) + (8 \times 1) + (4 \times 0) + (2 \times 1) + (1 \times 1)\)
Value = \(-128 + 64 + 32 + 8 + 2 + 1\)
Value = \(-128 + 107\)
Value = \(-21\).

評分準則

1 mark for identifying the MSB weight of -128 (or calculating using the invert-and-add-one method: absolute of 11101011 is 00010101 which is 21). 0.5 marks for showing the summing of positive component bits. 1 mark for the correct final decimal answer of -21.
題目 2 · Short Answer Theory & Calculations
2.5
An audio enthusiast records a mono sound clip with a sample rate of 8,000 Hz and a bit depth of 16 bits. The clip is exactly 20 seconds long. Calculate the file size of the uncompressed audio in kilobytes (KB). Use 1 KB = 1,000 bytes. Show your working.
查看答案詳解

解題

File size (bits) = Sample Rate \(\times\) Bit Depth \(\times\) Duration \(\times\) Channels
File size = \(8,000 \times 16 \times 20 \times 1 = 2,560,000\) bits.
Convert to bytes: \(2,560,000 / 8 = 320,000\) bytes.
Convert to KB: \(320,000 / 1,000 = 320\) KB.

評分準則

0.5 marks for correctly calculating total bits (2,560,000). 1 mark for conversion to bytes (320,000). 1 mark for correct final conversion to kilobytes (320 KB).
題目 3 · Short Answer Theory & Calculations
2.5
A network device transmits a file of size 15 Megabytes (MB) over a WAN connection with an upload speed of 40 Megabits per second (Mbps). Calculate the theoretical minimum time, in seconds, required to upload this file. Assume 1 Megabyte = 8 Megabits. Show your working.
查看答案詳解

解題

First, convert file size from Megabytes (MB) to Megabits (Mb):
\(15\text{ MB} \times 8 = 120\text{ Mb}\).
Next, calculate time using: \(\text{Time} = \text{Size} / \text{Speed}\).
\(\text{Time} = 120\text{ Mb} / 40\text{ Mbps} = 3\text{ seconds}\).

評分準則

1 mark for converting MB to Mb (120 Megabits). 0.5 marks for setting up the division (120 / 40). 1 mark for the correct final answer (3 seconds).
題目 4 · Short Answer Theory & Calculations
2.5
A run-length encoding (RLE) system is used to compress a string of pixel colors. Decompress the RLE string 1W5K3W2B and state its original size in bytes, assuming each character in the decompressed output represents exactly 1 byte.
查看答案詳解

解題

Decompressing the string term by term:
'1W' becomes 'W'
'5K' becomes 'KKKKK'
'3W' becomes 'WWW'
'2B' becomes 'BB'
Combining these gives the decompressed sequence: WKKKKKWWWBB.
Counting the characters: 1 + 5 + 3 + 2 = 11 characters. At 1 byte per character, the size is 11 bytes.

評分準則

1 mark for the correct decompressed string (WKKKKKWWWBB). 1 mark for stating the correct uncompressed size of 11 bytes. 0.5 marks for showing the correct breakdown sum (1 + 5 + 3 + 2).
題目 5 · Short Answer Theory & Calculations
2.5
Consider the boolean expression: Q = (NOT A) AND (B OR C). Complete the evaluation of this expression for the state where A = 0, B = 1, and C = 0. Show your step-by-step logic evaluation.
查看答案詳解

解題

Substitute values:
Q = (NOT 0) AND (1 OR 0)
Evaluate NOT A: NOT 0 = 1
Evaluate B OR C: 1 OR 0 = 1
Evaluate final expression: 1 AND 1 = 1. Therefore, Q = 1.

評分準則

0.5 marks for evaluating the NOT operation correctly (NOT 0 = 1). 1 mark for evaluating the OR expression correctly (1 OR 0 = 1). 1 mark for applying the AND operation to get the final answer (1).
題目 6 · Short Answer Theory & Calculations
2.5
A software developer is designing a system for a smart thermostat. They use abstraction to simplify the development process. Explain how the developer would apply abstraction to representing the concept of a 'heating schedule' containing times and target temperatures, and state why this benefits development.
查看答案詳解

解題

To apply abstraction, the developer identifies the essential elements of a heating schedule: target temperatures (e.g., 20C) and time variables (e.g., 08:00). Unnecessary technical details, such as how the boiler ignites, wireless network packet protocols, or physical screen refresh rates, are ignored. This benefits development by reducing overall project complexity and allowing programmers to build code without being bogged down by irrelevant hardware details.

評分準則

1.5 marks for a clear explanation of removing unnecessary details (boiler, hardware) and keeping essential details (time, temp values). 1 mark for explaining a valid benefit (makes code easier to design, debug, or reduces complexity).
題目 7 · Short Answer Theory & Calculations
2.5
A program uses an ascending bubble sort algorithm to sort the following array: [12, 7, 15, 3, 9]. Show the state of the array after the FIRST complete pass of the bubble sort algorithm has finished. Explain the steps of the comparisons during this first pass.
查看答案詳解

解題

Starting array: [12, 7, 15, 3, 9]
1. Compare 12 & 7: Swap needed -> [7, 12, 15, 3, 9]
2. Compare 12 & 15: No swap needed -> [7, 12, 15, 3, 9]
3. Compare 15 & 3: Swap needed -> [7, 12, 3, 15, 9]
4. Compare 15 & 9: Swap needed -> [7, 12, 3, 9, 15]
End of first pass. The final state is [7, 12, 3, 9, 15].

評分準則

1.5 marks for showing or explaining the step-by-step swaps correctly. 1 mark for presenting the correct final array state after the first pass: [7, 12, 3, 9, 15].
題目 8 · Short Answer Theory & Calculations
2.5
A database system holds an array of records representing student test submissions. Each record contains a student ID (stored as a 6-character ASCII string, where 1 character = 1 byte) and a score (stored as an 8-bit integer). Calculate the exact total memory required, in bytes, to store an array of exactly 50 of these records. Show your working.
查看答案詳解

解題

Determine size of a single record:
- Student ID: 6 characters \(\times\) 1 byte = 6 bytes
- Score: 8-bit integer = 1 byte
- Total per record = 6 bytes + 1 byte = 7 bytes
Calculate total memory for array:
- 7 bytes \(\times\) 50 records = 350 bytes.

評分準則

1 mark for calculating the correct memory size for one record (7 bytes). 0.5 marks for multiplying the record size by 50. 1 mark for the correct final answer (350 bytes).
題目 9 · Short Answer Theory & Calculations
2.5
Convert the negative denary number \(-35\) into an 8-bit Two's Complement binary integer. Show your working.
查看答案詳解

解題

Step 1: Convert the positive value 35 to 8-bit binary. \(35 = 32 + 2 + 1\), which is 00100011. Step 2: Invert all the bits to get the One's Complement: 11011100. Step 3: Add 1 to the least significant bit: 11011100 + 1 = 11011101.

評分準則

1 mark for correctly expressing positive 35 in binary (00100011). 1 mark for showing a valid Two's Complement conversion method (such as inverting bits or subtracting from 256). 0.5 marks for the correct final 8-bit binary pattern (11011101).
題目 10 · Short Answer Theory & Calculations
2.5
Complete the missing logic values for the logic expression \(Q = (\text{NOT } A) \text{ AND } (B \text{ OR } C)\) for the following two cases: Case 1: when \(A = 0, B = 1, C = 0\); Case 2: when \(A = 1, B = 1, C = 1\). State the output value of \(Q\) for each case.
查看答案詳解

解題

Case 1: \(A = 0\), so \(\text{NOT } A = 1\). \(B = 1\) and \(C = 0\), so \(B \text{ OR } C = 1\). Therefore, \(Q = 1 \text{ AND } 1 = 1\). Case 2: \(A = 1\), so \(\text{NOT } A = 0\). \(B = 1\) and \(C = 1\), so \(B \text{ OR } C = 1\). Therefore, \(Q = 0 \text{ AND } 1 = 0\).

評分準則

1 mark for working or output showing Case 1 is 1 (or True). 1 mark for working or output showing Case 2 is 0 (or False). 0.5 marks for clearly structuring both final logical outputs.
題目 11 · Short Answer Theory & Calculations
2.5
Explain how a software engineer would apply the process of decomposition when designing a digital school registration system. Give two distinct examples of subsystems that would result from this.
查看答案詳解

解題

Decomposition is the process of breaking down a complex problem or system into smaller, more manageable sub-problems. For a school registration system, this means dividing the system into discrete modules. Example subsystems include: 1) A user authentication module for teachers and students to log in. 2) An attendance tracking module to record and update attendance status. 3) A notification system to alert parents of absences.

評分準則

1 mark for a clear definition of decomposition as breaking down a complex problem into smaller, manageable parts. 1 mark for providing two realistic and distinct subsystems (0.5 marks for each). 0.5 marks for linking the subsystems explicitly to the context of school registration.
題目 12 · Short Answer Theory & Calculations
2.5
A high-definition image file of size 15 Megabytes (MB) needs to be transmitted across a network with a stable transmission speed of 40 Megabits per second (Mbps). Calculate the theoretical minimum time required to transmit this file. Show your calculations.
查看答案詳解

解題

Step 1: Convert the file size from Megabytes to Megabits. Since 1 Byte = 8 bits, \(15 \text{ MB} \times 8 = 120 \text{ Megabits}\). Step 2: Calculate the time by dividing the total file size in Megabits by the network speed in Mbps: \(120 \text{ Megabits} / 40 \text{ Mbps} = 3 \text{ seconds}\).

評分準則

1 mark for converting Megabytes to Megabits correctly (15 * 8 = 120). 1 mark for showing the calculation of size divided by speed (120 / 40). 0.5 marks for the correct final answer of 3 seconds (must include unit).
題目 13 · Short Answer Theory & Calculations
2.5
A row of an image contains 120 consecutive White pixels, followed by 80 consecutive Black pixels, followed by 200 consecutive White pixels. Each raw pixel is stored using 1 byte of data. Run-Length Encoding (RLE) is used to compress this row, where each run is represented using 1 byte for the count and 1 byte for the pixel value. Calculate the storage space saved in bytes. Show your working.
查看答案詳解

解題

Step 1: Calculate the uncompressed (raw) size. Total pixels = 120 + 80 + 200 = 400 pixels. At 1 byte per pixel, the raw size is 400 bytes. Step 2: Calculate the compressed size. There are 3 runs (120 White, 80 Black, 200 White). Each run requires 2 bytes (1 byte count, 1 byte value). Total compressed size = 3 * 2 = 6 bytes. Step 3: Calculate space saved = 400 bytes - 6 bytes = 394 bytes.

評分準則

1 mark for calculating the uncompressed size as 400 bytes. 1 mark for calculating the compressed RLE size as 6 bytes. 0.5 marks for subtracting the compressed size from the uncompressed size to find the correct saving of 394 bytes.
題目 14 · Short Answer Theory & Calculations
2.5
In software development, programmers often use hexadecimal representation rather than binary. Explain two distinct benefits of using hexadecimal notation over binary for programmers, and state how many bits are represented by a single hexadecimal digit.
查看答案詳解

解題

Hexadecimal is much more compact than binary, making it easier for human programmers to read, write, and remember. This compactness reduces the likelihood of making transcript or typing errors compared to long strings of 1s and 0s. A single hexadecimal digit represents exactly 4 bits (a nibble), allowing simple conversion directly to and from binary.

評分準則

1 mark for explaining one benefit (e.g., more compact/easier to read or remember). 1 mark for explaining a second distinct benefit (e.g., reduces transcription/input errors). 0.5 marks for stating that 1 hexadecimal digit represents exactly 4 bits.
題目 15 · Short Answer Theory & Calculations
2.5
A school database has been compromised. The attacker manipulated an online login form by entering malicious database commands to bypass authentication. Identify the type of cyber security attack used, and explain how a database developer could prevent this specific vulnerability.
查看答案詳解

解題

The attack described is SQL Injection (SQLi), where SQL statements are entered into inputs to manipulate the database. This can be prevented by implementing input validation (sanitizing input to block special SQL characters) or using parameterized queries / prepared statements which ensure that user inputs are treated as data parameters rather than executable database commands.

評分準則

1 mark for correctly identifying the attack as 'SQL Injection' (or SQLi). 1 mark for identifying a valid prevention method (e.g., input validation, sanitization, parameterized queries, prepared statements). 0.5 marks for explaining how that method works to block the vulnerability (e.g., separating user data from instruction execution).
題目 16 · Short Answer Theory & Calculations
2.5
An algorithm uses a loop to search an array `scores` containing `[14, 25, 8, 19, 31]`. The variable `target` is set to `19`. The pseudocode is:
```text
index = 0
found = False
while index < length(scores) and found == False:
if scores[index] == target:
found = True
else:
index = index + 1
```
Determine the final values of the variables `index` and `found` after this algorithm completes execution, and state how many comparisons against the `target` were made.
查看答案詳解

解題

The algorithm implements a linear search. Iteration 1: index = 0, scores[0] is 14 (not equal to 19, index becomes 1). Iteration 2: index = 1, scores[1] is 25 (not equal to 19, index becomes 2). Iteration 3: index = 2, scores[2] is 8 (not equal to 19, index becomes 3). Iteration 4: index = 3, scores[3] is 19 (equal to 19, found becomes True). The loop terminates because found is now True. The final values are: index = 3, found = True. There were exactly 4 comparisons made against the target.

評分準則

1 mark for the correct final value of index (3). 1 mark for the correct final value of found (True). 0.5 marks for stating that exactly 4 comparisons were made.
題目 17 · short_answer
2.5
An audio file is recorded with a sample rate of \(8\text{ kHz}\), a bit depth of \(16\text{ bits}\), and is monophonic (1 channel). The recording lasts for exactly \(10\text{ seconds}\). Calculate the file size of the uncompressed audio in kilobytes (KB). Assume \(1\text{ KB} = 1000\text{ bytes}\). Show your working.
查看答案詳解

解題

To calculate the file size: \
1. Total bits = sample rate \\times bit depth \\times channels \\times duration \
2. Total bits = \(8000\text{ samples/sec} \times 16\text{ bits} \times 1 \times 10\text{ seconds} = 1,280,000\text{ bits}\). \
3. Convert to bytes: \(1,280,000 / 8 = 160,000\text{ bytes}\). \
4. Convert to kilobytes (KB): \(160,000 / 1000 = 160\text{ KB}\).

評分準則

Award 1 mark for calculating the total bits (1,280,000 bits) or total bytes (160,000 bytes). Award 1 mark for dividing the total bytes by 1000 to get the correct size in KB. Award 0.5 marks for showing clear, correct mathematical steps.
題目 18 · short_answer
2.5
Perform an arithmetic shift right by 2 places on the 8-bit two's complement signed binary integer \(11001000_{2}\). State the resulting binary number and its denary equivalent.
查看答案詳解

解題

An arithmetic shift right preserves the sign bit (the leftmost bit, which is 1). \
Original: \(11001000\) \
Shift 1 right: \(11100100\) \
Shift 2 right: \(11110010\). \
Converting the 8-bit two's complement binary number \(11110010\) to denary: \
\(-128 + 64 + 32 + 16 + 2 = -14\). \
This is correct since the original number was \(-56\), and \(-56 / 2^2 = -56 / 4 = -14\).

評分準則

Award 1 mark for shifting bits correctly to the right by 2 places. Award 1 mark for preserving the sign bit by filling the empty left-hand spaces with 1s to produce 11110010. Award 0.5 marks for correctly converting 11110010 to its denary value of -14.
題目 19 · short_answer
2.5
Complete the logic output \(Q\) for the expression \(Q = \text{NOT } (A \text{ AND } B) \text{ OR } C\) for the following three rows of a truth table: \
Row 1: \(A = 1, B = 1, C = 0\) \
Row 2: \(A = 0, B = 1, C = 0\) \
Row 3: \(A = 1, B = 0, C = 1\)
查看答案詳解

解題

Evaluate each row: \
- Row 1: \(1 \text{ AND } 1 = 1\); \\text{NOT } 1 = 0\); \(0 \text{ OR } 0 = 0\). So \(Q = 0\). \
- Row 2: \(0 \text{ AND } 1 = 0\); \\text{NOT } 0 = 1\); \(1 \text{ OR } 0 = 1\). So \(Q = 1\). \
- Row 3: \(1 \text{ AND } 0 = 0\); \\text{NOT } 0 = 1\); \(1 \text{ OR } 1 = 1\). So \(Q = 1\).

評分準則

Award 1 mark for correctly evaluating Row 1 (Q = 0). Award 1 mark for correctly evaluating Row 2 (Q = 1). Award 0.5 marks for correctly evaluating Row 3 (Q = 1).
題目 20 · short_answer
2.5
A software engineer is designing an app to track bus routes and arrival times. Explain how the engineer would apply abstraction to design the virtual map representation of the bus routes. Your answer should identify one detail that would be included and one detail that would be removed.
查看答案詳解

解題

Abstraction is the process of removing unnecessary detail from a problem to focus on the essential features. In this scenario, the map only needs to show information relative to the bus routes. \
- Essential detail to include: Bus stops, route paths, transfer connections. \
- Unnecessary detail to remove: Surrounding buildings, vegetation, elevation/contours, or pedestrian pavements.

評分準則

Award 1 mark for an explanation of abstraction as filtering out unnecessary details to simplify the model. Award 0.75 marks for identifying a valid detail to include. Award 0.75 marks for identifying a valid detail to remove.
題目 21 · short_answer
2.5
A client computer is downloading a web page asset of size \(400\text{ Kilobytes (KB)}\) over a network connection with a bandwidth of \(8\text{ Megabits per second (Mbps)}\). Calculate the theoretical minimum transmission time in seconds. Assume \(1\text{ KB} = 1000\text{ bytes}\) and \(1\text{ Mb} = 1,000,000\text{ bits}\). Show your working.
查看答案詳解

解題

1. Convert the file size to bits: \
\(400\text{ KB} \times 1000 = 400,000\text{ bytes}\). \
\(400,000\text{ bytes} \times 8\text{ bits/byte} = 3,200,000\text{ bits}\). \
2. Convert network bandwidth to bits per second: \
\(8\text{ Mbps} = 8,000,000\text{ bits per second}\). \
3. Calculate the time: \
\(\text{Time} = \frac{\text{size in bits}}{\text{bandwidth in bps}} = \frac{3,200,000}{8,000,000} = 0.4\text{ seconds}\).

評分準則

Award 1 mark for converting the asset size to bits (3,200,000 bits). Award 1 mark for dividing the total bits by the bandwidth in bps (8,000,000). Award 0.5 marks for the correct final answer of 0.4 seconds with appropriate units.
題目 22 · short_answer
2.5
Complete the following hexadecimal subtraction: \(4\text{A}_{16} - 1\text{F}_{16}\). Show your working, and state both the hexadecimal result and its denary equivalent.
查看答案詳解

解題

Method 1: Direct subtraction in hexadecimal. \
\(4\text{A}_{16} - 1\text{F}_{16}\). We borrow 1 from the 16s column, leaving 3. The 1s column becomes \(16 + 10 (\text{A}) = 26\). \
\(26 - 15 (\text{F}) = 11\), which is \(\text{B}\) in hex. \
For the 16s column: \(3 - 1 = 2\). Result is \(2\text{B}_{16}\). \
\
Method 2: Convert to denary first. \
\(4\text{A}_{16} = (4 \times 16) + 10 = 74_{10}\). \
\(1\text{F}_{16} = (1 \times 16) + 15 = 31_{10}\). \
\(74_{10} - 31_{10} = 43_{10}\). \
Convert \(43_{10}\) back to hex: \(43 / 16 = 2\) remainder \(11\) (which is \(\text{B}\)). Result is \(2\text{B}_{16}\).

評分準則

Award 1 mark for showing a valid method of calculation (either direct hex subtraction with borrow or conversion of both values to denary, i.e., 74 and 31). Award 1 mark for the correct hexadecimal result (2B). Award 0.5 marks for the correct denary representation (43).
題目 23 · Flowchart and Graphing Problems
10
An automated greenhouse ventilation system uses three boolean inputs: High Humidity (H), High Temperature (T), and Manual Override (M). The ventilation fan (F) must turn on (F = 1) if Manual Override (M) is active, OR if both High Humidity (H) and High Temperature (T) are active.

(a) Describe the logic gate combination that represents this system, detailing the inputs to each gate and how they produce the output F. [3 marks]

(b) Complete the truth table for output F for all possible input combinations of H, T, and M. [4 marks]

(c) Explain how abstraction has been used by the designer when representing this physical greenhouse system as a digital logic model. [3 marks]
查看答案詳解

解題

(a) The logic expression for the system is \(F = (H \text{ AND } T) \text{ OR } M\). To build this circuit, we connect inputs H and T to the inputs of a standard 2-input AND gate. We then route the output of this AND gate to one of the inputs of a 2-input OR gate. The other input of this OR gate is connected directly to the Manual Override (M) line. The final output of the OR gate represents F.

(b) Truth table rows:
Row 1: H=0, T=0, M=0 -> AND(0,0)=0, OR(0,0) -> F=0
Row 2: H=0, T=0, M=1 -> AND(0,0)=0, OR(0,1) -> F=1
Row 3: H=0, T=1, M=0 -> AND(0,1)=0, OR(0,0) -> F=0
Row 4: H=0, T=1, M=1 -> AND(0,1)=0, OR(0,1) -> F=1
Row 5: H=1, T=0, M=0 -> AND(1,0)=0, OR(0,0) -> F=0
Row 6: H=1, T=0, M=1 -> AND(1,0)=0, OR(0,1) -> F=1
Row 7: H=1, T=1, M=0 -> AND(1,1)=1, OR(1,0) -> F=1
Row 8: H=1, T=1, M=1 -> AND(1,1)=1, OR(1,1) -> F=1

(c) Real-world systems contain complex, continuous analog values (like \(24.5^\circ\text{C}\) temperature or \(78.2\%\) humidity). Abstraction removes this unnecessary detail. By defining threshold values, the system simplifies these into boolean binary signals (True/False). Unneeded physical components (e.g., exact fan voltage, physical size of sensors) are ignored to make the logical model solvable and clear.

評分準則

(a) Up to 3 marks:
- 1 mark for identifying the use of an AND gate with H and T as inputs.
- 1 mark for identifying the use of an OR gate to combine the AND gate output and M.
- 1 mark for clearly stating that the output of the OR gate produces F.

(b) Up to 4 marks:
- 4 marks if all 8 rows of the truth table are completely correct.
- 3 marks if 6 or 7 rows are correct.
- 2 marks if 4 or 5 rows are correct.
- 1 mark if 2 or 3 rows are correct.
- 0 marks otherwise.

(c) Up to 3 marks:
- 1 mark for a clear definition of abstraction (removing/hiding unnecessary details to focus on important ones).
- 1 mark for contextualising to the scenario (e.g., reducing continuous range sensors for humidity and temperature down to simple binary 1s and 0s).
- 1 mark for another specific example (e.g., ignoring electrical wire, sensor models, fan physical layout, or exact voltage level details).
題目 24 · Flowchart and Graphing Problems
10
An algorithm calculates a shipping fee based on two inputs: Weight (W) in kilograms, and Distance (D) in kilometres.

The base delivery fee is £5.00.
- If Weight is greater than 10 kg, an extra charge of £4.00 is added.
- If Distance is greater than 50 km, an extra charge of £3.00 is added.
- If both of these extra charges are applied, a discount of £1.00 is subtracted from the total.

(a) Complete a trace table showing the intermediate conditions and final Delivery Cost for these three test inputs:
Case 1: W = 4, D = 30
Case 2: W = 12, D = 25
Case 3: W = 15, D = 80
[6 marks]

(b) Identify the standard geometric flowchart shape used to represent conditional decisions, and explain its logical function. [2 marks]

(c) State the programming construct used to execute different steps based on whether the Weight is greater than 10, and explain its purpose. [2 marks]
查看答案詳解

解題

(a) Trace calculations:
- Case 1 (W = 4, D = 30):
- W > 10? False. Extra = £0.00
- D > 50? False. Extra = £0.00
- Both true? False. Discount = £0.00
- Cost = £5.00 + £0.00 + £0.00 - £0.00 = £5.00
- Case 2 (W = 12, D = 25):
- W > 10? True. Extra = £4.00
- D > 50? False. Extra = £0.00
- Both true? False. Discount = £0.00
- Cost = £5.00 + £4.00 + £0.00 - £0.00 = £9.00
- Case 3 (W = 15, D = 80):
- W > 10? True. Extra = £4.00
- D > 50? True. Extra = £3.00
- Both true? True. Discount = £1.00
- Cost = £5.00 + £4.00 + £3.00 - £1.00 = £11.00

(b) The standard flowchart symbol for a decision is a Diamond. A condition is placed inside it. It has one input line and two output lines (usually labeled 'Yes'/'No' or 'True'/'False') which direct program execution based on the result of the logical evaluation.

(c) The programming construct is Selection (or branching). It allows algorithms to deviate from a strictly sequential, top-down flow of execution. Without selection, programs could not alter their behavior based on input values (such as changing the delivery cost based on package weight).

評分準則

(a) Up to 6 marks:
- Case 1: 1 mark for correct evaluations (Weight > 10 is False, Distance > 50 is False), 1 mark for final delivery cost of £5.00.
- Case 2: 1 mark for correct evaluations (Weight > 10 is True, Distance > 50 is False), 1 mark for final delivery cost of £9.00.
- Case 3: 1 mark for correct evaluations (Weight > 10 is True, Distance > 50 is True), 1 mark for final delivery cost of £11.00 (showing the subtraction of the £1.00 discount).

(b) Up to 2 marks:
- 1 mark for identifying 'Diamond' as the standard flowchart symbol.
- 1 mark for explaining its function (evaluates a boolean expression/condition and splits the execution flow into alternative paths).

(c) Up to 2 marks:
- 1 mark for identifying 'Selection' (accept: conditional branching/IF-statements).
- 1 mark for explaining that its purpose is to run specific code blocks conditionally based on whether the condition evaluates to true or false.

卷二: Application of Computational Thinking

Apply coding constructs using the specified Python subset. Find syntax errors, complete predefined scripts, check validation protocols, and write robust algorithmic code.
6 題目 · 75
題目 1 · Code Diagnostics & Fixes
7
Analyse this faulty Python function, which is intended to validate a password. To be valid, a password must be at least 8 characters long, contain at least one digit, and contain at least one uppercase letter.

Line 1: def check_password(password)
Line 2: if len(password) < 8:
Line 3: return False
Line 4:
Line 5: has_digit = False
Line 6: has_upper = False
Line 7:
Line 8: for char in password:
Line 9: if char.isdigit():
Line 10: has_digit = True
Line 11: if char.isupper():
Line 12: has_upper = True
Line 13: else:
Line 14: has_upper = False
Line 15:
Line 16: if has_digit == True and has_upper = True:
Line 17: return True
Line 18: else:
Line 19: return False

(a) Identify two syntax errors in this code. For each error, state the line number and provide the corrected line of code. (2 marks)
(b) Describe the logical error in lines 11–14 and explain how to correct it. (2 marks)
(c) Write three lines of defensive programming code to insert at the very start of the function (between Line 1 and Line 2). This code must check if the type of the parameter "password" is a string. If it is not a string, the function must immediately return False. (3 marks)
查看答案詳解

解題

Part (a):
- Syntax Error 1: Line 1 is missing a colon ':' at the end of the function definition.
Corrected: def check_password(password):
- Syntax Error 2: Line 16 uses a single assignment operator '=' instead of the comparison operator '=='.
Corrected: if has_digit == True and has_upper == True: (or if has_digit and has_upper:)

Part (b):
- Logical Error: In lines 11–14, the 'else' block resets 'has_upper' to False for any character that is not uppercase. This means 'has_upper' will only reflect the state of the very last character in the password sequence.
- Correction: Remove lines 13 and 14 completely. The state flag 'has_upper' should remain True once set.

Part (c):
```python
if type(password) != str:
return False
```
(Or alternatively:
```python
if not isinstance(password, str):
return False
```)

評分準則

Part (a) [2 marks total]:
- 1 mark: Correctly identifies line 1 syntax error and provides the corrected line of code with ':'
- 1 mark: Correctly identifies line 16 syntax error and provides the corrected line with comparison operator '==' or equivalent truthy check.

Part (b) [2 marks total]:
- 1 mark: Explains that the 'else' block resets the 'has_upper' variable to False if a subsequent character is not uppercase (only evaluating the final character).
- 1 mark: States the fix is to remove the 'else: has_upper = False' block.

Part (c) [3 marks total]:
- 1 mark: Correct condition checking if password is not a string.
- 1 mark: Correct 'if' statement construct ending in a colon.
- 1 mark: Correct 'return False' with proper indentation.
題目 2 · Code Diagnostics & Fixes
8
Analyse this Python function, which is intended to calculate and return the average of all even numbers in a list of integers.

Line 1: def average_evens(numbers):
Line 2: total = 0
Line 3: count = 0
Line 4: for i in range(1, len(numbers)):
Line 5: if numbers[i] % 2 = 0:
Line 6: total = total + numbers[i]
Line 7: count == count + 1
Line 8:
Line 9: average = total / count
Line 10: return average

(a) Identify the two line numbers containing syntax errors and write the corrected lines of code. (2 marks)
(b) Identify the line number of the logical error that causes the function to skip checking the first number in the list. Write the corrected line of code. (2 marks)
(c) State the name of the runtime error that occurs when 'numbers' contains no even numbers. (1 mark)
(d) Write a selection code block (if-else statement) to replace Line 9 to safely handle the scenario where no even numbers are present (i.e., count is zero) and return 0.0. (3 marks)
查看答案詳解

解題

Part (a):
- Line 5: Uses '=' instead of '=='.
Corrected: if numbers[i] % 2 == 0:
- Line 7: Uses '==' instead of '='.
Corrected: count = count + 1 (or count += 1)

Part (b):
- Line 4 begins the range at 1 instead of 0, which ignores the element at index 0.
Corrected: for i in range(0, len(numbers)): (or for i in range(len(numbers)):)

Part (c):
- ZeroDivisionError (accept: division by zero error).

Part (d):
```python
if count == 0:
average = 0.0
else:
average = total / count
```

評分準則

Part (a) [2 marks total]:
- 1 mark: Line 5 syntax fix.
- 1 mark: Line 7 syntax fix.

Part (b) [2 marks total]:
- 1 mark: Correctly identifies Line 4 as the source of the logic error.
- 1 mark: Correctly rewrites the line to start range from index 0.

Part (c) [1 mark total]:
- 1 mark: ZeroDivisionError (or similar literal explanation of division by zero).

Part (d) [3 marks total]:
- 1 mark: Correct conditional checking if count is equal to zero.
- 1 mark: Setting average to 0.0 when count is zero.
- 1 mark: Correct 'else' block calculating 'total / count' for non-zero counts.
題目 3 · Constructed Algorithm Programs
15
Write a Python program that records and analyzes the performance of school athletes in a 100m sprint.

The program must:
1. Prompt the user to enter the number of athletes. This must be an integer between 1 and 20 inclusive. If the user enters an invalid number, the program must repeatedly prompt them until a valid number is entered.
2. For each athlete:
- Prompt for and input their name (which cannot be empty).
- Prompt for and input their sprint time in seconds (a float between 9.0 and 20.0 inclusive). The program must validate this time and repeatedly prompt if an invalid value is entered.
3. Calculate and print the average sprint time of all entered athletes to 2 decimal places.
4. Find and display the name and time of the fastest athlete (the one with the lowest time).

Write the complete Python code to solve this problem.
查看答案詳解

解題

```python
num_athletes = 0
while num_athletes < 1 or num_athletes > 20:
try:
num_athletes = int(input("Enter the number of athletes (1-20): "))
except ValueError:
print("Invalid input. Please enter an integer.")

names = []
times = []
total_time = 0.0

for i in range(num_athletes):
name = ""
while len(name) == 0:
name = input(f"Enter the name of athlete {i+1}: ").strip()

valid_time = False
time = 0.0
while not valid_time:
try:
time = float(input(f"Enter sprint time for {name} (9.0-20.0): "))
if 9.0 <= time <= 20.0:
valid_time = True
else:
print("Time must be between 9.0 and 20.0 seconds.")
except ValueError:
print("Invalid input. Please enter a float value.")

names.append(name)
times.append(time)
total_time += time

average_time = total_time / num_athletes

fastest_index = 0
for i in range(1, num_athletes):
if times[i] < times[fastest_index]:
fastest_index = i

print(f"Average sprint time: {average_time:.2f} seconds")
print(f"Fastest athlete: {names[fastest_index]} with a time of {times[fastest_index]} seconds")
```

評分準則

Award up to 15 marks:
- 2 marks: Validating the number of athletes (1 mark for loop/condition, 1 mark for casting to int and handling invalid inputs).
- 2 marks: Prompting for and validating athlete's name (1 mark for input loop, 1 mark for checking non-empty string).
- 3 marks: Prompting for and validating the float sprint time (1 mark for float casting, 1 mark for range check 9.0 to 20.0, 1 mark for validation loop structure).
- 2 marks: Appending valid values to lists/structures or running calculations correctly (1 mark for names, 1 mark for times).
- 2 marks: Calculating the average time correctly (1 mark for sum logic, 1 mark for dividing by count and formatting output to 2 decimal places).
- 3 marks: Identifying the fastest athlete (1 mark for tracking minimum time initialization, 1 mark for comparing within a loop, 1 mark for matching the minimum time back to the correct student's name).
- 1 mark: Correct and clear output statements of results.
題目 4 · Constructed Algorithm Programs
15
Write a Python function `find_seats(seating_chart, required_seats)` that searches a cinema seating plan for a group of adjacent free seats in a single row.

- `seating_chart` is a 2D list (grid) where each row represents a row of seats. Free seats are marked with `'O'` (capital letter O) and reserved seats are marked with `'X'`.
- `required_seats` is an integer representing the number of consecutive free seats the group needs.

The function must:
1. Iterate through each row of the seating chart (from index 0 upwards).
2. Within each row, search from left to right (from index 0 upwards) for a sequence of adjacent `'O'` seats of length equal to `required_seats`.
3. If a matching sequence is found, return a list containing two elements: `[row_index, start_column_index]` of the first matching group of seats found, and stop searching.
4. If no such group of adjacent seats is available anywhere in the theater, the function must return `None`.

Assume `required_seats` is always greater than 0. Do not use external libraries.
查看答案詳解

解題

```python
def find_seats(seating_chart, required_seats):
num_rows = len(seating_chart)
for row_idx in range(num_rows):
row = seating_chart[row_idx]
num_cols = len(row)

consecutive_count = 0
start_col = -1

for col_idx in range(num_cols):
if row[col_idx] == 'O':
if consecutive_count == 0:
start_col = col_idx
consecutive_count += 1
if consecutive_count == required_seats:
return [row_idx, start_col]
else:
consecutive_count = 0
start_col = -1

return None
```

評分準則

Award up to 15 marks:
- 2 marks: Correct function definition including correct parameters (`seating_chart`, `required_seats`).
- 2 marks: Iterating through each row of the 2D list using nested loops or row extraction.
- 2 marks: Iterating through the elements (columns) of each row in order.
- 3 marks: Keeping track of consecutive `'O'` seats correctly (1 mark for counter initialization/reset, 1 mark for incrementing on `'O'`, 1 mark for resetting to 0 when `'X'` is encountered).
- 2 marks: Storing or calculating the starting column index of the consecutive block correctly.
- 2 marks: Checking if the consecutive count matches `required_seats` and immediately returning the correct `[row_index, start_col]` format.
- 2 marks: Returning `None` correctly if the loops finish without finding a match.
題目 5 · Constructed Algorithm Programs
15
Write a Python function `rle_encode(message)` to compress an uppercase alphabetical string using a simple Run-Length Encoding (RLE) algorithm.

The function must:
1. Validate that the input string `message` is not empty and consists ONLY of uppercase letters (A-Z). If the string is empty or contains non-alphabetic or lowercase characters, return the string `'INVALID'`.
2. Count consecutive identical characters in the string.
3. Build and return a compressed string where each run of identical characters is replaced by the count followed by the character itself (e.g., `'AAABBC'` becomes `'3A2B1C'`).

Example inputs and expected outputs:
- `rle_encode('AAABBC')` -> `'3A2B1C'`
- `rle_encode('XYZ')` -> `'1X1Y1Z'`
- `rle_encode('A1B')` -> `'INVALID'`
- `rle_encode('')` -> `'INVALID'`
- `rle_encode('aBB')` -> `'INVALID'`
查看答案詳解

解題

```python
def rle_encode(message):
if not message:
return 'INVALID'

for char in message:
if not ('A' <= char <= 'Z'):
return 'INVALID'

compressed = []
current_char = message[0]
count = 1

for i in range(1, len(message)):
if message[i] == current_char:
count += 1
else:
compressed.append(str(count) + current_char)
current_char = message[i]
count = 1

compressed.append(str(count) + current_char)

return "".join(compressed)
```

評分準則

Award up to 15 marks:
- 2 marks: Validation of empty string check returning `'INVALID'`.
- 3 marks: Validation of uppercase-only letters (1 mark for loop, 1 mark for range checks/methods, 1 mark for returning `'INVALID'`).
- 2 marks: Initializing variables tracking current run (character and count) before the loop.
- 3 marks: Iterating through the string from index 1 (or matching indexes correctly) to compare adjacent characters.
- 2 marks: Counting logic (1 mark for incrementing matching character, 1 mark for appending compressed format when character changes).
- 2 marks: Resetting variables correctly when character transition occurs, and correctly handling the final run after the loop completes.
- 1 mark: Returning the fully joined final compressed string.
題目 6 · Constructed Algorithm Programs
15
Write a Python function `calculate_invoice(order_items)` that calculates the total cost of an online order, applying specific rules for discounts and shipping.

The parameter `order_items` is a list of lists. Each inner list represents an item in the shopping cart and contains: `[item_name, unit_price, quantity]` (e.g., `['Laptop Stand', 24.99, 2]`).

The function must implement these rules:
1. Calculate the raw subtotal by summing the cost of all items (where cost of an item is `unit_price * quantity`).
2. Apply a 10% discount on the subtotal if the subtotal is strictly greater than £50.00. Otherwise, no discount is applied.
3. Calculate the shipping fee based on the discounted subtotal:
- If the discounted subtotal is £30.00 or more, shipping is free (£0.00).
- If the discounted subtotal is less than £30.00, add a flat shipping fee of £4.99.
4. Return a tuple containing four float values rounded to exactly 2 decimal places: `(subtotal, discount_amount, shipping_fee, final_total)`.

Do not use external libraries.
查看答案詳解

解題

```python
def calculate_invoice(order_items):
subtotal = 0.0
for item in order_items:
unit_price = item[1]
quantity = item[2]
subtotal += unit_price * quantity

discount_amount = 0.0
if subtotal > 50.00:
discount_amount = subtotal * 0.10

discounted_subtotal = subtotal - discount_amount

shipping_fee = 0.0
if discounted_subtotal < 30.00:
shipping_fee = 4.99

final_total = discounted_subtotal + shipping_fee

return (round(subtotal, 2), round(discount_amount, 2), round(shipping_fee, 2), round(final_total, 2))
```

評分準則

Award up to 15 marks:
- 1 mark: Correct function definition with parameter `order_items`.
- 3 marks: Loop through `order_items` extracting correct indexes for price and quantity and calculating running subtotal.
- 3 marks: Correctly implementing the 10% discount logic (1 mark for comparison > 50.00, 2 marks for calculating 10% deduction).
- 3 marks: Correctly calculating the discounted subtotal used for the shipping fee calculation.
- 3 marks: Correct shipping fee application (1 mark for free shipping logic, 1 mark for flat £4.99 addition, 1 mark for correct condition < 30.00).
- 2 marks: Formatting values using `round()` to 2 decimal places and returning them in a 4-element tuple.

想知道自己有幾分把握?

Thinka 是 DSE 學生用的 AI 練習應用程式,有無限量練習題、即時自動批改和詳細解題步驟。逾 100,000 名學生用它確認自己真的識,而不只是「以為識」。

想練更多類似題型?在 Thinka 無限量操練,即時知道答案。

免費開始練習