PythonPython · Chapterبەش 9 · Lectureوانە 9.7

Processing Two-Dimensional Listsکارکردن لەسەر لیستە دووڕەهەندەکان

Working with tables: the total of all values, totals row by row and column by column (and the slide's misplaced print), the row with the largest sum, sorting rows lexicographically or by a computed key, and passing tables to and from functions — with the shared-rows trap of shallow copies.

کارکردن لەگەڵ خشتە: کۆی هەموو ، کۆ بە و بە (و printـە هەڵە دانراوەکەی سلایدەکە)، ئەو گەورەترین کۆی هەیە، بە یان بەپێی کلیلێکی حیسابکراو و ناردن و گەڕاندنەوەی خشتە بۆ و لێیانەوە — لەگەڵ داوی هاوبەشەکانی .

12 min read11 خولەک خوێندنەوە · 10 stepsهەنگاو

What you will learnچی فێر دەبیت

  • Add up a whole table, each row and each column with nested loops, putting the accumulator and the print in the right place.
  • Find the row with the largest sum and report its index.
  • Explain how sort() orders rows, and rank rows by a computed total with key=.
  • Write functions that read, return and process tables, and protect a table with a deep copy.
  • بە هەموو خشتەکە، هەر و هەر کۆ بکەیتەوە و و print لە شوێنی دروستدا دابنێیت.
  • ئەو بدۆزیتەوە کە گەورەترین کۆی هەیە و ڕابگەیەنیت.
  • ڕوون بکەیتەوە sort() چۆن ڕیز دەکات و بە key= بەپێی کۆیەکی حیسابکراو ڕیز بکەیت.
  • بنووسیت کە خشتە دەخوێننەوە، دەیگەڕێننەوە و کاری لەسەر دەکەن و خشتەیەک بە بپارێزیت.

Adding up the whole tableکۆکردنەوەی هەموو خشتەکە

Processing a table almost always means visiting its values with two loops. The simplest job is the total of every value: start an accumulator total at 0, and let the inner loop add each value of each row to it.

کارکردن لەسەر خشتە نزیکەی هەمیشە واتە سەردانی بە دوو . سادەترین کار کۆی هەموو : بە ناوی total لە 0ـەوە دەست پێ بکە و با هەر هەر بۆی زیاد بکات.

The total of a matrixکۆی گشتیی ماتریکسێکtotal.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]    # assume a list is given
total = 0
for row in matrix:
    for value in row:
        total += value
print("Total is", total)                     # print the total
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

The accumulator starts at 0, before both loops.

پێش هەردوو لە 0ـەوە دەست پێ دەکات.

Lineدێڕی 4

On the slide this inner for line is indented by only one space. Python accepts it, but PEP 8 asks for 4 spaces at every level.

لە سلایدەکەدا ئەم دێڕەی forـی ناوەوە تەنها بە یەک بۆشایی چووەتە ناوەوە. وەریدەگرێت، بەڵام ⁦PEP 8⁩ بۆ هەموو ئاستێک 4 بۆشایی دەخوازێت.

The inner loop can also be replaced by sum(row), which adds one whole row. Here is the same idea on the marks table from the previous lesson:

دەکرێت بە sum(row)ـیش جێگە بگیرێتەوە، کە تەواو کۆ دەکاتەوە. ئەمە هەمان بیرۆکەیە لەسەر خشتەی نمرەکانی وانەی پێشوو:

total_marks.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [
    [85, 72, 90, 64],    # Aram:   Programming, Maths, English, Logic
    [78, 95, 70, 88],    # Shilan
    [92, 60, 81, 75],    # Karwan
    [66, 84, 77, 93],    # Dilan
]

total = 0
for row in marks:
    total += sum(row)          # sum() adds one whole row at a time
print("All marks together:", total)
print("Average mark:", total / (len(marks) * len(marks[0])))
Quick checkپشکنینی خێراWhere must total = 0 be for a grand total of the whole table?بۆ کۆی گشتیی هەموو خشتەکە، total = 0 دەبێت لە کوێ بێت؟

Row by row: one total for each rowڕیز بە ڕیز: بۆ هەر ڕیزێک کۆیەک

