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

sum, max, min and Sortingsum، max، min و ڕیزکردن

The built-in functions sum, max and min (and the empty-list trap), averages, finding the smallest and largest with a loop and the min_position bug, sort() versus sorted() with reverse= and key=, how selection sort works, collecting matches, and Lab 3 and Lab 4 tasks on random, even and odd numbers.

sum، max و min (و داوی بەتاڵ)، تێکڕا، دۆزینەوەی بچووکترین و گەورەترین بە و هەڵەی min_position، sort() بەرامبەر sorted() لەگەڵ reverse= و key=، چۆنیەتیی کارکردنی ، کۆکردنەوەی ئەوانەی دەگونجێن و ئەرکەکانی تاقیگەی 3 و 4 لەسەر ، ژمارەی جووت و تاک.

22 min read20 خولەک خوێندنەوە · 21 stepsهەنگاو

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

  • Use sum, max, min and len to get totals, extremes and averages, and handle empty lists.
  • Find the smallest and largest value and their positions with a loop, without the NameError trap.
  • Choose between sort() and sorted(), and use reverse=True and key=.
  • Explain and write selection sort, and say why Python's own sort is preferred in practice.
  • Collect and count the elements that pass a test, with a loop or a list comprehension.
  • sum، max، min و len بەکار بهێنیت بۆ کۆی گشتی، بەرزترین و نزمترین و تێکڕا و بەتاڵ چارەسەر بکەیت.
  • بچووکترین و گەورەترین و شوێنەکانیان بە بدۆزیتەوە، بەبێ کەوتنە داوی NameError.
  • لە نێوان sort() و sorted() هەڵبژێریت و reverse=True و key= بەکار بهێنیت.
  • ڕوون بکەیتەوە و بینووسیت و بڵێیت بۆچی لە ڕاستەقینەدا خودی باشترە.
  • کە لە تاقیکردنەوەیەک دەردەچن کۆ بکەیتەوە و بیانژمێریت، بە یان .

sum, max and minsum، max و min

A list of numbers often needs the same three answers: the total, the largest value and the smallest value. Python has a built-in function for each, so you do not need to write a loop: sum(mylist), max(mylist) and min(mylist).

ژمارە زۆرجار پێویستی بە هەمان سێ وەڵام هەیە: کۆی گشتی، گەورەترین و بچووکترین . بۆ هەریەکەیان هەیە، بۆیە پێویست ناکات بنووسیت: sum(mylist)، max(mylist) و min(mylist).

Total, largest, smallestکۆی گشتی، گەورەترین، بچووکترینsum_max_min.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [2, 5, 1, 8, 9, 2]

total = sum(mylist)
print(" The total = ", total)
print(" The total = ", sum(mylist))    # the same, in one line

maximum = max(mylist)
minimum = min(mylist)
print(" The Maximum number = ", maximum)
print(" The Minimum number = ", minimum)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

sum adds all the items, from left to right, starting at 0.

sum هەموو کۆ دەکاتەوە، لە چەپەوە بۆ ڕاست و لە 0ـەوە دەست پێ دەکات.

Lineدێڕی 5

You can use the result directly, without a variable.

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

Quick checkپشکنینی خێراWhat does max([3, 11, 7]) - min([3, 11, 7]) give?max([3, 11, 7]) - min([3, 11, 7]) چی دەدات؟

sum, max and minsum، max و min

Strings, and empty listsزنجیرەنووسەکان و لیستەکانی بەتاڵ

max and min also work on a list of strings: they compare the words letter by letter, like a dictionary, so "pear" is the largest and "apple" the smallest. (Capital letters come before small letters — see Working with strings.) An empty list is a special case: its sum is 0, but it has no largest or smallest item, so max([]) and min([]) stop the program with a ValueError — unless you give a default= value.

max و min لەسەر لە کار دەکەن: وشەکان پیت بە پیت بەراورد دەکەن، وەک فەرهەنگێکی وشە، بۆیە "pear" گەورەترینە و "apple" بچووکترین. (پیتە گەورەکان پێش پیتە بچووکەکان دێن — کارکردن لەگەڵ زنجیرەنووسەکان ببینە.) بەتاڵ حاڵەتێکی تایبەتە: کۆکەی 0ـە، بەڵام گەورەترین و بچووکترین نییە، بۆیە max([]) و min([]) بە ValueError ڕادەگرن — مەگەر default= بدەیت.

Strings and an empty listزنجیرەنووسەکان و لیستێکی بەتاڵstrings_and_empty.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
fruits = ["pear", "apple", "fig"]
print(max(fruits), min(fruits))

print(sum([]))               # adding nothing gives 0
print(max([], default=0))    # default= is returned for an empty list
print(max([]))               # no default: an error
Quick checkپشکنینی خێراWhich call stops the program with an error?کام بانگکردن بە هەڵەیەک ڕادەگرێت؟

Lab: sum and averageتاقیگە: کۆ و تێکڕا

ExerciseڕاهێنانLab 3, Task 1-1تاقیگەی 3، ئەرکی ⁦1-1⁩

Write a Python program that prints the sum and the average of these numbers: 2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2.

Python بنووسە کە کۆ و تێکڕای ئەم ژمارانە چاپ بکات: ⁦2.7⁩، ⁦32⁩، ⁦768⁩، ⁦89.1⁩، ⁦21⁩، ⁦90.3⁩، ⁦135⁩، ⁦77⁩، ⁦43⁩، ⁦38.2⁩.

Expected outputدەرخستەکەی چاوەڕوانکراو
The list of the numbers are :  [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]
Sum is  1296.3
Average is  129.63
Hintئاماژە

sum(numbers) gives the total and len(numbers) gives how many numbers there are.

sum(numbers) کۆی گشتی دەدات و len(numbers) ژمارەی ژمارەکان دەدات.

Show answerوەڵامەکە پیشان بدە
lab3_task1_1.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
numbers = [2.7, 32, 768, 89.1, 21, 90.3, 135, 77, 43, 38.2]
total = sum(numbers)
print("The list of the numbers are : ", numbers)
print("Sum is ", total)
print("Average is ", total / len(numbers))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

Divide by len(numbers), not by a typed 10: if the list grows, the average stays right.

دابەش بکە بەسەر len(numbers)، نەک ⁦10⁩ێکی نووسراو: ئەگەر گەورە بوو، تێکڕاکە هەر دروست دەمێنێتەوە.

average=x1+x2+⋯+xnn=1296.310=129.63\text{average} = \frac{x_1 + x_2 + \cdots + x_n}{n} = \frac{1296.3}{10} = 129.63

The average (mean) is the sum divided by how many numbers there are.

تێکڕا () بریتییە لە کۆکە دابەش بەسەر ژمارەی ژمارەکان.

Smallest and largest of numbers you typeبچووکترین و گەورەترینی ئەو ژمارانەی دەینووسیت

A list does not have to be written in the code. This program first asks how many numbers you will type, fills an empty list with append in a loop, and then lets min and max do the work.

پێویست ناکات لە ناو کۆدەکەدا بنووسرێت. ئەم سەرەتا دەپرسێت چەند ژمارە دەنووسیت، بەتاڵ لە ناو بە append پڕ دەکاتەوە و پاشان کارەکە بە min و max دەسپێرێت.

