Skip to content
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

homework_lesson_7 #1845

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import timeit
import random


# 1 вариант
def bubble_sorting_1(lst):
for i in range(len(lst)-1, -1, -1):
for j in range(len(lst)-1, -1, -1):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
return lst


# 2 вариант
def bubble_sorting_2(lst):
attribute = False
for i in range(len(lst)-1, -1, -1):
for j in range(len(lst)-1, -1, -1):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
attribute = True
if attribute is False:
return lst
return lst


my_list = [random.randint(-100, 100) for _ in range(30)]


print('1 ВАРИАНТ')
print(f'Исходный массив: {my_list}')
print(f'Отсортированный массив: {bubble_sorting_1(my_list[:])}')
print(timeit.timeit("bubble_sorting_1(my_list[:])", globals=globals(), number=1000))
print()

print('2 ВАРИАНТ')
my_list = bubble_sorting_1(my_list[:])
print(f'Исходный массив: {my_list}')
print(f'Отсортированный массив: {bubble_sorting_2(my_list[:])}')
print(timeit.timeit("bubble_sorting_2(my_list[:])", globals=globals(), number=1000))
print()


'''
Вывод
Второй вариант выполняется быстрее. Моя доработка заключается в проверке ситуации
когда один из элементов не выполнил ни одну перестановку с другими элементами массива.
В такой ситуации attribute остается в значении False и сортировка прерывается.
'''
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено

Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import operator
import timeit
import numpy as np


def merge_sort(lst, compare=operator.lt):
if len(lst) < 2:
return lst[:]
else:
middle = int(len(lst) / 2)
left = merge_sort(lst[:middle], compare)
right = merge_sort(lst[middle:], compare)
return merge(left, right, compare)


def merge(left, right, compare):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while i < len(left):
result.append(left[i])
i += 1
while j < len(right):
result.append(right[j])
j += 1
return result


n = int(input('Введите количество элементов: '))
arr = np.random.uniform(0, 50, n)
print(arr)
print(merge_sort(arr))
arr = np.random.uniform(0, 50, 10) # 10 элементов 0.017962699999999998
print(f'10 элементов {timeit.timeit("merge_sort(arr[:])",globals=globals(),number=1000)}')
arr = np.random.uniform(0, 50, 100) # 100 элементов 0.22295299999999996
print(f'100 элементов {timeit.timeit("merge_sort(arr[:])",globals=globals(),number=1000)}')
arr = np.random.uniform(0, 50, 1000) # 1000 элементов 2.9044693
print(f'1000 элементов {timeit.timeit("merge_sort(arr[:])",globals=globals(),number=1000)}')

# Вывод:
# На большом количестве данных сортировка слиянием показывает достаточно высокие
# результаты, таким образом скорость уменьшается чуть больше чем на порядок,
# почти так же как и увеличивается кол-во данных.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

выполнено

Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import random
from statistics import median


def get_data_from_user() -> list:
while True:
el_count = input("Введите m: ")
print(el_count)
if el_count.isdigit():
el_count = int(el_count)
break
else:
print("Ввод неверный, повторите попытку")

return [random.randint(0, 50) for _ in range(2 * el_count + 1)]


orig_list = get_data_from_user()
med_index = orig_list
print("Оригинальный список: ")
print(*orig_list)

print("Медиана из модуля statistics(для проверки): ", median(orig_list))

[orig_list.remove(max(orig_list)) for _ in range(int(len(orig_list) / 2))]

print("Медиана полученная удалением максимальных элементов: ", max(orig_list))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

мы договорились сделать

  1. решение с сортировкой
  2. без нее
  3. встроенной функцией
  4. выполнить замеры и сделать аналитику результатов