Often you need a result per row — each student's total, each shop's weekly sales. Then the total must start again for every row: either with sum(row), or with total = 0 placed inside the outer loop, before the inner one.

زۆرجار ئەنجامێکت بۆ هەر پێویستە — کۆی هەر خوێندکارێک، فرۆشی هەفتانەی هەر دوکانێک. ئەوکات کۆکە دەبێت بۆ هەر لە سەرەتاوە دەست پێ بکاتەوە: یان بە sum(row)، یان بە total = 0 کە لە ناو و پێش دادەنرێت.

The sum of each rowکۆی هەر ڕیزێکrow_sums.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in range(len(matrix)):
    print("Sum for row", row, "is", sum(matrix[row]))
Each student's total and averageکۆ و تێکڕای هەر خوێندکارێکstudent_totals.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [
    [85, 72, 90, 64],    # Aram:   Programming, Maths, English, Logic
    [78, 95, 70, 88],    # Shilan
    [92, 60, 81, 75],    # Karwan
    [66, 84, 77, 93],    # Dilan
]
names = ["Aram", "Shilan", "Karwan", "Dilan"]

for i in range(len(marks)):
    total = sum(marks[i])
    average = total / len(marks[i])
    print(f"{names[i]:7} total {total}  average {average:.2f}")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 12

:.2f prints the average with two decimal places.

:.2f تێکڕاکە بە دوو ژمارە دوای خاڵ چاپ دەکات.

Quick checkپشکنینی خێراWhich student has the largest total?کام خوێندکار گەورەترین کۆی هەیە؟

Column by columnستوون بە ستوون

A column is not stored as one list — its values are spread over all the rows. So for a column total the loops swap roles: the outer loop walks the columns, and the inner loop goes down the rows, adding matrix[row][column]. The total starts at 0 again for every column.

وەک یەک هەڵناگیرێت — بەسەر هەموو بڵاو بوونەتەوە. بۆیە بۆ کۆی ڕۆڵ دەگۆڕنەوە: بەسەر دەڕوات و بە دادەبەزێت و matrix[row][column] زیاد دەکات. کۆکە بۆ هەر دووبارە لە 0ـەوە دەست پێ دەکات.

The slide's versionوەشانی سلایدەکەcolumn_sums_slide.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]    # assume a list is given
for column in range(len(matrix[0])):
    total = 0
    for row in range(len(matrix)):
        total += matrix[row][column]
print("Sum for last column is", total)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

This print is outside the column loop, so it runs once, after the last column.

ئەم printـە لە دەرەوەی ، بۆیە یەکجار جێبەجێ دەبێت، دوای دوایین .

Animation on the 3 × 3 matrix 1 to 9. Row by row: row 0 lights up and its sum 6 appears at the right, then row 1 with 15, then row 2 with 24. Column by column: column 0 lights up and 12 appears below it (1 + 4 + 7), then column 1 with 15, then column 2 with 18. At the end both the row sums and the column sums add up to the same total, 45.
Animation on the 3 × 3 matrix 1 to 9. Row by row: row 0 lights up and its sum 6 appears at the right, then row 1 with 15, then row 2 with 24. Column by column: column 0 lights up and 12 appears below it (1 + 4 + 7), then column 1 with 15, then column 2 with 18. At the end both the row sums and the column sums add up to the same total, 45.
Row sums go to the right, column sums go below; both add up to 45.کۆی دەچێتە لای ڕاست و کۆی دەچێتە خوارەوە؛ هەردووکیان دەبنە ⁦45⁩.CêIT
Total and average of each subjectکۆ و تێکڕای هەر وانەیەکsubject_totals.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [
    [85, 72, 90, 64],    # Aram:   Programming, Maths, English, Logic
    [78, 95, 70, 88],    # Shilan
    [92, 60, 81, 75],    # Karwan
    [66, 84, 77, 93],    # Dilan
]
subjects = ["Programming", "Maths", "English", "Logic"]

for column in range(len(subjects)):
    total = 0
    for row in range(len(marks)):
        total += marks[row][column]
    print(f"{subjects[column]:12} total {total}  average {total / len(marks):.2f}")
