Informatics 9. Билингвальный учебник | страница 26




Example 4

List = [64, 34, 25, 12, 22, 11, 90]

for i in range(n):

# Last i elements are already in place

for j in range(0, n-i-1):

# traverse the array from 0 to n-i-1

# Swap if the element found is greater than the next element

if List[j] > List[j+1]:

List[j], List[j+1] = List[j+1], List[j]

print(“Sorted array is:”)

print(List)

Output

Sorted array is:

[11, 12, 22, 25, 34, 64, 90]


Keep in mind

Iterable - sequence (string, tuple, list) or collection (set, dictionary, frozen set) or any iterator.


Keep in mind

Use list.sort() when you want to mutate the list, sorted() when you want a new sorted object back. For lists, list.sort() is faster than sorted() because it doesn’t have to create a copy.


Activity

Make small research about common sorting algorithms.


Literacy

1. Which method of sorting you usually use?

2. How often is sorting used in real life?


Terminology

sort – сұрыптау – сортировать

ascending – өсу тəртібі – по возрастанию

descending – кему тəртібі – по убыванию

reverse – кері – обратная

traverse – айналдыру – перемещать


3.6 REMOVING ELEMENTS FROM A LIST

You will:

Learn to swap elements in a list;

В наших предыдущих уроках мы добавляли элементы в список. Теперь мы будем удалить элемент из списка.

Мы используем функцию Pop (), чтобы удалить элемент из списка. Функция pop () удаляет элемент в указанном индексе или удаляет последний элемент, если индекс не указан.


Example 1

clrs = [“Red”, “Blue”, “Black”, “Green”, “White”]

print(clrs)

clr = clrs.pop(3)

print(“{0} was removed”.format(clr))

Output

[‘Red’, ‘Blue’, ‘Black’, ‘Green’, ‘White’]

Green was removed

Убираем элемент с индексом 3. Метод pop () возвращает значение удаленного элемента; выводим результат на экран.


Example 2

clr = clrs.pop()

print(“{0} was removed”.format(clr))

Output

White was removed

The last element from the list, namely “White” string, is removed from the list.

The remove() method removes a particular item from a list.


Example 3

clrs.remove(“Blue”)

print(clrs)

Output [‘Red’, ‘Black’] Practice 1 You’ve just earned 50 000 000 tenges, awesome! You decide to build a pool house and a garage. Can you add the information to the areas list?

areas=[“hallway”, 11.25, “kitchen”, 18.0, “chillzone”, 20.0, “bedroom”, 10.75, “bathroom”, 10.50 ]

Information: “poolhouse”, 24.5 “garage, 15.45

Example #3 removes a “Blue” string from the “clrs” list. From the output of the script we can see the effects of the described methods.