From f94d0aa917ef122adeea4d2143f9cfa697d0825c Mon Sep 17 00:00:00 2001 From: PeseC Date: Mon, 6 Mar 2023 23:00:40 +0400 Subject: [PATCH] commit 1 - Uploaded everything --- function.py | 182 ++++++++++++++++++++++++++++++++++++++++++++++++++++ rand.py | 48 ++++++++++++++ 2 files changed, 230 insertions(+) create mode 100644 function.py create mode 100644 rand.py diff --git a/function.py b/function.py new file mode 100644 index 0000000..5ed5236 --- /dev/null +++ b/function.py @@ -0,0 +1,182 @@ +from random import randint +from colorama import init, Fore +import numpy as np +import random +import os + +init(autoreset=True) + +# --------------------------заполнение-и-вывод-списка------------------------------------ + +def rand(): + range1 = int(input(Fore.GREEN + "Введите длинну списка: " + Fore.RESET)) + range2 = int(input(Fore.GREEN + "Введите предел чисел: " + Fore.RESET)) + massive = random.sample(range(0, range2), range1) + return massive + +def print_table(masive, num_cols): + massive = masive + num_rows = len(massive) // num_cols + (len(massive) % num_cols > 0) + for i in range(num_rows): + row = massive[i*num_cols:(i+1)*num_cols] + row += [''] * (num_cols - len(row)) # добавляем пустые элементы до num_cols + print((Fore.BLUE + '{:<7}' * num_cols).format(*row)) + +# -----------------------------вывод-графиков------------------------------------------ + +def real_graph(masive): #вещественный график=-=--=-=-=-=-=-= + massive = masive + max_height = max(massive) + length = len(massive) + for i in range(max_height, 0, -1): + for q in range(0, length): + if massive[q] >= i: + print(Fore.RED + "[]", end="") + else: + print(Fore.RED + " ", end="") + + print(' ', Fore.BLUE + str(i)) + +def percentage_graph(masive, max_or_mean): #процентный график=-=--=-=-=-=-=-= + massive = masive + + # нахождение высоты + max_height = max(massive) / 20 # делит таблицу на 20 частей по 5% + + # нахождение длинны + chunks = np.array_split(massive, 20)# Разбиваем массив на 20 частей + max_values = np.zeros(20)# Инициализируем массивы для хранения максимальных значений и их индексов + max_indices = np.zeros(20) + if max_or_mean == "arf": + means = [int(np.nanmean(chunk)) for chunk in chunks]# вычисляем среднее арифметическое каждого подсписка + elif max_or_mean == "max": + for i, chunk in enumerate(chunks): # Находим максимальное значение и его индекс в каждой части + if len(chunk) > 0: + max_index = np.argmax(chunk) + max_indices[i] = i*len(chunk) + max_index + else: + print(Fore.RED + "Приятель, делай выбор!") + return + + # строим график + for i in range(21, 0, -1): + index_height = int((max_height * i) - max_height) # создаёт индекс для сравнения высот + for q in range(0, 20): + if max_or_mean == "arf": + value = means[q] + elif max_or_mean == "max": + index_lenght = max_indices[q] # создаёт индекс длинны для сравненияс высотой + value = massive[int(index_lenght)] + if len(massive) > 0 and value >= index_height: + print(Fore.RED + "[]", end="") + else: + print(Fore.RED + " ", end="") + print(' ', Fore.BLUE + str((i-1)*5), Fore.BLUE + '%') + +# -----------------------------назначение-настроек---------------------------------------------- + +def graf(show_graph): # параметр базового вывода графика + while True: + if show_graph is not None: + print(Fore.GREEN + "Выводится ли график - ", Fore.BLUE + str(show_graph)) + else: + print(Fore.GREEN + "Выводится ли график - ", Fore.BLUE + "None") + show_graph = input(Fore.GREEN + "Строить график? - yes или no\n" + Fore.RESET) + if show_graph in ['yes', 'no']: + break + os.system("cls") + print(Fore.RED + "Приятель, делай выбор!") + return show_graph + +def type_graf(show_graph, max_or_mean): # параметр типа графика + if show_graph == 'yes': + while True: + if max_or_mean is not None: + print(Fore.GREEN + "Тип графика - ", Fore.BLUE + str(max_or_mean)) + else: + print(Fore.GREEN + "Тип графика - ", Fore.BLUE + "None") + max_or_mean = input(Fore.GREEN + "Строить график по арифметической сумме(arf)\nили высшим точкам(max)?\n" + Fore.RESET) + if max_or_mean in ['arf', 'max']: + break + os.system("cls") + print(Fore.RED + "Приятель, делай выбор!") + elif show_graph == 'no': + max_or_mean = 'arf' + return max_or_mean + +def num_column(num_cols): # параметр кол-ва столбцов таблице + while True: + try: + if num_cols is not None: + print(Fore.GREEN + "кол-во колнок - ", Fore.BLUE + str(num_cols)) + else: + print(Fore.GREEN + "кол-во колнок - ", Fore.BLUE + "None") + num_cols = int(input(Fore.GREEN + "Укажите кол-во колнок в таблиц\n(не больше 10) - \n" + Fore.RESET)) + except ValueError: + os.system("cls") + print(Fore.RED + "Приятель, числа надо вводить, ЧИСЛА!\nЗаново!") + continue + if 2 <= num_cols <= 10: + break + os.system("cls") + print(Fore.RED + "Приятель, не больше 10!") + return num_cols + +# -----------------------------menu-------------------------------------------------- + +def menu(show_graph, max_or_mean, num_cols): + while True: + os.system("cls") + menu = input( + Fore.GREEN + + "\nДля продолжения нажмите Enter.\nЕсли хотите изменить настройки введите change\nпосмотреть настройки - set\nЕсли хотите завершить работу введите end.\n\n " + + Fore.RED + ) + + match menu: + case "": + os.system("cls") + breaker = None + return breaker, show_graph, max_or_mean, num_cols + case "set": + setings(show_graph, max_or_mean, num_cols) + case "change": + show_graph, max_or_mean, num_cols = changes(show_graph, max_or_mean, num_cols) + case "end": + os.system("cls") + print( + Fore.GREEN + + "Спасибо за то, что воспользовались услугами\nкомпании ООО'Random'.\nС вас много деняг." + ) + breaker = False + return breaker, show_graph, max_or_mean, num_cols + case other: + pass + +def setings(show_graph, max_or_mean, num_cols): + while True: + os.system("cls") + print(Fore.GREEN + "Выводится ли график - ", Fore.BLUE + str(show_graph)) + print(Fore.GREEN + "Тип графика - ", Fore.BLUE + str(max_or_mean)) + print(Fore.GREEN + "кол-во колнок - ", Fore.BLUE + str(num_cols)) + menu = input(Fore.GREEN + "\nДля возвращения нажмите Enter. ") + break + +def changes(show_graph, max_or_mean, num_cols): + while True: + os.system("cls") + change = input( + Fore.GREEN + + "Если хотите выводить/не выводить график\nвведите graf\nЕсли хотите изменить тип графика\nвведите type\nЕсли хотите изменить кол-во столбцов\nвведите col\nЕсли хотите вернуться к работе то\nвведите cont\n" + + Fore.RED + ) + match change: + case "graf": + show_graph = graf(show_graph) + case "type": + max_or_mean = type_graf(show_graph, max_or_mean) + case "col": + num_cols = num_column(num_cols) + case "cont": + return show_graph, max_or_mean, num_cols + diff --git a/rand.py b/rand.py new file mode 100644 index 0000000..941fcc9 --- /dev/null +++ b/rand.py @@ -0,0 +1,48 @@ +from colorama import init, Fore +import os +import function + +init(autoreset=True) + +os.system("cls") + +masive = [] # инициализация основного масива + +show_graph = None # параметр базового вывода графика +show_graph = function.graf(show_graph) + +max_or_mean = None # параметр типа графика +max_or_mean = function.type_graf(show_graph, max_or_mean) + +num_cols = None # параметр кол-ва столбцов таблице +num_cols = function.num_column(num_cols) + +while True: + try: + masive = function.rand() # заполнение массива случайными числами + match show_graph: + case "yes": + function.print_table(masive, num_cols) + max_height = max(masive) + length = len(masive) + if max_height > 20 or length > 20: + function.percentage_graph(masive, max_or_mean) + else: + function.real_graph(masive) + input() + + case "no": + function.print_table(masive, num_cols) + input() + + except ValueError: + os.system("cls") + print(Fore.RED + "Приятель, внимательнее! \nЗаново!") + continue + + breaker, show_graph, max_or_mean, num_cols = function.menu(show_graph, max_or_mean, num_cols) + + if breaker == False: + break + +# ВСЁ ГОТОВО) \ No newline at end of file