min() and max() on typed numbersmin() و max() لەسەر ژمارە نووسراوەکانmin_max_input.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
num_list = []
count = int(input("Please enter element length in list : "))
for i in range(1, count + 1):
    value = int(input("Please enter the Value of Element : "))
    num_list.append(value)

print("The Smallest Element in this List is : ", min(num_list))
print("The Largest Element in this List is : ", max(num_list))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

int(input(...)) turns the typed text into a whole number.

int(input(...)) دەقە نووسراوەکە دەکات بە .

Lineدێڕی 3

range(1, count + 1) runs count times.

range(1, count + 1) ژمارەی count جار دەخولێتەوە.

Quick checkپشکنینی خێراThe user types the count 3 and then 4, −1-1, 10. What is printed for the largest element? ژمارەی 3 دەنووسێت و پاشان 4، −1-1، ⁦10⁩. بۆ گەورەترین چی چاپ دەکرێت؟

Finding the smallest and largest with a loopدۆزینەوەی بچووکترین و گەورەترین بە خولێک

min and max give the value, but not where it is. To get the position too, scan the list yourself. Keep two variables, "smallest so far" and "largest so far". Start them with the first element, then visit every other element once and update a variable whenever you meet something better.

min و max دەدەن، بەڵام نەک شوێنەکەی. بۆ ئەوەی شوێنەکەشی بزانیت، خۆت بەسەر بڕۆ. دوو ڕابگرە: «بچووکترین تا ئێستا» و «گەورەترین تا ئێستا». بە یەکەم دەستیان پێ بکە، پاشان یەکجار سەردانی هەموو تر بکە و هەر کاتێک شتێکی باشترت بینی نوێ بکەرەوە.

The cheapest tomatoes in the bazaarهەرزانترین تەماتە لە بازاڕدا

You walk along the bazaar to find the cheapest kilo of tomatoes. At the first stall you remember its price and its place. At every next stall you compare: if it is cheaper, you forget the old one and remember the new price and place. At the end of the street you know the cheapest price and where it was.

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

Where the analogy stops workingسنووری ئەم نموونەیە

You must start with a real price — the first stall's — not with 0 (nothing is cheaper than 0). And you must remember the place from the very first stall, or you have no place to report when the first stall was already the cheapest. The program below forgets exactly that.

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

The slide's programبەرنامەکەی سلایدەکەmin_max_loop_slide.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
NumList = []
Number = int(input("How many element in list?  "))
for i in range(1, Number + 1):
      value = int(input("Please enter the Value of Element : "))
      NumList.append(value)

smallest =largest= NumList[0]
for j in range(1, Number):
      if smallest > NumList[j]:
            smallest = NumList[j]
            min_position = j
      if largest < NumList[j]:
            largest = NumList[j]
            max_position = j

print("The Smallest Element in this List is : ", smallest)
print("The Index position of Smallest Element in this List is : ", min_position)
print("The Largest Element in this List is : ", largest)
print("The Index position of Largest Element in this List is : ", max_position)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 7

Both "so far" variables start with the first element.

هەردوو «تا ئێستا» بە یەکەم دەست پێ دەکەن.

Lineدێڕی 8

The loop starts at index 1: index 0 is already in smallest and largest.

لە 1ـەوە دەست پێ دەکات: 0 پێشتر لە smallest و largestـدایە.

Lineدێڕی 10-11

A smaller value replaces smallest, and its index is remembered.

بچووکتر جێگەی smallest دەگرێتەوە و لە بیر دەگیرێت.

Trace of the scan for 6 8 1 7 5بەدواداچوونی گەڕانەکە بۆ ⁦6 8 1 7 5⁩
jjNumList[j]NumList[j]smallest (position)smallest (شوێن)largest (position)largest (شوێن)
startسەرەتا66 (not set)6 (دانەنراوە)6 (not set)6 (دانەنراوە)
1868 (1)
211 (2)8 (1)
371 (2)8 (1)
451 (2)8 (1)
Quick checkپشکنینی خێراIn the trace, why is min_position never set at the start?لە بەدواداچوونەکەدا، بۆچی min_position لە سەرەتادا دانانرێت؟

Finding the smallest and largest with a loopدۆزینەوەی بچووکترین و گەورەترین بە خولێک

A hidden bug: min_position may not existهەڵەیەکی شاراوە: لەوانەیە min_position بوونی نەبێت

Now type 3 numbers where the smallest comes first: 1, 5, 3. No later element is smaller than 1, so the if that creates min_position never runs. When the program reaches print(…, min_position) the name does not exist:

ئێستا 3 ژمارە بنووسە کە بچووکترینیان یەکەمـە: 1، 5، 3. هیچ دواتر لە 1 بچووکتر نییە، بۆیە ئەو ifـەی min_position دروست دەکات هەرگیز جێبەجێ نابێت. کاتێک دەگاتە print(…, min_position) ئەو ناوە بوونی نییە:

The same program, input 1 5 3هەمان بەرنامە، نێوخستەی بەکارهێنەر ⁦1 5 3⁩min_max_loop_bug.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
NumList = []
Number = int(input("How many element in list?  "))
for i in range(1, Number + 1):
      value = int(input("Please enter the Value of Element : "))
      NumList.append(value)

smallest =largest= NumList[0]
for j in range(1, Number):
      if smallest > NumList[j]:
            smallest = NumList[j]
            min_position = j
      if largest < NumList[j]:
            largest = NumList[j]
            max_position = j

print("The Smallest Element in this List is : ", smallest)
print("The Index position of Smallest Element in this List is : ", min_position)
print("The Largest Element in this List is : ", largest)
print("The Index position of Largest Element in this List is : ", max_position)
Fixed (and in PEP 8 style)چاککراو (و بە شێوازی ⁦PEP 8⁩)min_max_loop_fixed.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
num_list = []
count = int(input("How many element in list?  "))
for i in range(count):
    num_list.append(int(input("Please enter the Value of Element : ")))

smallest = largest = num_list[0]
min_position = max_position = 0          # the first element is the best so far
for j in range(1, count):
    if num_list[j] < smallest:
        smallest = num_list[j]
        min_position = j
    if num_list[j] > largest:
        largest = num_list[j]
        max_position = j

print("The Smallest Element in this List is : ", smallest)
print("The Index position of Smallest Element in this List is : ", min_position)
print("The Largest Element in this List is : ", largest)
print("The Index position of Largest Element in this List is : ", max_position)

If you only need the position of the smallest value, Python can also do it in one line: values.index(min(values)) — min finds the value and index finds its first position.

ئەگەر تەنها شوێنی بچووکترین پێویستە، دەتوانێت بە یەک دێڕیش بیکات: values.index(min(values)) — min دەدۆزێتەوە و index یەکەم شوێنی.

index_of_min.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
values = [1, 5, 3]
print(min(values), values.index(min(values)))
print(max(values), values.index(max(values)))
Quick checkپشکنینی خێراWhich input makes the slide's program crash?کام وا دەکات سلایدەکە بوەستێت؟

Lab: smallest and largest even numberتاقیگە: بچووکترین و گەورەترین ژمارەی جووت

