أسئلة المقال وتتبع الشيفرة وتصحيح الأخطاء وكتابة الشيفرة في بنك أسئلة الأسبوع:
هياكل البيانات والخوارزميات (DSA27) · الأسبوع 1
Why this course · Python basics (Lecture 01, Lab 01)
هذه اختبارات للتدريب الذاتي، تُحفظ إجاباتك على هذا الجهاز فقط ولا تُرسل إلى أحد. الأسئلة والشرح بالإنجليزية لغة المقرر.
-
"Every general-purpose programming language is Turing-complete." What does that tell you?
Turing-completeness is about what can be computed: the same set of problems. It says nothing about speed (a), is not the same claim as "only the syntax differs" (c) — languages differ in cost to write, read and run — and programs are certainly not portable between languages (d).
-
Python's type system is best described as:
Dynamic: types are checked at run time and a name can be rebound to a different type. Strong: Python refuses to mix incompatible types silently (see M03). "Static" (a, b) describes C, Java, Rust; "weak" (b, c) describes C's implicit conversions or JavaScript's
"3" + 5. -
What does
"3" + 5do in Python?TypeError: can only concatenate str (not "int") to str."35"(a) is JavaScript's answer — weak typing.8(b) would need an implicit conversion Python refuses to make. It is valid syntax, so not (d). -
How does Rust manage memory?
Ownership and borrowing are checked at compile time. Manual
free(a) is C/C++; a garbage collector (b) is Python, Java, Go; (d) describes no mainstream language. -
Where and why was C created?
Ritchie, Bell Labs, early 1970s, grown out of Thompson's B, in order to write Unix (rewritten in C in 1973). Stroustrup (b) created C++; Knuth (c) created TeX; van Rossum (d) created Python.
-
An Abstract Data Type specifies:
The ADT is the contract. Memory layout (a) is exactly what it leaves out — that belongs to the data structure. The language (b) and class hierarchy (c) are implementation choices.
-
Which of these is the declarative (comprehension) style from Lecture 01?
A generator expression inside
sumstates the result wanted. (a) and (d) are procedural — steps and state; (c) is functional — composingmapandfilter. -
What does the TIOBE index actually count?
TIOBE counts search-engine hits. It measures how much people write about a language, not quality (b); GitHub activity is Octoverse (c); self-reported usage is the Stack Overflow survey (d).
-
In the course's three levels of knowledge, which is know-why?
Know-what is (a) and (d) — recall. Know-how is (b) — building it. Know-why is choosing and justifying by cost, which is what the exam weighs.
-
To pass this course, a student needs:
Both thresholds, from the bylaws: ≥ 60% overall and ≥ 30% of the final. (c) is the common misreading — a strong coursework mark cannot rescue a final below 30%. And attendance below 75% bars you from the final entirely.
-
What is
-7 // 2?//is floor division: it rounds down. −3.5 rounded down is −4.-3(a) is rounding towards zero, which is C's behaviour;-3.5(b) is what/gives. -
What is
-7 % 3?Python keeps
a == (a // b) * b + a % b. Here-7 // 3is −3, and −3 × 3 + 2 = −7, so the remainder is 2. With a positive divisor,%is never negative in Python. -
What is
2 ** 3 ** 2?**groups right to left:2 ** (3 ** 2)= 2⁹ = 512.64(a) is(2 ** 3) ** 2. -
What is
type(8 / 4)?/always returns afloat, even when the division is exact:8 / 4is2.0. Use//for an integer result. -
With
word = "Python", what isword[1:4]?Indices 1, 2, 3 — up to but not including 4:
"yth"."ytho"(b) includes index 4. -
What is
"Mansoura"[::-2]?Step −2 from the end: indices 7, 5, 3, 1 →
a,u,s,a."aruosnaM"(b) is[::-1];"Mnor"(c) is[::2]. -
After
a = [1, 2, 3],b = a,b.append(4), what isa?b = acopies nothing: both names refer to the same list, so appending throughbchanges whatasees. -
After
a = [1, 2]andc = a[:], what arec is aandc == a?a[:]makes a new list with equal contents: a different object (isisFalse) with the same values (==isTrue). -
grid = [[0] * 2] * 2, thengrid[0][0] = 1. What isgrid?[[0] * 2] * 2puts two references to one inner list into the outer list. Changing it throughgrid[0]shows throughgrid[1]. The correct construction is[[0] * 2 for _ in range(2)]. -
What is
round(2.5) + round(3.5)?Python rounds exact halves to the nearest even number:
round(2.5)is 2 andround(3.5)is 4 — total 6. -
Why is
0.1 + 0.2 == 0.3Falsein Python?A float is a binary fraction; 0.1 has no exact binary representation, so
0.1 + 0.2is0.30000000000000004. Not a bug (a) — every language with IEEE floats does this. Compare floats with a tolerance. -
What happens when you run
s = "abc"thens[0] = "z"?Strings are immutable. (c) is how you should do it —
s = "z" + s[1:]— but item assignment itself is refused. -
A function's body is
print(width * height)and nothing else. What doesx = area(3, 4)store inx?A function with no
returnreturnsNone. The12appears on the screen, but it is not returned. Tests see only what is returned. -
What does
int("4.5")do?int()of a string accepts only an integer literal. Useint(float("4.5"))if truncation is really what you want. -
In C, reading
a[10]from a 5-element array returns whatever happens to be in memory; in Python,a[10]on a 5-element list raisesIndexError. Which explanation matches Lecture 01?"A portable assembler; trust the programmer" is C's founding decision. A bounds check costs time on every access, so C leaves it out. It is not a bug (a). Python is not compiled to machine code (b); it checks because its designers preferred a loud failure to silent corruption.
-
What does Python print for
2 ** 64 + 1?A Python
intgrows as large as memory allows, so the answer is exact. Wrapping round (b) is what a fixed-size C integer does.OverflowError(c) is raised by some float operations, not byintarithmetic, and (d) would need a float in the expression. -
Why do the course's exercises never call
input()?tests/calls each function with arguments and checks what it returns, and a test cannot type at a keyboard.input()exists in Python 3 (c) and returns a string (b), never anint. -
What is
f'{7:03d}|{3.14159:.2f}'?:03dmeans an integer, at least 3 wide, padded with zeros:007.:.2fmeans two digits after the point:3.14. (a) ignores the format, and (d) has the wrong precision. -
What does this print?
a = [1, 2, 3] b = a a = a + [4] b.append(5) print(a, b)b = amakes two names for one list. Thena = a + [4]builds a new list and rebinds onlya.bstill names the old list, sob.append(5)changes only that one. (b) and (c) assume that+changes the list in place;appenddoes,+does not. -
xs = [42, "hello", 3.14]holds anint, astrand afloatin one list. Why is that possible?The list holds references, as the ladder in Lecture 01 shows, so the objects themselves can be of any type. Nothing is converted (a), and Python lists declare no element type (b).
-
Lecture 01 lists three properties we care about in an algorithm. In the lecture's order, they are:
Correctness first, because a fast wrong answer is worthless; then time, then space. (a) puts speed before correctness, which is exactly the habit the lecture warns against.
-
You time linear and binary search on a sorted list of 20 items, and linear search is faster. Does this contradict "binary search is O(log n), linear search is O(n)"?
Big-O describes growth and throws constant factors away. Binary search does more work per step, so at small n linear search can win: the crossover point that a measurement shows. The measurement is not wrong (b), and binary search is O(log n) at every size (c).
-
An O(n2) program takes 2 seconds on today's data. The data grows ten times larger. About how long will it take now?
O(n2): ten times the data means 102 = 100 times the work, so about 200 seconds. (a) is what an O(n) program would do.
-
TIOBE ranked Visual Basic above Rust in September 2026. What does Lecture 01 conclude from rankings like this?
TIOBE counts search results, a proxy for how much people write about a language. The lecture keeps two uses for rankings, trends over years and "is it still alive?", so (d) goes too far, and neither (a) nor (c) follows from a search count.
-
What is
'a,b,,c'.split(',')?Splitting on an exact separator keeps the empty string between two commas that are next to each other. It is
split()with no argument that splits on runs of whitespace and drops empty pieces, which is where (b) comes from. -
A shop stores prices in pounds as
floatvalues and adds them up. Why does Lab 01 say not to, and what should it do instead?Most decimal fractions are not exact in binary (
0.1 + 0.1 + 0.1 == 0.3isFalse), and the errors add up over many sums. Store the smallest unit as anint, which is exact. Floats can be negative (b) and go far above a million (c). -
What do
'banana'.find('z')and'banana'.index('z')do?findreturns-1when the substring is absent;indexraisesValueError(substring not found). Neither returnsNone(d), and the error is aValueError, not anIndexError. -
Lecture 01 calls Python's built-in
list,dict,sortedandheapq"the honest case against Python — for us". Why are they a problem in this course?The course studies how structures work and what they cost. Calling the built-in that does it for you hides both, which is why the course re-implements them and, from Lecture 02, forbids
list,dictandsetas storage insidedsa/. The built-ins are usually faster than student code, because they run in C, so (b) is the wrong way round. -
Which pairing of designer, language and decision is correct?
Stroustrup's rule for C++ was that it should leave no gap below it. "Readability" is van Rossum's Python (a), "fewer features" is Go, by Pike, Thompson and Griesemer (b), and "trust the programmer" is Ritchie's C (d).
-
Lecture 01 says you cannot write badly-indented Python. Why?
In Python the indentation is the block structure, so there is no separate layout that could be bad while the code stays the same. Nothing re-indents your code (a, c), and the indentation is not ignored (b).
-
What does this print?
def min_max(a, b): if a < b: return a, b return b, a result = min_max(9, 2) print(type(result).__name__, result[0])return a, breturns one value, a tuple. Here9 < 2is false, so the secondreturngives(2, 9), andresult[0]is2. (c) takes the order of the arguments instead of the order returned. -
What does this print?
grid = [[0, 0], [0, 0]] copy = grid[:] copy[0][0] = 9 copy[1] = [7, 7] print(grid)grid[:]is a shallow copy: a new outer list holding the same inner lists.copy[0][0] = 9changes an inner list that both share, sogridsees it.copy[1] = [7, 7]rebinds a slot of the new outer list only, sogriddoes not see it, which rules out (c). (a) assumes a deep copy.
36 درجات
أسئلة المقال
10 أسئلة مقالية (36 درجة). اكتب إجابتك أولًا، ثم اعرض الإجابة النموذجية ونقاط التصحيح، وقدّر درجتك بأمانة: كل نقطة تساوي درجة تقريبًا.
مجموع درجات المقال: 0 / 36
-
"All programming languages are the same; only the syntax differs." Explain what is true in this statement and what is wrong with it. Give one concrete example of a design decision that makes two languages genuinely different.
الإجابة النموذجية ونقاط التصحيح
- True part: general-purpose languages are Turing-complete, so they can all compute the same set of functions.
- What is wrong: equivalence of what can be computed says nothing about the cost — to write, to read and maintain, to run — nor about which mistakes the language lets survive into production.
- A language is a set of design decisions with authors and reasons (language → design → philosophy).
- Example, any one well explained: C trusts the programmer and does no bounds checking, so
a[10]on a 5-element array silently corrupts memory, while Python raisesIndexError; or Python is strongly typed ("3" + 5is an error) while JavaScript is weak ("35"); or Rust's ownership versus C's manualfree.
-
Explain the two independent axes of type systems. Place Python and JavaScript on both axes, and show with one expression how their behaviour differs.
الإجابة النموذجية ونقاط التصحيح
- Static vs dynamic is when types are checked — at compile time, or at run time.
- Strong vs weak is how strictly types are kept apart — refusing, or silently converting.
- Python is dynamic and strong; JavaScript is dynamic and weak.
"3" + 5: Python raisesTypeError; JavaScript returns"35". Neither is a bug — they are different decisions about loud failure versus convenient conversion.
-
Describe the three approaches to memory management from Lecture 01, naming one language that uses each. Which one does Python use, and why does that make data structures harder to see in Python?
الإجابة النموذجية ونقاط التصحيح
- Manual (C, C++): the programmer allocates and frees — fast, and the source of many security bugs. Garbage collected (Python, Java, Go): the runtime frees unreachable objects — safe, less control. Ownership (Rust): the compiler proves each allocation is freed exactly once — safe and fast, harder to satisfy.
- Python uses garbage collection (reference counting plus a cycle collector).
- Consequence: removing a node from a linked list is just "stop referring to it" — no
free, no visible pointer — so the structure is invisible unless you use the debugger to watch references change.
-
Distinguish an Abstract Data Type from a data structure. Illustrate with the Stack ADT and two different structures that implement it.
الإجابة النموذجية ونقاط التصحيح
- ADT: the contract — operations, their meaning, their cost — with nothing about storage.
- Data structure: a concrete arrangement of data in memory that fulfils the contract.
- Stack ADT:
pushadds,popremoves the most recent,peeklooks; all O(1). - Two structures: a dynamic array with the top at the end; a linked list with the top at the head. Both honest stacks; they differ in memory overhead, cache behaviour and whether one operation can occasionally be slow. Choosing between them is the engineering.
-
Give two reasons the course uses Python, and the honest drawback of Python for this course. How does the course deal with that drawback?
الإجابة النموذجية ونقاط التصحيح
- For, any two: the field (research, data, AI/ML) runs on Python; it binds to fast C/C++/CUDA underneath; it reads close to pseudocode, so the algorithm survives onto the page; students meet it again in every program.
- Against: Python already has the structures as built-ins —
list,dict,deque,sorted,heapq— which hides exactly what the course studies. - Remedy: the course reimplements them, and (from Lecture 02) structures may store data only in the course
Array, in nodes, or in structures students built — never inlist,dictorset.
-
"In Python a variable is not a box holding a value; it is a name bound to an object." Explain this with a short code example and a diagram, and state one consequence for lists.
الإجابة النموذجية ونقاط التصحيح
a = [1, 2, 3]creates a list object and binds the nameato it;b = abinds a second name to the same object — no copy.- Diagram: two names,
aandb, with arrows to one list object. - Consequence:
b.append(4)changes whatashows. To get an independent list, copy it:a[:],a.copy()orlist(a)— and that copy is shallow.
-
"Measure, do not assert." Explain why the course asks you to measure an algorithm's cost, what a measurement shows that a Big-O table does not, and one way a measurement can mislead you, with how to avoid it.
الإجابة النموذجية ونقاط التصحيح
- Why measure: a claim about cost is a hypothesis. Timing the code over growing n and plotting it against reference curves checks the claim instead of arguing about it (
viz.complexity.measureandplot_growth). - What it shows that Big-O does not: the constant factors, and so the crossover point. Linear search can beat binary search at small n, because binary search does more work per step, even though it wins at scale.
- How it can mislead: one run is noisy, a small n hides the growth, and one machine is not every machine.
- Avoiding it: time many sizes over a wide range, repeat the runs and take the best or the average, and judge the shape (the slope on a log–log plot), not one number.
- Why measure: a claim about cost is a hypothesis. Timing the code over growing n and plotting it against reference curves checks the claim instead of arguing about it (
-
"
printis notreturn." Explain the difference with a two-line function, say what a test sees in each case, and explain why the exercises use parameters andreturnrather thaninput()andprint().الإجابة النموذجية ونقاط التصحيح
def f(x): print(x * 2)shows the value on the screen and returnsNone;def g(x): return x * 2hands the value back to the caller.- A test sees only what is returned:
assert f(3) == 6fails, becausef(3)isNone, although "6" appeared on the screen. - Exercises take parameters and return results because a test can call them with any input and check the output automatically. A function that calls
input()waits for a keyboard that a test does not have, andprint()gives the test nothing to check.
-
"Which language is best?" is not a question. Rewrite it as the real questions it hides, and explain why the ecosystem of a language matters more than its syntax, naming at least three parts of an ecosystem.
الإجابة النموذجية ونقاط التصحيح
- The real questions: best for what task (firmware, a web service, data analysis…), for whom (one learner, or a large team for ten years), by which measure (speed to write, speed to run, safety, hiring), and when (this project, or one maintained until 2035).
- Change any one of them and the answer changes, so "best" alone has no answer.
- Ecosystem, any three: libraries, tooling (debugger, profiler, package manager, test runner), community (answers already written), interoperability (calling fast code written in another language), longevity.
- Why it beats syntax: you stop noticing syntax after two weeks, but you work inside the ecosystem for years. Whether someone has already solved your problem, well, matters more than how a loop is spelt.
-
Compare Python's
intandfloatwith C'sint: what happens when a value gets very large, what that costs, and why0.1 + 0.2 == 0.3isFalse. State the two rules Lab 01 gives for working with floats.الإجابة النموذجية ونقاط التصحيح
- C
inthas a fixed size (usually 32 bits) and silently wraps round when it overflows: 231 - 1 plus 1 becomes -231. - Python
intgrows as large as memory allows, so2 ** 100is exact. The cost is that arithmetic on huge integers is not O(1): it takes longer as the number of digits grows. - A
floatis a 64-bit binary fraction. 0.1, 0.2 and 0.3 have no exact binary form, so0.1 + 0.2is0.30000000000000004. This is not a bug; C, Java and JavaScript do the same. - Rules: never compare floats with
==after arithmetic (round them, or testabs(x - y) < 1e-9), and never store money as a float (store piasters as anint).
- C