Informatics 9. Билингвальный учебник - [13]

Шрифт
Интервал

print(sorted(pyTuple))

Output

[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]

[‘P’, ‘h’, ‘n’, ‘o’, ‘t’, ‘y’]

[‘a’, ‘e’, ‘i’, ‘o’, ‘u’]


Bubble sort in python

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.


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.

A del keyword can be used to delete list elements as well. In the example below, we have a list of strings. We use the del keyword to delete list elements.


Example 4

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

print(clrs)

del clrs[1]

print(clrs)

Output

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

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

We remove the second string from the list. It is the “Blue” string.


Example 5

del clrs[:]

print(clrs)

Output

[]

Here we remove all the remaining elements from the list. The [ : ] characters refer to all items of a list.


Practice 2

1. Create and initialize a list;

2. Enter random 10 numbers into the list;

3. Remove 5 elements using different methods of removing;


Practice 3

There was a mistake! The amount of money you’ve earned is not that big after all and it looks like the pool house isn’t going to happen. You decide to remove the corresponding string and float from the areas list.

areas = [“hallway”, 11.25, “kitchen”, 18.0, “chill zone”, 20.0, “bedroom”, 10.75, “bathroom”, 10.50, “poolhouse”, 24.5, “garage”, 15.45]


Keep in mind

We can delete only existing elements. If we write del clrs[15], we will receive an IndexError message.


Literacy

1. Explain the differences between pop(), remove(), del and [ : ]?

2. What would happen if write pop() with the same index?

3. What would happen if we try to delete an item that doesn’t exist?


Terminology

remove – алып тастау – удалить

alphabetize – əліпбилік ретпен қою – располагать по алфавиту

corresponding – сəйкес келетін – соответствующий


3.7 TWO-DIMENSIONAL LIST IN PYTHON

You will:

create two-dimensional array in python;

use two-dimensional array.


In real-world often tasks have to store rectangular data table. How to write them in python list?

Список вложенный в список

Вы уже видели, что элемент в списке может быть объектом любого типа. Объект в списке также может иметь отдельный список, и элементы в этом списке тоже могут отдельным списком итд.


Example 1

>>> x = [‘a’, [‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff ’], ‘g’, [‘hh’, ‘ii’], ‘j’]

>>> x

[‘a’, [‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff ’], ‘g’, [‘hh’, ‘ii’], ‘j’]

The object structure that x references is diagrammed below:

x[0], x[2], and x[4] are strings, each one character long:

>>> print(x[0], x[2], x[4])

a g j

But x[1] and x[3] are sublists:

>>> x[1]


[‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff ’]

>>> x[3]

[‘hh’, ‘ii’]