ExerciseڕاهێنانLab 4, Task 3تاقیگەی 4، ئەرکی 3

Use a for loop and an if statement: read 10 numbers, then print only the smallest and the largest even number, each with its index in the list. Test with 45 78 77 98 3 17 36 8 17 55.

و بەکار بهێنە: ⁦10⁩ ژمارە بخوێنەوە، پاشان تەنها بچووکترین و گەورەترین ژمارەی جووت چاپ بکە، هەریەکەیان لەگەڵ لە . بە ⁦45 78 77 98 3 17 36 8 17 55⁩ تاقی بکەرەوە.

Expected output (from the lab sheet)دەرخستەکەی چاوەڕوانکراو (لە پەڕەی تاقیگەکەوە)
The minimum even number =  8 its index =   7
The maximum even number =  98 its index = 3
Hintئاماژە

You cannot start from numbers[0] as on the slides — it may be odd. Start from None and let the first even number fill it.

ناتوانیت وەک سلایدەکان لە numbers[0]ـەوە دەست پێ بکەیت — لەوانەیە تاک بێت. لە Noneـەوە دەست پێ بکە و با یەکەم ژمارەی جووت پڕی بکاتەوە.

Show answerوەڵامەکە پیشان بدە
lab4_task3.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
numbers = []
for i in range(10):
    numbers.append(int(input("enter a number :  ")))

min_even = max_even = None      # no even number seen yet
min_index = max_index = -1
for i in range(len(numbers)):
    if numbers[i] % 2 == 0:
        if min_even is None or numbers[i] < min_even:
            min_even, min_index = numbers[i], i
        if max_even is None or numbers[i] > max_even:
            max_even, max_index = numbers[i], i

print("The minimum even number = ", min_even, "its index = ", min_index)
print("The maximum even number = ", max_even, "its index =", max_index)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

The first element (45) is odd, so it cannot be the starting "best so far". None means "nothing found yet".

یەکەم ⁦(45)⁩ تاکە، بۆیە ناتوانێت «باشترین تا ئێستا»ی سەرەتا بێت. None واتە «هێشتا هیچ نەدۆزراوەتەوە».

Lineدێڕی 8

% 2 == 0 keeps only the even numbers.

% 2 == 0 تەنها ژمارە جووتەکان دەهێڵێتەوە.

Lineدێڕی 9

The first even number fills the empty None; later ones must be smaller.

یەکەم ژمارەی جووت Noneـە بەتاڵەکە پڕ دەکاتەوە؛ ئەوانەی دواتر دەبێت بچووکتر بن.

Quick checkپشکنینی خێراIf none of the 10 numbers is even, what does this program print for the minimum?ئەگەر هیچ یەک لە ⁦10⁩ ژمارەکە جووت نەبێت، ئەم بۆ بچووکترین چی چاپ دەکات؟

sort() and sorted()sort() و sorted()

Python gives you two ways to sort, and the difference matters. sorted(mylist) is a built-in function: it builds a new, sorted list and returns it; mylist stays as it was. mylist.sort() is a list method: it sorts the list itself, in place, and returns None. Both sort in ascending order (smallest first) unless you ask otherwise.

دوو ڕێگەت بۆ پێ دەدات و جیاوازییەکەیان گرنگە. sorted(mylist) : نوێی ڕیزکراو دروست دەکات و دەیگەڕێنێتەوە؛ mylist وەک خۆی دەمێنێتەوە. mylist.sort() : خودی لە شوێنی خۆیدا ڕیز دەکات و None دەگەڕێنێتەوە. هەردووکیان بە ڕیز دەکەن (بچووکترین یەکەم)، مەگەر داوای شتێکی تر بکەیت.

sorted(): a new listsorted(): لیستێکی نوێsorted_new_list.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
sort2 = sorted(mylist)
print(sort2)
print(mylist)
sort(): the same list, sortedsort(): هەمان لیست، ڕیزکراوsort_in_place.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
sort1 = mylist.sort()
print(sort1)
print(mylist)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

A classic mistake: sort() returns None, so sort1 is None. The sorted numbers are in mylist.

هەڵەیەکی باو: sort() None دەگەڕێنێتەوە، بۆیە sort1 دەبێتە None. ژمارە ڕیزکراوەکان لە mylistـدان.

Two lanes. Top lane, new = sorted(mylist): mylist [4, 7, 8, 4, -2, 7, 0, 8, 4] stays unchanged and a second, new list [-2, 0, 4, 4, 4, 7, 7, 8, 8] appears, named new. Bottom lane, mylist.sort(): the one list mylist itself becomes [-2, 0, 4, 4, 4, 7, 7, 8, 8], and the call returns None.دوو ڕێڕەو. ڕێڕەوی سەرەوە، new = sorted(mylist): mylist [4, 7, 8, 4, -2, 7, 0, 8, 4] نەگۆڕاو دەمێنێتەوە و لیستێکی دووەمی نوێ [-2, 0, 4, 4, 4, 7, 7, 8, 8] بە ناوی new دەردەکەوێت. ڕێڕەوی خوارەوە، mylist.sort(): هەمان یەک لیست، خودی mylist، دەبێتە [-2, 0, 4, 4, 4, 7, 7, 8, 8] و بانگکردنەکە None دەگەڕێنێتەوە.
sorted() makes a new list; sort() changes the list and returns None.sorted() نوێ دروست دەکات؛ sort() دەگۆڕێت و None دەگەڕێنێتەوە.CêIT
Quick checkپشکنینی خێراscores = [70, 50, 90] and then best = scores.sort(). What is best?scores = [70, 50, 90] و پاشان best = scores.sort(). best چییە؟

sort() and sorted()sort() و sorted()

Largest first: reverse=Trueگەورەترین یەکەم: reverse=True

To sort in descending order (largest first), add reverse=True. It works the same way for both tools: sorted(…, reverse=True) returns a new list, mylist.sort(reverse=True) changes the list.

بۆ بە (گەورەترین یەکەم)، reverse=True زیاد بکە. بۆ هەردوو ئامرازەکە هەمان شێوە کار دەکات: sorted(…, reverse=True) نوێ دەگەڕێنێتەوە و mylist.sort(reverse=True) دەگۆڕێت.

sorted(…, reverse=True)sorted(…, reverse=True)sorted_desc.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
sort1 = sorted(mylist, reverse=True)
print(sort1)
print(mylist)
sort(reverse=True)sort(reverse=True)sort_desc.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
sort1 = mylist.sort(reverse=True)
print(sort1)
print(mylist)
Quick checkپشکنینی خێراWhich line prints [9, 5, 1] and leaves nums = [5, 1, 9] unchanged?کام دێڕ [9, 5, 1] چاپ دەکات و nums = [5, 1, 9] وەک خۆی دەهێڵێتەوە؟

sort() and sorted()sort() و sorted()

Sorting by a rule: key=ڕیزکردن بەپێی یاسایەک: key=

Sometimes the normal order is not what you want. With key= you give a function, and Python sorts by its result for each item instead of by the item itself. key=str.lower compares names without caring about capital letters; key=len sorts words by their length. min and max accept key= too.

