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 لەسەر ، ژمارەی جووت و تاک.
What you will learnچی فێر دەبیت
- Use
sum,max,minandlento get totals, extremes and averages, and handle empty lists. - Find the smallest and largest value and their positions with a loop, without the
NameErrortrap. - Choose between
sort()andsorted(), and usereverse=Trueandkey=. - 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).
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)The total = 27 The total = 27 The Maximum number = 9 The Minimum number = 1
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 3
sumadds all the items, from left to right, starting at 0.sumهەموو کۆ دەکاتەوە، لە چەپەوە بۆ ڕاست و لە 0ـەوە دەست پێ دەکات.- Lineدێڕی 5
You can use the result directly, without a variable.
دەتوانیت ئەنجامەکە ڕاستەوخۆ بەکار بهێنیت، بەبێ .
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= بدەیت.
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 errorpear apple
0
0
Traceback (most recent call last):
File "strings_and_empty.py", line 6, in <module>
print(max([])) # no default: an error
^^^^^^^
ValueError: max() iterable argument is emptyLab: sum and averageتاقیگە: کۆ و تێکڕا
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.
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وەڵامەکە پیشان بدە
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))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
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ێکی نووسراو: ئەگەر گەورە بوو، تێکڕاکە هەر دروست دەمێنێتەوە.
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() و 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))Please enter element length in list : 5 Please enter the Value of Element : 3 Please enter the Value of Element : 6 Please enter the Value of Element : 7 Please enter the Value of Element : 2 Please enter the Value of Element : 9 The Smallest Element in this List is : 2 The Largest Element in this List is : 9
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
int(input(...))turns the typed text into a whole number.int(input(...))دەقە نووسراوەکە دەکات بە .- Lineدێڕی 3
range(1, count + 1)runscounttimes.range(1, count + 1)ژمارەیcountجار دەخولێتەوە.
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 دەدەن، بەڵام نەک شوێنەکەی. بۆ ئەوەی شوێنەکەشی بزانیت، خۆت بەسەر بڕۆ. دوو ڕابگرە: «بچووکترین تا ئێستا» و «گەورەترین تا ئێستا». بە یەکەم دەستیان پێ بکە، پاشان یەکجار سەردانی هەموو تر بکە و هەر کاتێک شتێکی باشترت بینی نوێ بکەرەوە.
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 هەرزانتر نییە). هەروەها دەبێت شوێنەکە هەر لە یەکەم دوکانەوە لە بیر بگریت، دەنا ئەگەر یەکەم دوکان خۆی هەرزانترین بوو هیچ شوێنێکت نییە بیڵێیت. خوارەوە ڕێک ئەوە لە بیر دەکات.
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)How many element in list? 5 Please enter the Value of Element : 6 Please enter the Value of Element : 8 Please enter the Value of Element : 1 Please enter the Value of Element : 7 Please enter the Value of Element : 5 The Smallest Element in this List is : 1 The Index position of Smallest Element in this List is : 2 The Largest Element in this List is : 8 The Index position of Largest Element in this List is : 1
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
smallestandlargest.لە 1ـەوە دەست پێ دەکات: 0 پێشتر لە
smallestوlargestـدایە.- Lineدێڕی 10-11
A smaller value replaces
smallest, and its index is remembered.بچووکتر جێگەی
smallestدەگرێتەوە و لە بیر دەگیرێت.
jj | NumList[j]NumList[j] | smallest (position)smallest (شوێن) | largest (position)largest (شوێن) |
|---|---|---|---|
| startسەرەتا | 6 | 6 (not set)6 (دانەنراوە) | 6 (not set)6 (دانەنراوە) |
| 1 | 8 | 6 | 8 (1) |
| 2 | 1 | 1 (2) | 8 (1) |
| 3 | 7 | 1 (2) | 8 (1) |
| 4 | 5 | 1 (2) | 8 (1) |
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) ئەو ناوە بوونی نییە:
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)How many element in list? 3
Please enter the Value of Element : 1
Please enter the Value of Element : 5
Please enter the Value of Element : 3
The Smallest Element in this List is : 1
Traceback (most recent call last):
File "min_max_loop_bug.py", line 17, in <module>
print("The Index position of Smallest Element in this List is : ", min_position)
^^^^^^^^^^^^
NameError: name 'min_position' is not defined. Did you mean: 'max_position'?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)How many element in list? 3 Please enter the Value of Element : 1 Please enter the Value of Element : 5 Please enter the Value of Element : 3 The Smallest Element in this List is : 1 The Index position of Smallest Element in this List is : 0 The Largest Element in this List is : 5 The Index position of Largest Element in this List is : 1
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 یەکەم شوێنی.
values = [1, 5, 3]
print(min(values), values.index(min(values)))
print(max(values), values.index(max(values)))1 0 5 1
Lab: smallest and largest even numberتاقیگە: بچووکترین و گەورەترین ژمارەی جووت
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 تاقی بکەرەوە.
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وەڵامەکە پیشان بدە
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)enter a number : 45 enter a number : 78 enter a number : 77 enter a number : 98 enter a number : 3 enter a number : 17 enter a number : 36 enter a number : 8 enter a number : 17 enter a number : 55 The minimum even number = 8 its index = 7 The maximum even number = 98 its index = 3
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
The first element (45) is odd, so it cannot be the starting "best so far".
Nonemeans "nothing found yet".یەکەم (45) تاکە، بۆیە ناتوانێت «باشترین تا ئێستا»ی سەرەتا بێت.
Noneواتە «هێشتا هیچ نەدۆزراوەتەوە».- Lineدێڕی 8
% 2 == 0keeps only the even numbers.% 2 == 0تەنها ژمارە جووتەکان دەهێڵێتەوە.- Lineدێڕی 9
The first even number fills the empty
None; later ones must be smaller.یەکەم ژمارەی جووت
Noneـە بەتاڵەکە پڕ دەکاتەوە؛ ئەوانەی دواتر دەبێت بچووکتر بن.
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)[-2, 0, 4, 4, 4, 7, 7, 8, 8] [4, 7, 8, 4, -2, 7, 0, 8, 4]
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)None [-2, 0, 4, 4, 4, 7, 7, 8, 8]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
A classic mistake:
sort()returnsNone, sosort1isNone. The sorted numbers are inmylist.هەڵەیەکی باو:
sort()Noneدەگەڕێنێتەوە، بۆیەsort1دەبێتەNone. ژمارە ڕیزکراوەکان لەmylistـدان.
sorted() makes a new list; sort() changes the list and returns None.sorted() نوێ دروست دەکات؛ sort() دەگۆڕێت و None دەگەڕێنێتەوە.CêITsort() 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)[8, 8, 7, 7, 4, 4, 4, 0, -2] [4, 7, 8, 4, -2, 7, 0, 8, 4]
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)None [8, 8, 7, 7, 4, 4, 4, 0, -2]
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= وەردەگرن.
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['Dilan', 'Shilan', 'aram', 'karwan'] ['aram', 'Dilan', 'karwan', 'Shilan'] ['fig', 'pear', 'kiwi', 'banana'] banana
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
Upper-case letters come before lower-case ones, so
DilanandShilancome first.پیتە گەورەکان پێش پیتە بچووکەکان دێن، بۆیە
DilanوShilanیەکەم دێن.- Lineدێڕی 6
pearandkiwiboth have 4 letters and keep their original order: Python's sort is a stable sort (why that matters).pearوkiwiهەردووکیان 4 پیتن و ڕیزبەندییە سەرەتاییەکەیان دەپارێزن: (بۆچی گرنگە).
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 و بەم شێوەیە. دوای هەر جارێک بەشی سەرەتای ڕیزکراوە و چیتر دەستی لێ نادرێت.
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 comparisons, so it is slow for big lists, but it is easy to follow by hand.
سادەی : بچووکترین بەشە ڕیزنەکراوەکە بدۆزەرەوە، بیگوازەرەوە بۆ سەرەتای ئەو بەشە و بۆ ئەوەی ماوەتەوە دووبارەی بکەرەوە. نزیکەی بەراورد پێویست دەکات، بۆیە بۆ گەورە خاوە، بەڵام بە دەست بەدواداچوونی ئاسانە.
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)pass 1: [-2, 7, 8, 4, 4, 7, 0, 8, 4] pass 2: [-2, 0, 8, 4, 4, 7, 7, 8, 4] pass 3: [-2, 0, 4, 8, 4, 7, 7, 8, 4] pass 4: [-2, 0, 4, 4, 8, 7, 7, 8, 4] pass 5: [-2, 0, 4, 4, 4, 7, 7, 8, 8] pass 6: [-2, 0, 4, 4, 4, 7, 7, 8, 8] pass 7: [-2, 0, 4, 4, 4, 7, 7, 8, 8] pass 8: [-2, 0, 4, 4, 4, 7, 7, 8, 8] [-2, 0, 4, 4, 4, 7, 7, 8, 8]
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
startto 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].](/_astro/py-list-functions-and-sorting-selection-sort.en.DihMGBrd.gif)
![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].](/_astro/py-list-functions-and-sorting-selection-sort.ckb.Bis29Pc5.gif)
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.
مامۆستا بە یەک سەیرکردن هەموو پۆلەکە دەبینێت. کۆمپیوتەر لە هەر جارێکدا تەنها دەتوانێت دوو بەراورد بکات، بۆیە دەبێت لە هەموو جارێکدا سەیری هەموو بەشە ڕیزنەکراوەکە بکات.
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 values the first pass compares pairs, the next , and so on down to 1:
ئەمە چەند کارە؟ بۆ یەکەم جار جووت بەراورد دەکات، دواتر و بەم شێوەیە تا 1:
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.
ژماردنی هەنگاوەکان بەم شێوەیە ئەو ڕێگەیەیە کە بەرنامەسازەکان پێ بەراورد دەکەن (بەراوردکردنی ئەلگۆریزمەکان). دوو تری ( و ) و ئەوەی ئەم ژمارانە بۆ گەورە دەیگەیەنن، لە ڕیزکردنی بڵقی، ڕیزکردن بە تێخستن و خێرایی ڕیزکردن دێن.
Lab: descending order and the odd numbersتاقیگە: ڕیزی نزمبوونەوە و ژمارە تاکەکان
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 تاقی بکەرەوە.
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وەڵامەکە پیشان بدە
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.")enter number 45 enter number 32 enter number 67 enter number 91 enter number 0 enter number 17 enter number 91 enter number 84 enter number 3 enter number 72 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
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4
sorted(..., reverse=True)prints a sorted copy;numberskeeps the typed order.sorted(..., reverse=True)کۆپییەکی ڕیزکراو چاپ دەکات؛numbersڕیزبەندیی نووسراوەکە دەپارێزێت.- Lineدێڕی 6-9
Collect the odd numbers in a new list:
n % 2 == 1means the remainder after dividing by 2 is 1.ژمارە تاکەکان لە نوێدا کۆ بکەرەوە:
n % 2 == 1واتە دوای دابەشکردن بەسەر 2دا 1ـە.- Lineدێڕی 11
If no odd number was typed,
oddsis empty andmin(odds)would crash.if odds:isFalsefor 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 زیادی بکە. کە هەر جارێک یەکێک زیاد دەبێت پێت دەڵێت چەندن.
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)The number of elements greater than 0 is 7 Which are : [4, 7, 8, 4, 7, 8, 4]
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 nextprinton 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، پەیامەکە درۆ دەکات. لەبری ئەوە لە ناو دەقەکەدا بەکار بهێنە:
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}")4 elements are greater than 5: [7, 8, 7, 8]
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 دەکات.
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[7, 8, 7, 8] [7, 7]
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تاقیگە: ژمارە هەڕەمەکییەکان و جووتەکانیان
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وەڵامەکە پیشان بدە
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()The list of all random elements with its index no. 0 = 23 1 = 29 2 = 28 3 = 22 4 = 25 5 = 29 6 = 27 7 = 30 8 = 29 9 = 21 The list of all even numbers in the list with its index no. 2 = 28 3 = 22 7 = 30
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 indexi % 2 == 0would give the elements at even positions instead.تاقی بکەرەوە:
numbers[i] % 2 == 0. تاقیکردنەوەیi % 2 == 0لەبری ئەوە شوێنە جووتەکان دەدات.
A solved quiz: counting, filtering, sortingتاقیکردنەوەیەکی چارەسەرکراو: ژماردن، پاڵاوتن، ڕیزکردن
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):
ڕەسەنەکە (وەک ڕادەست کراوە):
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وەڵامەکە پیشان بدە
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)Enter an integer: 3 Enter an integer: 8 Enter an integer: 15 Enter an integer: 5 Enter an integer: 12 Enter an integer: 20 Enter an integer: 7 Enter an integer: 14 Enter an integer: 1 Enter an integer: 6 The list: [3, 8, 15, 5, 12, 20, 7, 14, 1, 6] Number of elements between 5 and 15 is 6 which are: [8, 5, 12, 7, 14, 6] Numbers of even elements is 5 which are: [6, 8, 12, 14, 20]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 9-12
This inner loop compares
awith 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 بنووسە. دەقی ئەرکەکە بڕیار دەدات؛ کاتێک ڕوون نییە بپرسە.
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)Enter an integer: 3 Enter an integer: 8 Enter an integer: 15 Enter an integer: 5 Enter an integer: 12 Enter an integer: 20 Enter an integer: 7 Enter an integer: 14 Enter an integer: 1 Enter an integer: 6 The list: [3, 8, 15, 5, 12, 20, 7, 14, 1, 6] Number of elements between 5 and 15 is 6 which are: [8, 5, 12, 7, 14, 6] Number of even elements is 5 which are: [6, 8, 12, 14, 20]
Common mistakesهەڵە باوەکان
| Mistakeهەڵە | What happensچی ڕوو دەدات | Fixچارەسەر |
|---|---|---|
x = mylist.sort() | x is Nonex دەبێتە None | mylist.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دەستپێکردنی «بچووکترین تا ئێستا» بە 0 | wrong 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 == 0 | tests the index, not the value تاقی دەکاتەوە، نەک | numbers[i] % 2 == 0 |
Exercisesڕاهێنانەکان
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وەڵامەکە پیشان بدە
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)highest: 30 lowest: 16 range: 14 average: 23.0 day of the highest: 4
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 5
indexgives 0–6; add 1 for a day number.index0–6 دەدات؛ 1 زیاد بکە بۆ ژمارەی ڕۆژ.
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وەڵامەکە پیشان بدە
marks = [55, 91, 78, 64, 88, 70, 95]
top = sorted(marks, reverse=True)[:3]
print("top three:", top)
print("marks unchanged:", marks)top three: [95, 91, 88] marks unchanged: [55, 91, 78, 64, 88, 70, 95]
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 2
sorted(…, reverse=True)makes a new list; the slice[:3]keeps its first three items.sorted(…, reverse=True)نوێ دروست دەکات؛[:3]یەکەم سێ دەهێڵێتەوە.
Change selection_sort so that it sorts in descending order. Which single comparison must change?
selection_sort بگۆڕە بۆ ئەوەی بە ڕیز بکات. کام یەک بەراورد دەبێت بگۆڕدرێت؟
Show answerوەڵامەکە پیشان بدە
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)[8, 8, 7, 7, 4, 4, 4, 0, -2]
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 تەنها کۆدەکە ڕاستگۆ دەهێڵێتەوە.)
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وەڵامەکە پیشان بدە
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]))95 91 3 None
Explain the codeڕوونکردنەوەی کۆدەکە
- Lineدێڕی 4-6
A new largest value: the old
firstmoves down intosecond.گەورەترینێکی نوێ:
firstـی پێشوو دادەبەزێت بۆsecond.- Lineدێڕی 7-8
v < firstskips a copy of the largest value, so[7, 7, 3]gives 3, not 7.v < firstکۆپییەکی گەورەترین پشتگوێ دەخات، بۆیە[7, 7, 3]ئەنجامی 3 دەدات، نەک 7.
v | first | second |
|---|---|---|
| 55 | 55 | None |
| 91 | 91 | 55 |
| 78 | 91 | 78 |
| 64 | 91 | 78 |
| 88 | 91 | 88 |
| 70 | 91 | 88 |
| 95 | 95 | 91 |
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])ـیش کار دەکات کاتێک لانیکەم دوو جیاوازی تێدابێت، بەڵام کاری زۆر زیاتر دەکات.
Summaryپوختە
sum,maxandmingive the total, largest and smallest of a list;max/minof an empty list is aValueErrorunless you givedefault=.- Average =
sum(values) / len(values); round it for people withround(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()sortsxin place and returnsNone. Both takereverse=Trueandkey=.- Selection sort: repeatedly select the smallest of the unsorted part and swap it into place — about comparisons, fine for learning, too slow for big lists.
- To collect all matches,
appendthem 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=وەردەگرن.- : بە دووبارە بچووکترینی بەشە ڕیزنەکراوەکە هەڵبژێرە و بیخەرە شوێنی خۆی — نزیکەی بەراورد، بۆ فێربوون باشە، بۆ گەورە زۆر خاوە.
- بۆ کۆکردنەوەی هەموو ئەوانەی دەگونجێن، بە
appendبیانخە ناو بەتاڵ (یان بەکار بهێنە)؛len(result)دەیانژمێرێت.
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.ڤیدیۆیەک کە بینەران زۆریان پێ خۆش بووە و لە کۆمێنتەکانیاندا ستایشیان کردووە، بۆ ئەم وانەیە هەڵبژێردراوە.
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زاراوە سەرەکییەکان
Two-Dimensional Listsلیستە دووڕەهەندەکان
Related lecturesوانە پەیوەندیدارەکان
- Logical Operators and Nested ifکارپێکەرە لۆجیکییەکان و ڕستەی ifـی ناوەکی
- Working with Stringsکارکردن لەگەڵ زنجیرەنووسەکان
- Processing Two-Dimensional Listsکارکردن لەسەر لیستە دووڕەهەندەکان
- Priority Queues and Heapsکیووە پێشینەییەکان و هیپەکان
- Bubble Sort, Insertion Sort and How Fast Sorting Isڕیزکردنی بڵقی، ڕیزکردن بە تێخستن و خێرایی ڕیزکردن
References and further readingسەرچاوەکان و خوێندنەوەی زیاتر
- Python built-in functions: sum(), max(), min(), sorted(), len()
- Python Sorting Techniques (HOWTO): sort vs sorted, key functions, reverse, stability, Timsort
- Python tutorial 5.1: More on lists (list.sort, list.index), 5.1.3 list comprehensions
- Python Standard Library: random (randint includes both ends)
- Python language reference: comparisons (chained comparisons)
- Selection sort (algorithm, number of comparisons and swaps)
- Python tutorial 15: Floating-point arithmetic — issues and limitations
This lecture is a first edition. The Kurdish text and terminology are waiting for review by Kurdish IT teachers.ئەم وانەیە چاپی یەکەمە. دەقە کوردییەکە و زاراوەکانی چاوەڕێی پێداچوونەوەی مامۆستایانی کوردی بواری IT ن.