Quick checkپشکنینی خێراIn the column loop, what does matrix[row][column] visit while column is 2?لە ، کاتێک column 2ـە، matrix[row][column] سەردانی چی دەکات؟

The row with the largest sumئەو ڕیزەی گەورەترین کۆی هەیە

This combines two ideas you know: the row sum and the "largest so far" scan. Keep the largest sum in maxRow and its row number in indexOfMaxRow. Start with row 0, then compare every other row's sum and update both variables when a bigger one appears.

ئەمە دوو بیرۆکەی ناسراو پێکەوە دەبەستێت: کۆی و گەڕانی «گەورەترین تا ئێستا». گەورەترین کۆ لە maxRowـدا و ژمارەی لە indexOfMaxRowـدا ڕابگرە. بە 0 دەست پێ بکە، پاشان کۆی هەموو تر بەراورد بکە و کاتێک کۆیەکی گەورەتر دەرکەوت هەردوو نوێ بکەرەوە.

The slide's programبەرنامەکەی سلایدەکەmax_row.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]    # assume a list is given
maxRow = sum(matrix[0])          # get sum of the first row in maxRow
indexOfMaxRow = 0

for row in range(1, len(matrix)):
    if sum(matrix[row]) > maxRow:
        maxRow = sum(matrix[row])
        indexOfMaxRow = row

print("Row with the index ", indexOfMaxRow, "has the maximum sum of", maxRow)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2-3

Both variables start with row 0, so they always exist — unlike the min_position bug of the sorting lesson.

هەردوو بە 0 دەست پێ دەکەن، بۆیە هەمیشە بوونیان هەیە — بە پێچەوانەی هەڵەی min_positionـی وانەی .

Lineدێڕی 5

The loop starts at row 1: row 0 is already the "best so far".

لە 1ـەوە دەست پێ دەکات: 0 پێشتر «باشترین تا ئێستا»یە.

The same scan finds the best student in the marks table. (In new code use snake_case names such as best_total, as PEP 8 suggests.) The last two lines show a shortcut from sorting with key=: max(marks, key=sum) returns the row with the largest sum.

هەمان گەڕان باشترین خوێندکار لە خشتەی نمرەکاندا دەدۆزێتەوە. (لە کۆدی نوێدا ناوی snake_case وەک best_total بەکار بهێنە، وەک ⁦PEP 8⁩ پێشنیاری دەکات.) دوو دێڕی کۆتایی ڕێگەیەکی کورت لە ڕیزکردن بە key= پیشان دەدەن: max(marks, key=sum) ئەو دەگەڕێنێتەوە کە گەورەترین کۆی هەیە.

The best studentباشترین خوێندکارbest_student.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [
    [85, 72, 90, 64],    # Aram:   Programming, Maths, English, Logic
    [78, 95, 70, 88],    # Shilan
    [92, 60, 81, 75],    # Karwan
    [66, 84, 77, 93],    # Dilan
]
names = ["Aram", "Shilan", "Karwan", "Dilan"]

best_total = sum(marks[0])
best_index = 0
for row in range(1, len(marks)):
    row_total = sum(marks[row])
    if row_total > best_total:
        best_total = row_total
        best_index = row
print("Best student:", names[best_index], "with", best_total)

# the same with max() and key= (see the sorting lesson)
best_row = max(marks, key=sum)
print(best_row, "is row", marks.index(best_row))
Quick checkپشکنینی خێراIf two rows had the same largest sum, which index would the slide's program report?ئەگەر دوو هەمان گەورەترین کۆیان هەبوایە، سلایدەکە کام ڕادەگەیەنێت؟

Sorting the rows of a tableڕیزکردنی ڕیزەکانی خشتەیەک

sort() works on a two-dimensional list too. It compares whole rows the way a dictionary compares words: first by their first elements; when those are equal, by the second elements; when those are equal too, by the third, and so on. This is called lexicographic order — the same rule that < and > use on two lists (< and >: dictionary order for lists).