هەندێک جار ڕیزبەندییە ئاساییەکە ئەوە نییە کە دەتەوێت. بە key= دەدەیت و بەپێی ئەنجامی ئەو بۆ هەر ڕیز دەکات، نەک بەپێی خودی . key=str.lower ناوەکان بەراورد دەکات بەبێ گرنگیدان بە پیتە گەورەکان؛ key=len وشەکان بەپێی درێژییان ڕیز دەکات. min و maxـیش key= وەردەگرن.

Sorting with key=ڕیزکردن بە key=sort_keys.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
names = ["Shilan", "aram", "Dilan", "karwan"]
print(sorted(names))                  # capitals first
print(sorted(names, key=str.lower))   # compare the lower-case forms

words = ["pear", "fig", "banana", "kiwi"]
print(sorted(words, key=len))         # shortest first
print(max(words, key=len))            # the longest word
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

Upper-case letters come before lower-case ones, so Dilan and Shilan come first.

پیتە گەورەکان پێش پیتە بچووکەکان دێن، بۆیە Dilan و Shilan یەکەم دێن.

Lineدێڕی 6

pear and kiwi both have 4 letters and keep their original order: Python's sort is a stable sort (why that matters).

pear و kiwi هەردووکیان 4 پیتن و ڕیزبەندییە سەرەتاییەکەیان دەپارێزن: (بۆچی گرنگە).

Quick checkپشکنینی خێراWhat does sorted(["bb", "a", "ccc"], key=len, reverse=True) give?sorted(["bb", "a", "ccc"], key=len, reverse=True) چی دەدات؟

Inside a sort: selection sortلە ناو ڕیزکردنێکدا: ڕیزکردن بە هەڵبژاردن

How does a computer sort? There are many algorithms. The easiest to follow is selection sort, and you can build it from two pieces of this course: the "smallest so far" scan with its position (from the previous screens) and the one-line swap (Lab 3, Task 4). Find the smallest value of the whole list and swap it to position 0. Then find the smallest of the unsorted part and swap it to position 1, and so on. After each pass the front part is sorted and never touched again.

کۆمپیوتەر چۆن ڕیز دەکات؟ زۆر هەن. ئاسانترینیان بۆ بەدواداچوون و دەتوانیت لە دوو پارچەی ئەم کۆرسە دروستی بکەیت: گەڕانی «بچووکترین تا ئێستا» لەگەڵ شوێنەکەی (لە پەڕەکانی پێشوو) و ئاڵوگۆڕی یەک دێڕی (تاقیگەی 3، ئەرکی ⁦4⁩). بچووکترین هەموو بدۆزەرەوە و بیگوازەرەوە بۆ شوێنی 0. پاشان بچووکترینی بەشە ڕیزنەکراوەکە بدۆزەرەوە و بیگوازەرەوە بۆ شوێنی 1 و بەم شێوەیە. دوای هەر جارێک بەشی سەرەتای ڕیزکراوە و چیتر دەستی لێ نادرێت.

Definitionپێناسە

A simple : find the smallest item of the unsorted part, swap it to the front of that part, and repeat with the rest. It needs about n2/2n^2/2 comparisons, so it is slow for big lists, but it is easy to follow by hand.

سادەی : بچووکترین بەشە ڕیزنەکراوەکە بدۆزەرەوە، بیگوازەرەوە بۆ سەرەتای ئەو بەشە و بۆ ئەوەی ماوەتەوە دووبارەی بکەرەوە. نزیکەی n2/2n^2/2 بەراورد پێویست دەکات، بۆیە بۆ گەورە خاوە، بەڵام بە دەست بەدواداچوونی ئاسانە.

Selection sort, built from the min-position scanڕیزکردن بە هەڵبژاردن، دروستکراو لە گەڕانی شوێنی بچووکترینselection_sort.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def selection_sort(values):
    n = len(values)
    for start in range(n - 1):
        # 1. find the position of the smallest value from start to the end
        min_position = start
        for j in range(start + 1, n):
            if values[j] < values[min_position]:
                min_position = j
        # 2. swap it to the front of the unsorted part
        values[start], values[min_position] = values[min_position], values[start]
        print(f"pass {start + 1}: {values}")

mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
selection_sort(mylist)
print(mylist)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 3

One pass for each position except the last: when 8 of 9 places are right, the last one is right too.

یەک جار بۆ هەر شوێنێک جگە لە دوایین: کاتێک 8 لە 9 شوێن دروستن، دوایینیش دروستە.

Lineدێڕی 5-8

The same scan as before, but it only looks at the unsorted part, from start to the end.

هەمان گەڕانی پێشوو، بەڵام تەنها سەیری بەشە ڕیزنەکراوەکە دەکات، لە startـەوە تا کۆتایی.

Lineدێڕی 10

The swap from Lab 3, Task 4. The function changes the caller's list in place, like sort().

ئاڵوگۆڕەکەی تاقیگەی 3، ئەرکی 4. لە شوێنی خۆیدا دەگۆڕێت، وەک sort().

Animation of selection sort on [4, 7, 8, 4, -2, 7, 0, 8, 4]. Pass 1: the smallest value -2 is found at index 4 and swapped with index 0. Pass 2: 0 at index 6 swaps with index 1. Pass 3: 4 at index 3 swaps with index 2. Pass 4: 4 at index 4 swaps with index 3. Pass 5: 4 at index 8 swaps with index 4. Passes 6 to 8: each smallest value is already in place. The sorted part grows from the left until the list is [-2, 0, 4, 4, 4, 7, 7, 8, 8].
Animation of selection sort on [4, 7, 8, 4, -2, 7, 0, 8, 4]. Pass 1: the smallest value -2 is found at index 4 and swapped with index 0. Pass 2: 0 at index 6 swaps with index 1. Pass 3: 4 at index 3 swaps with index 2. Pass 4: 4 at index 4 swaps with index 3. Pass 5: 4 at index 8 swaps with index 4. Passes 6 to 8: each smallest value is already in place. The sorted part grows from the left until the list is [-2, 0, 4, 4, 4, 7, 7, 8, 8].
Each pass selects the smallest of the unsorted part and swaps it into place.هەر جارێک بچووکترینی بەشە ڕیزنەکراوەکە هەڵدەبژێرێت و دەیخاتە شوێنی خۆی.CêIT
Lining up for the class photoڕیزبوون بۆ وێنەی پۆل

The teacher lines the class up by height for a photo. She picks the shortest student and puts them first, then the shortest of those still waiting goes second, and so on. That is selection sort.

مامۆستا پۆلەکە بەپێی باڵا ڕیز دەکات بۆ وێنە. کورتترین خوێندکار هەڵدەبژێرێت و دەیخاتە یەکەم، پاشان کورتترینی ئەوانەی هێشتا چاوەڕێن دووەم دەبێت و بەم شێوەیە. ئەمە .

Where the analogy stops workingسنووری ئەم نموونەیە

The teacher sees the whole class at a glance. The computer can only compare two values at a time, so it must look at every value of the unsorted part in every pass.

مامۆستا بە یەک سەیرکردن هەموو پۆلەکە دەبینێت. کۆمپیوتەر لە هەر جارێکدا تەنها دەتوانێت دوو بەراورد بکات، بۆیە دەبێت لە هەموو جارێکدا سەیری هەموو بەشە ڕیزنەکراوەکە بکات.

