-
Notifications
You must be signed in to change notification settings - Fork 0
Lesson7 #7
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: Lesson6
Are you sure you want to change the base?
Lesson7 #7
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| # Это просто материал урока, не дз | ||
| import random | ||
|
|
||
| # Генерация массива размера SIZE с числами в диапазоне от MIN до MAX | ||
| def ar_gen(SIZE, MIN, MAX): | ||
| array = [] | ||
| for _ in range(SIZE): | ||
| array.append(random.randint(MIN, MAX)) | ||
| return array | ||
|
|
||
| def sel_sort(array): | ||
| for i in range(len(array)): | ||
| min_pos = i | ||
| for j in range(i + 1, len(array)): | ||
| if array[j] < array[min_pos]: | ||
| min_pos = j | ||
|
|
||
| array[i], array[min_pos] = array[min_pos], array[i] | ||
|
|
||
| def ins_sort(array): | ||
| for i in range(1, len(array)): | ||
| spam = array[i] | ||
| j = i | ||
| while array[j - 1] > spam and j > 0: | ||
| array[j] = array[j - 1] | ||
| j -= 1 | ||
| array[j] = spam | ||
|
|
||
| def quick_sort(array, fst, lst): | ||
| if fst >= lst: | ||
| return | ||
|
|
||
| pivot = array[random.randint(fst, lst)] | ||
| i, j = fst, lst | ||
|
|
||
| while i <= j: | ||
| while array[i] < pivot: | ||
| i += 1 | ||
|
|
||
| while array[j] > pivot: | ||
| j -= 1 | ||
|
|
||
| if i <= j: | ||
| array[i], array[j] = array[j], array[i] | ||
| i, j = i + 1, j - 1 | ||
|
|
||
| quick_sort(array, fst, j) | ||
| quick_sort(array, i, lst) | ||
|
|
||
| def quick_sort_2(array): | ||
| if len(array) <= 1: | ||
| return array | ||
|
|
||
| pivot = random.choice(array) | ||
| small = [] | ||
| medium = [] | ||
| large = [] | ||
|
|
||
| for item in array: | ||
| if item < pivot: | ||
| small.append(item) | ||
| elif item > pivot: | ||
| large.append(item) | ||
| else: | ||
| medium.append(item) | ||
|
|
||
| return quick_sort_2(small) + medium + quick_sort_2(large) | ||
|
|
||
| array = ar_gen(10, 0, 10) | ||
| new = quick_sort_2(array) | ||
| print(new) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| # Отсортировать по убыванию методом «пузырька» одномерный целочисленный массив, заданный случайными числами | ||
| # на промежутке [-100; 100). Вывести на экран исходный и отсортированный массивы. | ||
| import random | ||
|
|
||
| # Генерация массива размера SIZE с числами в диапазоне от MIN до MAX | ||
| def ar_gen(SIZE, MIN, MAX): | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. аргументы функции пишите строчными буквами. Они не могут быть константами по определению. |
||
| array = [] | ||
| for _ in range(SIZE): | ||
| array.append(random.randint(MIN, MAX)) | ||
| return array | ||
|
|
||
| # Функция сортировки массива | ||
| def bubble_sort(array): | ||
| n = 0 | ||
| while n < len(array): | ||
| subcount = 0 | ||
| if n % 2 == 0: | ||
| for i in range(len(array) - 1): | ||
| if array[i] > array[i + 1]: | ||
| array[i], array[i + 1] = array[i + 1], array[i] | ||
| subcount += 1 | ||
| else: # Добавляем обратный проход для ускорения "всплытия" :) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Это называется шейкерная сортировка. |
||
| i = len(array) - 1 | ||
| while i > 0: | ||
| if array[i] < array[i - 1]: | ||
| array[i], array[i - 1] = array[i - 1], array[i] | ||
| subcount += 1 | ||
| i -= 1 | ||
| if subcount == 0: # Добавляем проверку на число перестановок за проход | ||
| print(f'Cycles: {n}') # Выводим число итоговое число проходов | ||
| break | ||
| n += 1 | ||
|
|
||
| array = ar_gen(1000, -100, 100) | ||
| print(array) | ||
| bubble_sort(array) | ||
| print(array) | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,45 @@ | ||
| # Отсортируйте по возрастанию методом слияния одномерный вещественный массив, заданный случайными числами | ||
| # на промежутке [0; 50). Выведите на экран исходный и отсортированный массивы. | ||
| import random | ||
|
|
||
| def ar_gen(SIZE, MIN, MAX): | ||
| array = [] | ||
| for _ in range(SIZE): | ||
| #array.append(random.randint(MIN, MAX)) | ||
| array.append(random.uniform(MIN, MAX)) | ||
| return array | ||
|
|
||
| def merge(left, right): | ||
| result = [] | ||
| while len(left) != 0 and len(right) != 0: | ||
| if left[0] < right[0]: | ||
| result.append(left[0]) | ||
| left.remove(left[0]) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Алгоритм верный. |
||
| else: | ||
| result.append(right[0]) | ||
| right.remove(right[0]) | ||
| if len(left) == 0: | ||
| result += right | ||
| else: | ||
| result += left | ||
| return result | ||
|
|
||
| def merge_sort(array): | ||
| if len(array) <= 1: | ||
| return array | ||
| else: | ||
| left = [] | ||
| right = [] | ||
| for i in range(0, len(array) // 2): | ||
| left.append(array[i]) | ||
| for i in range(len(array) // 2, len(array)): | ||
| right.append(array[i]) | ||
| left = merge_sort(left) | ||
| right = merge_sort(right) | ||
| return merge(left, right) | ||
|
|
||
| array = ar_gen(10, 0, 50) | ||
|
|
||
| print(array) | ||
| print(merge_sort(array)) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| # Массив размером 2m + 1, где m – натуральное число, заполнен случайным образом. Найти в массиве медиану. | ||
| # Медианой называется элемент ряда, делящий его на две равные части: в одной находятся элементы, которые | ||
| # не меньше медианы, в другой – не больше ее. | ||
| # Задачу можно решить без сортировки исходного массива. | ||
| # Но если это слишком сложно, то используйте метод сортировки, который не рассматривался на уроках. | ||
| import random | ||
|
|
||
| def ar_gen(SIZE, MIN, MAX): | ||
| array = [] | ||
| for _ in range(SIZE): | ||
| array.append(random.randint(MIN, MAX)) | ||
| #array.append(random.uniform(MIN, MAX)) | ||
| return array | ||
|
|
||
| def find_med(array): | ||
| source = array.copy() | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Кроме сложности по времени решили добавить сложность по памяти. |
||
| result = [] | ||
| i = len(source) - 1 | ||
| while i > -1: | ||
| pointer = i | ||
| for j in range(0,len(source)): | ||
| if source[j] < source[pointer]: | ||
| pointer = j | ||
| result.append(source[pointer]) | ||
| source.remove(source[pointer]) | ||
| i -= 1 | ||
| answer = len(result) // 2 | ||
| return result[answer] | ||
|
|
||
| array = ar_gen(7, 0, 10) | ||
| print(array) | ||
| print(find_med(array)) | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Не буду его проверять )))