sort() لەسەر کار دەکات. تەواو بەو شێوەیە بەراورد دەکات کە فەرهەنگ وشەکان بەراورد دەکات: سەرەتا بەپێی یەکەم ؛ کاتێک ئەوانە یەکسان بن، بەپێی دووەمەکان؛ کاتێک ئەوانیش یەکسان بن، بەپێی سێیەمەکان و بەم شێوەیە. بەمە دەوترێت — هەمان یاسا کە < و > لەسەر دوو بەکاری دەهێنن (< و >: ڕیزبەندیی فەرهەنگی بۆ لیستەکان).

Sorting pointsڕیزکردنی خاڵەکانsort_points.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
points = [[4, 2], [1, 7], [4, 5], [1, 2], [1, 1], [4, 1]]
points.sort()
print(points)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

[1, 7], [1, 2] and [1, 1] share the first element 1, so the second element decides their order: 1, 2, 7.

[1, 7]، [1, 2] و [1, 1] هەمان یەکەم 1ـیان هەیە، بۆیە دووەم ڕیزبەندییان دیاری دەکات: 1، 2، 7.

To rank students by their total, the normal order is not enough — it would sort by name. Give sort a key function that computes the total of a row, and reverse=True for the largest first. Keeping the name inside each row means it moves together with the marks.

بۆ خوێندکاران بەپێی کۆیان، ڕیزبەندییە ئاساییەکە بەس نییە — بەپێی ناو ڕیز دەکات. key بدە بە sort کە کۆی حیساب بکات و reverse=True بۆ ئەوەی گەورەترین یەکەم بێت. هێشتنەوەی ناوەکە لە ناو هەر وا دەکات لەگەڵ نمرەکاندا بجووڵێت.

A ranking by totalڕیزبەندی بەپێی کۆranking.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
students = [
    ["Aram", 85, 72, 90, 64],
    ["Shilan", 78, 95, 70, 88],
    ["Karwan", 92, 60, 81, 75],
    ["Dilan", 66, 84, 77, 93],
]

def total(row):
    return sum(row[1:])          # skip the name in position 0

students.sort(key=total, reverse=True)
for place, row in enumerate(students, start=1):
    print(place, row[0], total(row))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 8-9

row[1:] is a slice without the name, so sum only adds the marks.

row[1:] بە بەبێ ناوەکە دەدات، بۆیە sum تەنها نمرەکان کۆ دەکاتەوە.

Lineدێڕی 12

enumerate(…, start=1) numbers the places from 1.

enumerate(…, start=1) پلەکان لە 1ـەوە ژمارە دەکات.

Quick checkپشکنینی خێراWhat does [[2, 9], [2, 1], [1, 5]] look like after .sort()?[[2, 9], [2, 1], [1, 5]] دوای .sort() چۆن دەبێت؟

Passing tables to functionsناردنی خشتە بۆ کردارەکان

A two-dimensional list goes into a function exactly like a one-dimensional one: the function receives a reference to the same table. A function can also build a table and return it. Splitting the work into functions keeps each part short: get_matrix reads a table, accumulate adds it up and main connects them.

ڕێک وەک یەکڕەهەند دەچێتە ناو : بۆ هەمان خشتە وەردەگرێت. دەتوانێت خشتەیەکیش دروست بکات و بیگەڕێنێتەوە. دابەشکردنی کارەکە بۆ چەند هەر بەشێک کورت دەهێڵێتەوە: get_matrix خشتەیەک دەخوێنێتەوە، accumulate کۆی دەکاتەوە و main پێکیانەوە دەبەستێت.

Reading and adding up a table with functionsخوێندنەوە و کۆکردنەوەی خشتە بە کردارەکانmatrix_functions.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def get_matrix():
    matrix = []                                  # create an empty list
    number_of_rows = int(input("Enter the number of rows: "))
    number_of_columns = int(input("Enter the number of columns: "))
    for row in range(number_of_rows):
        matrix.append([])                        # add an empty new row
        for column in range(number_of_columns):
            value = int(input("Enter a value and press Enter: "))
            matrix[row].append(value)
    return matrix

def accumulate(m):
    total = 0
    for row in m:
        total += sum(row)
    return total

def main():
    m = get_matrix()                             # get a list
    print(m)
    print("\nSum of all elements is", accumulate(m))    # display the sum