Quick checkپشکنینی خێراAfter pass 2 of selection sort on [5, 3, 9, 1], what is the list?دوای جاری 2ـی لەسەر [5, 3, 9, 1]، چییە؟

Selection Sort Algorithm Explained (Full Code Included) - Python Algorithms Series for BeginnersDerrick Sherrill · Englishئینگلیزی · 88K viewsبینین · 2.3K likesلایک

Selection sort step by step: find the smallest remaining value, swap it to the front, repeat — then the same in Python code.

هەنگاو بە هەنگاو: بچووکترین لە بەشی ڕیزنەکراو بدۆزەوە، بە جێگۆڕکێ بیبە بۆ پێشەوە و دووبارەی بکەرەوە؛ پاشان بە کۆدی .

Whole video (5:47): the idea on a list, then the Python function with two loops.

هەموو ڤیدیۆکە ⁦(5:47)⁩: بیرۆکەکە لەسەر ، پاشان بە و بە دوو .

Inside a sort: selection sortلە ناو ڕیزکردنێکدا: ڕیزکردن بە هەڵبژاردن

How much work is selection sort?ڕیزکردن بە هەڵبژاردن چەند کارە؟

How much work is that? For nn values the first pass compares n−1n-1 pairs, the next n−2n-2, and so on down to 1:

ئەمە چەند کارە؟ بۆ nn یەکەم جار n−1n-1 جووت بەراورد دەکات، دواتر n−2n-2 و بەم شێوەیە تا 1:

(n−1)+(n−2)+⋯+1=n(n−1)2n=9: 9⋅82=36(n-1) + (n-2) + \cdots + 1 = \frac{n(n-1)}{2} \qquad n = 9:\ \frac{9 \cdot 8}{2} = 36

For 1,000 values that is 499,500 comparisons. Python's own sort() and sorted() use a much faster algorithm, Timsort (Why Python's sort() is better), so in real programs use them — write selection sort to understand sorting, not to replace them.

بۆ ⁦1000⁩ دەبێتە ⁦499500⁩ بەراورد. sort() و sorted()ـی خودی زۆر خێراتر بەکار دەهێنن، Timsort (بۆچی sort()ـی Python باشترە)، بۆیە لە ڕاستەقینەدا ئەوان بەکار بهێنە — بۆ تێگەیشتن لە بنووسە، نەک بۆ ئەوەی جێگەیان بگریتەوە.

Counting steps like this is how programmers compare algorithms (Comparing algorithms). Two more sorting algorithms, bubble sort and insertion sort, and what such counts mean for big lists, follow in Bubble Sort, Insertion Sort and How Fast Sorting Is.

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

Quick checkپشکنینی خێراHow many comparisons does selection sort make for a list of 5 values? بۆ لە 5 چەند بەراورد دەکات؟

Lab: descending order and the odd numbersتاقیگە: ڕیزی نزمبوونەوە و ژمارە تاکەکان

ExerciseڕاهێنانLab 4, Task 2-1تاقیگەی 4، ئەرکی ⁦2-1⁩

You may use the built-in functions for sorting and for the maximum and minimum. Read 10 numbers, print the list in descending order, and print only the maximum and the minimum of the odd numbers in the list. Test with 45 32 67 91 0 17 91 84 3 72.

دەتوانیت بۆ و بۆ گەورەترین و بچووکترین بەکار بهێنیت. ⁦10⁩ ژمارە بخوێنەوە، بە چاپ بکە و تەنها گەورەترین و بچووکترینی ژمارە تاکەکانی ناو چاپ بکە. بە ⁦45 32 67 91 0 17 91 84 3 72⁩ تاقی بکەرەوە.

Expected output (from the lab sheet)دەرخستەکەی چاوەڕوانکراو (لە پەڕەی تاقیگەکەوە)
My list in descending order = [91, 91, 84, 72, 67, 45, 32, 17, 3, 0]
The minimum odd number =  3
The maximum odd number =  91
Hintئاماژە

Build a second list with only the odd numbers, then use min and max on it.

دووەم دروست بکە کە تەنها ژمارە تاکەکانی تێدابێت، پاشان min و maxـی لەسەر بەکار بهێنە.

Show answerوەڵامەکە پیشان بدە
lab4_task2_1.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
numbers = []
for i in range(10):
    numbers.append(int(input(" enter number  ")))
print(" My list in descending order =", sorted(numbers, reverse=True))

odds = []
for n in numbers:
    if n % 2 == 1:
        odds.append(n)

if odds:
    print("The minimum odd number = ", min(odds))
    print("The maximum odd number = ", max(odds))
else:
    print("There is no odd number in the list.")
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

sorted(..., reverse=True) prints a sorted copy; numbers keeps the typed order.

sorted(..., reverse=True) کۆپییەکی ڕیزکراو چاپ دەکات؛ numbers ڕیزبەندیی نووسراوەکە دەپارێزێت.

Lineدێڕی 6-9

Collect the odd numbers in a new list: n % 2 == 1 means the remainder after dividing by 2 is 1.

ژمارە تاکەکان لە نوێدا کۆ بکەرەوە: n % 2 == 1 واتە دوای دابەشکردن بەسەر 2دا 1ـە.

Lineدێڕی 11

If no odd number was typed, odds is empty and min(odds) would crash. if odds: is False for an empty list.

ئەگەر هیچ ژمارەیەکی تاک نەنووسرابێت، odds بەتاڵە و min(odds) دەوەستێت. if odds: بۆ بەتاڵ Falseـە.

Collecting and counting matchesکۆکردنەوە و ژماردنی ئەوانەی دەگونجێن

index and in find the first element that fits. To find all of them, start with an empty list and append every element that passes the test. A counter that goes up by one each time tells you how many there are.

index و in یەکەم دەدۆزنەوە کە دەگونجێت. بۆ دۆزینەوەی هەموویان، بە بەتاڵ دەست پێ بکە و هەر کە لە تاقیکردنەوەکە دەردەچێت بە append زیادی بکە. کە هەر جارێک یەکێک زیاد دەبێت پێت دەڵێت چەندن.

All elements greater than a limitهەموو دانەکان کە لە سنوورێک گەورەترنmatches.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
limit = 0
counter = 0
result = []
for element in mylist:
    if element > limit:
        result.append(element)
        counter = counter + 1
print("The number of elements greater than 0 is ", counter, end="  ")
print(" Which are : ", result)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4

An empty list that will collect the matches.

بەتاڵ کە ئەوانەی دەگونجێن کۆ دەکاتەوە.

Lineدێڕی 8

The counter goes up together with every append.

لەگەڵ هەموو appendـێکدا زیاد دەبێت.

Lineدێڕی 9

end=" " keeps the next print on the same line.

end=" " وا دەکات printـی داهاتوو لەسەر هەمان دێڕ بێت.

Two small improvements. The counter is always equal to len(result), so you do not need it. And the message types "0" by hand; if you change limit to 5 the message would lie. Use the variable in the text instead:

دوو باشترکردنی بچووک. هەمیشە یەکسانە بە len(result)، بۆیە پێویستت پێی نییە. هەروەها پەیامەکە «0» بە دەست دەنووسێت؛ ئەگەر limit بگۆڕیت بۆ 5، پەیامەکە درۆ دەکات. لەبری ئەوە لە ناو دەقەکەدا بەکار بهێنە:

matches_better.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
limit = 5
result = []
for element in mylist:
    if element > limit:
        result.append(element)
print(f"{len(result)} elements are greater than {limit}: {result}")
Quick checkپشکنینی خێراWith limit = 7 in the first program, what is counter?ئەگەر لە یەکەمدا limit = 7 بێت، counter چەندە؟

Collecting and counting matchesکۆکردنەوە و ژماردنی ئەوانەی دەگونجێن

Extra: the same in one lineزیاتر: هەمان شت بە یەک دێڕ

Python has a short form for "make a list of the elements that pass a test": a list comprehension. Read [element for element in mylist if element > limit] as "the list of every element in mylist that is greater than limit". It does exactly what the loop with append does.

شێوەیەکی کورتی هەیە بۆ « لە کە لە تاقیکردنەوەیەک دەردەچن دروست بکە»: . [element for element in mylist if element > limit] وا بخوێنەوە: « هەموو mylist کە لە limit گەورەترن». ڕێک هەمان کاری لەگەڵ append دەکات.

A list comprehensionlist comprehensioncomprehension.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
mylist = [4, 7, 8, 4, -2, 7, 0, 8, 4]
limit = 5
result = [element for element in mylist if element > limit]
print(result)
print([n for n in mylist if n % 2 == 1])    # the odd numbers
List Comprehensions - Visually ExplainedVisually Explained · Englishئینگلیزی · 75K viewsبینین · 3.4K likesلایک · Partبەشی 0:15–4:54 (ofلە 9:02)

How to build a list in one line with a list comprehension, step by step, also with strings and an if condition.

هەنگاو بە هەنگاو پیشان دەدات چۆن بە لە یەک دێڕدا دروست دەکەیت، پاشان هەمان کار لەگەڵ و if دەکات.

Watch 0:15–4:54: the syntax, strings, and conditions (4:08). The performance and parallel parts are extra.

لە ⁦0:15⁩ تا ⁦4:54⁩ سەیر بکە: ، و ⁦(4:08)⁩. بەشەکانی خێرایی و کاری هاوتەریب زیادەن.

Lab: random numbers and the even onesتاقیگە: ژمارە هەڕەمەکییەکان و جووتەکانیان

ExerciseڕاهێنانLab 3, Task 5تاقیگەی 3، ئەرکی 5

Write a program that fills a list with ten random integers between 20 and 30, then prints every element with its index number, and then every even number in the list with its index number.

بنووسە کە بە دە تەواو لە نێوان ⁦20⁩ و ⁦30⁩دا پڕ بکاتەوە، پاشان هەموو لەگەڵ ژمارەی چاپ بکات و پاشان هەموو ژمارەیەکی جووتی ناو لەگەڵ ژمارەی .

Hintئاماژە

import random, then random.randint(20, 30) inside a loop. Use end=" " to keep each list on one line.

import random، پاشان random.randint(20, 30) لە ناو . بۆ ئەوەی هەر لەسەر یەک دێڕ بێت end=" " بەکار بهێنە.

Show answerوەڵامەکە پیشان بدە
lab3_task5.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
import random
random.seed(3)    # only so that this example run can be repeated; remove it

numbers = []
for i in range(10):
    numbers.append(random.randint(20, 30))

print("The list of all random elements with its index no.")
for i in range(len(numbers)):
    print(i, "=", numbers[i], end="   ")
print()

print("The list of all even numbers in the list with its index no.")
for i in range(len(numbers)):
    if numbers[i] % 2 == 0:
        print(i, "=", numbers[i], end="   ")
print()
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 6

random.randint(20, 30) can return both 20 and 30.

random.randint(20, 30) دەتوانێت هەم ⁦20⁩ و هەم ⁦30⁩ بگەڕێنێتەوە.

Lineدێڕی 15

Test the value: numbers[i] % 2 == 0. Testing the index i % 2 == 0 would give the elements at even positions instead.

تاقی بکەرەوە: numbers[i] % 2 == 0. تاقیکردنەوەی i % 2 == 0 لەبری ئەوە شوێنە جووتەکان دەدات.

A solved quiz: counting, filtering, sortingتاقیکردنەوەیەکی چارەسەرکراو: ژماردن، پاڵاوتن، ڕیزکردن

ExerciseڕاهێنانQuiz program Q1بەرنامەی تاقیکردنەوەی ⁦Q1⁩

Read 10 integers into a list. Count and show the elements "between 5 and 15". Count the even elements and show them sorted. Here is a student's solution that was handed in for a quiz (only eval is replaced by int, and one typo is fixed). Run it with 3 8 15 5 12 20 7 14 1 6.

⁦10⁩ بخوێنەوە بۆ ناو . کە «لە نێوان 5 و ⁦15⁩دان» بژمێرە و پیشانیان بدە. بژمێرە و بە ڕیزکراوی پیشانیان بدە. ئەمە چارەسەری خوێندکارێکە کە بۆ تاقیکردنەوەیەک ڕادەستی کراوە (تەنها eval گۆڕدراوە بە int و هەڵەیەکی نووسین چاک کراوە). بە ⁦3 8 15 5 12 20 7 14 1 6⁩ جێبەجێی بکە.

The original program (as handed in):

ڕەسەنەکە (وەک ڕادەست کراوە):

q1_original.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
num = []
result = []
evenLst = []
count = 0
evenNum = 0
for i in range(10):
    a = int(input("Enter an integer: "))
    num.append(a)
    for j in range(5, 15):
        if a == j:
            count += 1
            result.append(a)
    if a % 2 == 0:
        evenNum += 1
        evenLst.append(a)

print("The list:", num)
print(f"Number of elements between 5 and 15 is {count} which are:", result)
evenLst.sort()
print(f"Numbers of even elements is {evenNum} which are:", evenLst)
Show answerوەڵامەکە پیشان بدە
q1_original.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
num = []
result = []
evenLst = []
count = 0
evenNum = 0
for i in range(10):
    a = int(input("Enter an integer: "))
    num.append(a)
    for j in range(5, 15):
        if a == j:
            count += 1
            result.append(a)
    if a % 2 == 0:
        evenNum += 1
        evenLst.append(a)

print("The list:", num)
print(f"Number of elements between 5 and 15 is {count} which are:", result)
evenLst.sort()
print(f"Numbers of even elements is {evenNum} which are:", evenLst)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 9-12

This inner loop compares a with 5, 6, …, 14 — range(5, 15) stops before 15. So 15 is not counted, and the loop does ten comparisons for every number.

ئەم a لەگەڵ 5، 6، …، ⁦14⁩ بەراورد دەکات — range(5, 15) پێش ⁦15⁩ دەوەستێت. بۆیە ⁦15⁩ ناژمێردرێت و بۆ هەر ژمارەیەک دە بەراورد دەکات.

Lineدێڕی 19

evenLst.sort() sorts the list in place before it is printed.