main()                                           # invoke main function
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 10

The function returns the table it built; main keeps it in m.

ئەو خشتەیەی دروستی کرد دەگەڕێنێتەوە؛ main لە mـدا هەڵیدەگرێت.

Lineدێڕی 12

accumulate receives a reference to the same table and only reads it.

accumulate بۆ هەمان خشتە وەردەگرێت و تەنها دەیخوێنێتەوە.

Lineدێڕی 21

\n at the start prints an empty line first.

\n لە سەرەتادا یەکەمجار دێڕێکی بەتاڵ چاپ دەکات.

Quick checkپشکنینی خێراWhy can accumulate(m) see the values that get_matrix() read?بۆچی accumulate(m) ئەو دەبینێت کە get_matrix() خوێندنییەوە؟

Passing tables to functionsناردنی خشتە بۆ کردارەکان

Functions can change the caller's tableکردارەکان دەتوانن خشتەی بانگکەرەکە بگۆڕن

Because a function gets a reference, it can change the caller's table — sometimes that is the plan (adding a bonus to everyone), sometimes it is a surprise. If you need to keep the old table, a shallow copy is not enough: copy() makes a new outer list, but the rows inside are still shared. Use copy.deepcopy() (or copy each row).

لەبەر ئەوەی وەردەگرێت، دەتوانێت خشتەی بگۆڕێت — هەندێک جار ئەمە مەبەستە (زیادکردنی نمرەی زیادە بۆ هەمووان)، هەندێک جار سەرسوڕهێنەرە. ئەگەر دەتەوێت خشتە کۆنەکە بپارێزیت، بەس نییە: copy() نوێ دروست دەکات، بەڵام ناوەوە هێشتا هاوبەشن. copy.deepcopy() بەکار بهێنە (یان هەر کۆپی بکە).

A shallow copy does not protect a tableکۆپیی ڕووکەش خشتە ناپارێزێتshared_rows.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import copy

def add_bonus(table, bonus):
    for row in table:
        for i in range(len(row)):
            row[i] += bonus           # changes the caller's rows

marks = [[85, 72], [78, 95]]
add_bonus(marks, 5)
print(marks)                          # changed by the function

backup = marks.copy()                 # shallow: shares the rows
safe = copy.deepcopy(marks)           # deep: its own rows
add_bonus(marks, 1)
print(backup)                         # changed too!
print(safe)                           # unchanged
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

row is one of the caller's rows, so row[i] += bonus changes the caller's table.

row یەکێکە لە ، بۆیە row[i] += bonus خشتەی دەگۆڕێت.

Lineدێڕی 12

backup has its own outer list, but its rows are marks's rows.

backup خۆی هەیە، بەڵام هەمان marksـن.

The full story of references, shallow and deep copies is in Lists, references and copies.

هەموو چیرۆکی ، و لە لیستەکان، ئاماژەکان و کۆپیـدایە.

Quick checkپشکنینی خێراAfter backup = marks.copy() and marks[0][0] = 0, what is backup[0][0]?دوای backup = marks.copy() و marks[0][0] = 0، backup[0][0] چییە؟

Your Lists Are Being Copied WRONG In Python (Shallow Copy VS. Deep Copy)Indently · Englishئینگلیزی · 28K viewsبینین · 1.2K likesلایک · Partبەشی 1:31–6:44 (ofلە 6:44)

Why b = a gives one list two names, why copy() still shares the inner lists, and how copy.deepcopy() fixes it.

بۆچی b = a دوو ناو دەداتە یەک ، بۆچی copy() هێشتا ناوەوە هاوبەش دەکات و چۆن copy.deepcopy() چاکی دەکاتەوە.

Watch from 1:31: copy() of a list of lists still shares the rows; deepcopy() makes new rows.

لە ⁦1:31⁩ بەدواوە سەیر بکە: copy() بۆ هێشتا هاوبەش دەهێڵێتەوە؛ deepcopy() نوێ دروست دەکات.

Common mistakesهەڵە باوەکان

Processing tables: mistakes to avoidکارکردن لەسەر خشتە: ئەو هەڵانەی دەبێت لێیان دوور بیت
MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
total = 0 before the loops when you want one total per row/columntotal = 0 پێش کاتێک بۆ هەر / کۆیەکت دەوێتthe totals run on into each otherکۆکان تێکەڵی یەکتر دەبنreset total = 0 inside the outer looptotal = 0 لە ناو دووبارە دابنێ
print after both loopsprint دوای هەردوو only the last column's total is shownتەنها کۆی دوایین پیشان دەدرێتprint inside the outer loop, after the inner loopلە ناو ، دوای چاپ بکە
matrix[column][row]rows and columns swapped (or IndexError if the table is not square) و گۆڕاونەتەوە (یان IndexError ئەگەر خشتەکە چوارگۆشە نەبێت)matrix[row][column]
range(len(matrix)) for the columnsrange(len(matrix)) بۆ wrong count when the table is not squareژمارەی هەڵە کاتێک خشتەکە چوارگۆشە نییەrange(len(matrix[0]))
sorting rows that start with a name, expecting a ranking by marks ئەو بە ناو دەست پێ دەکەن، بە چاوەڕوانیی ڕیزبەندی بەپێی نمرەrows are sorted by name بەپێی ناو ڕیز دەکرێنsort(key=…) with a function that computes the totalsort(key=…) لەگەڵ کە کۆکە حیساب دەکات
backup = table.copy()the rows are still shared هێشتا هاوبەشنcopy.deepcopy(table)

Exercisesڕاهێنانەکان

Exerciseڕاهێنان1. The hardest subject1. قورسترین وانە

Using the marks table, find the subject with the lowest average.

بە بەکارهێنانی خشتەی نمرەکان، ئەو وانەیە بدۆزەرەوە کە نزمترین تێکڕای هەیە.

Hintئاماژە

Column averages + the "smallest so far" scan.

تێکڕای + گەڕانی «بچووکترین تا ئێستا».

Show answerوەڵامەکە پیشان بدە
ex1_hardest.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [
    [85, 72, 90, 64],    # Aram:   Programming, Maths, English, Logic
    [78, 95, 70, 88],    # Shilan
    [92, 60, 81, 75],    # Karwan
    [66, 84, 77, 93],    # Dilan
]
subjects = ["Programming", "Maths", "English", "Logic"]

lowest_index = 0
lowest_average = sum(row[0] for row in marks) / len(marks)
for column in range(1, len(subjects)):
    average = sum(row[column] for row in marks) / len(marks)
    if average < lowest_average:
        lowest_average = average
        lowest_index = column
print("Hardest subject:", subjects[lowest_index], lowest_average)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 10

sum(row[0] for row in marks) adds column 0 down all rows (a short form of the inner loop).

sum(row[0] for row in marks) 0 بە هەموو کۆ دەکاتەوە (شێوەیەکی کورتی ).

Exerciseڕاهێنان2. Best in one subject2. باشترین لە یەک وانەدا

Find who has the highest Maths mark. The column is fixed (1); scan the rows.

بیدۆزەرەوە کێ بەرزترین نمرەی بیرکاریی هەیە. جێگیرە ⁦(1)⁩؛ بەسەر بگەڕێ.

Show answerوەڵامەکە پیشان بدە
ex2_best_maths.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [
    [85, 72, 90, 64],    # Aram:   Programming, Maths, English, Logic
    [78, 95, 70, 88],    # Shilan
    [92, 60, 81, 75],    # Karwan
    [66, 84, 77, 93],    # Dilan
]
names = ["Aram", "Shilan", "Karwan", "Dilan"]

column = 1                     # Maths
best_row = 0
for row in range(1, len(marks)):
    if marks[row][column] > marks[best_row][column]:
        best_row = row
print("Best in Maths:", names[best_row], marks[best_row][column])
Exerciseڕاهێنان3. The sum of the main diagonal3. کۆی تیرەی سەرەکی

In a square matrix the main diagonal is matrix[0][0], matrix[1][1], matrix[2][2] … Add it up with one loop.

لە بریتییە لە matrix[0][0]، matrix[1][1]، matrix[2][2] … بە یەک کۆی بکەرەوە.