evenLst.sort() پێش چاپکردن لە شوێنی خۆیدا ڕیز دەکات.

A chained comparison says the same in one test: 5 <= a < 15 means "a is at least 5 and less than 15". If 15 should count too, write 5 <= a <= 15. The task wording decides; ask when it is not clear.

هەمان شت بە یەک تاقیکردنەوە دەڵێت: 5 <= a < 15 واتە «a لانیکەم 5ـە و لە ⁦15⁩ بچووکترە». ئەگەر ⁦15⁩ـیش بژمێردرێت، 5 <= a <= 15 بنووسە. دەقی ئەرکەکە بڕیار دەدات؛ کاتێک ڕوون نییە بپرسە.

q1_simple.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
num = []
for i in range(10):
    num.append(int(input("Enter an integer: ")))

between = [a for a in num if 5 <= a < 15]     # the same test as range(5, 15)
evens = sorted(a for a in num if a % 2 == 0)

print("The list:", num)
print(f"Number of elements between 5 and 15 is {len(between)} which are:", between)
print(f"Number of even elements is {len(evens)} which are:", evens)
Quick checkپشکنینی خێراWhich test is the same as the inner loop for j in range(5, 15): if a == j: for whole numbers?بۆ ، کام تاقیکردنەوە هەمانە وەک for j in range(5, 15): if a == j:؟

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

sum, max, min and sorting: mistakes to avoidsum، max، min و : ئەو هەڵانەی دەبێت لێیان دوور بیت
MistakeهەڵەWhat happensچی ڕوو دەداتFixچارەسەر
x = mylist.sort()x is Nonex دەبێتە Nonemylist.sort() on its own line, or x = sorted(mylist)mylist.sort() لە دێڕێکی جیادا، یان x = sorted(mylist)
sorted(mylist) …expecting mylist itself to be sorted afterwardsچاوەڕوانی ئەوەی کە دواتر خودی mylist ڕیزکراو بێتuse the returned list, or call mylist.sort() بەکار بهێنە، یان mylist.sort() بانگ بکە
min(odds)ValueError when odds is emptyValueError کاتێک odds بەتاڵەif odds: first, or min(odds, default=None)سەرەتا if odds:، یان min(odds, default=None)
a position variable set only inside if شوێن کە تەنها لە ناو ifـدا دادەنرێتNameError when the first element is the bestNameError کاتێک یەکەم باشترینەstart it next to smallest: min_position = 0لە تەنیشت smallest دەستی پێ بکە: min_position = 0
starting "smallest so far" at 0دەستپێکردنی «بچووکترین تا ئێستا» بە 0wrong when all numbers are positiveهەڵەیە کاتێک هەموو ژمارەکان لە 0 گەورەترنstart with the first element, or with Noneبە یەکەم دەست پێ بکە، یان بە None
dividing by a typed 10دابەشکردن بەسەر ⁦10⁩ێکی نووسراوwrong average when the list growsتێکڕای هەڵە کاتێک گەورە دەبێتlen(numbers)
i % 2 == 0tests the index, not the value تاقی دەکاتەوە، نەک numbers[i] % 2 == 0

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

Exerciseڕاهێنان1. A week of temperatures1. پلەی گەرمیی هەفتەیەک

The noon temperatures of a week are [18, 25, 21, 30, 16, 27, 24]. Print the highest, the lowest, the difference between them, the average (one decimal place) and the day number (1–7) of the highest.

پلەی گەرمیی نیوەڕۆی هەفتەیەک بریتییە لە [18, 25, 21, 30, 16, 27, 24]. بەرزترین، نزمترین، جیاوازیی نێوانیان، تێکڕا (بە یەک ژمارە دوای خاڵ) و ژمارەی ڕۆژی ⁦(1–7)⁩ بەرزترین چاپ بکە.

Hintئاماژە

max, min, sum, len, round and index are enough.

max، min، sum، len، round و index بەسن.

Show answerوەڵامەکە پیشان بدە
ex1_temperatures.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
temps = [18, 25, 21, 30, 16, 27, 24]
print("highest:", max(temps), "lowest:", min(temps))
print("range:", max(temps) - min(temps))
print("average:", round(sum(temps) / len(temps), 1))
print("day of the highest:", temps.index(max(temps)) + 1)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 5

index gives 0–6; add 1 for a day number.

index ⁦0–6⁩ دەدات؛ 1 زیاد بکە بۆ ژمارەی ڕۆژ.

Exerciseڕاهێنان2. The three best marks2. سێ باشترین نمرە

Print the three highest marks of [55, 91, 78, 64, 88, 70, 95], largest first, without changing the list.

سێ بەرزترین نمرەی [55, 91, 78, 64, 88, 70, 95] چاپ بکە، گەورەترین یەکەم، بەبێ گۆڕینی .

Hintئاماژە

sorted does not change the list; then take a slice.

sorted ناگۆڕێت؛ پاشان بە یەکەم سێیان وەربگرە.

Show answerوەڵامەکە پیشان بدە
ex2_top_three.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
marks = [55, 91, 78, 64, 88, 70, 95]
top = sorted(marks, reverse=True)[:3]
print("top three:", top)
print("marks unchanged:", marks)
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 2

sorted(…, reverse=True) makes a new list; the slice [:3] keeps its first three items.

sorted(…, reverse=True) نوێ دروست دەکات؛ [:3] یەکەم سێ دەهێڵێتەوە.

Exerciseڕاهێنان3. Selection sort, largest first3. ڕیزکردن بە هەڵبژاردن، گەورەترین یەکەم

Change selection_sort so that it sorts in descending order. Which single comparison must change?

selection_sort بگۆڕە بۆ ئەوەی بە ڕیز بکات. کام یەک بەراورد دەبێت بگۆڕدرێت؟

Show answerوەڵامەکە پیشان بدە
ex3_selection_desc.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def selection_sort_desc(values):
    n = len(values)
    for start in range(n - 1):
        max_position = start
        for j in range(start + 1, n):
            if values[j] > values[max_position]:    # > instead of <
                max_position = j
        values[start], values[max_position] = values[max_position], values[start]

nums = [4, 7, 8, 4, -2, 7, 0, 8, 4]
selection_sort_desc(nums)
print(nums)

Search for the largest of the unsorted part instead of the smallest: > instead of <. (Renaming min_position to max_position only keeps the code honest.)

لەبری بچووکترین، بەدوای گەورەترینی بەشە ڕیزنەکراوەکەدا بگەڕێ: > لەبری <. (گۆڕینی ناوی min_position بۆ max_position تەنها کۆدەکە ڕاستگۆ دەهێڵێتەوە.)

Exerciseڕاهێنان4. The second-largest mark, in one pass4. دووەم بەرزترین نمرە، بە یەک گەڕان

Write second_largest(values), which returns the second-largest different value of a list without sorting it: walk through the list only once and keep two variables, first and second. Test it on [55, 91, 78, 64, 88, 70, 95], on [7, 7, 3] and on [4], which has no second value (return None).