Hintئاماژە

On the diagonal the row index and the column index are equal.

لەسەر و یەکسانن.

Show answerوەڵامەکە پیشان بدە
ex3_diagonal.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
diagonal = 0
for i in range(len(matrix)):
    diagonal += matrix[i][i]
print("Diagonal sum:", diagonal)

Mathematics has a name for this sum: the trace of the matrix. See The trace of a square matrix.

بیرکاری ناوێکی بۆ ئەم کۆیە هەیە: . کۆی تیرەی ماتریکسێکی چوارگۆشەیی ببینە.

Exerciseڕاهێنان4. A week of sales4. فرۆشی هەفتەیەک

Three shops record their sales for five days in sales. Print each shop's weekly total (row sums) and each day's total over all shops (column sums).

سێ دوکان فرۆشی پێنج ڕۆژیان لە salesـدا تۆمار دەکەن. کۆی هەفتانەی هەر دوکانێک (کۆی ) و کۆی هەر ڕۆژێک بۆ هەموو دوکانەکان (کۆی ) چاپ بکە.

Show answerوەڵامەکە پیشان بدە
ex4_sales.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
sales = [            # 3 shops × 5 days (made-up numbers, in thousands of dinars)
    [120, 95, 130, 110, 150],
    [80, 100, 90, 85, 120],
    [140, 135, 160, 150, 170],
]
for shop in range(len(sales)):
    print("Shop", shop + 1, "week total:", sum(sales[shop]))
for day in range(len(sales[0])):
    day_total = 0
    for shop in range(len(sales)):
        day_total += sales[shop][day]
    print("Day", day + 1, "all shops:", day_total)
Exerciseڕاهێنان5. Challenge: count the bombs5. ڕاهێنانی قورستر: بۆمبەکان بژمێرە

In a Minesweeper-style game a 6×66 \times 6 board hides 6 bombs, and every safe cell shows how many of its neighbours (up to 8) are bombs. Store the board as a two-dimensional list (1 = bomb, 0 = safe) and print the board of numbers, with * for a bomb.

لە یارییەکی وەک Minesweeper، تەختەیەکی 6×66 \times 6 شەش بۆمبی تێدا شاراوەتەوە و هەر خانەیەکی سەلامەت پیشان دەدات چەند لە خانە دراوسێکانی (تا 8 خانە) بۆمبن. تەختەکە وەک هەڵبگرە (1 = بۆمب، 0 = سەلامەت) و تەختەی ژمارەکان چاپ بکە، بە * بۆ بۆمب.

Hintئاماژە

The neighbours of the cell in row r, column c lie in rows r - 1 to r + 1 and columns c - 1 to c + 1. Check that a neighbour is inside the board first: grid[-1] does not fail — it is the last row — so it would quietly count the wrong cells.

دراوسێکانی خانەی r و c لە r - 1 تا r + 1 و c - 1 تا c + 1ـدان. سەرەتا بپشکنە کە دراوسێکە لە ناو تەختەکەدایە: grid[-1] هەڵە نادات — دوایین — بۆیە بە بێدەنگی خانەی هەڵە دەژمێرێت.

Show answerوەڵامەکە پیشان بدە
Counting the bombs around every cellژماردنی بۆمبەکانی دەوری هەر خانەیەکex5_bombs.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
grid = [                     # 1 = bomb, 0 = safe (6 bombs)
    [0, 1, 0, 0, 0, 0],
    [0, 0, 0, 1, 0, 0],
    [1, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0],
    [0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 1],
]
size = len(grid)

def bombs_around(r, c):
    count = 0
    for dr in (-1, 0, 1):
        for dc in (-1, 0, 1):
            rr, cc = r + dr, c + dc
            if 0 <= rr < size and 0 <= cc < size:
                count += grid[rr][cc]
    return count

for r in range(size):
    line = []
    for c in range(size):
        if grid[r][c] == 1:
            line.append("*")
        else:
            line.append(str(bombs_around(r, c)))
    print(" ".join(line))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 13-14

Two small loops visit the 3×33 \times 3 block around the cell (the cell itself is 0, so it adds nothing).

دوو بچووک سەردانی ئەو چوارگۆشە 3×33 \times 3ـیە دەکەن کە دەوری خانەکەی داوە (خودی خانەکە 0ـە، بۆیە هیچ زیاد ناکات).

Lineدێڕی 16

Only neighbours inside the board are counted.

تەنها ئەو دراوسێیانە دەژمێردرێن کە لە ناو تەختەکەدان.

0 <= rr < size keeps the search on the board. Without it, a cell in row 0 would look at grid[-1], the bottom row (Which indexes are allowed?). A playable game would also read the player's row and column safely, as in A safe input function.

0 <= rr < size گەڕانەکە لە ناو تەختەکەدا دەهێڵێتەوە. بەبێ ئەو، خانەیەک لە 0 سەیری grid[-1] دەکات، واتە خوارەوە (کام ئیندێکسەکان ڕێگەپێدراون؟). یارییەکی تەواو هەروەها و یاریزانەکە بە سەلامەتی دەخوێنێتەوە، وەک لە کردارێکی نێوخستەی سەلامەت: ⁦get_int()⁩.

Quick checkپشکنینی خێراWhich loop order gives one total per column?کام ڕیزبەندیی بۆ هەر کۆیەک دەدات؟

Summaryپوختە

  • Whole table: one accumulator before both loops (or sum(row) for each row).
  • Per row: reset the total for every row — sum(table[row]).
  • Per column: outer loop over columns, inner loop over rows, table[row][column]; print inside the outer loop.
  • Largest row: start with row 0 as "best so far" and update the sum and the index together.
  • sort() orders rows lexicographically; use key= to sort by a computed value such as a total.
  • Tables are passed to and returned from functions by reference; use copy.deepcopy() to keep an independent copy.
  • هەموو خشتەکە: یەک پێش هەردوو (یان sum(row) بۆ هەر ).
  • بۆ هەر : کۆکە بۆ هەر سفر بکەرەوە — sum(table[row]).
  • بۆ هەر : بەسەر ، بەسەر ، table[row][column]؛ لە ناو چاپ بکە.
  • گەورەترین : بە 0 وەک «باشترین تا ئێستا» دەست پێ بکە و کۆ و پێکەوە نوێ بکەرەوە.
  • sort() بە ڕیز دەکات؛ بۆ بەپێی حیسابکراو وەک کۆ key= بەکار بهێنە.
  • خشتە بە دەنێردرێت بۆ و لێیانەوە دەگەڕێتەوە؛ بۆ کۆپییەکی سەربەخۆ copy.deepcopy() بەکار بهێنە.
Review questionsپرسیارەکانی پێداچوونەوە
Why does the slide's column program print only one line?بۆچی بەرنامەکەی ستوونەکانی سلایدەکە تەنها یەک دێڕ چاپ دەکات؟

Its print is after the column loop, so it runs once, with the last column's total. Indent it into the column loop.

printـەکەی دوای ، بۆیە یەکجار جێبەجێ دەبێت، بە کۆی دوایین . بیبە ناو .

How does [[4, 2], [1, 7], [4, 1]].sort() decide the order?[[4, 2], [1, 7], [4, 1]].sort() چۆن ڕیزبەندییەکە دیاری دەکات؟

By the first elements (1 before 4), and for equal first elements by the second ones: [[1, 7], [4, 1], [4, 2]].

بەپێی یەکەم (⁦1⁩ پێش ⁦4⁩)؛ بۆ یەکەمی یەکسانیش بەپێی دووەمەکان: [[1, 7], [4, 1], [4, 2]].

Lesson complete!وانەکە تەواو بوو!

Well done. Review the key terms, then go on to the next lesson.دەستخۆش. سەیرێکی زاراوە سەرەکییەکان بکەرەوە، پاشان بڕۆ بۆ وانەی داهاتوو.

Key termsزاراوە سەرەکییەکان

Next lessonوانەی داهاتوو

Tuples, Sets and Dictionariesتاپڵەکان، کۆمەڵەکان و فەرهەنگەکان

References and further readingسەرچاوەکان و خوێندنەوەی زیاتر

This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.