second_largest(values) بنووسە کە دووەم گەورەترین (جیاواز لە گەورەترین) دەگەڕێنێتەوە بەبێ : تەنها یەکجار بەسەر بڕۆ و دوو ڕابگرە، first و second. لەسەر [55, 91, 78, 64, 88, 70, 95]، [7, 7, 3] و [4] تاقی بکەرەوە؛ [4] هیچ دووەمی نییە (None بگەڕێنەوە).

Hintئاماژە

When a new largest value comes, the old largest becomes the second. A value between the two replaces only second.

کاتێک گەورەتر لە first دێت، گەورەترینی پێشوو دەبێتە دووەم. لە نێوان ئەو دووانەدا تەنها جێگەی second دەگرێتەوە.

Show answerوەڵامەکە پیشان بدە
ex4_second_largest.pyPYTHONType in a terminalلە تێرمیناڵدا بینووسە
def second_largest(values):
    first = second = None            # nothing seen yet
    for v in values:
        if first is None or v > first:
            second = first           # the old best moves down to second place
            first = v
        elif v < first and (second is None or v > second):
            second = v
    return second

marks = [55, 91, 78, 64, 88, 70, 95]
print(max(marks), second_largest(marks))
print(second_largest([7, 7, 3]))
print(second_largest([4]))
Explain the codeڕوونکردنەوەی کۆدەکە
Lineدێڕی 4-6

A new largest value: the old first moves down into second.

گەورەترینێکی نوێ: firstـی پێشوو دادەبەزێت بۆ second.

Lineدێڕی 7-8

v < first skips a copy of the largest value, so [7, 7, 3] gives 3, not 7.

v < first کۆپییەکی گەورەترین پشتگوێ دەخات، بۆیە [7, 7, 3] ئەنجامی 3 دەدات، نەک 7.

Trace for the marks listبەدواداچوون بۆ نمرەکان
vfirstsecond
5555None
919155
789178
649178
889188
709188
959591

One pass looks at every value only once. Sorting first (sorted(set(values))[-2]) also works when the list has at least two different values, but sorting does much more work.

یەک گەڕان سەیری هەر تەنها یەکجار دەکات. لە سەرەتاوە (sorted(set(values))[-2])ـیش کار دەکات کاتێک لانیکەم دوو جیاوازی تێدابێت، بەڵام کاری زۆر زیاتر دەکات.

Quick checkپشکنینی خێراWhich tool would you use to get the sorted marks and keep the original order in marks?کام ئامراز بەکار دەهێنیت بۆ وەرگرتنی نمرە ڕیزکراوەکان و پاراستنی ڕیزبەندییە سەرەتاییەکە لە marksـدا؟

Summaryپوختە

  • sum, max and min give the total, largest and smallest of a list; max/min of an empty list is a ValueError unless you give default=.
  • Average = sum(values) / len(values); round it for people with round(x, 2).
  • To know where the smallest or largest is, scan with "best so far" variables — and give the position variables a starting value.
  • sorted(x) returns a new sorted list; x.sort() sorts x in place and returns None. Both take reverse=True and key=.
  • Selection sort: repeatedly select the smallest of the unsorted part and swap it into place — about n22\frac{n^2}{2} comparisons, fine for learning, too slow for big lists.
  • To collect all matches, append them to an empty list (or use a list comprehension); len(result) counts them.
  • sum، max و min کۆی گشتی، گەورەترین و بچووکترینی دەدەن؛ max/minـی بەتاڵ ValueErrorـە مەگەر default= بدەیت.
  • تێکڕا = sum(values) / len(values)؛ بۆ خەڵک بە round(x, 2) نزیکی بکەرەوە.
  • بۆ زانینی شوێنی بچووکترین یان گەورەترین، بە «باشترین تا ئێستا» بگەڕێ — و سەرەتایی بدە بە شوێن.
  • sorted(x) نوێی ڕیزکراو دەگەڕێنێتەوە؛ x.sort() x لە شوێنی خۆیدا ڕیز دەکات و None دەگەڕێنێتەوە. هەردووکیان reverse=True و key= وەردەگرن.
  • : بە دووبارە بچووکترینی بەشە ڕیزنەکراوەکە هەڵبژێرە و بیخەرە شوێنی خۆی — نزیکەی n22\frac{n^2}{2} بەراورد، بۆ فێربوون باشە، بۆ گەورە زۆر خاوە.
  • بۆ کۆکردنەوەی هەموو ئەوانەی دەگونجێن، بە append بیانخە ناو بەتاڵ (یان بەکار بهێنە)؛ len(result) دەیانژمێرێت.
Review questionsپرسیارەکانی پێداچوونەوە
Why does print(mylist.sort()) print None?بۆچی print(mylist.sort()) None چاپ دەکات؟

sort() changes the list in place and returns None on purpose, so you do not mistake it for a new list. Print mylist after sorting, or print sorted(mylist).

sort() لە شوێنی خۆیدا دەگۆڕێت و بە مەبەست None دەگەڕێنێتەوە، بۆ ئەوەی بە نوێی تێنەگەیت. دوای mylist چاپ بکە، یان sorted(mylist) چاپ بکە.

When should the "best so far" start at None?کەی دەبێت «باشترین تا ئێستا» بە None دەست پێ بکات؟

When the first element may not qualify, for example when you want the smallest even number and the first number is odd.

کاتێک لەوانەیە یەکەم پڕ نەکاتەوە، بۆ نموونە کاتێک بچووکترین ژمارەی جووتت دەوێت و یەکەم ژمارە تاکە.

Why learn selection sort if Python has sort()?بۆچی ڕیزکردن بە هەڵبژاردن فێر ببین ئەگەر Python sort()ـی هەیە؟

It shows what sorting really involves — comparing and swapping — and it practises loops, indexes and swaps. In real programs use sort() or sorted().

پیشان دەدات بە ڕاستی چی تێدایە — بەراوردکردن و ئاڵوگۆڕ — و ڕاهێنانە لەسەر ، و ئاڵوگۆڕ. لە ڕاستەقینەدا sort() یان sorted() بەکار بهێنە.

Next: tables of data stored as lists of rows, in Two-dimensional lists.

داهاتوو: خشتەی کە وەک لە هەڵدەگیرێت، لە لیستە دووڕەهەندەکان.

Videoڤیدیۆ

Watch a videoسەیری ڤیدیۆیەک بکە

A video that viewers liked a lot and praised in their comments, chosen for this lesson.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.

Python Tutorial for Beginners 4: Lists, Tuples, and SetsCorey Schafer · Englishئینگلیزی · 1.8M viewsبینین · 43K likesلایک · Partبەشی 10:10–14:17 (ofلە 29:04)

Negative indexes count from the end of a list; tuples are lists you cannot change; sets keep different values, unordered, with fast membership tests.

لە کۆتایی دەژمێرن؛ وەک ، بەڵام ناگۆڕدرێن؛ جیاواز بەبێ ڕیزبەندی هەڵدەگرن و بە خێرایی دەزانیت تێیاندایە یان نا.

Watch 10:10–14:17, 'Sorting Lists': sort(), sort(reverse=True), sorted(), and min(), max() and sum().

لە ⁦10:10⁩ تا ⁦14:17⁩ سەیر بکە، بەشی Sorting Lists: sort()، sort(reverse=True)، sorted()، هەروەها min()، max() و sum().

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

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

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

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

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

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

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