Иван Иванов

All generations.

generate functionWed, 03 May 2023

Напиши код программы на языке python. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Написать алгоритм рассадки людей от 1 до m дней, так чтобы за за количество дней от 1 до m все люди посидел с максимально возможным количеством человек исходя из заданных значений. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 2 Введите количество мест за 2-м столом: 1 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2] Пример ввода 2 Введите количество людей: 6 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 3 Введите количество мест за 2-м столом: 3 Пример вывода 2 День 1: На столе 1 сидят люди с номерами: [1, 2, 3] На столе 2 сидят люди с номерами: [4, 5, 6] День 2: На столе 1 сидят люди с номерами: [1, 3, 5] На столе 2 сидят люди с номерами: [2, 4, 6]

def create_table(number_of_people, number_of_tables, *table_sits): a = [0] * number_of_people tables = [] for i in range(1, number_of_tables + 1): tables.append(i) return a, tables people, tables = create_table(int(input()), int(input()), *map(int, input().split())) def add_people(a, tables, number_of_people): for i in range(number_of_people): if i == 0: a[i] = tables[i] else: a[i] = tables[(i % len(tables))] return a def print_result(people, tables, number_of_people, number_of_tables): for i in range(1, number_of_people + 1): print(f"День {i}:") for j in range(1, number_of_t

Python
View
generate functionWed, 01 Mar 2023

Vanya was given n cubes for her birthday. He and his friends decided to build a pyramid out of them. Vanya wants to build a pyramid in the following way: there should be 1 cube at the top of the pyramid, 1 + 2 = 3 cubes at the second level, 1 + 2 + 3 = 6 cubes at the third level, and so on. Thus, at the i-th level of the pyramid there should be 1 + 2 + ... + (i - 1) + i cubes. Vanya wants to know what is the maximum height of the pyramid he can create using the available cubes. Input data The first line contains an integer n (1 ≤ n ≤ 104) — the number of cubes given to Vanya. Output Print in a single line the maximum possible height of the pyramid.

a = int(input()) step = 1 step_sum = 0 while True: if step_sum + step <= a: step_sum += step step += 1 else: break print(step - 1)

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Output the maximum element excluding the area above the main diagonal.

def max_el_matrix(n): matrix = [] for i in range(n): matrix.append(list(map(int, input().split()))) max_el = -100 for i in range(n): for j in range(n): if i < j: if matrix[i][j] > max_el: max_el = matrix[i][j] return max_el max_el_matrix(4)

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Output the maximum element excluding the area above the main diagonal.

def find_max_exluding_main_diagonal(matrix): rows, columns = len(matrix), len(matrix[0]) max_num = matrix[0][0] for i in range(1, rows): for j in range(i): if max_num < matrix[i][j]: max_num = matrix[i][j] return max_num # Test matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] find_max_exluding_main_diagonal(matrix)

Python
View
generate functionMon, 03 Apr 2023

'''Напишите генератор батчей, который будет принимать на вход признаки, ответы и размер батча. Генератор должен возвращать tuple из ( Xbatch , ybatch ). Если размер датасета не делится на batch_size, то последний маленький батч возвращать не нужно.''' def generate_batches(X, y, batch_size): """ param X: np.array[n_objects, n_features] --- матрица объекты-признаки param y: np.array[n_objects] --- вектор целевых переменных """ assert len(X) == len(y) np.random.seed(42) X = np.array(X) y = np.array(y) perm = np.random.permutation(len(X)) for batch_start in <YOUR CODE>: #YOUR CODE yield #YOUR CODE

def generate_batches(X, y, batch_size): """ param X: np.array[n_objects, n_features] --- матрица объекты-признаки param y: np.array[n_objects] --- вектор целевых переменных """ assert len(X) == len(y) np.random.seed(42) X = np.array(X) y = np.array(y) perm = np.random.permutation(len(X)) for batch_start in range(0, len(X), batch_size): batch_inds = perm[batch_start:batch_start + batch_size] yield X[batch_inds], y[batch_inds]

Python
View
generate functionFri, 10 Mar 2023

a list of city names is given in one line separated by a space. Iterate through all these names with a for loop and determine if the name of the next city begins with the last letter of the previous city in the list. If the letters 'ь', 'ъ', 'ы' are the last ones, then the next letter from the end is taken. Display YES if the sequence matches this rule and NO otherwise.

def city_names(data): for i in range(0, len(data) - 1): if data[i][-1] == 'ь' or data[i][-1] == 'ы' or data[i][-1] == 'ъ': if data[i + 1][0] == data[i][-2]: print('YES') else: print('NO') else: if data[i + 1][0] == data[i][-1]: print('YES') else: print('NO') data = input().split() city_names(data)

Python
View
generate functionMon, 03 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m и заполняет её числами от 1 до n⋅m в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(),система примет и такое решение Тестовые данные Sample Input 1: 3 7 Sample Output 1: 1 4 7 10 13 16 19 2 5 8 11 14 17 20 3 6 9 12 15 18 21

n, m = int(input()), int(input()) matrix = [[str(i*m+j+1).ljust(3) for j in range(m)] for i in range(n)] for row in matrix: print(' '.join(row))

Python
View
generate functionTue, 28 Feb 2023

Matrix multiplication Write two functions that each multiply two square matrices, one without using numpy's built-in functions, and the other using numpy. The input to the first task is given lists of size size by size elements in each. The second task receives objects of type np.ndarray --- square matrices of the same size. The first function should return a list of lists, and the second should return np.array.

a = [[1,2,3],[1,2,3],[1,2,3]] b = [[3,3,3],[3,3,3],[3,3,3]] # without using numpy def matmul(a, b): r = [[0,0,0], [0,0,0], [0,0,0]] for i in range(len(a)): for j in range(len(a[0])): for k in range(len(a[0])): r[i][j] += a[i][k] * b[k][j] return r matmul(a, b) # using numpy import numpy as np def matmul_np(a, b): return np.matmul(a, b) matmul_np(np.array(a), np.array(b))

Python
View
generate functionThu, 13 Apr 2023

'''Имеется двумерный кортеж, размером 5 x 5 элементов: t = ((1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)) Вводится натуральное число N (N < 5). Необходимо на основе кортежа t сформировать новый аналогичный кортеж t2 размером N x N элементов. Результат вывести на экран в виде таблицы чисел. Sample Input: 3 Sample Output: 1 0 0 0 1 0 0 0 1'''

def f(n): t = ((1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)) t2 = [] for i in range(n): t2.append(t[i][:n]) for i in range(n): print(*t2[i])

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python используй жадный алгоритм. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Каждый день люди садятся друг с другом за столы так чтоб наибольшее количество людей могло познакомиться друг с другом. Считается что люди познакомились если они уже сидели за одним столом. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами

def greedy_algorithm(T): T = T.sort(reverse=True) min_sum = sum(T) for t in T: min_sum = min(min_sum, t + greedy_algorithm(T[1:])) return min_sum def hard_algorithm(T): n = len(T) T = sorted(T, reverse=True) cur_sum = 0 while True: min_i = 0 min_value = 99999 for i in range(n): if T[i] < min_value: min_value = T[i] min_i = i cur_sum += min_value T.remove(min_value) n = len(T) if not n: break T[min_i] = T[min_i] * 2 return cur_sum count_people = int(input()) count_days = int(input()) count_tables = int(

Python
View
generate functionFri, 12 May 2023

Вашей программе на вход поступает два числа a и b. Выведите числа от a до b включительно чередуя у них знак. Например для чисел 5 и 10 нужно вывести: 5 -6 7 -8 9 -10 У границы a знак остается такой же какой и был. 0 в чередование знаков включается. Sample Input 1: 5 10 Sample Output 1: 5 -6 7 -8 9 -10 Sample Input 2: 1 2 Sample Output 2: 1 -2 Sample Input 3: -5 5 Sample Output 3: -5 4 -3 2 -1 0 1 -2 3 -4 5 Sample Input 4: 5 -5 Sample Output 4: Sample Input 5: 1 3 Sample Output 5: 1 -2 3 Sample Input 6: -2 2 Sample Output 6: -2 1 0 -1 2

a = int(input()) b = int(input()) for i in range(a, b+1): if i == a: print(i) elif i%2 == 0: print(-i) else: print(i)

Python
View
generate functionWed, 22 Feb 2023

An integer k is entered (1 <= k <= 365). Determine which day of the week (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday) is the k-th day of a non-leap year in which January 1 is Monday.

def which_day(number): if number == 1: return "Monday" elif number == 2: return "Tuesday" elif number == 3: return "Wednesday" elif number == 4: return "Thursday" elif number == 5: return "Friday" elif number == 6: return "Saturday" elif number == 7: return "Sunday" else: return "Out of range" #input which_day(1) #output "Monday"

Python
View
generate functionThu, 16 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

backpack = int(input()) sum = 0 num = 0 while True: i = int(input()) sum += i num += 1 if sum > backpack: break print('Enough!') print(sum) print(num)

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers whose sum is equal to n. In the ten numbers displayed, the numbers do not go in a row. The range of output numbers is strictly not less than 0.001 and not more than 1. The displayed ten digits have strictly twelve digits after the decimal point. The output numbers are strictly greater than 0 and less than 1.

def print_nums(n): s = 0 i = 0 while i < 10: num = random.uniform(0.001, 1) if s + num <= n: print(round(num, 12)) s += num i += 1 else: num = n - s print(round(num, 12)) s = n i += 1 print_nums(0.5)

Python
View
generate functionWed, 08 Feb 2023

The two decided to compete in typing on the Button Racing website. During the execution, you must enter the text from the characters. The first participant types one character in v1 milliseconds and has a ping of t1 milliseconds. The second participant types one character in v2 milliseconds and has a ping of t2 milliseconds. Joining with ping (latency) in t millisecond contests for adherents: Exactly t milliseconds after the start of the competition, the participant receives a text that must be entered. Immediately after that, he starts typing this text. Exactly t milliseconds after he retyped the entire text, the site receives information about it. The winner in the competition is the participant whose success information came first. If the information came from opposite sides, it turned out that there was a draw. According to the given description of the text and information about the available, defined source data. Input data The first line contains five values of numbers s, v1, v2, t1, t2 (1 ≤ s, v1, v2, t1, t2 ≤ 1000) — the number of characters in the text, the speed of typing with the first number, the speed of typing first, ping of the first presence and ping of the second content. Output If the first participant wins, print "First". If the second participant wins, print "Second". In case of a draw, print "Friendship".

s = int(input()) v1 = int(input()) v2 = int(input()) t1 = int(input()) t2 = int(input()) time1 = v1 * s + 2 * t1 time2 = v2 * s + 2 * t2 if time1 < time2: print('First') elif time1 > time2: print('Second') else: print('Friendship')

Python
View
generate functionFri, 10 Mar 2023

a list of city names is given in one line separated by a space. Iterate through all these names with a for loop and determine if the name of the next city begins with the last letter of the previous city in the list. Display YES if the sequence matches this rule and NO otherwise.

def city_match(string): string = string.split(' ') for i in range(len(string)-1): if string[i][-1] == string[i+1][0]: print('YES') else: print('NO') city_match('London Berlin Madrid Moscow')

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python используй жадный алгоритм. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Каждый день люди садятся друг с другом за столы так чтоб наибольшее количество людей могло познакомиться друг с другом. Считается что люди познакомились если они уже сидели за одним столом. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами

def greedy(n, m, k, a) ...

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers whose sum is equal to n. In the ten numbers displayed, the numbers do not go in a row. The range of output numbers is strictly not less than 0.001 and not more than 1. The displayed ten digits have strictly twelve digits after the decimal point. The output numbers are strictly greater than 0 and less than 1.

def get_random_number(n): result = [] while n > 0: num = random.random() if num not in result: if n - num >= 0 and n - num <= 1: result.append(num) n -= num return result get_random_number(0.999)

Python
View
generate functionTue, 28 Feb 2023

Using Numpy, write an array coding function (Run-Length Encoding). The function of repetition of elements compresses the function into one element and considers the number of repetitions. The function returns a motorcade of two Numpy veins of the same length. The first contains elements, and the second - how many times they need to be repeated.

def RLE(array): inds = np.add.reduceat(np.not_equal(array[1:], array[:-1]), np.arange(len(array))) array = array[inds] lens = np.diff(np.append(inds, len(array))) return array, lens

Python
View
generate functionFri, 10 Feb 2023

Implement the Neuron class, which will have several methods: __init__. Takes as input an array of neuron weights --- =(1,…,)w=(w 1​ ,…,w n​ ), as well as the activation function f (default argument (�) = � f(x)=x). Stores the weights and the function inside the class. forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed! forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed!

class Neuron: def __init__(self, weights, function=lambda x: x): self.weights = weights self.function = function self.inputs = None def forward(self, inputs): self.inputs = inputs if len(inputs) != len(self.weights): return None return self.function(sum([x*y for x,y in zip(self.weights, self.inputs)])) def backlog(self): return self.inputs

Python
View
generate functionMon, 10 Apr 2023

'''Напишите программу для вычисления суммы двух матриц. Формат входных данных На вход программе подаются два натуральных числа n и m — количество строк и столбцов в матрицах, затем элементы первой матрицы, затем пустая строка, далее следуют элементы второй матрицы. Формат выходных данных Программа должна вывести результирующую матрицу, разделяя элементы символом пробела.'''

n = int(input()) m = int(input()) numbers = [] for i in range(n): row = input().split() numbers.append([int(x) for x in row]) for i in range(n): row = input().split() for i in range(len(row)): numbers[i][i] += int(row[i]) for row in numbers: print(' '.join([str(x) for x in row]))

Python
View
generate functionTue, 28 Feb 2023

Using Numpy, write an array coding function (Run-Length Encoding). The function of repetition of elements compresses the function into one element and considers the number of repetitions. The function returns a motorcade of two Numpy veins of the same length. The first contains elements, and the second - how many times they need to be repeated.

import numpy as np def run_length_encoding(array): repeats = [] current = None counter = 0 for element in array: if element == current: counter += 1 else: if current is not None: repeats.append((current, counter)) current = element counter = 1 repeats.append((current, counter)) values, counts = zip(*repeats) return np.array(values), np.array(counts) run_length_encoding([1, 1, 2, 2, 2, 5])

Python
View
regexTue, 28 Feb 2023

check Microsoft Outlook email

^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$

generate functionThu, 09 Mar 2023

Let's go through all the numbers from a to b inclusive and display them on the screen, while the following conditions must be met: skip (do not display) numbers that are divisible by 2 or 3. if you meet a number that is a multiple of 777, you must force the loop to end, do not print this number itself Try not to use a for loop

def func(a, b): while a <= b: if a % 2 == 0 or a % 3 == 0: a += 1 else: print(a) a += 1 if a % 777 == 0: break print(func(1, 100))

Python
View
generate functionMon, 03 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m и заполняет её числами от 1 до n⋅m в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(),система примет и такое решение Тестовые данные Sample Input 1: 3 4 Sample Output 1: 1 2 3 4 5 6 7 8 9 10 11 12

def matrix(n,m): k = 1 matrix = [] for i in range(n): r = [] for j in range(m): r.append(str(k).ljust(3)) k += 1 matrix.append(r) for i in range(len(matrix)): for j in range(len(matrix[i])): print (matrix[i][j], end="") print('\n', end="") n = int(input()) m = int(input()) matrix(n,m)

Python
View
generate functionWed, 08 Feb 2023

When playing "Cities", players take turns calling the names of cities so that the first letter of each new word coincides with the last letter of the previous one. At the same time, it is believed that if the last letter of the previous word is f, then the letter preceding f should be compared with the first letter of the next word. Write a program that reads two lines in a row, and then prints "Good" if the last character of the first line matches the first character of the second (subject to the f rule), and "Bad" otherwise.

def func(line1, line2): return "Good" if (line1[-1] == line2[0] and line1[-2] != "f") or (line1[-1] == "f" and line2[0] == line1[-3]) else "Bad"

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Output the maximum element located on the main diagonal and below the main diagonal

# 1 2 3 # 4 5 6 # 7 8 9 def add(a, b): return a + b def max_el(a): if n == 1: return a[0][0] if n == 2: return max(a[0][0], a[1][0], a[1][1]) res = a[0][0] for i in range(len(a)): for j in range(len(a[i])): if i == j: if a[i][j] > res: res = a[i][j] if i > j: if a[i][j] > res: res = a[i][j] return res n = int(input()) a = [] for i in range(n): a.append(list(map(int, input().split()))) print(max_el(a))

Python
View
generate functionFri, 10 Feb 2023

Реализуйте класс "Нейрон", у которого будет несколько методов: __init__. Принимает на вход массив весов нейрона --- � = ( � 1 , … , � � ) w=(w 1 ​ ,…,w n ​ ), а также функцию активации � f (аргумент по умолчанию � ( � ) = � f(x)=x). Сохраняет веса и функцию внутри класса. forward. Принимает на вход массив � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- входы нейрона. Возвращает значение функции � f, примененное к числу � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Возвращает массив � x, который подавался на вход функции forward при её последнем вызове. Если ранее функция forward не вызывалось, возвращает None. В этом задании функция print вам не понадобится. Результаты выполнения функций нужно возвращать, а не печатать!

class Neuron: def __init__(self, w, activation_function=lambda x: x): """ Инициализируем нейрон. w - вектор весов нейрона размера (m, 1), где m - количество входов activation_function - активационная функция нейрона, сигмоидальная функция по умолчанию """ # Присваиваем значение атрибуту activation_function self.activation_

Python
View
generate functionMon, 20 Mar 2023

On the first line, one character is entered - a lowercase letter. The sentence is entered on the second line. Output It is necessary to output a list of words (a word is a part of a sentence surrounded by white space characters) in which the entered letter is present in any case, in the same order in which they occur in the sentence.

letter = input() sentence = input() sentence_list = sentence.split() for word in sentence_list: for c in word: if c.upper() == letter.upper(): print(word) break

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15

n, m = int(input()), int(input()) def create_matrix(n, m): matrix = [[0] * m for i in range(n)] return matrix matrix = create_matrix(n, m) count = 1 for i in range(n): for j in range(m): matrix[i][j] = count count += 1 for i in matrix: for j in i: print(str(j).ljust(3), end = '') print()

Python
View
generate functionThu, 13 Apr 2023

'''Имеется двумерный кортеж, размером 5 x 5 элементов: t = ((1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)) Вводится натуральное число N (N < 5). Необходимо на основе кортежа t сформировать новый аналогичный кортеж t2 размером N x N элементов. Результат вывести на экран в виде таблицы чисел. Sample Input: 3 Sample Output: 1 0 0 0 1 0 0 0 1'''

t = ((1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)) n = int(input()) t2 = t[:n] for i in range(n): t2[i] = t2[i][:n] for j in range(n): print(t2[i][j], end=' ') print()

Python
View
generate functionTue, 14 Feb 2023

To calculate C(n, k) in other cases, the following recursive formula is used: C(n, k) = C(n - 1, k) + C(n - 1, k - 1). Implement a program that, given n and k, calculates C(n, k). Your program is given a string containing two integers n and k (1 ≤ n ≤ 10, 0 ≤ k ≤ 10) as input. Your program should output a single number: C(n, k). Note: You can count two numbers n and k, for example, as follows: n, k = map(int, input().split())

def comb(n, k): if k > n: return 0 elif k == 0: return 1 else: return comb(n-1, k) + comb(n-1, k-1) n, k = map(int, input().split()) result = comb(n, k) print(result)

Python
View
generate functionFri, 27 Jan 2023

hack the pentagon

def hack_pentagon(network, password): if network == "pentagon": if password == "secret": return True else: return False else: return False hack_pentagon("pentagon", "secret")

Python
View
generate functionMon, 10 Apr 2023

'''Напишите программу для вычисления суммы двух матриц. Формат входных данных На вход программе подаются два натуральных числа n и m — количество строк и столбцов в матрицах, затем элементы первой матрицы, затем пустая строка, далее следуют элементы второй матрицы. Формат выходных данных Программа должна вывести результирующую матрицу, разделяя элементы символом пробела.'''

N, M = int(input()), int(input()) matrix_a = [] for i in range(N): matrix_a.append([int(x) for x in input().split()]) matrix_b = [] for i in range(N): matrix_b.append([int(x) for x in input().split()]) matrix_c = [] for i in range(N): matrix_c.append([matrix_a[i][j] + matrix_b[i][j] for j in range(M)]) for x in matrix_c: print(*x)

Python
View
generate functionMon, 20 Mar 2023

A natural number N is entered (that is, a positive integer). Required to create a two-dimensional (nested) list of size N x N elements, consisting of all ones, and then, write fives in the last column. Display this list on the screen as a table of numbers, as shown in the example below. P.S. Be careful there should be no spaces at the end of the lines!

def fives(): size = int(input()) matrix = [] for i in range(size): matrix.append([]) for j in range(size): if j < size - 1: matrix[i].append(1) else: matrix[i].append(5) for i in range(size): print(*matrix[i]) fives()

Python
View
generate functionTue, 07 Mar 2023

a fractional number n is entered from the keyboard. Output ten numbers whose sum is equal to n. The numbers range from 0.001213245678 to n. The numbers are positive. The first two digits after the decimal point in the number can be equal to 0. The remaining digits in the number go without repetition. The number must have twelve significant decimal places.

def digits(n): a = '' while len(a) < 12: b = str(n)[:3] if int(b) > 999: b = str(n)[:2] if int(b) > 99: b = str(n)[0] if int(b) > 9: b = str(b)[:1] if b not in a: a += b else: b = str(n)[5] if b not in a: a += b n += 0.000000000001 return a digits(0.001213245678)

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "спиралью" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести матрицу в соответствии образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 4 5 Sample Output 1: 1 2 3 4 5 14 15 16 17 6 13 20 19 18 7 12 11 10 9 8

def spiral(x, y): a = [[0] * y for i in range(x)] dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 for i in range(max(x, y)**2): while True: nx, ny = x + dx[i % 4], y + dy[i % 4] if 0 <= nx < x and 0 <= ny < y and a[nx][ny] == 0: x, y = nx, ny break else: i += 1 a[x][y] = c c += 1 return a print(spiral(4, 5))

Python
View
generate functionMon, 13 Mar 2023

A natural number N is entered (that is, a positive integer). It is required to create a two-dimensional (nested) list of N x N elements, consisting of all ones, and then write fives in the last column. Display this list on the screen as a table of numbers, as shown in the example below. P.S. Be careful there should be no spaces at the end of the lines!

def fives(n): matrix = [] for i in range(n): matrix.append([]) for j in range(n): if j == n-1: matrix[i].append(5) else: matrix[i].append(1) for i in range(n): for j in range(n): print(matrix[i][j], end='') print() fives(10)

Python
View
generate functionFri, 10 Feb 2023

Write a program that contains the basic elements of a square matrix below the main diagonal. The elements of the main diagonal are also taken into account. The input is a natural number n is the number of rows and columns in the matrix, the number of matrix elements (integers) line by line, separated by a space.

n = int(input("Please insert n: ")) matrix = [[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): matrix[i][j] = int(input("Please insert matrix[{}][{}]: ".format(i, j))) diagonal = 0 for i in range(n): for j in range(n): if i == j or i + j == n - 1: diagonal += matrix[i][j] print("The sum of the diagonal is: " + str(diagonal))

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 Sample Input 2: 3 4 Sample Output 2: 1 2 4 7 3 5 8 10 6 9 11 12 Sample Input 3: 2 2 Sample Output 3: 1 2 3 4 Sample Input 4: 8 1 Sample Output 4: 1 2 3 4 5 6 7 8 Sample Input 5: 8 2 Sample Output 5: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

n, m = int(input()), int(input()) spisok = [i for i in range(1, n*m+1)] matrix = [spisok[i*m:i*m+m] for i in range(n)] for i in range(n): for j in range(m): print(str(matrix[i][j]).ljust(3), end='') print()

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, которая считывает строку с числом � n, которое задаёт количество чисел, которые нужно считать. Далее считывает � n строк с числами � � x i ​ , по одному числу в каждой строке. Итого будет � + 1 n+1 строк. При считывании числа � � x i ​ программа должна на отдельной строке вывести значение � ( � � ) f(x i ​ ). Функция f(x) уже реализована и доступна для вызова. Функция вычисляется достаточно долго и зависит только от переданного аргумента � x. Для того, чтобы уложиться в ограничение по времени, нужно избежать повторного вычисления значений.

n = int(input()) input_x = [int(input()) for i in range(n)] def f(x): return x*x for x in input_x: print(f(x))

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 Sample Input 2: 3 4 Sample Output 2: 1 2 4 7 3 5 8 10 6 9 11 12 Sample Input 3: 2 2 Sample Output 3: 1 2 3 4 Sample Input 4: 8 1 Sample Output 4: 1 2 3 4 5 6 7 8 Sample Input 5: 8 2 Sample Output 5: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

def generate_matrix(n, m): matrix = [] k = 1 while k <= n * m: i = (k - 1) // m j = (k - 1) % m matrix.append([0] * j + [k] + [0] * (m - 1 - j)) k += 1 return matrix n, m = [int(s) for s in input().split()] a = generate_matrix(n, m) for row in a: print(' '.join([str(elem) for elem in row]))

Python
View
generate functionFri, 10 Mar 2023

a list of city names is given in one line separated by a space. Iterate through all these names with a for loop and determine if the name of the next city begins with the last letter of the previous city in the list. If the letters 'ь', 'ъ', 'ы' are the last ones, then the next letter from the end is taken. Display YES if the sequence matches this rule and NO otherwise.

def func(data): last_letter = data[0][-1] for item in data[1:]: if last_letter == 'ы': last_letter = data[-2] elif last_letter == 'ь' or last_letter == 'ъ': last_letter = data[-3] elif item.startswith(last_letter): last_letter = item[-1] continue else: return 'NO' return 'YES'

Python
View
generate functionTue, 07 Mar 2023

The program takes two natural numbers as input. n and m are the number of rows and columns in the matrix, then n lines of m integers each, separated by a space character. Write a program that finds the indices (row and column) of the first occurrence of the maximum element. Input Data Format Two numbers n and m are given as input to the program on different lines — the number of rows and columns in the matrix, then the matrix elements themselves row by row separated by a space.

n=int(input()) m=int(input()) max_ind = 0 max_row = 0 max_val = -1 for i in range(n): row = list(map(int, input().split())) for j in range(m): if row[j] > max_val: max_ind = j max_row = i max_val = row[j] print(max_row, max_ind)

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def buy_socks(num_socks,num_buy): return num_socks + num_buy*(num_socks//num_buy)

Python
View
generate functionThu, 20 Apr 2023

На вход вашему серверу пришло время в минутах, которое провел пользователь на сайте , а также время начала сессии. Вам нужно определить сколько времени было на цифровых часах у пользователя, когда он закрывал сайт. Ваша программа получает на вход 3 переменные, каждая в новой строке: time_mins – количество минут, которое пользователь провел на сайте start_hours – время в часах, когда пользователь зашел на сайт start_mins – время в минутах, когда пользователь зашел на сайт Программа должна вывести через пробел количество часов и минут, когда пользователь закрыл сайт

def get_time(time_mins, start_hours, start_mins): total_mins = start_hours * 60 + start_mins + time_mins total_hours = total_mins // 60 total_mins = total_mins % 60 return total_hours, total_mins

Python
View
generate functionFri, 10 Feb 2023

Implement the Neuron class, which will have several methods: __init__. Takes as input an array of neuron weights --- =(1,…,)w=(w 1​ ,…,w n​ ), as well as the activation function f (default argument (�) = � f(x)=x). Stores the weights and the function inside the class. forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed! forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed!

class Neuron: def __init__(self, weights, activation_function = lambda x: x): weights = [] self.weights = weights self.activation_function = activation_function self.x = None def forward(self, input_data): self.x = input_data y = 0 for w_i, x_i in zip(self.weights, input_data): y += w_i * x_i return self.activation_function(y) def backward(self): return self.x

Python
View
generate functionMon, 20 Mar 2023

A natural number N is entered (that is, a positive integer). Required to create a two-dimensional (nested) list of size N x N elements, consisting of all ones, and then, write fives in the last column. Display this list on the screen as a table of numbers, as shown in the example below. P.S. Be careful there should be no spaces at the end of the lines!

N=5 def create_list(a): list_of_lists = [] for i in range(a): inner_list = [] for j in range(a): if j == N-1: inner_list.append(5) else: inner_list.append(1) list_of_lists.append(inner_list) return list_of_lists create_list(N)

Python
View
generate functionTue, 28 Feb 2023

X: np.array [num_row, num_column] --- matrix-argument a: float --- meaning for converting odd elements of lines into x Return s: np.array [num_row, num_column*2] --- Matrix, where the lines are flexible lines of the original matrix X with lines, which are their transformations The function takes on the input matrix X dimensions n x m, the number a and Returns the matrix with dimensions n x m*2, the i-th line of which is glued I-th line X with its transformation of its line Transformation (X [I]), written in the reverse order, where the transformation for the number K is defined as: Transformation (k) = a if ind (k) % 2 == 0 else k ** 3 In the implementation of this function, it is necessary to use the functionality of the Numpy package

def task_1(X, a): m = X.shape[1] n = X.shape[0] res = np.zeros(n*m*2).reshape(n, m*2) for i in range(n): res[i, :m] = X[i] res[i, m:] = [x if ind(x)%2==0 else x**3 for x in X[i][::-1]] return res

Python
View
generate functionTue, 11 Apr 2023

'''Имеется закодированная строка с помощью азбуки Морзе. Коды разделены между собой пробелом. Необходимо ее раскодировать, используя азбуку Морзе из предыдущего занятия. Полученное сообщение (строку) вывести на экран. morze = {'а': '.-', 'б': '-...', 'в': '.--', 'г': '--.', 'д': '-..', 'е': '.', 'ё': '.', 'ж': '...-', 'з': '--..', 'и': '..', 'й': '.---', 'к': '-.-', 'л': '.-..', 'м': '--', 'н': '-.', 'о': '---', 'п': '.--.', 'р': '.-.', 'с': '...', 'т': '-', 'у': '..-', 'ф': '..-.', 'х': '....', 'ц': '-.-.', 'ч': '---.', 'ш': '----', 'щ': '--.-', 'ъ': '--.--', 'ы': '-.--', 'ь': '-..-', 'э': '..-..', 'ю': '..--', 'я': '.-.-', ' ': '-...-'} Результат кодирования вывести в виде строки.'''

def decode_morze(code): words = code.split(' ') letters = [] for word in words: letter = '' for char in word: letter += char if letter in morze: letters.append(morze[letter]) letter = '' return ''.join(letters) print(decode_morze('-- -.-- --- ...'))

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers whose sum is equal to n. In the ten numbers displayed, the numbers do not go in a row. The range of output numbers is from 0.001 to 1. The output ten digits have exactly twelve digits after the decimal point.

import random def make_number(n): number = [] left = n right = 0 for i in range(9): tmp = random.uniform(0.001, left) number.append(round(tmp, 12)) left -= tmp right += tmp number.append(round(left + right, 12)) return number def main(): n = float(input()) numbers = make_number(n) for number in numbers: print(number) main()

Python
View
generate functionTue, 28 Feb 2023

A two -dimensional array X. For each line of array X, the following transformation must be made. Let the line X be given. It is necessary to build a new array, where all elements with odd indices are required to be replaced by the number A (the default value A = 1). All elements with even indices need to be built into the cube. Then write the elements in the reverse order regarding their positions. At the end, it is required to drain an array X with a converted X and display. Write a function that performs this transformation for each line of the two -dimensional array X. The array X should remain unchanged. Use the Numpy library. Example: x = [100,200,300,400,500]] -> [[100, A, 300, A, 500]] -> [[500 ** 3, A, 300 ** 3, A, 100 ** 3]] -> -> -> Close -> [[100,200,300,400,500,500 ** 3, A, 300 ** 3, A, 100 ** 3]]]

import numpy as np def transform_array(x, a=1): x = np.array(x) for i, el in enumerate(x): x[i] = el ** 3 if i % 2 == 0 else a return x[::-1] def transform_array_all(x, a=1): x = np.array(x) y = np.array([]) for i, el in enumerate(x): if i % 2 == 0: el = el ** 3 else: el = a y = np.append(y, el) return np.append(x, y[::-1]) x = np.array([100,200,300,400,500]) print(transform_array(x)) print(transform_array_all(x))

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the matrix, the number of matrix elements (integers) line by line separated by a space. draw the maximum element below the main diagonal. The elements of the main diagonal are also taken into account.

def max_below_main_diagonal(n): max = -100 for k in range(1,n): for i in range(0,n): for j in range(0,n): if (i+j) == k: if A[i][j] > max: max = A[i][j] print(max) max_below_main_diagonal(2)

Python
View
generate functionThu, 13 Apr 2023

'''Имеется двумерный кортеж, размером 5 x 5 элементов: t = ((1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)) Вводится натуральное число N (N < 5). Необходимо на основе кортежа t сформировать новый аналогичный кортеж t2 размером N x N элементов. Результат вывести на экран в виде таблицы чисел. Sample Input: 3 Sample Output: 1 0 0 0 1 0 0 0 1'''

t = ((1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)) def make_list(t, n): return [t[i][:n] for i in range(n)] n = int(input()) print(make_list(t, n))

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (число повторяется столько раз, чему равно). На вход программе передаётся неотрицательное целое число n — столько элементов последовательности должна отобразить программа. На выходе ожидается последовательность чисел, записанных через пробел в одну строку. Например, если n = 7, то программа должна вывести 1 2 2 3 3 3 4.

#1 n = int(input()) a = [] for i in range(n): a.append(i + 1) for j in range(i): a.append(i + 1) for i in range(n - 1): print(a[i], end=' ') print(a[n - 1]) #2 n = int(input()) for i in range(1, n + 1): print((str(i) + ' ') * i, end='')

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m заполнив её "змейкой" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение Тестовые данные Sample Input 1: 3 5 Sample Output 1: 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15

print(*[range(1, 6) + range(5, 0, -1) + range(6, 11) + range(10, 5, -1) + range(11, 16)] * 3)

Python
View
generate functionFri, 10 Feb 2023

__init__. Takes as input an array of neuron weights --- =(1,…,)w=(w 1​ ,…,w n​ ), as well as the activation function f (default argument (�) = � f(x)=x). Stores the weights and the function inside the class. forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed!

class Neuron: def __init__(self, weights, activation_function = lambda x: x): self.weights = weights self.activation_function = activation_function self.backlog = None def forward(self, inputs): self.backlog = inputs weighted_input = 0 for i in range(len(inputs)): weighted_input += inputs[i] * weights[i] return self.activation_function(weighted_input)

Python
View
generate functionMon, 06 Mar 2023

output ten numbers whose sum is equal to the number entered from the keyboard. digits do not repeat in numbers. twelve significant digits. the numbers are positive.

def split_number(number): numbers = [i for i in range(10)] while number > 0: digit = number % 10 if digit in numbers: numbers.remove(digit) else: return False number = int(number / 10) return True def calculate(number): if number < 10 or not split_number(number): return [] maximum = 10 ** (len(str(number)) - 1) for i in range(maximum, 10 ** len(str(number))): if split_number(i) and number - i > 0 and split_number(number - i): return [i, number - i] print(calculate(int(input())))

Python
View
generate functionFri, 12 May 2023

Вашей программе на вход поступает два числа a и b. Выведите числа от a до b включительно чередуя у них знак. Например для чисел 5 и 10 нужно вывести: 5 -6 7 -8 9 -10 У границы a знак остается такой же какой и был. 0 в чередование знаков включается. Sample Input 1: 5 10 Sample Output 1: 5 -6 7 -8 9 -10 Sample Input 2: 1 2 Sample Output 2: 1 -2 Sample Input 3: -5 5 Sample Output 3: -5 4 -3 2 -1 0 1 -2 3 -4 5 Sample Input 4: 5 -5 Sample Output 4: Sample Input 5: 1 3 Sample Output 5: 1 -2 3 Sample Input 6: -2 2 Sample Output 6: -2 1 0 -1 2

a = int(input()) b = int(input()) if a <= b: for i in range(a, b + 1): if i % 2 == 0: i = i * (-1) print(i) else: print(i) else: for i in range(a, b - 1, -1): if i % 2 == 0: i = i * (-1) print(i) else: print(i)

Python
View
generate functionWed, 12 Apr 2023

Имеется словарь с наименованиями предметов и их весом (в граммах): things = {'карандаш': 20, 'зеркальце': 100, 'зонт': 500, 'рубашка': 300, 'брюки': 1000, 'бумага': 200, 'молоток': 600, 'пила': 400, 'удочка': 1200, 'расческа': 40, 'котелок': 820, 'палатка': 5240, 'брезент': 2130, 'спички': 10} Сергей собирается в поход и готов взвалить на свои хрупкие плечи максимальный вес в N кг (вводится с клавиатуры). Он решил класть в рюкзак предметы в порядке убывания их веса (сначала самые тяжелые, затем, все более легкие) так, чтобы их суммарный вес не превысил значения N кг. Все предметы даны в единственном экземпляре. Выведите список предметов (в строчку через пробел), которые берет с собой Сергей в порядке убывания их веса. P. S. 1 кг = 1000 грамм Sample Input: 10 Sample Output: палатка брезент удочка брюки пила карандаш спички

def knapsack(max_weight): # write your code here return 0 if __name__ == '__main__': max_weight = int(input()) result = knapsack(max_weight) print(result)

Python
View
generate functionTue, 14 Feb 2023

Let the coordinates x 1,y 1 of the first point be input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates x 2 ,y 2 of the second point are set to 3, 6 respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

(𝑥𝑖−𝑥𝑗)2+(𝑦𝑖−𝑦𝑗)2

Python
View
generate functionMon, 03 Apr 2023

Проверьте, является ли двумерный массив симметричным относительно главной диагонали. Главная диагональ — та, которая идёт из левого верхнего угла двумерного массива в правый нижний. Входные данные Программа получает на вход число n<100, являющееся числом строк и столбцов в массиве. Далее во входном потоке идет n строк по n чисел, являющихся элементами массива. Выходные данные Программа должна выводить слово Yes для симметричного массива и слово No для несимметричного.

def sym(a): l = len(a) for i in range(l): for j in range(l): if a[i][j] != a[j][i]: return False return True sym([[1, 2, 3], [2, 3, 4], [3, 4, 5]])

Python
View
generate functionFri, 17 Feb 2023

The operation of the traffic light for pedestrians is programmed as follows: at the beginning of each hour, a green signal is on for three minutes, then red for two minutes, green again for three minutes, etc. Given a real number t, which means the time in minutes, elapsed since the beginning of the next hour. Determine what color signal is on for pedestrians at this moment. Display the message (without quotes) "green" for green and "red" for red.

def traffic_light_color(t): if t % 5 < 3: return 'green' else: return 'red' traffic_light_color(5)

Python
View
generate functionMon, 03 Apr 2023

'''Задан целочисленный двумерный массив, состоящий из N строк и M столбцов. Требуется вычислить сумму элементов в каждой строке и в каждом столбце. Программа получает на вход два натуральных числа N и M – количество строк и столбцов двумерного массива. В каждой из последующих N строк записаны M целых чисел – элементы массива. Все числа во входных данных не превышают 1000 по абсолютной величине. В первой строке вам необходимо вывести N чисел – суммы элементов массива для каждой строки в отдельности. Во второй строке в аналогичном формате выведите M чисел – суммы элементов для каждого столбца.'''

a = int(input()) b = int(input()) matrix = [] for i in range(a): matrix.append(list(map(int, input().split()))) def sum_line(m): summ = [] for line in m: summ.append(sum(line)) return(summ) def sum_column(m): summ = [] for column in zip(*m): summ.append(sum(column)) return(summ) print(' '.join([str(i) for i in sum_line(matrix)])) print(' '.join([str(i) for i in sum_column(matrix)]))

Python
View
generate functionTue, 28 Feb 2023

A two -dimensional array X. For each line of array X, the following transformation must be made. Let the line X be given. It is necessary to build a new array, where all elements with odd indices are required to be replaced by the number A (the default value A = 1). All elements with even indices need to be built into the cube. Then write the elements in the reverse order regarding their positions. At the end, it is required to drain an array X with a converted X and display. Write a function that performs this transformation for each line of the two -dimensional array X. The array X should remain unchanged. Use the Numpy library. Example: x = [100,200,300,400,500]] -> [[100, A, 300, A, 500]] -> [[500 ** 3, A, 300 ** 3, A, 100 ** 3]] -> -> -> Close -> [[100,200,300,400,500,500 ** 3, A, 300 ** 3, A, 100 ** 3]]]

import numpy as np def changeX(X, a = 1): Y = np.array(X) for i in range(len(Y)): Y[i] = Y[i][::-1] for j in range(len(Y[i])): if j % 2 == 0: Y[i][j] = a else: Y[i][j] = Y[i][j] ** 3 return np.concatenate((X, Y), axis = 0) changeX(np.array([[1,2,3,4,5,6],[100,200,300,400,500,600]]))

Python
View
generate functionMon, 20 Feb 2023

Implement the Neuron class, which will have several methods: __init__. It takes as input an array of neuron weights --- w=(w1,…,wn) , as well as an activation function f (by default, f(x)=x ). Stores the weights and the function inside the class. forward. It takes as input an array x=(x1,…,xN) --- neuron inputs. Returns f(w1x1+…+wnxn) . backlog. Returns the last array x that was passed to the forward function. class Neuron: def __init__(self, w, f = lambda x: x): #YOUR CODE HERE def forward(self, x): #YOUR CODE HERE def backlog(self): #YOUR CODE HERE

# Define the neuron class with two methods: class Neuron: def __init__(self, w, f = lambda x: x): self.w = w self.f = f def forward(self, x): """ Calculates neuron output """ # Your code here return self.f(np.dot(self.w,x)) def backlog(self): return self.x

Python
View
generate functionFri, 10 Mar 2023

An arithmetic expression is written as a string, for example: "10 + 25 - 12" or "10 + 25 - 12 + 20 - 1 + 3", etc. That is, the number of actions can be different. It is necessary to perform the calculation and display the result on the screen. It is assumed that only addition (+) and subtraction (-) are used here as arithmetic operations, and non-negative integers are used as operands. Note that these operators can be written with or without spaces.

def arithmetic(expr): # replace all spaces expr = expr.replace(" ", "") # split at operators expr_arr = re.split('\+|-', expr) print(expr_arr) # iterate for num, op in zip(expr_arr[1:], expr_arr[:-1]): if op == "-": expr_arr[0] = str(int(expr_arr[0]) - int(num)) else: expr_arr[0] = str(int(expr_arr[0]) + int(num)) return expr_arr[0] arithmetic("10+25-12")

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

def add_to_dict(dict, key, val): if key in dict: dict[key].append(val) else: dict[key] = [val] return dict def birthdays(): d = {} while True: try: line = input() except EOFError: break if not line: break l = line.split() key = l[0] val = l[1] d = add_to_dict(d, key, val) return d def print_value(values): names = [] for i in values: names.append(i) return ', '.join(names) d = birthdays() for key in sorted(d.keys()): print(key + ': ' + print_value(d[key]))

Python
View
generate functionTue, 14 Feb 2023

Let the coordinates � 1 x 1 ​ , � 1 y 1 ​ of the first point are fed to the input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates � 2 , � 2 x 2 ​ ,y 2 ​ the second point are set to 3, 6, respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

((x1-x2)**2 + (y1-y2)**2)**0.5

Python
View
generate functionTue, 28 Feb 2023

A two -dimensional array X. For each line of array X, the following transformation must be made. Let the line X be given. It is necessary to build a new array, where all elements with odd indices are required to be replaced by the number A (the default value A = 1). All elements with even indices need to be built into the cube. Then write the elements in the reverse order regarding their positions. At the end, it is required to drain an array X with a converted X and display. Write a function that performs this transformation for each line of the two -dimensional array X. The array X should remain unchanged. Use the Numpy library. Example: x = [100,200,300,400,500]] -> [[100, A, 300, A, 500]] -> [[500 ** 3, A, 300 ** 3, A, 100 ** 3]] -> -> -> Close -> [[100,200,300,400,500,500 ** 3, A, 300 ** 3, A, 100 ** 3]]]

import numpy as np def convert(X): """ The function converts the given array X into a new array of the form described above. The array X is not changed. """ # Create a copy of the original array Y = np.copy(X) # Get the number of rows and columns of the array m, n = Y.shape # The transformation of each line of the array Y for i in range(m): # Replace all odd indices with the number 1 Y[i, 1::2] = 1 # Replace all even indices with their cubes Y[i, ::2] = np.power(Y[i, ::2], 3) # Reverse the elements in each line Y[i] = Y[i, ::-1] return Y

Python
View
generate functionTue, 21 Feb 2023

m and n are entered (in one line separated by a space) to determine: a) the date of the previous day (assume that m and n do not characterize January 1); b) the date of the next day (assume that m and n do not characterize December 31). The problem is to assume that the year is not a leap year. Print the previous date and the next date (in the format: mm.dd, where m is the day of the month; d is the number of the day) in one line separated by a space. P.S. Number of days in non-leap year months starting from January: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31

m = int(input()) n = int(input()) if m == 1: print('12', n-1) elif n == 1: print(m-1, 31) elif m == 3: print(2, n-1) elif m == 8 or m == 5 or m == 10 or m == 12: print(m, n-1) else: print(m, n-1) if m == 12: print('1', n+1) elif n == 31: if m == 1 or m == 3 or m == 5 or m == 7 or m == 8 or m == 10: print(m+1, 1) else: print(m, n+1) elif m == 2: print(m, n+1) else: print(m, n+1)

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир Для считывания списка целиком в программе уже записаны начальные строчки: import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines()))

def fun_1(lst_in): result = {} for i in lst_in: if i[0] not in result: result[i[0]] = [i[1:]] else: result[i[0]].append(i[1:]) for i in result: print(i, ':', ', '.join(result[i]))

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: <день рождения 1> имя_1 <день рождения 2> имя_2 ... <день рождения N> имя_N Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): день рождения 1: имя1, ..., имяN1 день рождения 2: имя1, ..., имяN2 ... день рождения M: имя1, ..., имяNM Для считывания списка целиком в программе уже записаны начальные строчки: import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines())) Sample Input: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Sample Output: 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

def get_list(raw_list): # на входе список строк # на выходе словарь {день:[имена]} get_list(['3 Сергей', '5 Николай', '4 Елена', '7 Владимир', '5 Юлия', '4 Светлана']) {3: ['Сергей'], 5: ['Николай', 'Юлия'], 4: ['Елена', 'Светлана'], 7: ['Владимир']}

Python
View
generate functionWed, 01 Mar 2023

At each iteration of the loop, an integer is entered. It is necessary to calculate the product of only positive numbers, until the value 0 is entered. Implement skipping calculations using the continue statement, and also use a while loop. Display the result of the work.

def get_positive_sum(): total = 0 while True: user_input = int(input('Enter a number (0 to exit): ')) if user_input == 0: break elif user_input < 0: continue else: total += user_input return total get_positive_sum()

Python
View
generate functionTue, 28 Feb 2023

A two -dimensional array X. For each line of array X, the following transformation must be made. Let the line X be given. It is necessary to build a new array, where all elements with odd indices are required to be replaced by the number A (the default value A = 1). All elements with even indices need to be built into the cube. Then write the elements in the reverse order regarding their positions. At the end, it is required to drain an array X with a converted X and display. Write a function that performs this transformation for each line of the two -dimensional array X. The array X should remain unchanged. Use the Numpy library.

import numpy as np def transform(X, A=1): X = X.copy() for i, row in enumerate(X): X[i] = row[::-1] for j, elem in enumerate(X[i]): if j % 2 == 0: X[i][j] = A * elem**3 else: X[i][j] = A return X X = np.arange(1, 9).reshape(2, 4) print(X) print(transform(X, A=2))

Python
View
generate functionMon, 03 Apr 2023

Магическим квадратом порядка n называется квадратная таблица размера n×n, составленная из всех чисел 1,2,3,…,n**2 так, что суммы по каждому столбцу, каждой строке и каждой из двух диагоналей равны между собой. Напишите программу, которая проверяет, является ли заданная квадратная матрица магическим квадратом. Формат входных данных На вход программе подаётся натуральное число n — количество строк и столбцов в матрице, затем элементы матрицы: n строк, по n чисел в каждой, разделённые пробелами. Формат выходных данных Программа должна вывести слово YES, если матрица является магическим квадратом, и слово NO в противном случае.

def magic_square(matrix): n = len(matrix) total = n * (n ** 2 + 1) // 2 return all(total == sum(row) for row in matrix) and all(total == sum(col) for col in zip(*matrix)) and total == sum(matrix[i][i] for i in range(n)) and total == sum(matrix[i][n - i - 1] for i in range(n))

Python
View
generate functionMon, 20 Feb 2023

Implement the Neuron class, which will have several methods: __init__. It takes as input an array of neuron weights --- w=(w1,…,wn) , as well as an activation function f (by default, f(x)=x ). Stores the weights and the function inside the class. forward. It takes as input an array x=(x1,…,xN) --- neuron inputs. Returns f(w1x1+…+wnxn) . backlog. Returns the last array x that was passed to the forward function. class Neuron: def __init__(self, w, f = lambda x: x): #YOUR CODE HERE def forward(self, x): #YOUR CODE HERE def backlog(self): #YOUR CODE HERE

class Neuron: def __init__(self, w, f = lambda x: x): self.w = w self.f = f def forward(self, x): self.x = x return self.f(sum(self.x*self.w)) def backlog(self): return self.x def __call__(self, x): return self.forward(x)

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def sock(n, m): return n + n / (m-1)

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers whose sum is equal to n. In the ten numbers displayed, the numbers do not go in a row. The range of output numbers is strictly not less than 0.001 and not more than 1. The displayed ten digits have strictly twelve digits after the decimal point. The output numbers are strictly greater than 0 and less than 1.

import numpy as np def fun(n): if n<0: return False n = n - 10 a = np.random.rand(10) a = a/sum(a)*10 b = [] for i in range(10): b.append(round(a[i],12)) return b

Python
View
generate functionWed, 05 Apr 2023

В метании молота состязается n спортcменов. Каждый из них сделал m бросков. Побеждает спортсмен, у которого максимален наилучший бросок. Если таких несколько, то из них побеждает тот, у которого наилучшая сумма результатов по всем попыткам. Если и таких несколько, победителем считается спортсмен с минимальным номером. Определите номер победителя соревнований. Входные данные Программа получает на вход два числа n и m, являющиеся числом строк и столбцов в массиве. Далее во входном потоке идет n строк по m чисел, являющихся элементами массива. Выходные данные Программа должна вывести одно число - номер победителя соревнований. Не забудьте, что строки (спортсмены) нумеруются с 0. Решение задачи Youtube Patreon Boosty Sample Input 1: 3 3 1 2 7 1 3 5 4 1 6 Sample Output 1: 0

def solution(n, m, ar): winner = 0 max_sum = 0 max_element = 0 sum_elements = 0 for i in range(n): max_element = 0 sum_elements = 0 for j in range(m): sum_elements += ar[i][j] if ar[i][j] > max_element: max_element = ar[i][j] if max_element >= max_sum: if max_element == max_sum and sum_elements < winner: winner = i elif max_element > max_sum: winner = i max_sum = max_element return winner n = int(input()) m = int(input()) arr = [[] for _ in range(n)] for i in range(n): arr[i] = list(map(int, input().split())) print(solution(n, m, arr))

Python
View
generate functionTue, 14 Feb 2023

Let the coordinates x 1,y 1 of the first point be input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates x 2 ,y 2 of the second point are set to 3, 6 respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

d = sqrt((x2-x1)^2 + (y2-y1)^2)

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the matrix, the number of matrix elements (integers) line by line separated by a space. draw the maximum element below the main diagonal. The elements of the main diagonal are also taken into account.

def func(): n = int(input()) m = [] for i in range(n): m.append([int(j) for j in input().split()]) max_num = -float('inf') for i in range(n): for j in range(n): if i > j and m[i][j] > max_num: max_num = m[i][j] print(max_num)

Python
View
generate functionTue, 14 Feb 2023

Let's take a number. Let's multiply it by its first digit. The result is multiplied by the first digit of the result. And so on. Obviously, when the first digit of the next number in such a sequence becomes equal to 1, the numbers stop changing. But this does not happen for all initial numbers. Let's write a program that will at least approximately determine the fate of the entered number n. Starting with the number n, multiply the given number by its first digit until the resulting number has the first digit equal to 1, or until it exceeds a billion. Output the result as an answer.

def first_digit(n): while n > 1 and n < 10**9: n = n * (n // 10) return n

Python
View
generate functionFri, 17 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

n = int(input()) a = 0 b = 0 while a + b <= n: b = int(input()) if a + b <= n: a += b else: break print("Enough!") print(a)

Python
View
generate functionMon, 03 Apr 2023

В метании молота состязается n спортcменов. Каждый из них сделал m бросков. Побеждает спортсмен, у которого максимален наилучший бросок. Если таких несколько, то из них побеждает тот, у которого наилучшая сумма результатов по всем попыткам. Если и таких несколько, победителем считается спортсмен с минимальным номером. Определите номер победителя соревнований. Входные данные Программа получает на вход два числа n и m, являющиеся числом строк и столбцов в массиве. Далее во входном потоке идет n строк по m чисел, являющихся элементами массива. Выходные данные Программа должна вывести одно число - номер победителя соревнований. Не забудьте, что строки (спортсмены) нумеруются с 0. Решение задачи Youtube Patreon Boosty Sample Input 1: 3 3 1 2 7 1 3 5 4 1 6 Sample Output 1: 0

n = int(input()) m = int(input()) a = [] for i in range(n): a.append(list(map(int,input().split()))) maximum = -100 for i in range(n): for j in range(m): if a[i][j] > maximum: maximum = a[i][j] winner = i if a[winner].count(maximum) >= 2: m = 0 for k in range(m): m += a[winner][k] for i in range(n): s = 0 for j in range(m): s += a[i][j] if s > m: m = s winner = i print(winner)

Python
View
generate functionThu, 13 Apr 2023

«Морской бой» - игра для двух участников, в которой игроки по очереди называют координаты на неизвестной им карте соперника. Если у соперника по этим координатам имеется корабль, то корабль или его часть «топится», а попавший получает право сделать еще один ход. Цель игрока - первым поразить все корабли противника. «Морской бой» очень популярен среди учеников одной физико-математической школы. Ребята очень любят в него играть на переменах. Вот и сейчас ученики Иннокентий и Емельян начали новую партию. Правила, по которым ребята расставляют корабли перед началом партии, несколько отличаются от классических. Во-первых, игра происходит на поле размером N×M, а не 10×10. Во-вторых, число кораблей, их размер и форма выбираются ребятами перед партией - так играть намного интереснее. Емельян уже расставил все свои корабли, кроме одного однопалубного. Такой корабль занимает ровно одну клетку. Задана расстановка кораблей Емельяна. Найдите число способов поставить оставшийся однопалубный корабль. При этом учитывайте, что по правилам его можно ставить только в ту клетку, все соседние с которой не заняты. В этой задаче соседними считаются клетки, имеющие общую сторону. Программа считывает два числа: N и M (1 ≤ N, M ≤ 100). Последующие N строк описывают игровое поле - каждая из них содержит M символов. Символом «.» (точка) обозначена свободная клетка, символом «*» (звездочка) - занятая кораблем. Необходимо вывести на экран ответ на задачу

N, M = map(int, input().split()) m1 = [] for i in range(N): m1.append(list(input())) cnt = 0 for i in range(N): for j in range(M): flag = True if m1[i][j] == ".": if i > 0 and m1[i - 1][j] == "*": flag = False if i < N - 1 and m1[i + 1][j] == "*": flag = False if j > 0 and m1[i][j - 1] == "*": flag = False if j < M - 1 and m1[i][j + 1] == "*": flag = False if flag: cnt += 1 print(cnt)

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Output the maximum element excluding the area above the main diagonal. def matrix(): n = int(input()) a = [] for i in range(n): a.append([int(s) for s in input().split()]) res = -100 for i in range(n): for j in range(n): if i > j and a[i][j] > res: res = a[i][j] print(res) matrix() Failed test #1 of 11. Wrong answer This is a sample test from the problem statement! Test input: 3 1 4 5 6 7 8 1 1 6 Correct output: 7 Your code output: 6

def matrix(): n = int(input()) a = [] for i in range(n): a.append([int(s) for s in input().split()]) res = -100 for i in range(n): for j in range(n): if i > j and a[i][j] > res: res = a[i][j] print(res) matrix()

Python
View
generate functionMon, 06 Mar 2023

output ten numbers whose sum is equal to the number entered from the keyboard. digits do not repeat in numbers. twelve significant digits. the numbers are positive.

def numbers(n): digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] n1, n2, n3, n4, n5, n6, n7, n8, n9, n10 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for i in range(10): for j in range(10): for k in range(10): for l in range(10): for m in range(10): for o in range(10): for p in range(10): for q in range(10): for r in range(10): for s in range(10): if digits[i] + digits[j] + digits[k] + digits[l] + digits[m] + digits[o] + digits[p] + digits[q] + digits[r] + digits[s] == n: n1 = digits[i] n2 = digits[j] n

Python
View
generate functionTue, 14 Feb 2023

Let's take a number. Let's multiply it by its first digit. The result is multiplied by the first digit of the result. And so on. Obviously, when the first digit of the next number in such a sequence becomes equal to 1, the numbers stop changing. But this does not happen for all initial numbers. Let's write a program that will at least approximately determine the fate of the entered number n. Starting with the number n, multiply the given number by its first digit until the resulting number has the first digit equal to 1, or until it exceeds a billion. Output the result as an answer.

def func(n): a = n while n > 10 and n < 1000000000: n *= n // 10 return n

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def sock_pairs(n, m): total_days = 0 all_socks = n # loop till there are socks print("Here are all the socks: ", all_socks) while all_socks > 0: all_socks = all_socks - 1 print("I took 1 sock, so now I have: ", all_socks) total_days = total_days + 1 if total_days % m == 0: all_socks = all_socks + 1 print("It's ", total_days, " days, so I have a new sock, so now I have: ", all_socks) print("total days", total_days) return total_days sock_pairs(5, 2)

Python
View
generate functionMon, 03 Apr 2023

'''Задан целочисленный двумерный массив, состоящий из N строк и M столбцов. Требуется вычислить сумму элементов в каждой строке и в каждом столбце. Программа получает на вход два натуральных числа N и M – количество строк и столбцов двумерного массива. В каждой из последующих N строк записаны M целых чисел – элементы массива. Все числа во входных данных не превышают 1000 по абсолютной величине. В первой строке вам необходимо вывести N чисел – суммы элементов массива для каждой строки в отдельности. Во второй строке в аналогичном формате выведите M чисел – суммы элементов для каждого столбца.'''

def sum_array(array): # проверка на размерность массива if len(array) < 1 or len(array[0]) < 1: return 0 # определяем размерность массива n = len(array) m = len(array[0]) # рассчитываем суммы в строках и столбцах sums_line = [sum(array[i]) for i in range(n)] sums_column = [sum([array[i][j] for i in range(n)]) for j in range(m)] return sums_line, sums_column print(*sum_array([[1, 2, 3], [4, 5, 6

Python
View
generate functionThu, 13 Apr 2023

Манао работает на спортивном телевидении. Он долгое время наблюдал за футбольными матчами чемпионата одной страны и начал замечать разные закономерности. Например, у каждой команды есть две формы: домашняя и выездная. Когда команда проводит матч на своем стадионе, футболисты надевают домашнюю форму, а когда на чужом — выездную. Единственное исключение из этого правила — когда цвет домашней формы принимающей команды совпадает с цветом формы гостей. В таком случае домашняя команда облачается в свою выездную форму. Цвета домашней и выездной формы для каждой команды различны. В чемпионате страны участвует n команд и он состоит из n·(n - 1) матчей: каждая из команд принимает каждую другую команду на своем стадионе. Манао задумался, а сколько раз в течение одного чемпионата случится, что команда, играющая на своем стадионе, оденет выездную форму? Обратите внимание, что для подсчета этого количества порядок матчей не играет никакого значения. Вам даны цвета домашней и выездной формы каждой команды. Для удобства эти цвета пронумерованы целыми числами таким образом, что никакие два разных цвета не имеют одинаковый номер. Помогите Манао найти ответ на его вопрос. Входные данные В первой строке содержится целое число n (2 ≤ n ≤ 30). В каждой из следующих n строк записана пара разделенных одним пробелом различных целых чисел hi, ai (1 ≤ hi, ai ≤ 100) — номер цвета домашней и выездной форм i-ой команды соответственно. Выходные данные В единственной строке выведите количество матчей, в которых домашняя команда выступит в выездной форме. Разбор задачи Youtube Patreon Boosty Sample Input 1: 3 1 2 2 4 3 4 Sample Output 1: 1

n = int(input()) home = [] away = [] for i in range(n): h, a = map(int, input().split()) home.append(h) away.append(a) count = 0 for i in range(n): for j in range(n): if i != j and home[i] == away[j]: count += 1 print(count)

Python
View
generate functionTue, 21 Mar 2023

На вход программе поступает строка, состоящая из нескольких слов, знаком разделителем между словами будем считать символ пробела. Ваша задача исключить из строки дублирующие слова: первое появление слова остается в строке, второе и все последующие появления исключаются. При сравнении на дубли строк регистр букв не учитывать, это значит слова python и PyThOn считаются одинаковыми. В качестве ответа необходимо вывести итоговую строку без дублей

def del_dublicate_words(s): my_list = s.split() my_list = list(set(my_list)) return ' '.join(my_list)

Python
View
generate functionTue, 11 Apr 2023

Вводится список целых чисел в одну строчку через пробел. С помощью словаря выделите только уникальные (не повторяющиеся) введенные значения и, затем, сформируйте список из уникальных чисел. Выведите его на экран в виде набора чисел, записанных через пробел. P. S. Такая задача, обычно решается через множества, но мы их еще не проходили, поэтому воспользуемся словарем.

a = [1, 2, 3, 4, 4, 5, 5, 6] b = [] d = {} for i in a: if i not in d: d[i] = True b.append(i) print(b)

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 Sample Input 2: 3 4 Sample Output 2: 1 2 4 7 3 5 8 10 6 9 11 12 Sample Input 3: 2 2 Sample Output 3: 1 2 3 4 Sample Input 4: 8 1 Sample Output 4: 1 2 3 4 5 6 7 8 Sample Input 5: 8 2 Sample Output 5: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

# напишите функцию, которая возвращает матрицу с образцом def matrix_pattern(n, m): return matrix # напишите функцию, которая выводит матрицу с образцом на экран def print_matrix_pattern(n, m): matrix = matrix_pattern(n, m) for i in range(n): for j in range(m): print('{}'.format(matrix[i][j]), end=' ') print() n, m = map(int, input().split()) print_matrix_pattern(

Python
View
generate functionThu, 13 Apr 2023

'''Вводятся целые числа в одну строку через пробел. На их основе формируется кортеж. Необходимо создать еще один кортеж с уникальными (не повторяющимися) значениями из первого кортежа. Результат отобразите в виде списка чисел через пробел. P. S. Подобные задачи решаются, как правило, с помощью множеств, но в качестве практики пока обойдемся без них. Sample Input: 8 11 -5 -2 8 11 -5 Sample Output: 8 11 -5 -2'''

s = tuple(map(int, input().split())) s1 = [] for i in s: if i not in s1: s1.append(i) print(*s1)

Python
View
generate functionWed, 12 Apr 2023

Имеется словарь с наименованиями предметов и их весом (в граммах): things = {'карандаш': 20, 'зеркальце': 100, 'зонт': 500, 'рубашка': 300, 'брюки': 1000, 'бумага': 200, 'молоток': 600, 'пила': 400, 'удочка': 1200, 'расческа': 40, 'котелок': 820, 'палатка': 5240, 'брезент': 2130, 'спички': 10} Сергей собирается в поход и готов взвалить на свои хрупкие плечи максимальный вес в N кг (вводится с клавиатуры). Он решил класть в рюкзак предметы в порядке убывания их веса (сначала самые тяжелые, затем, все более легкие) так, чтобы их суммарный вес не превысил значения N кг. Все предметы даны в единственном экземпляре. Выведите список предметов (в строчку через пробел), которые берет с собой Сергей в порядке убывания их веса. P. S. 1 кг = 1000 грамм Sample Input: 10 Sample Output: палатка брезент удочка брюки пила карандаш спички

n = int(input()) things = {'карандаш': 20, 'зеркальце': 100, 'зонт': 500, 'рубашка': 300, 'брюки': 1000, 'бумага': 200, 'молоток': 600, 'пила': 400, 'удочка': 1200, 'расческа': 40, 'котелок': 820, 'палатка': 5240, 'брезент': 2130, 'спички': 10} def choose_things(things, n): res = [] things = {k: v for k, v in sorted(things.items(), key=lambda item: item[1], reverse=True)} for item, value in things.items(): if value <= n:

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

def create_dict(list_of_strings): lst = [] for i in list_of_strings: lst.append(i.split()) dic = {} for j in lst: dic[j[0]] = dic.get(j[0], '') + j[1] + ', ' for i in dic.keys(): dic[i] = dic[i][0:-2] return dic

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 Sample Input 2: 3 4 Sample Output 2: 1 2 4 7 3 5 8 10 6 9 11 12 Sample Input 3: 2 2 Sample Output 3: 1 2 3 4 Sample Input 4: 8 1 Sample Output 4: 1 2 3 4 5 6 7 8 Sample Input 5: 8 2 Sample Output 5: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

n, m = [int(s) for s in input().split()] matrix = [[0 for x in range(m)] for y in range(n)] for i in range(n): for j in range(m): if i == 0: matrix[i][j] = j+1 elif i == 1: matrix[i][j] = matrix[i-1][j] + i else: matrix[i][j] = matrix[i-1][j] + i + 1 for row in matrix: for elem in row: print(str(elem).ljust(3), end = '') print()

Python
View
generate functionMon, 20 Feb 2023

Given an array A[0,…,N−1] . Write a function that takes one required argument A and one optional argument erase, which defaults to 1. Return an array B[0,…,N−1] , where Bi=A0+…+Ai is an array of partial sums of array A , after removing from array B, all elements equal to erase. Try to do it in linear time without using Numpy. def cumsum_and_erase(<YOUR CODE>): #YOUR CODE B = #YOUR CODE return B A = [5, 1, 4, 5, 14] B = cumsum_and_erase(A, erase=10) assert B == [5, 6, 15, 29], "Something is wrong! Please try again"

def cumsum_and_erase(A, erase = 1): partial = 0 B = [] for num in A: partial += num if partial != erase: B.append(partial) else: partial = 0 return B

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def Vasya(n, m): if n >= m: return m else: return n Vasya(5, 4)

Python
View
generate functionTue, 28 Feb 2023

Using Numpy, write an array coding function (Run-Length Encoding). The function of repetition of elements compresses the function into one element and considers the number of repetitions. The function returns a motorcade of two Numpy veins of the same length. The first contains elements, and the second - how many times they need to be repeated. Example: Encode (np.array ([1, 2, 2, 3, 3, 1, 1, 5, 5, 2, 3, 3, 3])) = (np.array ([1, 2, 3, 1, 1, 1, 1, 1, 5, 2, 3]), np.array ([1, 2, 2, 2, 2, 1, 2]))

def encode(a): c = [] index = 0 a_len = len(a) while index < a_len: c.append(a[index]) b = 1 while index + 1 < a_len and a[index] == a[index + 1]: index += 1 b += 1 c.append(b) index += 1 c = np.array(c) return c[0::2], c[1::2] encode(np.array([1,2,2,3,3,1,1,5,5,2,3,3,3,2,2]))

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m заполнив её "змейкой" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение Тестовые данные Sample Input 1: 3 5 Sample Output 1: 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15

n, m = [int(i) for i in input().split()] a = [] for i in range(n): b = [] for j in range(m): b.append(0) a.append(b) print(a)

Python
View
generate functionMon, 03 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу для создания матрицы размером n x m, заполнив её символами '.' и '*' в шахматном порядке. В левом верхнем углу должна стоять точка. Выведите полученную матрицу (без кавычек и скобочек) на экран, разделяя элементы пробелами.

def chess(n, m): matrix = [['.'] * m for i in range(n)] x, y = 0, 0 symbol = '*' value = '.' while x < n and y < m: matrix[x][y] = symbol y += 1 x += 1 if x == n or y == m: x -= 1 y -= 1 while x > 0 and y > 0: x -= 1 y -= 1 if y == m - 1 and x >= 0: x += 2 y -= 1 if x == n - 1 and y <= m - 1: x -= 1 y += 2 symbol, value = value, symbol for row in matrix: print(' '.join(row)) row, col = input().split() chess(int(row), int(col))

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

file = open('birth_days.txt', 'r') dict = {} for line in file: month, name = line.split() if month not in dict: dict.update({month: [name]}) else: dict[month].append(name) for key, value in dict.items(): print(f'{key}: {", ".join(value)}')

Python
View
generate functionTue, 04 Apr 2023

'''Выведите таблицу размером n×n, заполненную числами от 1 до n ** 2 по спирали, выходящей из левого верхнего угла и закрученной по часовой стрелке, как показано в примере Sample Input: 5 Sample Output: 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9'''

def spiral(n): dx, dy = 1, 0 # Starting increments x, y = 0, 0 # Starting location myarray = [[None]* n for j in range(n)] for i in range(n**2): myarray[x][y] = i nx, ny = x+dx, y+dy if 0 <= nx < n and 0 <= ny < n and myarray[nx][ny] == None: x, y = nx, ny else: dx, dy = -dy, dx x, y = x+dx, y+dy return myarray n = int(input()) for x in spiral(n): print(*x)

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. Например, если на вход подаётся список "1 3 5 6 10", то на выход ожидается список "13 6 9 15 7" (без кавычек). Если на вход пришло только одно число, надо вывести его же. Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом.

a = [int(i) for i in input().split()] def f(a): b = [] if len(a) == 1: b.append(a[0]) else: b.append(a[-1] + a[1]) for i in range(1, len(a) - 1): b.append(a[i - 1] + a[i + 1]) b.append(a[0] + a[-2]) return b print(' '.join([str(i) for i in f(a)]))

Python
View
generate functionMon, 10 Apr 2023

'''Напишите программу для вычисления суммы двух матриц. Формат входных данных На вход программе подаются два натуральных числа n и m — количество строк и столбцов в матрицах, затем элементы первой матрицы, затем пустая строка, далее следуют элементы второй матрицы. Формат выходных данных Программа должна вывести результирующую матрицу, разделяя элементы символом пробела.'''

def addMatrix(matrix1, matrix2): for i in range(len(matrix1)): for j in range(len(matrix1[0])): matrix1[i][j] += matrix2[i][j] return matrix1 n, m = map(int, input().split()) matrix1 = [] matrix2 = [] for i in range(n): matrix1.append(list(map(int, input().split()))) input() for i in range(n): matrix2.append(list(map(int, input().split()))) addMatrix(matrix1, matrix2) for i in matrix1: for x in i: print(x, end=' ') print()

Python
View
generate functionFri, 14 Apr 2023

'''Дана прямоугольная матрица размером NxM, в которой заполнены значения только в первом столбце и в первом ряду. Все остальные элементы равны нулю и мы считаем их незаполненными. Ваша задача заполнить каждый пустой элемент путем сложения соседа слева и соседа сверху. Начинать нужно с тех элементов, у которых оба указанных соседа заполнены (не равны нулю) Входные данные Программа сперва принимает в одной строке на вход два числа N и M - количество строк и столбцов в списке, а затем в N строках записаны элементы списка. Выходные данные Вывести заполненную матрицу Sample Input 1: 5 4 1 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 Sample Output 1: 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 1 5 15 35'''

def matrix(a, b): matrix = [[0] * b for i in range(a)] for i in range(a): matrix[i] = [int(x) for x in input().split()] for i in range(1, a): for j in range(1, b): if matrix[i][0] == 0 and matrix[0][j] == 0: matrix[i][j] = 0 elif matrix[i][0] == 0: matrix[i][j] = matrix[i][j - 1] elif matrix[0][j] == 0: matrix[i][j] = matrix[i - 1][j] else: matrix[i][j] = matrix[i][j - 1] + matrix[i - 1][j] for j in range(a): for i in range(b): print(matrix[j][i], end=' ') print()

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

Python
View
generate functionTue, 28 Feb 2023

A two -dimensional array X. For each line of array X, the following transformation must be made. Let the line X be given. It is necessary to build a new array, where all elements with odd indices are required to be replaced by the number A (the default value A = 1). All elements with even indices need to be built into the cube. Then write the elements in the reverse order regarding their positions. At the end, it is required to drain an array X with a converted X and display. Write a function that performs this transformation for each line of the two -dimensional array X. The array X should remain unchanged. Use the Numpy library. Example: x = [100,200,300,400,500]] -> [[100, A, 300, A, 500]] -> [[500 ** 3, A, 300 ** 3, A, 100 ** 3]] -> -> -> Close -> [[100,200,300,400,500,500 ** 3, A, 300 ** 3, A, 100 ** 3]]]

import numpy as np def array_transformation(x): x = np.asarray(x) a = np.arange(0, x.size, 2) b = np.arange(1, x.size, 2) x[a] = x[a] ** 3 x[b] = 1 x[::-1] return x # test case array_transformation([[1, 2, 3], [4, 5, 6]])

Python
View
generate functionWed, 15 Mar 2023

You receive a word as input and your task in the while loop is to bypass all its letters and print them in the phrase format: "Current letter: <letter>". As soon as you meet the lowercase English letters "e" or "a" you need to print the phrase "Aha! Found”, stop typing letters and forcibly exit the loop. If the word does not contain the letters "e" or "a", you must print the phrase "Printed out all the letters"

word = input() i = 0 while i < len(word): if word[i] in 'ae': print("Aha!") break print("Current letter: ", word[i]) i += 1 else: print("Printed out all the letters")

Python
View
generate functionWed, 08 Feb 2023

When playing "Cities", players take turns calling the names of cities so that the first letter of each new word coincides with the last letter of the previous one. At the same time, it is believed that if the last letter of the previous word is f, then the letter preceding f should be compared with the first letter of the next word. Write a program that reads two lines in a row, and then prints "Good" if the last character of the first line matches the first character of the second (subject to the f rule), and "Bad" otherwise.

def cities(a, b): return a[-1] == b[0] or a[-2] == b[0] and a[-1] == 'f' cities('Moscow', 'Nagoya')

Python
View
generate functionTue, 07 Mar 2023

a fractional number n is entered from the keyboard. Output ten numbers whose sum is equal to n. The numbers range from 0.001213245678 to n. The numbers are positive. The first two digits after the decimal point in the number can be equal to 0. The remaining digits in the number go without repetition. The number must have twelve significant decimal places.

# -*- coding: utf-8 -*- import itertools def func(n): n = round(n,8) n = str(n).split('.')[1] n = n[:4] lst = list(itertools.combinations(range(10), 4)) lst = [i[:2] for i in lst if i[2] == i[3] and i[0] != i[1] and i[0]!=0 and i[1]!=0] lst = [i[0]*10 + i[1] for i in lst] lst = [1.0*int(n[i:i+2])/100 for i in range(len(n)) if i % 2 == 0] s = sum(lst) lst = [0.01*i for i in lst] lst.append(n-s) return lst

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Написать алгоритм рассадки людей от 1 до m дней, так чтобы за за количество дней от 1 до m все люди посидел с максимально возможным количеством человек исходя из заданных значений. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 2 Введите количество мест за 2-м столом: 1 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2] Пример ввода 2 Введите количество людей: 6 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 3 Введите количество мест за 2-м столом: 3 Пример вывода 2 День 1: На столе 1 сидят люди с номерами: [1, 2, 3] На столе 2 сидят люди с номерами: [4, 5, 6] День 2: На столе 1 сидят люди с номерами: [1, 3, 5] На столе 2 сидят люди с номерами: [2, 4, 6]

def make_seating(input_values_list): people_count = 0 days_count = 0 seating_map = list() day_seating = list() tables_seating_map = list() if len(input_values_list) >= 4: people_count = int(input_values_list[0]) days_count = int(input_values_list[1]) tables_count = int(input_values_list[2]) tables_seating_map = list(map(int, input_values_list[3:])) if sum(tables_seating_map) != people_count: return None seating_map = make_seating_list(tables_seating_map, people_count, days_count) if len(seating_map) == 0: return None else: return None return seating_map def make_seating_list(tables_seating_map

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, которая считывает строку с числом � n, которое задаёт количество чисел, которые нужно считать. Далее считывает � n строк с числами � � x i ​ , по одному числу в каждой строке. Итого будет � + 1 n+1 строк. При считывании числа � � x i ​ программа должна на отдельной строке вывести значение � ( � � ) f(x i ​ ). Функция f(x) уже реализована и доступна для вызова. Функция вычисляется достаточно долго и зависит только от переданного аргумента � x. Для того, чтобы уложиться в ограничение по времени, нужно избежать повторного вычисления значений.

def f(x): return ... n = int(input()) for i in range(n): x = int(input()) print(f(x))

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Написать алгоритм рассадки людей от 1 до m дней, так чтобы за за количество дней от 1 до m все люди посидел с максимально возможным количеством человек исходя из заданных значений. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 2 Введите количество мест за 2-м столом: 1 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2] Пример ввода 2 Введите количество людей: 6 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 3 Введите количество мест за 2-м столом: 3 Пример вывода 2 День 1: На столе 1 сидят люди с номерами: [1, 2, 3] На столе 2 сидят люди с номерами: [4, 5, 6] День 2: На столе 1 сидят люди с номерами: [1, 3, 5] На столе 2 сидят люди с номерами: [2, 4, 6]

max_people = 1 n = int(input("Введите количество людей: ")) m = int(input("Введите количество дней: ")) k = int(input("Введите количество столов: ")) days = list() for i in range(0, m): days.append([]) for z in range(0, k): days[i].append([]) for j in range(0, int(input("Введите количество мест за " + str(z + 1) + "-м столом: "))): days[i][z].append(j + 1) for i in range(0, m): print

Python
View
generate functionTue, 21 Feb 2023

The date of a certain day is characterized by two natural numbers: m (serial number of the month) and n (number). According to the entered m and n (in one line separated by a space), determine: a) the date of the previous day (assume that m and n do not characterize January 1); b) the date of the next day (assume that m and n do not characterize December 31). The problem is to assume that the year is not a leap year. Print the previous date and the next date (in the format: mm.dd, where m is the day of the month; d is the number of the day) in one line separated by a space. P.S. Number of days in non-leap year months starting from January: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31

def date(m, n): if n - 1 != 0: n -= 1 else: n = 30 if m - 1 != 0: m -= 1 if n + 1 <= 30: n += 1 else: n = 1 if m + 1 <= 12: m += 1 return m, n date(12, 31)

Python
View
generate functionMon, 20 Feb 2023

Given an array A[0,…,N−1] . Write a function that takes one required argument A and one optional argument erase, which defaults to 1. Return an array B[0,…,N−1] , where Bi=A0+…+Ai is an array of partial sums of array A , after removing from array B, all elements equal to erase. Try to do it in linear time without using Numpy. def cumsum_and_erase(<YOUR CODE>): #YOUR CODE B = #YOUR CODE return B A = [5, 1, 4, 5, 14] B = cumsum_and_erase(A, erase=10) assert B == [5, 6, 15, 29], "Something is wrong! Please try again"

def cumsum_and_erase(A, erase=1): #YOUR CODE B = [0 for _ in range(len(A))] B[0] = A[0] for i in range(1,len(A)): B[i] = B[i-1] + A[i] while erase in B: B.remove(erase) return B A = [5, 1, 4, 5, 14] B = cumsum_and_erase(A, erase=10) assert B == [5, 6, 15, 29], "Something is wrong! Please try again"

Python
View
generate functionFri, 17 Mar 2023

def numerical_derivative_2d(func, epsilon): """ Function for approximate calculation of the gradient of a function of two variables. :param func: np.array[2] -> float - arbitrary differentiable function :param epsilon: float - the maximum amount of increment along the axes :return: another function that approximates the gradient at a point """ def grad_func(x): """ :param x: np.array[2] - the point at which you want to calculate the gradient :return: np.array[2] - approximate value of the gradient at this point """ <YOUR CODE> return <YOUR CODE> return grad_func def grad_descent_2d(func, low, high, start=None, callback=None): """ Gradient Descent Implementation for Functions of Two Variables with few local minima but known square neighborhood global minimum. All tests will be of this nature. Note that the function gradient is not given here. It must be calculated approximately. :param func: np.ndarray -> float - function :param low: the left margin of the interval along each of the axes :param high: the right limit of the interval along each of the axes """ eps=1e-10 df = numerical_derivative_2d(func, eps) <YOUR CODE> return <YOUR CODE>

def grad_descent_2d(func, low, high, start=None, callback=None): """ Gradient Descent Implementation for Functions of Two Variables with few local minima but known square neighborhood global minimum. All tests will be of this nature. Note that the function gradient is not given here. It must be calculated approximately. :param func: np.ndarray -> float - function :param low: the left margin of the interval along each of the axes :param high: the right limit of the interval along each of the axes """ eps=1e-10 df = numerical_derivative_2d(func, eps) <YOUR CODE> return <YOUR CODE>

Python
View
generate functionWed, 01 Mar 2023

You have two non-decreasing sorted lists of n and m elements Your task is to merge them into one sorted list of size n + m Input The program receives as input two numbers n and m - the number of elements of the first list and the second list Then the elements of the first sorted list come from a new line, and from the next line - the second list Output Merge two lists into one in non-decreasing order and output the elements of the resulting list P.S: it is forbidden to use the built-in sorting Note: to display the resulting list, you can use the following construction print(*result) # where result is the final list

n = int(input()) m = int(input()) a = [int(input()) for _ in range(n)] b = [int(input()) for _ in range(m)] c = a + b for i in range(len(c)): m = min(c) print(m, end=' ') c.remove(m) print()

Python
View
generate functionTue, 14 Feb 2023

Pust' koordinaty � 1 x 1​, � 1 y 1​pervoy tochki podayutsya na vkhod (podrazumevayetsya, chto oni podstavlyayutsya sistemoy iz zalozhennykh testovykh chisel). Puskay koordinaty � 2 , � 2 x 2​,y 2​vtoroy tochki zadany znacheniyami 3, 6 sootvetstvenno. Neobkhodimo nayti yevklidovo rasstoyaniye mezhdu dvumya tochkami. Yesli rasstoyaniye strogo bol'she epsilon, vyvesti na ekran "Vne klastera" (s pomoshch'yu print), inache vyvesti "V klastere". Evklidovo rasstoyaniye zadayem formuloy � = ( � 1 − � 2 ) 2 + ( � 1 − � 2 ) 2 r= (x 1​−x 2​) 2 +(y 1​−y 2​) 2​ Ещё 566 / 5 000 Результаты перевода Перевод Let the coordinates � 1 x 1 ​ , � 1 y 1 ​ of the first point are fed to the input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates � 2 , � 2 x 2 ​ ,y 2 ​ the second point are set to 3, 6, respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

r = (x 1​−x 2​)2+(y 1​−y 2​)2

Python
View
generate functionTue, 07 Mar 2023

import random n = int(input()) # вводим число lst = [] # инициализирую список для накопления значений while n != 0 and len(lst) < 10: a = random.randrange(1, n, 12) # создаем случайное двенадцатизначное число меньше n lst.append(('0.' + str(a).zfill(12))) # заполнить число нулями слева если нет 12 порядков и дополняем "0," n -= a print(*lst, sep='\n')

import random n = int(input()) # вводим число lst = [] # инициализирую список для накопления значений while n != 0 and len(lst) < 10: a = random.randrange(1, n, 12) # создаем случайное двенадцатизначное число меньше n lst.append(('0.' + str(a).zfill(12))) # заполнить число нулями слева если нет 12 порядков и д

Python
View
generate functionTue, 14 Feb 2023

Let the coordinates � 1 x 1 ​ , � 1 y 1 ​ of the first point are fed to the input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates � 2 , � 2 x 2 ​ ,y 2 ​ the second point are set to 3, 6, respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

D = sqrt((x2 - x1)**2 + (y2 - y1)**2).

Python
View
generate functionWed, 08 Feb 2023

When playing "Cities", players take turns calling the names of cities so that the first letter of each new word coincides with the last letter of the previous one. At the same time, it is believed that if the last letter of the previous word is f, then the letter preceding f should be compared with the first letter of the next word. Write a program that reads two lines in a row, and then prints "Good" if the last character of the first line matches the first character of the second (subject to the f rule), and "Bad" otherwise.

def cities(a, b): if a[-1].upper() == b[0].upper() and a[-1].upper() != 'F': return 'Good' elif a[-2].upper() == b[0].upper(): return 'Good' else: return 'Bad' cities('Moscow', 'London') cities('London', 'Washington') cities('Sofia', 'Whashington')

Python
View
generate functionThu, 02 Mar 2023

A natural number n is entered (that is, a positive integer). Loop through all integers in the interval [1; n] and form a list of multiples of 3 and 5 at the same time. Output the resulting sequence of numbers as a space-separated string if the value of n is less than 100. Otherwise, display the message "n is too large" (without quotes). Use an else statement in the program after the while lo

def mult35(n): if n >= 100: print("n is too large") elif n < 100: i = 1 while i <= n: if i % 3 == 0 and i % 5 == 0: print(i, end=" ") i += 1

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def vasya(n, m): return n + (m - n % m) vasya(1, 2)

Python
View
generate functionTue, 28 Feb 2023

A two -dimensional array X. For each line of array X, the following transformation must be made. Let the line X be given. It is necessary to build a new array, where all elements with odd indices are required to be replaced by the number A (the default value A = 1). All elements with even indices need to be built into the cube. Then write the elements in the reverse order regarding their positions. At the end, it is required to drain an array X with a converted X and display. Write a function that performs this transformation for each line of the two -dimensional array X. The array X should remain unchanged. Use the Numpy library. Example: x = [100,200,300,400,500]] -> [[100, A, 300, A, 500]] -> [[500 ** 3, A, 300 ** 3, A, 100 ** 3]] -> -> -> Close -> [[100,200,300,400,500,500 ** 3, A, 300 ** 3, A, 100 ** 3]]]

def convert(array, a=1): new_array = [] for i in array: new_array.append(i**3) new_array.append(a) new_array.reverse() return array + new_array convert([1, 2, 3])

Python
View
generate functionTue, 28 Feb 2023

A two -dimensional array X. For each line of array X, the following transformation must be made. Let the line X be given. It is necessary to build a new array, where all elements with odd indices are required to be replaced by the number A (the default value A = 1). All elements with even indices need to be built into the cube. Then write the elements in the reverse order regarding their positions. At the end, it is required to drain an array X with a converted X and display. Write a function that performs this transformation for each line of the two -dimensional array X. The array X should remain unchanged. From Copy Import Copy Def NP_TRANSFORMATION (X, A = 1): "" "" X: np.array [num_row, num_column] --- matrix-argument a: float --- meaning for converting odd elements of lines into x Return s: np.array [num_row, num_column*2] --- Matrix, where the lines are flexible lines of the original matrix X with lines, which are their transformations The function takes on the input matrix X dimensions n x m, the number a and Returns the matrix with dimensions n x m*2, the i-th line of which is glued I-th line X with its transformation of its line Transformation (X [I]), written in the reverse order, where the transformation for the number K is defined as: Transformation (k) = a if ind (k) % 2 == 0 else k ** 3 In the implementation of this function, it is necessary to use the functionality of the Numpy package

def transformation(X, A=1): ''' X: np.array [num_row, num_column] --- matrix-argument a: float --- meaning for converting odd elements of lines into x Returns: np.array [num_row, num_column*2] --- Matrix, where the lines are flexible lines of the original matrix X with lines, which are their transformations The function takes on the input matrix X dimensions n x m, the number a and Returns the matrix with dimensions n x m*2, the i-th line of which is glued I-th line X with its transformation of its line Transformation (X [I]), written in the reverse order, where the transformation for the number K is defined as: Transformation (k) = a if ind (k) % 2 == 0 else k ** 3 In the implementation of this function, it is necessary to use the functionality of the Numpy package ''' return X

Python
View
generate functionThu, 16 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

def backpack(n, *args): vol = 0 i = 0 for arg in args: i += 1 vol += arg if vol > n: print("Enough!") print("%d" %(i-1)) print("%d" %(vol-arg)) break backpack(10, 10, 10, 10)

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (число повторяется столько раз, чему равно). На вход программе передаётся неотрицательное целое число n — столько элементов последовательности должна отобразить программа. На выходе ожидается последовательность чисел, записанных через пробел в одну строку. Например, если n = 7, то программа должна вывести 1 2 2 3 3 3 4.

def func(n): result = [] for i in range(1, n+1): result.append(i) result.append(i) result.append(i) return result

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15

n, m = int(input()), int(input()) a = [[0] * m for i in range(n)] k = 1 for j in range(m): for i in range(n): a[i][j] = k k += 1 for row in a: print(' '.join([str(elem).ljust(3) for elem in row]))

Python
View
generate functionTue, 28 Feb 2023

Matrix multiplication Write two functions that each multiply two square matrices, one without using numpy's built-in functions, and the other using numpy. The input to the first task is given lists of size size by size elements in each. The second task receives objects of type np.ndarray --- square matrices of the same size. The first function should return a list of lists, and the second should return np.array.

def multiply(a, b): # TODO: your code here return c pass def multiply_numpy(a, b): # TODO: your code here return c pass

Python
View
generate functionTue, 07 Mar 2023

a fractional number n is entered from the keyboard. Output ten numbers. The sum of all ten numbers displayed is n. All ten numbers displayed are positive. Numbers must have twelve significant decimal places. The first two digits after the decimal point in the printed numbers can be equal to 0. The rest of the digits in the ten output numbers go without repetition.

def sum(n): a = 10 q = n/a r = n%a for i in range(0,a-1): x = q*10 y = int(x) x = x-y x = x*10 print(x) n = n-x print(n) sum(100.123456789012)

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, на вход которой подаётся список чисел одной строкой. Программа должна для каждого элемента этого списка вывести сумму двух его соседей. Для элементов списка, являющихся крайними, одним из соседей считается элемент, находящий на противоположном конце этого списка. Например, если на вход подаётся список "1 3 5 6 10", то на выход ожидается список "13 6 9 15 7" (без кавычек). Если на вход пришло только одно число, надо вывести его же. Вывод должен содержать одну строку с числами нового списка, разделёнными пробелом.

def list_sum(list_): if len(list_) == 1: return list_[0] else: if len(list_) == 2: return list_[0] + list_[1] else: return list_[0] + list_[-1] lst = list(map(int, input().split())) lst_ = [list_sum(lst[:i] + lst[i+1:]) for i in range(len(lst))] print(' '.join(map(str,lst_)))

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир Для считывания списка целиком в программе уже записаны начальные строчки: import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines()))

import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines())) # считывание дней для словаря days = list(map(lambda x: int(x.split()[0]), lst_in)) # считывание имен для словаря names = list(map(lambda x: x.split()[1], lst_in)) # словарь b_dict = {} for i in range(len(days)): b_dict[days[i]] = b_dict.get(days[i], '') + ', ' + names[i] # вывод дл

Python
View
generate functionTue, 14 Feb 2023

Pust' koordinaty � 1 x 1​, � 1 y 1​pervoy tochki podayutsya na vkhod (podrazumevayetsya, chto oni podstavlyayutsya sistemoy iz zalozhennykh testovykh chisel). Puskay koordinaty � 2 , � 2 x 2​,y 2​vtoroy tochki zadany znacheniyami 3, 6 sootvetstvenno. Neobkhodimo nayti yevklidovo rasstoyaniye mezhdu dvumya tochkami. Yesli rasstoyaniye strogo bol'she epsilon, vyvesti na ekran "Vne klastera" (s pomoshch'yu print), inache vyvesti "V klastere". Evklidovo rasstoyaniye zadayem formuloy � = ( � 1 − � 2 ) 2 + ( � 1 − � 2 ) 2 r= (x 1​−x 2​) 2 +(y 1​−y 2​) 2​ Ещё 566 / 5 000 Результаты перевода Перевод Let the coordinates � 1 x 1 ​ , � 1 y 1 ​ of the first point are fed to the input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates � 2 , � 2 x 2 ​ ,y 2 ​ the second point are set to 3, 6, respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

r = (x 1​−x 2​) 2 +(y 1​−y 2​) 2

Python
View
generate functionWed, 12 Apr 2023

Имеется словарь с наименованиями предметов и их весом (в граммах): things = {'карандаш': 20, 'зеркальце': 100, 'зонт': 500, 'рубашка': 300, 'брюки': 1000, 'бумага': 200, 'молоток': 600, 'пила': 400, 'удочка': 1200, 'расческа': 40, 'котелок': 820, 'палатка': 5240, 'брезент': 2130, 'спички': 10} Сергей собирается в поход и готов взвалить на свои хрупкие плечи максимальный вес в N кг (вводится с клавиатуры). Он решил класть в рюкзак предметы в порядке убывания их веса (сначала самые тяжелые, затем, все более легкие) так, чтобы их суммарный вес не превысил значения N кг. Все предметы даны в единственном экземпляре. Выведите список предметов (в строчку через пробел), которые берет с собой Сергей в порядке убывания их веса. P. S. 1 кг = 1000 грамм Sample Input: 10 Sample Output: палатка брезент удочка брюки пила карандаш спички

def pack(N): things = {'карандаш': 20, 'зеркальце': 100, 'зонт': 500, 'рубашка': 300, 'брюки': 1000, 'бумага': 200, 'молоток': 600, 'пила': 400, 'удочка': 1200, 'расческа': 40, 'котелок': 820, 'палатка': 5240, 'брезент': 2130, 'спички': 10} items = sorted(things.items(), key=lambda x: x[1], reverse=True) res = [] for i in range(len(items)): res.append(items[i][0]) if sum(items[:i+1]) > N:

Python
View
generate functionFri, 14 Apr 2023

'''Дана прямоугольная матрица размером NxM, в которой заполнены значения только в первом столбце и в первом ряду. Все остальные элементы равны нулю и мы считаем их незаполненными. Ваша задача заполнить каждый пустой элемент путем сложения соседа слева и соседа сверху. Начинать нужно с тех элементов, у которых оба указанных соседа заполнены (не равны нулю) Входные данные Программа сперва принимает в одной строке на вход два числа N и M - количество строк и столбцов в списке, а затем в N строках записаны элементы списка. Выходные данные Вывести заполненную матрицу Sample Input 1: 5 4 1 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 Sample Output 1: 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 1 5 15 35'''

def get_last_value(matrix, n, m, i, j, answer): if (n - 1) == i and (m - 1) == j: return answer + matrix[i][j] if (n - 1) == i: return get_last_value(matrix, n, m, i, j + 1, answer + matrix[i][j]) if (m - 1) == j: return get_last_value(matrix, n, m, i + 1, j, answer + matrix[i][j]) return get_last_value(matrix, n, m, i, j + 1, answer + matrix[i][j]) def fill_matrix(matrix, n, m, i, j, answer): if (n - 1) == i and (m - 1) == j: return answer + matrix[i][j] if (n - 1) == i: return get_last_value(matrix, n, m, i, j + 1, answer + matrix

Python
View
generate functionMon, 03 Apr 2023

На вход программе подается натуральное число n. Напишите программу, которая создает матрицу размером n×n заполнив её в соответствии с образцом. Формат входных данных На вход программе подается натуральное число n — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение Тестовые данные Sample Input 1: 5 Sample Output 1: 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1

n = int(input()) for i in range(n): for j in range(n): if i == 0 or j == 0 or i == n - 1 or j == n - 1: print(1, end=' ') else: print(0, end=' ') print()

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: <день рождения 1> имя_1 <день рождения 2> имя_2 ... <день рождения N> имя_N Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): день рождения 1: имя1, ..., имяN1 день рождения 2: имя1, ..., имяN2 ... день рождения M: имя1, ..., имяNM Для считывания списка целиком в программе уже записаны начальные строчки: import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines())) Sample Input: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Sample Output: 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines())) # ваша основная логика здесь # пример: # печать обратного входного списка for s in lst_in[::-1]: print(s)

Python
View
generate functionWed, 08 Feb 2023

When playing "Cities", players take turns calling the names of cities so that the first letter of each new word coincides with the last letter of the previous one. At the same time, it is believed that if the last letter of the previous word is f, then the letter preceding f should be compared with the first letter of the next word. Write a program that reads two lines in a row, and then prints "Good" if the last character of the first line matches the first character of the second (subject to the f rule), and "Bad" otherwise.

def cities (a, b): return a[-1] == b[0] cities('Moscow', 'Piter')

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python. n людей за m дней должны посидеть за k столами. сумма мест за столами равно n. Максимальное количество людей должно познакомиться друг с другом. Считается что люди познакомились если они уже сидели за одним столом. вывести значения как в примере Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2]

3 n = int(input('Количество людей: ')) m = int(input('Количество дней: ')) k = int(input('Количество столов: ')) tables = [[] for _ in range(k)] for day in range(1, m + 1): print(f'\nДень {day}:') for table in range(1, k + 1): tables[table - 1].append(table) print(f'\tНа столе {table} сидят люди с номерами: {tables[table - 1]}') if len(tables[table - 1]) == n: tables[table - 1] = []

Python
View
generate functionTue, 28 Feb 2023

Matrix multiplication Write two functions that each multiply two square matrices, one without using numpy's built-in functions, and the other using numpy. The input to the first task is given lists of size size by size elements in each. The second task receives objects of type np.ndarray --- square matrices of the same size. The first function should return a list of lists, and the second should return np.array.

def my_matmul(X, Y): result = [[0 for i in range(len(Y[0]))] for j in range(len(X))] for i in range(len(X)): for j in range(len(Y[0])): for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] return result my_matmul([[1,2], [3,4]], [[2,0], [1,2]]) def numpy_matmul(X, Y): return np.matmul(X, Y) numpy_matmul(np.array([[1,2], [3,4]]), np.array([[2,0], [1,2]]))

Python
View
generate functionFri, 14 Apr 2023

'''Дана прямоугольная матрица размером NxM, в которой заполнены значения только в первом столбце и в первом ряду. Все остальные элементы равны нулю и мы считаем их незаполненными. Ваша задача заполнить каждый пустой элемент путем сложения соседа слева и соседа сверху. Начинать нужно с тех элементов, у которых оба указанных соседа заполнены (не равны нулю) Входные данные Программа сперва принимает в одной строке на вход два числа N и M - количество строк и столбцов в списке, а затем в N строках записаны элементы списка. Выходные данные Вывести заполненную матрицу Sample Input 1: 5 4 1 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 Sample Output 1: 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 1 5 15 35'''

n, m = map(int, input().split()) a = [[int(i) for i in input().split()] for j in range(n)] for i in range(1, n): for j in range(1, m): if a[i][0] == 0: a[i][0] = a[i - 1][0] if a[0][j] == 0: a[0][j] = a[0][j - 1] if a[i][j] == 0 and a[i][0] != 0 and a[0][j] != 0: a[i][j] = a[i - 1][j] + a[i][j - 1] print(a[i][j], end=' ') print()

Python
View
generate functionTue, 07 Mar 2023

import random n = int(input()) # вводим число lst = [] # инициализирую список для накопления значений while n != 0 and len(lst) < 10: a = random.randrange(1, n, 12) # создаем случайное двенадцатизначное число меньше n lst.append(('0.' + str(a).zfill(12))) # заполнить число нулями слева если нет 12 порядков и дополняем "0," n -= a print(*lst, sep='\n')

def myhash(string): h = 0 for ch in string: h += ord(ch) return h myhash('hello')

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers the total sum of which is equal to n. In the ten numbers displayed, the numbers do not go in a row. The output ten digits have exactly twelve digits after the decimal point. the numbers are positive.

def ten_numbers(n): import random list_10 = [] n1 = round(n/10 - random.randint(0, 10) / 1000, 12) print(n1) n2 = round(n1 - random.randint(0, 10) / 1000, 12) print(n2) n3 = round(n2 - random.randint(0, 10) / 1000, 12) print(n3) n4 = round(n3 - random.randint(0, 10) / 1000, 12) print(n4) n5 = round(n4 - random.randint(0, 10) / 1000, 12) print(n5) n6 = round(n5 - random.randint(0, 10) / 1000, 12) print(n6) n7 = round(n6 - random.randint(0, 10) / 1000, 12) print(n7) n8 = round(n7 - random.

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers the total sum of which is equal to n. In the ten numbers displayed, the numbers do not go in a row. The output ten digits have exactly twelve digits after the decimal point. the numbers are positive.

from decimal import Decimal def func(n): a = Decimal(str(n)) b = Decimal(str(n)) / 10 c = Decimal(str(n)) / 100 d = Decimal(str(n)) / 1000 e = Decimal(str(n)) / 10000 f = Decimal(str(n)) / 100000 g = Decimal(str(n)) / 1000000 h = Decimal(str(n)) / 10000000 i = Decimal(str(n)) / 100000000 j = Decimal(str(n)) / 1000000000 return [a, b, c, d, e, f, g, h, i, j] func(4)

Python
View
generate functionFri, 27 Jan 2023

find picture on pc

import os def find_picture(path): if os.path.isfile(path): return path elif os.path.isdir(path): for root, dirs, files in os.walk(path): for file in files: if file.endswith('.jpg') or file.endswith('.png'): return os.path.join(root, file) return None else: return None find_picture('/home/user/Pictures')

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the matrix, the number of matrix elements (integers) line by line separated by a space. draw the maximum element below the main diagonal

def max_element(n): matrix = [] for i in range(n): matrix.append([int(x) for x in input().split()]) max_elem = 0 for i in range(n): for j in range(n): if i > j: if matrix[i][j] > max_elem: max_elem = matrix[i][j] return max_elem print(max_element(int(input())))

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "змейкой" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇

n, m = [int(s) for s in input().split()] MATRIX = [[0] * m for i in range(n)] dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 for i in range(n+m-1): for j in range((n+m-i)//2): x += dx[i % 4] y += dy[i % 4] MATRIX[x][y] = c c += 1 for row in MATRIX: print(*row)

Python
View
generate functionThu, 13 Apr 2023

'''Вводятся целые числа в одну строку через пробел. На их основе формируется кортеж. Необходимо найти и вывести все индексы неуникальных (повторяющихся) значений в этом кортеже. Результат отобразите в виде строки чисел, записанных через пробел. Sample Input: 5 4 -3 2 4 5 10 11 Sample Output: 0 1 4 5'''

a = tuple(map(int, input().split())) b = [] for i in range(len(a)): for j in range(i + 1, len(a)): if a[i] == a[j]: b.append(i) b.append(j) print(*b)

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m заполнив её "змейкой" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение Тестовые данные Sample Input 1: 3 5 Sample Output 1: 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15

n, m = map(int, input().split()) a = [[0] * m for i in range(n)] x, y = 0, 0 dx, dy = 0, 1 for i in range(1, n * m + 1): a[x][y] = i nx, ny = x + dx, y + dy if 0 <= nx < n and 0 <= ny < m and not a[nx][ny]: x, y = nx, ny else: dx, dy = -dy, dx x, y = x + dx, y + dy for i in range(n): for j in range(m): print(str(a[i][j]).ljust(len(str(n*m))), end=' ') print()

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python. n людей за m дней должны посидеть за k столами. сумма мест за столами равно n. Максимальное количество людей должно познакомиться друг с другом. Считается что люди познакомились если они уже сидели за одним столом. вывести значения как в примере Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2]

def get_people_at_tables_by_days(people_count, days_count, tables_count): if people_count <= 0 or days_count <= 0 or tables_count <= 0: return [] # в первый день каждый люди сидят на своем месте # количество столов должно быть больше людей people_at_tables_by_days = [[[x] for x in range(1, people_count+1)]] if days_count > 1: # делим количество людей на количество столов

Python
View
generate functionWed, 12 Apr 2023

'''Напишите программу, которая возводит квадратную матрицу в степень m. Формат входных данных На вход программе подаётся натуральное число n — количество строк и столбцов в матрице, затем элементы матрицы, затем натуральное число m. Формат выходных данных Программа должна вывести результирующую матрицу, разделяя элементы символом пробела. '''

def function(n, m): matrix = [] for i in range(n): matrix.append(list((map(int, input().strip().split())))) m = int(input()) for i in range(m): matrix = multi_matrix(matrix, matrix) for el in matrix: for el2 in el: print(el2, end=' ') print() def multi_matrix(a, b): res_matrix = [[0] * len(a) for _ in range(len(a[0]))] for i in range(len(a)): for j in range(len(b)): for k in range(len(b[0])): res_matrix[i][j] += a[i][k] * b[k][j] return res_matrix n = int(input()) m = int(input()) function(n, m)

Python
View
generate functionFri, 17 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

def backpack(n): volume = [] count = 0 while True: volume_in = int(input()) if volume_in > n: print("Enough!") print(count, volume_in) break else: volume.append(volume_in) count += 1

Python
View
generate functionTue, 28 Feb 2023

Using Numpy, write an array coding function (Run-Length Encoding). The function of repetition of elements compresses the function into one element and considers the number of repetitions. The function returns a motorcade of two Numpy veins of the same length. The first contains elements, and the second - how many times they need to be repeated. Example: Encode (np.array ([1, 2, 2, 3, 3, 1, 1, 5, 5, 2, 3, 3, 3])) = (np.array ([1, 2, 3, 1, 1, 1, 1, 1, 5, 2, 3]), np.array ([1, 2, 2, 2, 2, 1, 2]))

def encode(arr): unique, count = np.unique(arr, return_counts=True) return unique, count encode(np.array([1, 2, 2, 3, 3, 1, 1, 5, 5, 2, 3, 3, 3]))

Python
View
generate functionWed, 08 Feb 2023

Write a program that prints the maximum element in the area below the main diagonal of a square matrix.

import numpy as np def max_below_diagonal(matrix): """Write a program that prints the maximum element in the area below the main diagonal of a square matrix.""" n = len(matrix) m = np.zeros([n,n]) for i in range(n): for j in range(n): m[j][i] = matrix[j][i] m = m.flatten('F') m = m[:n*n-n] return np.max(m) matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) max_below_diagonal(matrix)

Python
View
generate functionMon, 03 Apr 2023

Заполните пропуски в функции generate_batches def generate_batches(X, y, batch_size): """ param X: np.array[n_objects, n_features] --- матрица объекты-признаки param y: np.array[n_objects] --- вектор целевых переменных """ assert len(X) == len(y) np.random.seed(42) X = np.array(X) y = np.array(y) perm = np.random.permutation(len(X)) for batch_start in <YOUR CODE>: #YOUR CODE yield #YOUR CODE

def generate_batches(X, y, batch_size): """ param X: np.array[n_objects, n_features] --- матрица объекты-признаки param y: np.array[n_objects] --- вектор целевых переменных """ assert len(X) == len(y) np.random.seed(42) X = np.array(X) y = np.array(y) perm = np.random.permutation(len(X)) for batch_start in range(0, len(X), batch_size): batch_indices = perm[batch_start:batch_start + batch_size] yield X[batch_indices], y[batch_indices]

Python
View
generate functionMon, 03 Apr 2023

Паша очень любит кататься на общественном транспорте, а получая билет, сразу проверяет, счастливый ли ему попался. Билет считается счастливым, если сумма первых трех цифр совпадает с суммой последних трех цифр номера билета. Однако Паша очень плохо считает в уме, поэтому попросил вас написать программу, которая проверит равенство сумм и выведет "Счастливый", если суммы совпадают, и "Обычный", если суммы различны. На вход программе подаётся строка из шести цифр. Выводить нужно только слово "Счастливый" или "Обычный", с большой буквы.

def lucky_ticket(ticket_number): # put your code here pass lucky_ticket(123006) == 'Счастливый' lucky_ticket(12321) == 'Несчастливый' lucky_ticket(436751) == 'Несчастливый'

Python
View
generate functionTue, 07 Mar 2023

a twelve-digit number is entered. output ten twelve-digit numbers, the sum of which is equal to the input from the keyboard.

def f(n): if n>=10 and n<=100: return True else: return False def f1(num): num = [i for i in range(10, 100) if f(i)] return num def f2(m): m = [i for i in range(10, 100) if f(i)] return m def f3(n): n = [i for i in range(10, 100) if f(i)] return n def f4(num): num = [i for i in range(10, 100) if f(i)] return num def f5(num): num = [i for i in range(10, 100) if f(i)] return num def f6(num): num = [i for i in range(10, 100) if f(i)] return num def f7(num): num = [i for i in range(10, 100) if f(i

Python
View
generate functionFri, 10 Feb 2023

Implement the Neuron class, which will have several methods: __init__. Takes as input an array of neuron weights --- =(1,…,)w=(w 1​ ,…,w n​ ), as well as the activation function f (default argument (�) = � f(x)=x). Stores the weights and the function inside the class. forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed! forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed!

class Neuron(): def __init__(self, w: 'array of weights', f=lambda x: x): self.w = w self.f = f self.x = None def forward(self, x: "array of inputs"): self.x = x return self.f(sum([a*b for a, b in zip(self.w, x)])) def last_input(self): if self.x is not None: return self.x else: return None

Python
View
generate functionTue, 04 Apr 2023

Числа a, b, c и d являются натуральными и не превосходят 10, ≤a≤b, ≤c≤d. Следуйте формату вывода из примера, для разделения элементов внутри строки используйте '\t' — символ табуляции. Заметьте, что левым столбцом и верхней строкой выводятся сами числа из заданных отрезков — заголовочные столбец и строка таблицы. Sample Input 1: 7 10 5 6 Sample Output 1: 5 6 7 35 42 8 40 48 9 45 54 10 50 60

a, b, c, d = (int(input()) for _ in range(4)) for i in range(c, d + 1): print('\t', i, end='') print() for i in range(a, b + 1): print(i, end='\t') for j in range(c, d + 1): print(i * j, end='\t') print()

Python
View
generate functionFri, 17 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

n = int(input()) sum = 0 count = 0 while True: x = int(input()) sum += x count += 1 if sum >= n: break print('Enough!') print(sum) print(count)

Python
View
generate functionMon, 03 Apr 2023

На вход программе подается натуральное число n. Напишите программу, которая создает матрицу размером n×n заполнив её в соответствии с образцом. Формат входных данных На вход программе подается натуральное число n — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение Тестовые данные Sample Input 1: 5 Sample Output 1: 1 1 1 1 1 0 1 1 1 0 0 0 1 0 0 0 1 1 1 0 1 1 1 1 1

def matrix(n): for i in range(n): for j in range(n): if i == 0 or j == 0 or i == n-1 or j == n-1: print('1', end = ' ') else: print('0', end = ' ') print()

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def vasya(n, m): count = 0 sock_count = n while sock_count >= m: sock_count -= m - 1 count += 1 return count vasya(2, 3)

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers whose sum is equal to n. In the ten numbers displayed, the numbers do not go in a row. The range of output numbers is from 0.001 to 1. The output ten digits have exactly twelve digits after the decimal point. The output numbers are strictly greater than 0.

import random import math import decimal def get_nums(n): nums = [] remain = n for i in range(10): if remain <= 0: num = 0 elif i == 9: num = remain else: num = round(remain * random.random(), 12) nums.append(num) remain = remain - num return nums get_nums(1.23)

Python
View
generate functionWed, 22 Feb 2023

An integer k is entered (1 <= k <= 365). Determine which day of the week (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday or Sunday) is the k-th day of a non-leap year in which January 1 is Monday.

def day_of_week(k): if k < 1 or k > 365: return None days_in_year = 365 days_elapsed = k % days_in_year day = (days_elapsed + 1) % 7 day_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] return day_of_week[day] day_of_week(10)

Python
View
generate functionTue, 28 Feb 2023

X: np.array [num_row, num_column] --- matrix-argument a: float --- meaning for converting odd elements of lines into x Return s: np.array [num_row, num_column*2] --- Matrix, where the lines are flexible lines of the original matrix X with lines, which are their transformations The function takes on the input matrix X dimensions n x m, the number a and Returns the matrix with dimensions n x m*2, the i-th line of which is glued I-th line X with its transformation of its line Transformation (X [I]), written in the reverse order, where the transformation for the number K is defined as: Transformation (k) = a if ind (k) % 2 == 0 else k ** 3 In the implementation of this function, it is necessary to use the functionality of the Numpy package

def R(X, a): return np.hstack((X, np.apply_along_axis(lambda x: np.hstack((x, np.where(x % 2 == 0, a, x ** 3))), 1, X).reshape(X.shape[0], 2 * X.shape[1])))

Python
View
generate functionWed, 08 Feb 2023

When playing "Cities", players take turns calling the names of cities so that the first letter of each new word coincides with the last letter of the previous one. At the same time, it is believed that if the last letter of the previous word is f, then the letter preceding f should be compared with the first letter of the next word. Write a program that reads two lines in a row, and then prints "Good" if the last character of the first line matches the first character of the second (subject to the f rule), and "Bad" otherwise.

first = input() second = input() if first[-1] == second[0] and first[-1] != 'f': print("Good") elif first[-1] == second[0] or first[-2] == second[0]: print("Good") else: print("Bad")

Python
View
generate functionTue, 07 Mar 2023

The program takes two natural numbers as input. n and m are the number of rows and columns in the matrix, then n lines of m integers each, separated by a space character. Write a program that finds the indices (row and column) of the first occurrence of the maximum element. Input Data Format Two numbers n and m are given as input to the program on different lines — the number of rows and columns in the matrix, then the matrix elements themselves row by row separated by a space.

def max_elem(n, m, matrix): max_num = 0 index = [] for i in range(n): for j in range(m): if matrix[i][j] > max_num: max_num = matrix[i][j] index = [i, j] return index n = int(input()) m = int(input()) matrix = [[int(j) for j in input().split()] for i in range(n)] print(*max_elem(n, m, matrix))

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def calc(n, m): days = 0 for i in range(0, n): if i % m == 0: days += 1 return days print(calc(int(input().split()[0]), int(input().split()[1])))

Python
View
generate functionTue, 21 Mar 2023

Given a square matrix of numbers. Write a program that swaps elements on the main and secondary diagonals, with each element remaining in the same column (that is, in each column, you need to swap the element on the main diagonal and on the secondary diagonal). The input to the program is a natural number. n is the number of rows and columns in the matrix, then the matrix elements row by row separated by a space.

def SwapDiagonals(n,matrix): for i in range(n): matrix[i][i], matrix[i][n - 1 - i] = matrix[i][n - 1 - i], matrix[i][i] return matrix n = int(input()) matrix = [] for i in range(n): matrix.append(list(map(int, input().split()))) print(SwapDiagonals(n, matrix))

Python
View
generate functionTue, 07 Mar 2023

a fractional number n is entered from the keyboard. Output ten numbers. The sum of all ten numbers displayed is n. All ten numbers displayed are positive. Numbers must have twelve significant decimal places. The first two digits after the decimal point in the printed numbers can be equal to 0. The rest of the digits in the ten output numbers go without repetition.

import random def print_ten(x): r = random.Random() r.seed(x * x * x * x * x) random_nums = [] for i in range(10): random_nums.append(r.random()) print(random_nums) print_ten(10)

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the matrix, the number of matrix elements (integers) line by line separated by a space. draw the maximum element below the main diagonal. The elements of the main diagonal are also taken into account.

def max_matrix_element(n): if n < 2: return None matrix = [] for i in range(n): matrix.append(list(map(int, input().split()))) for i in range(n-1): for j in range(n-1): if matrix[i][j] < matrix[j][i] and i > j: matrix[i][j] = -1 return matrix max_matrix_element(3)

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "спиралью" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести матрицу в соответствии образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 4 5 Sample Output 1: 1 2 3 4 5 14 15 16 17 6 13 20 19 18 7 12 11 10 9 8

# ввод данных m, n = (int(i) for i in input().split()) spiral = [[0] * n for i in range(m)] # функция для прохода по спирали def go_spiral(spiral, start, end, i, j, status): if (end < start): return if (status == 'right'): while (j < end): spiral[i][j] = start j += 1 start += 1 i += 1 j -= 1 go_spiral(spiral, start, end, i, j, 'down') if (status == 'down'): while (i < end): spiral[i][j] = start i += 1 start += 1 i -= 1 j -= 1 go_spiral(spiral, start, end, i, j,

Python
View
generate functionWed, 03 May 2023

'''Напиши код программы на языке python. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Написать алгоритм рассадки людей от 1 до m дней, так чтобы за это время каждый из людей посидел с максимально возможным количеством человек. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами''' # Ввод данных от пользователя n = int(input("Введите количество людей: ")) m = int(input("Введите количество дней: ")) k = int(input("Введите количество столов: ")) # Создание списка количества мест за каждым столом seats = [] for i in range(k): seats.append(int(input(f"Введите количество мест за {i+1}-м столом: "))) # Создание списка гостей guests = [i+1 for i in range(n)] # Рассадка гостей за столами for day in range(1, m+1): print(f"День {day}:") for table in range(k): table_guests = guests[:seats[table]] guests = guests[seats[table]:] print(f" На столе {table+1} сидят люди с номерами: {table_guests}") if not guests: break

# Решение предыдущего задания def birthday(n, m, k): seats = [] for i in range(k): seats.append(int(input(f"Введите количество мест за {i+1}-м столом: "))) guests = [i+1 for i in range(n)] for day in range(1, m+1): print(f"День {day}:") for table in range(k): table_guests = guests[:seats[table]] guests = guests[seats[table]:] print(f" На столе {table+1} сидят люди с номерами: {table_guests}") if not guests

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def socks(n, m): return n + (n-1) / m socks(5, 3)

Python
View
generate functionWed, 01 Mar 2023

Vanya was given n cubes for her birthday. He and his friends decided to build a pyramid out of them. Vanya wants to build a pyramid in the following way: there should be 1 cube at the top of the pyramid, 1 + 2 = 3 cubes at the second level, 1 + 2 + 3 = 6 cubes at the third level, and so on. Thus, at the i-th level of the pyramid there should be 1 + 2 + ... + (i - 1) + i cubes. Vanya wants to know what is the maximum height of the pyramid he can create using the available cubes. Input data The first line contains an integer n (1 ≤ n ≤ 104) — the number of cubes given to Vanya. Output Print in a single line the maximum possible height of the pyramid.

def build_pyramid(n): return math.floor((1+8*n)**0.5)//2 build_pyramid(5)

Python
View
generate functionTue, 28 Feb 2023

Using Numpy, write an array coding function (Run-Length Encoding). The function of repetition of elements compresses the function into one element and considers the number of repetitions. The function returns a motorcade of two Numpy veins of the same length. The first contains elements, and the second - how many times they need to be repeated.

import numpy as np def encoding(a): a = np.array(a) i = 0 b = [] c = [] for j in range(len(a)): if a[j] == a[i]: c.append(a[i]) else: b.append(len(c)) c = [] i = j b.append(len(c)) return np.array([a[:len(a)-1], b])

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 Sample Input 2: 3 4 Sample Output 2: 1 2 4 7 3 5 8 10 6 9 11 12 Sample Input 3: 2 2 Sample Output 3: 1 2 3 4 Sample Input 4: 8 1 Sample Output 4: 1 2 3 4 5 6 7 8 Sample Input 5: 8 2 Sample Output 5: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

n, m = [int(i) for i in input().split()] a = [[0] * m for i in range(n)] for i in range(n): for j in range(m): a[i][j] = n * j + i + 1 for row in a: for elem in row: print(elem, end=" ") print()

Python
View
generate functionTue, 28 Feb 2023

def no_numpy_mult(first, second): """ param first: list of "size" lists, each contains "size" floats param second: list of "size" lists, each contains "size" floats """ #YOUR CODE: please do not use numpy result = #YOUR CODE: create list of lists, not np.array return result def numpy_mult(first, second): """ param first: np.array[size, size] param second: np.array[size, size] """ #YOUR CODE: please use numpy result = #YOUR CODE: create np.array return result

def no_numpy_mult(first, second): """ param first: list of "size" lists, each contains "size" floats param second: list of "size" lists, each contains "size" floats """ #YOUR CODE: please do not use numpy result = #YOUR CODE: create list of lists, not np.array return result def numpy_mult(first, second): """ param first: np.array[size, size] param second: np.array[size, size] """ #YOUR CODE: please use numpy result = #YOUR CODE: create np.array return result #### 函数多返回值 def foo(): print('hello') return 1, 2, 3 a, b, c = foo() print(a, b, c) # 1 2 3 print(foo()) # hello (1, 2, 3) a, b,

Python
View
generate functionWed, 08 Feb 2023

When playing "Cities", players take turns calling the names of cities so that the first letter of each new word coincides with the last letter of the previous one. At the same time, it is believed that if the last letter of the previous word is a soft sign, then the letter preceding the soft sign should be compared with the first letter of the next word. Write a program that reads two lines in a row, and then prints "Good" if the last character of the first line matches the first character of the second (subject to the soft sign rule), and "Bad" otherwise.

def cities(a, b): return a[-1] == b[0] or a[-2] == b[0] cities("Москва", "Ташкент")

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 5 5 Sample Output 1: 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4

row, col = int(input()), int(input()) def create_table(row, col, start): a = [] for i in range(row): b = [] for j in range(col): b.append(start) start += 1 if start == row + 1: start = 1 a.append(b) return a def print_table(a): for i in range(len(a)): b = '' for j in range(len(a[i])): b += str(a[i][j]).ljust(3) print(b) print_table(create_table(row, col, 1))

Python
View
generate functionWed, 05 Apr 2023

В метании молота состязается n спортcменов. Каждый из них сделал m бросков. Побеждает спортсмен, у которого максимален наилучший бросок. Если таких несколько, то из них побеждает тот, у которого наилучшая сумма результатов по всем попыткам. Если и таких несколько, победителем считается спортсмен с минимальным номером. Определите номер победителя соревнований. Входные данные Программа получает на вход два числа n и m, являющиеся числом строк и столбцов в массиве. Далее во входном потоке идет n строк по m чисел, являющихся элементами массива. Выходные данные Программа должна вывести одно число - номер победителя соревнований. Не забудьте, что строки (спортсмены) нумеруются с 0. Решение задачи Youtube Patreon Boosty Sample Input 1: 3 3 1 2 7 1 3 5 4 1 6 Sample Output 1: 0 Sample Input 2: 2 3 1 2 7 1 7 5 Sample Output 2: 1

def get_winner(a, n, m): max_sum = 0 winner = 0 max_num = 0 for i in range(n): curr_max = 0 sum = 0 for j in range(m): sum += a[i][j] if a[i][j] > curr_max: curr_max = a[i][j] if sum > max_sum: max_sum = sum winner = i max_num = curr_max elif sum == max_sum and curr_max > max_num: winner = i max_num = curr_max return winner

Python
View
code to explanationTue, 28 Feb 2023

import numpy as np def run_length_encoding(array): repeats = [] current = None counter = 0 for element in array: if element == current: counter += 1 else: if current is not None: repeats.append((current, counter)) current = element counter = 1 repeats.append((current, counter)) values, counts = zip(*repeats) return np.array(values), np.array(counts)

The function run_length_encoding takes an array, flattens and encodes it using run-length encoding, and returns the encoded values and the counts.

generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 5 5 Sample Output 1: 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4

def creat_matrix(n, m): matrix = [[0] * m for i in range(n)] for i in range(n): for j in range(m): matrix[i][j] = (i + j) % m + 1 return matrix n, m = [int(i) for i in input().split()] a = creat_matrix(n, m) for row in a: print(' '.join([str(elem) for elem in row]))

Python
View
generate functionMon, 03 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу для создания матрицы размером n x m, заполнив её символами '.' и '*' в шахматном порядке. В левом верхнем углу должна стоять точка. Выведите полученную матрицу на экран, разделяя элементы пробелами.

def chessboard(m, n): arr = [] for i in range(n): arr.append(["." if n % 2 == 0 else "*" for n in range(m)]) if i % 2 == 0: arr[i] = arr[i][::-1] return arr print(chessboard(2, 2)) print(chessboard(3, 3)) print(chessboard(3, 4)) print(chessboard(4, 3)) print(chessboard(4, 4)) print(chessboard(5, 3))

Python
View
generate functionMon, 20 Mar 2023

A natural number N is entered (that is, a positive integer). Required to create a two-dimensional (nested) list of size N x N elements, consisting of all ones, and then, write fives in the last column. Display this list on the screen as a table of numbers, as shown in the example below. P.S. Be careful there should be no spaces at the end of the lines!

def add_col_num(n): my_list = [] for i in range(n): my_list.append([1] * n) for i in range(n): for j in range(n): if j == n-1: my_list[i][j] = 5 for i in range(n): print(*my_list[i])

Python
View
generate functionFri, 10 Feb 2023

Implement the Neuron class, which will have several methods: __init__. Takes as input an array of neuron weights --- =(1,…,)w=(w 1​ ,…,w n​ ), as well as the activation function f (default argument (�) = � f(x)=x). Stores the weights and the function inside the class. forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed! forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed!

class Neuron: def __init__(self, weights, activation): self.xx = None self.weights = weights self.activation = activation def forward(self, inputs): self.xx = inputs return self.activation(np.dot(self.weights, self.inputs)) def backward(self): return self.xx

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m заполнив её "змейкой" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение Тестовые данные Sample Input 1: 3 5 Sample Output 1: 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15

n, m = [int(i) for i in input().split()] matrix = [[0] * m for i in range(n)] number = 1 for i in range(m): for j in range(n): if (i % 2 == 0 and j % 2 != 0) or (i % 2 != 0 and j % 2 == 0): matrix[j][i] = number number += 1 else: matrix[n - j - 1][i] = number number += 1 for i in range(n): print(" ".join([str(j).rjust(3) for j in matrix[i]]))

Python
View
generate functionMon, 06 Mar 2023

output ten random numbers whose sum is equal to the fractional number entered from the keyboard. digits in a row do not repeat in each number. Each number must contain twelve significant digits. the numbers are positive.

def fractional_number(num): a = ''.join(np.random.choice(np.arange(1, 10), size=11, replace=False)) b = ''.join(np.random.choice(np.arange(1, 10), size=11, replace=False)) c = ''.join(np.random.choice(np.arange(1, 10), size=11, replace=False)) d = ''.join(np.random.choice(np.arange(1, 10), size=11, replace=False)) e = ''.join(np.random.choice(np.arange(1, 10), size=11, replace=False)) f = ''.join(np.random.choice(np.arange(1, 10), size=11, replace=False)) g = ''.join(np.random.choice(np.arange(1, 10), size=11, replace=False)) h = ''.join(np.random.choice(np.arange(1, 10), size

Python
View
generate functionTue, 28 Feb 2023

Using Numpy, write an array coding function (Run-Length Encoding). The function of repetition of elements compresses the function into one element and considers the number of repetitions. The function returns a motorcade of two Numpy veins of the same length. The first contains elements, and the second - how many times they need to be repeated.

import numpy as np def encode(a): a = np.array(a) b = np.array(np.diff(a)) c = np.zeros(len(a)) c[0] = a[0] if(len(a)==1): return [a[0]], [1] else: for i in range(len(a)-1): if b[i] == 0: c[i+1] = 0 else: c[i+1] = a[i+1] d = np.unique(c, return_counts=True) return d[0], d[1] print(encode([1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2]))

Python
View
generate functionThu, 09 Feb 2023

Write a program that simulates checking a user's password. The user first enters a password, then enters a password confirmation. You need to handle the following situations: if the password entered by the user (for the first time) is shorter than 7 characters, the program displays Short if the password is long enough, but the password entered the second time does not match the first, the program displays Difference if this check is also successful, the program displays OK in Latin letters

def password_check(pw, pw_confirm): if len(pw) < 7: return 'Short' elif pw != pw_confirm: return 'Difference' else: return 'OK' pw = input() pw_confirm = input() print(password_check(pw, pw_confirm))

Python
View
generate functionWed, 08 Feb 2023

Write a program that outputs the number of elements of a square matrix in each row, larger than the arithmetic mean of the elements of this row.

def func(n, m, matrix): result = [] for i in range(n): count = 0 sum = 0 for j in range(m): sum += matrix[i][j] average = sum / m for j in range(m): if matrix[i][j] > average: count += 1 result.append(count) return result n = int(input()) m = int(input()) matrix = [] for i in range(n): matrix.append([int(elem) for elem in input().split()]) print(*func(n, m, matrix))

Python
View
generate functionWed, 08 Feb 2023

При игре в "Города" игроки по очереди называют названия городов так, чтобы первая буква каждого нового слова совпадала с последней буквой предыдущего. При этом считают, что если последняя буква предыдущего слова — мягкий знак, то с первой буквой следующего слова надо сравнивать букву, предшествующую мягкому знаку. Напишите программу, которая считывает подряд две строки, после чего выводит «Good», если последний символ первой строки совпадает с первым символом второй (с учётом правила про мягкий знак), и «Bad» в противном случае.

Входные данные Вводятся две строки. Каждая строка состоит не более чем из 100 символов и содержит только латинские буквы. Выходные данные Выведите ответ на задачу.

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "диагоналями" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 3 5 Sample Output 1: 1 2 4 7 10 3 5 8 11 13 6 9 12 14 15 Sample Input 2: 3 4 Sample Output 2: 1 2 4 7 3 5 8 10 6 9 11 12 Sample Input 3: 2 2 Sample Output 3: 1 2 3 4 Sample Input 4: 8 1 Sample Output 4: 1 2 3 4 5 6 7 8 Sample Input 5: 8 2 Sample Output 5: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

n, m = int(input()), int(input()) matrix = [[0 for j in range(m)] for i in range(n)] for i in range(n): for j in range(m): matrix[i][j] = i + 1 + m * j print(matrix[i][j], end=' ') print()

Python
View
generate functionWed, 01 Mar 2023

Vanya was given n cubes for her birthday. He and his friends decided to build a pyramid out of them. Vanya wants to build a pyramid in the following way: there should be 1 cube at the top of the pyramid, 1 + 2 = 3 cubes at the second level, 1 + 2 + 3 = 6 cubes at the third level, and so on. Thus, at the i-th level of the pyramid there should be 1 + 2  + (i -1) + i cubes. Print in a single line the maximum possible height of the pyramid. Input data The first line contains an integer n (1 ≤ n ≤ 104) — the number of cubes given to Vanya. Output Print in a single line the maximum possible height of the pyramid.

def max_level_of_pyramid(n): level = 0 while True: if n == 0: return level n -= level level += 1 max_level_of_pyramid(10)

Python
View
generate functionTue, 28 Feb 2023

Matrix multiplication Write two functions that each multiply two square matrices, one without using numpy's built-in functions, and the other using numpy. The input to the first task is given lists of size size by size elements in each. The second task receives objects of type np.ndarray --- square matrices of the same size. The first function should return a list of lists, and the second should return np.array.

import numpy as np def multiply_matrices_without_numpy(list_a, list_b): # Write your code here n = len(list_a) c = [[0 for x in range(n)] for y in range(n)] for i in range(n): for j in range(n): for k in range(n): c[i][j] += list_a[i][k] * list_b[k][j] return c def multiply_matrices_with_numpy(array_a, array_b): # Write your code here return np.dot(array_a, array_b)

Python
View
generate functionTue, 04 Apr 2023

'''Выведите таблицу размером n×n, заполненную числами от 1 до n ** 2 по спирали, выходящей из левого верхнего угла и закрученной по часовой стрелке, как показано в примере Sample Input: 5 Sample Output: 1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9'''

def matrix(n): lst = [[]] num = 1 for i in range(n): lst.append([]) for j in range(n): lst[i].append(0) j = 0 while j < n * n: for i in range(n): lst[i][j // n] = num num += 1 if num == n * n + 1: break j += 1 for i in range(n - 1, 0, -1): lst[i][(j - 1) // n] = num num += 1 if num == n * n + 1: break j += 1 if num == n * n + 1: break for i in range(n): for j in range(n): print(lst[i][j], end=" ") print()

Python
View
generate functionThu, 06 Apr 2023

Рассмотрим таблицу из n строк и n столбцов. Известно, что в клетке, образованной пересечением i-й строки и j-го столбца, записано число i × j. Строки и столбцы нумеруются с единицы. Дано целое положительное число x. Требуется посчитать количество клеток таблицы, в которых находится число x. Входные данные В единственной строке находятся числа n и x (1 ≤ n ≤ 105, 1 ≤ x ≤ 109) — размер таблицы и число, которое мы ищем в таблице. Выходные данные Выведите единственное число: количество раз, которое число x встречается в таблице. Решение задачи Youtube Patreon Boosty Sample Input 1: 10 5 Sample Output 1: 2 Sample Input 2: 6 12 Sample Output 2: 4 Sample Input 3: 5 13 Sample Output 3: 0

# n, x = (int(i) for i in input().split()) # ans = 0 # for i in range(1, n+1): # if x % i == 0 and x // i <= n: # ans += 1 # print(ans)

Python
View
generate functionFri, 10 Feb 2023

Implement the Neuron class, which will have several methods: __init__. Takes as input an array of neuron weights --- =(1,…,)w=(w 1​ ,…,w n​ ), as well as the activation function f (default argument (�) = � f(x)=x). Stores the weights and the function inside the class. forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed! forward. Takes an array as input � = ( � 1 , … , � � ) x=(x 1 ​ ,…,x n ​ ) --- neuron inputs. Returns the value of the function � f applied to a number � 1 � 1 + … + � � � � w 1 ​ x 1 ​ +…+w n ​ x n ​ . backlog. Returns an array � x, which was fed into the input of the forward function the last time it was called. Returns None if forward has not been called before. You won't need the print function for this assignment. The results of the execution of functions should be returned, not printed!

import numpy as np class Neuron: def __init__(self, weights, activation_function): self.weights = weights self.activation_function = activation_function self.input = None def forward(self, input_array): self.input = input_array return self.activation_function(np.dot(self.input, self.weights)) def backlog(self): return self.input

Python
View
generate functionTue, 07 Mar 2023

Given a natural number N. Determine if it is prime. A natural number N is called prime if it has only two divisors: one and the number N itself. As an answer, print "Yes" if the number is prime, "No" otherwise. Solve with a while loop

n = int(input()) def is_prime(n): if n == 2 or n == 3: return True if n%2 == 0 or n%3 == 0 or n<2: return False div = 5 while div <= n**.5: if n%div == 0 or n%(div+2) == 0: return False div +=6 return True if is_prime(n): print("Yes") else: print("No")

Python
View
generate functionTue, 07 Mar 2023

a fractional number n is entered from the keyboard. Output ten numbers. The sum of all ten numbers displayed is n. All ten numbers displayed are positive. Numbers must have twelve significant decimal places. The first two digits after the decimal point in the printed numbers can be equal to 0. The rest of the digits in the ten output numbers go without repetition.

def decimal(n): if (n <= 0): return None fraction = 0 print("n=", n) for i in range(10): number = "" if (n > 0.1): n = n - 0.1 number = f"0.{i}{i}" fraction += 0.1 elif (n > 0.01): n = n - 0.01 number = f"0.{i}0" fraction += 0.01 elif (n > 0.001): n = n - 0.001 number = f"0.0{i}" fraction += 0.001 else: number = f"0.0{i}" print(number) # print("fraction=", fraction) return True if fraction == 1 else False decimal(0.0001)

Python
View
generate functionMon, 20 Feb 2023

Implement the Neuron class, which will have several methods: __init__. It takes as input an array of neuron weights --- w=(w1,…,wn) , as well as an activation function f (by default, f(x)=x ). Stores the weights and the function inside the class. forward. It takes as input an array x=(x1,…,xN) --- neuron inputs. Returns f(w1x1+…+wnxn) . backlog. Returns the last array x that was passed to the forward function. class Neuron: def __init__(self, w, f = lambda x: x): #YOUR CODE HERE def forward(self, x): #YOUR CODE HERE def backlog(self): #YOUR CODE HERE

class Neuron: def __init__(self, w, f = lambda x: x): self.w = w self.f = f self.x = None def forward(self, x): self.x = x return self.f(sum([wi * xi for (wi, xi) in zip(self.w, x)])) def backlog(self): return self.x

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Output the maximum element located on the main diagonal and below the main diagonal

def main_diagonal(n): a = [] for i in range(n): a.append([0]*n) for i in range(n): a[i] = input().split() max_el = int(a[0][0]) for i in range(n): for j in range(n): if i > j and int(a[i][j]) > max_el: max_el = int(a[i][j]) return max_el main_diagonal(4)

Python
View
generate functionTue, 28 Feb 2023

X: np.array [num_row, num_column] --- matrix-argument a: float --- meaning for converting odd elements of lines into x Return s: np.array [num_row, num_column*2] --- Matrix, where the lines are flexible lines of the original matrix X with lines, which are their transformations The function takes on the input matrix X dimensions n x m, the number a and Returns the matrix with dimensions n x m*2, the i-th line of which is glued I-th line X with its transformation of its line Transformation (X [I]), written in the reverse order, where the transformation for the number K is defined as: Transformation (k) = a if ind (k) % 2 == 0 else k ** 3 In the implementation of this function, it is necessary to use the functionality of the Numpy package

def transformation(X): s = [] m,n = np.shape(X) for i in range(m): s.append(np.hstack((X[i], X[i][::-1]))) for k in range(m): for j in range(n): if (j % 2 == 0): s[k][j+n] = a else: s[k][j+n] = s[k][j+n] ** 3 s = np.array(s) return s

Python
View
generate functionMon, 03 Apr 2023

В Институте биоинформатики между информатиками и биологами устраивается соревнование. Победителям соревнования достанется большой и вкусный пирог. В команде биологов a человек, а в команде информатиков — b человек. Нужно заранее разрезать пирог таким образом, чтобы можно было раздать кусочки пирога любой команде, выигравшей соревнование, при этом каждому участнику этой команды должно достаться одинаковое число кусочков пирога. И так как не хочется резать пирог на слишком мелкие кусочки, нужно найти минимальное подходящее число. Напишите программу, которая помогает найти это число. Программа должна считывать размеры команд (два положительных целых числа a и b, каждое число вводится на отдельной строке) и выводить наименьшее число d, которое делится на оба этих числа без остатка.

def gcd(a, b): # находим остаток от деления а на b rem = a % b # если остаток равен 0, то возвращаем b if rem == 0: return b # иначе вызываем функцию снова # с аргументами b и остатока от деления return gcd(b, a % b)

Python
View
generate functionWed, 15 Mar 2023

def numerical_derivative_2d(func, epsilon): """ Функция для приближённого вычисления градиента функции двух переменных. :param func: np.array[2] -> float — произвольная дифференцируемая функция :param epsilon: float — максимальная величина приращения по осям :return: другая функция, которая приближённо вычисляет градиент в точке """ def grad_func(x): """ :param x: np.array[2] — точка, в которой нужно вычислить градиент :return: np.array[2] — приближённое значение градиента в этой точке """ <YOUR CODE> return <YOUR CODE> return grad_func def grad_descent_2d(func, low, high, start=None, callback=None): """ Реализация градиентного спуска для функций двух переменных Обратите внимание, что здесь градиент функции не дан. Его нужно вычислять приближённо. :param func: np.ndarray -> float — функция :param low: левая граница интервала по каждой из осей :param high: правая граница интервала по каждой из осей """ eps = 1e-10 df = numerical_derivative_2d(func, eps) <YOUR CODE> return <YOUR CODE>

class MyClass: def __init__(self): self.x = 0 self.y = 0 def add_x(self, x): self.x += x def add_y(self, y): self.y += y def add_xy(self, x, y): self.x += x self.y += y def print_xy(self): print('x = {}, y = {}'.format(self.x, self.y)) def set(self, x, y): self.x = x self.y = y def reset(self): self.x = 0 self.y = 0 m = MyClass() m.print_xy() m.add_xy(1, 2) m.print_xy() m.set(3, 4) m.print_xy()

Python
View
generate functionWed, 12 Apr 2023

Вводятся данные в формате: <день рождения 1> имя_1 <день рождения 2> имя_2 ... <день рождения N> имя_N Дни рождений и имена могут повторяться. На их основе сформировать словарь и вывести его в формате (см. пример ниже): день рождения 1: имя1, ..., имяN1 день рождения 2: имя1, ..., имяN2 ... день рождения M: имя1, ..., имяNM Для считывания списка целиком в программе уже записаны начальные строчки: import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines())) Sample Input: 3 Сергей 5 Николай 4 Елена 7 Владимир 5 Юлия 4 Светлана Sample Output: 3: Сергей 5: Николай, Юлия 4: Елена, Светлана 7: Владимир

import sys # считывание списка из входного потока lst_in = list(map(str.strip, sys.stdin.readlines()))

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Output the maximum element located on the main diagonal and below it

def find_max(n, matrix): max_num = matrix[0][0] for i in range(n): for j in range(i + 1, n): if matrix[i][j] > max_num: max_num = matrix[i][j] return max_num n = int(input()) matrix = [] for i in range(n): matrix.append([int(i) for i in input().split()]) print(find_max(n, matrix))

Python
View
generate functionMon, 03 Apr 2023

Паша очень любит кататься на общественном транспорте, а получая билет, сразу проверяет, счастливый ли ему попался. Билет считается счастливым, если сумма первых трех цифр совпадает с суммой последних трех цифр номера билета. Однако Паша очень плохо считает в уме, поэтому попросил вас написать программу, которая проверит равенство сумм и выведет "Счастливый", если суммы совпадают, и "Обычный", если суммы различны. На вход программе подаётся строка из шести цифр. Выводить нужно только слово "Счастливый" или "Обычный", с большой буквы.

def lucky_ticket(ticket_number): return sum([int(n) for n in ticket_number[:3]]) == sum([int(n) for n in ticket_number[3:]]) lucky_ticket("123321")

Python
View
generate functionFri, 10 Mar 2023

An arithmetic expression is written as a string, for example: "10 + 25 - 12" or "10 + 25 - 12 + 20 - 1 + 3", etc. That is, the number of actions can be different. It is necessary to perform the calculation and display the result on the screen. It is assumed that only addition (+) and subtraction (-) are used here as arithmetic operations, and non-negative integers are used as operands. Note that these operators can be written with or without spaces.

def arithmeticExpression(expression): return eval(expression) arithmeticExpression("1+2")

Python
View
generate functionMon, 03 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу для создания матрицы размером n x m, заполнив её символами '.' и '*' в шахматном порядке. В левом верхнем углу должна стоять точка. Выведите полученную матрицу (без кавычек и скобочек) на экран, разделяя элементы пробелами.

n, m = (int(i) for i in input().split()) for i in range(n): for j in range(m): if (i + j) % 2 == 0: print('.', end = '') else: print('*', end = '') print()

Python
View
generate functionMon, 03 Apr 2023

На вход программе подается натуральное число n. Напишите программу, которая создает матрицу размером n×n и заполняет её по следующему правилу: числа на побочной диагонали равны 1;числа, стоящие выше этой диагонали, равны 0;числа, стоящие ниже этой диагонали, равны 2.Полученную матрицу выведите на экран. Числа в строке разделяйте одним пробелом.

n = int(input()) a = [[1 if i == n - j - 1 else 2 if i < n - j - 1 else 0 for j in range(n)] for i in range(n)] for row in a: print(' '.join([str(elem) for elem in row])) n = int(input()) a = [[2 for j in range(n)] for i in range(n)] for row in range(n): a[row][n - row - 1] = 1 if row != n - row - 1: a[row][row] = 0 for row in a: print(' '.join([str(elem) for elem in row]))

Python
View
generate functionWed, 01 Mar 2023

Вводится список названных городов в одну строчку через пробел. Определить, что в этом списке все города имеют более 5 символов. Реализовать программу с использованием цикла во время перерыва оператора. Вывести ДА, если состояния и НЕТ - в наличии.

def cities_length(cities): for city in cities: if len(city) > 5: return True else: return False cities = ['Kyiv', 'Berlin', 'Munich'] cities_length(cities)

Python
View
generate functionWed, 01 Mar 2023

There is a one-dimensional list with a length of 10 elements, consisting of zeros: p = [0] * 10 At each iteration of the loop, the user enters an integer - the index of the list element p, by which the value 1 is written, if it is not already there. If 1 is already set, then do not change the list and ask the user for the next number again. It is necessary to arrange five units in a list like this. (After that, the cycle is interrupted). Implement the program with a while loop and use a continue statement when 1 cannot be added to the list. Display the result on the screen as a sequence of numbers separated by a space.

p = [0] * 10 count = 0 while count < 5: i = int(input()) if p[i] == 1: continue p[i] = 1 count += 1 print(*p)

Python
View
generate functionTue, 11 Apr 2023

'''Имеется закодированная строка с помощью азбуки Морзе. Коды разделены между собой пробелом. Необходимо ее раскодировать, используя азбуку Морзе из предыдущего занятия. Полученное сообщение (строку) вывести на экран. morze = {'а': '.-', 'б': '-...', 'в': '.--', 'г': '--.', 'д': '-..', 'е': '.', 'ё': '.', 'ж': '...-', 'з': '--..', 'и': '..', 'й': '.---', 'к': '-.-', 'л': '.-..', 'м': '--', 'н': '-.', 'о': '---', 'п': '.--.', 'р': '.-.', 'с': '...', 'т': '-', 'у': '..-', 'ф': '..-.', 'х': '....', 'ц': '-.-.', 'ч': '---.', 'ш': '----', 'щ': '--.-', 'ъ': '--.--', 'ы': '-.--', 'ь': '-..-', 'э': '..-..', 'ю': '..--', 'я': '.-.-', ' ': '-...-'} Результат кодирования вывести в виде строки.'''

morze = {'а': '.-', 'б': '-...', 'в': '.--', 'г': '--.', 'д': '-..', 'е': '.', 'ё': '.', 'ж': '...-', 'з': '--..', 'и': '..', 'й': '.---', 'к': '-.-', 'л': '.-..', 'м': '--', 'н': '-.', 'о': '---', 'п': '.--.', 'р': '.-.', 'с': '...', 'т': '-', 'у': '..-', 'ф': '..-.', 'х': '....', 'ц': '-.-.', 'ч': '---.', 'ш': '----', 'щ': '--.-', 'ъ': '--.--', 'ы': '-.--', 'ь': '-..-', 'э': '..-..', 'ю': '..--', 'я': '.-.-',

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Output the maximum element located on the main diagonal and below it

def matrix_sum(n): matrix = [] for i in range(n): matrix_elements = list(map(int, input().split(' '))) matrix.append(matrix_elements) max_sum = matrix[0][0] i = 0 while i < n: if sum(matrix[i][:i]) > max_sum: max_sum = sum(matrix[i][:i]) i += 1 return max_sum

Python
View
generate functionMon, 06 Mar 2023

output ten numbers whose sum is equal to the fractional number entered from the keyboard. digits in a row do not repeat in each number. Each number must contain twelve significant digits. the numbers are positive.

def check(a): m = a count = 0 while m > 0: m = m - 1 count = count + 1 return count def add(a, b): return a + b def create_tens(a, b): return [1 / (a - i) for i in range(b)] def check_num(a): if a < 0: return True return False def check_zero(a): if a == 0: return True return False def check_decimal(a): return (a - int(a)) != 0 def main(): x = int(input("Enter a number: ")) if check_num(x): print("The number is incorrect!") return if check_zero(x): print("ERROR!!! The number is zero!") return if check_decimal(x): print("The number is incorrect!") return count_

Python
View
generate functionThu, 13 Apr 2023

'''Имеется двумерный кортеж, размером 5 x 5 элементов: t = ((1, 0, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0), (0, 0, 0, 1, 0), (0, 0, 0, 0, 1)) Вводится натуральное число N (N < 5). Необходимо на основе кортежа t сформировать новый аналогичный кортеж t2 размером N x N элементов. Результат вывести на экран в виде таблицы чисел. Sample Input: 3 Sample Output: 1 0 0 0 1 0 0 0 1'''

n = int(input()) def build_matrix(n): t2 = tuple() for i in range(n): row = () for j in range(n): if i == j: row += (1,) else: row += (0,) t2 += (row,) return t2 t2 = build_matrix(n) for row in t2: for column in row: print(column, end = ' ') print()

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Draw the maximum element below the main diagonal. The elements of the main diagonal are also taken into account.

n = int(input()) matrix = [[int(i) for i in input().split()] for _ in range(n)] def main_diagonal(matrix, n): return [matrix[i][j] for i in range(n) for j in range(n) if i + j == n - 1] def main_diagonal_max(matrix, n): return max(main_diagonal(matrix, n)) print(main_diagonal_max(matrix, n))

Python
View
generate functionFri, 10 Mar 2023

a list of city names is given in one line separated by a space. Iterate through all these names with a for loop and determine if the name of the next city begins with the last letter of the previous city in the list. If the letters 'ь', 'ъ', 'ы' are the last ones, then the next letter from the end is taken. Display YES if the sequence matches this rule and NO otherwise.

def city_game(lst): for i in range(len(lst)-1): if(lst[i][-1] == lst[i+1][0]): print('YES') elif(lst[i][-1] == 'ь'): if(lst[i][-2] == lst[i+1][0]): print('YES') else: print('NO') elif(lst[i][-1] == 'ъ'): if(lst[i][-2] == lst[i+1][0]): print('YES') else: print('NO') elif(lst[i][-1] == 'ы'): if(lst[i][-2] == lst[i+1][0]): print('YES') else: print('NO') else: print('NO') city_game(['Москва', '

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m заполнив её "змейкой" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение Тестовые данные Sample Input 1: 3 5 Sample Output 1: 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15

n, m = [int(i) for i in input().split()] a = [[0] * m for i in range(n)] dx, dy = [0, 1, 0, -1], [1, 0, -1, 0] x, y, c = 0, -1, 1 for i in range(max(n, m)): for j in range(i+1): x += dx[i % 4] y += dy[i % 4] if 0 <= x < n and 0 <= y < m: a[x][y] = c c += 1 for i in range(n): for j in range(m): print(str(a[i][j]).ljust(len(str(a[n-1][m-1]))), end=' ') print()

Python
View
generate functionWed, 22 Feb 2023

n = int(input()) full = False stuffVolume = [] while full == False: x = int(input()) if (sum(stuffVolume + [x])) < n: stuffVolume.append(sum(stuffVolume + [x])) else: full = True print(sum(stuffVolume)) print(len(stuffVolume))

def add_to_list(stuffVolume): n = int(input()) full = False while full == False: x = int(input()) if (sum(stuffVolume + [x])) < n: stuffVolume.append(sum(stuffVolume + [x])) else: full = True return stuffVolume stuffVolume = [] add_to_list(stuffVolume) print(sum(stuffVolume)) print(len(stuffVolume))

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести указанную матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 5 5 Sample Output 1: 1 2 3 4 5 2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4

n, m = [int(i) for i in input().split()] a = [[abs((j+(i+1)) % (m)) + 1 for j in range(m)] for i in range(n)] for row in a: print(*row)

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def vasyasocks(n, m): if (n//m >= 1) and (n % m > 0): return n // m * (m-1) + (n % m) + 1 elif (n//m >= 1) and (n % m == 0): return n // m * (m-1) + m else: return n vasyasocks(2, 3)

Python
View
generate functionThu, 16 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

def backpack(n): sum = 0 qty = 0 while True: a = int(input()) if a == 0: break else: sum += a qty += 1 if sum >= n: break return sum, qty

Python
View
generate functionTue, 21 Mar 2023

На вход программе поступает строка, состоящая из нескольких слов, знаком разделителем между словами будем считать символ пробела. Ваша задача исключить из строки дублирующие слова: первое появление слова остается в строке, второе и все последующие появления исключаются. При сравнении на дубли строк регистр букв не учитывать, это значит слова python и PyThOn считаются одинаковыми. В качестве ответа необходимо вывести итоговую строку без дублей

def unique_words(text): words = text.lower().split() unique_words = [] for word in words: if word not in unique_words: unique_words.append(word) return " ".join(unique_words) print(unique_words("Hello hello world world world"))

Python
View
generate functionMon, 03 Apr 2023

Проверьте, является ли двумерный массив симметричным относительно главной диагонали. Главная диагональ — та, которая идёт из левого верхнего угла двумерного массива в правый нижний. Входные данные Программа получает на вход число n<100, являющееся числом строк и столбцов в массиве. Далее во входном потоке идет n строк по n чисел, являющихся элементами массива. Выходные данные Программа должна выводить слово Yes для симметричного массива и слово No для несимметричного.

def is_symmetric(n, m): for i in range(n): for j in range(m): if mass[i][j] != mass[n-i-1][m-j-1]: return 'No' return 'Yes' n = int(input()) m = int(input()) mass = [] for i in range(n): mass.append([int(j) for j in input().split()]) print(is_symmetric(n, m))

Python
View
generate functionMon, 03 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу для создания матрицы размером n x m, заполнив её символами '.' и '*' в шахматном порядке. В левом верхнем углу должна стоять точка. Выведите полученную матрицу на экран, разделяя элементы пробелами.

def chess(n, m): res = [] for i in range(n): tmp = [] for j in range(m): if (i + j) % 2 == 0: tmp.append('*') else: tmp.append('.') res.append(tmp) return res

Python
View
generate functionTue, 14 Feb 2023

Let the coordinates x 1,y 1 of the first point be input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates x 2 ,y 2 of the second point are set to 3, 6 respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

def in_cluster(x1, y1, x2, y2, epsilon = 0.1): if (x1 - x2)**2 + (y1 - y2)**2 > epsilon: print("Out of cluster") else: print("In cluster") in_cluster(1, 2, 3, 6)

Python
View
generate functionTue, 14 Feb 2023

Let the coordinates x 1,y 1 of the first point be input (it is assumed that they are substituted by the system from the embedded test numbers). Let the coordinates x 2 ,y 2 of the second point are set to 3, 6 respectively. Find the Euclidean distance between two points. If the distance is strictly greater than epsilon, print "Out of Cluster" (with print), otherwise print "In Cluster". The Euclidean distance is given by the formula

def distance(x1, y1, x2, y2): return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) distance(1, 5, 3, 6)

Python
View
generate functionMon, 03 Apr 2023

На вход программе подается натуральное число � n. Напишите программу, которая создает матрицу размером � × � n×n и заполняет её по следующему правилу: числа на побочной диагонали равны 1 1; числа, стоящие выше этой диагонали, равны 0 0; числа, стоящие ниже этой диагонали, равны 2 2. Полученную матрицу выведите на экран. Числа в строке разделяйте одним пробелом.

def create_matrix(n): m = [[0 for j in range(n)] for i in range(n)] for i in range(n): for j in range(n): if i == j: m[i][j] = 1 elif j > i: m[i][j] = 2 return m n = int(input()) m = create_matrix(n) [print(' '.join(str(i) for i in row)) for row in m]

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python используй жадный алгоритм. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Каждый день люди садятся друг с другом за столы так чтоб наибольшее количество людей могло познакомиться друг с другом. Считается что люди познакомились если они уже сидели за одним столом. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами

n = int(input()) m = int(input()) k = int(input()) d = {} for i in range(k): d[i] = int(input()) max_people = 0 for i in range(m): max_people = 0 for key, value in d.items(): if value > max_people: max_people = value best_table = key d[best_table] = value - 1 if d[best_table] == 0: del d[best_table] print(best_table, end=" ")

Python
View
generate functionFri, 27 Jan 2023

создать фаил ворд и сохранить в него погоду в москве C:\Users\rybikov\PycharmProjects\pythonProject2\venv\Scripts\python.exe C:\Users\rybikov\PycharmProjects\pythonProject2\main.py Traceback (most recent call last): File "C:\Users\rybikov\PycharmProjects\pythonProject2\main.py", line 1, in <module> import requests ModuleNotFoundError: No module named 'requests'

import requests def get_weather(city): url = "http://api.openweathermap.org/data/2.5/weather" params = {"q": city, "units": "metric", "appid": "e9185b28e9969fb7a300801eb026de9c"} result = requests.get(url, params=params) print(result.status_code) print(result.headers["Content-Type"]) print(result.url) print(result.json()) return result.json() city = input("city") weather = get_weather(city) def get_temp(weather): temp = weather["main"]["temp"] return temp def get_wind(weather): wind = weather["wind"]["speed"] return wind def get_humidity(weather): humidity = weather["main"]["humidity"] return humidity data

Python
View
generate functionMon, 06 Mar 2023

output ten random numbers whose sum is equal to the fractional number entered from the keyboard. digits in a row do not repeat in each number. Each number must contain twelve significant digits. the numbers are positive.

import random def rand_num(a): #a = float(input("Enter a number: ")) a_int = int(a) a_frac = a - a_int n = 10 nums = [] for i in range(1, n + 1): num = random.randint(10**(11), 10**12 - 1) nums.append(num) a_frac -= (num - int(num))/10**12 #print(a_frac) if a_int: nums.append(a_int) return nums print(rand_num(0.01))

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python. Вводится натуральное число n - количество людей. Вводится натуральное число m - количество дней. Вводится натуральное число k - количество столов. Введите количество мест за каждым столом. За каждым столом разное количество сидячих мест, но сумма всех мест равна n. Написать алгоритм рассадки людей от 1 до m дней, так чтобы за за количество дней от 1 до m все люди посидел с максимально возможным количеством человек исходя из заданных значений. Вывести на экран поэтапно с первого по m день, номера стола, людей сидящих за столами Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 2 Введите количество мест за 2-м столом: 1 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2] Пример ввода 2 Введите количество людей: 6 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за 1-м столом: 3 Введите количество мест за 2-м столом: 3 Пример вывода 2 День 1: На столе 1 сидят люди с номерами: [1, 2, 3] На столе 2 сидят люди с номерами: [4, 5, 6] День 2: На столе 1 сидят люди с номерами: [1, 3, 5] На столе 2 сидят люди с номерами: [2, 4, 6]

def answer(n, m, k, c): t = [0]*m for i in range(n): t[i%m] += 1 return t def test(): a = answer(3, 2, 2, [2, 1]) print (a) b = answer(6, 2, 2, [3, 3]) print (b) test()

Python
View
generate functionThu, 16 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

def backpack(n, *args): i = 0 for x in args: i += x if i > n: break print('Enough!') print(i) print(len(args)) backpack(10, 1, 2, 3, 4, 5, 6)

Python
View
generate functionFri, 10 Feb 2023

The input is a natural number n — the number of rows and columns in the square matrix. Next, the elements of the matrix are entered line by line with a space. Draw the maximum element below the main diagonal. The elements of the main diagonal are also taken into account.

import numpy as np def max_under_diagonal(a): n = len(a) max_elem = a[0][1] for i in range(n): for j in range(i+1, n): max_elem = max(max_elem, a[i][j]) return max_elem a = np.random.randint(0, 10, size=(3,3)) a = np.array([[1,2,3],[4,5,6],[7,8,9]]) print(max_under_diagonal(a))

Python
View
generate functionTue, 11 Apr 2023

Вводится список целых чисел в одну строчку через пробел. С помощью словаря выделите только уникальные (не повторяющиеся) введенные значения и, затем, сформируйте список из уникальных чисел. Выведите его на экран в виде набора чисел, записанных через пробел. P. S. Такая задача, обычно решается через множества, но мы их еще не проходили, поэтому воспользуемся словарем. Sample Input: 8 11 -4 5 2 11 4 8 Sample Output: 8 11 -4 5 2 4

a = [int(i) for i in input().split()] b = {} for i in a: b[i] = True c = [] for i in b: c.append(i) print(*c)

Python
View
generate functionFri, 07 Apr 2023

'''Дана матрица размером NxN, требуется найти максимальное значение среди элементов, расположенных на побочной диагонали. Под побочной диагональю матрицы подразумевается диагональ, проведённая из правого верхнего угла до левого нижнего угла.'' '''

def find_max_num(lst): max_num = 0 for i in lst: if i > max_num: max_num = i return max_num N = int(input()) a = [] for i in range(N): a.append(list(map(int, input().split()))) b = [] for i in range(N): b.append(a[i][(N-1)-i]) print(find_max_num(b))

Python
View
generate functionThu, 16 Feb 2023

We have a backpack with a capacity of n liters, and our task is to pack it to the limit as much as possible. We receive things, the volume of which is also measured in liters, and we must put them in our backpack without the possibility of skipping. As soon as the total volume of the new thing added exceeds the capacity of the backpack, your program should print the word "Enough!" and then on separate lines the total amount of things that we were able to pack in a backpack, and their number Input data The number n is the capacity of the backpack. Next come an arbitrary number of lines - the volume of the next item. Output The line "Enough!" and then two numbers - the total volume of packaged goods and their quantity. Each value is displayed on a separate line.

def backpack(n, lst): res = [] s = 0 for i in lst: if i + s <= n: res.append(i) s += i else: print("Enough!") print(sum(res)) print(len(res)) return sum(res), len(res) backpack(10, [1, 4, 3, 5, 2, 3, 4, 5, 3, 1, 2, 5, 3, 4, 5, 1, 2, 3, 4])

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python. n людей за m дней должны посидеть за k столами. сумма мест за столами равно n. Максимальное количество людей должно познакомиться друг с другом. Считается что люди познакомились если они уже сидели за одним столом. вывести значения как в примере Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2]

def tables(people_num, days_num, table_num): persons = [i for i in range(1, people_num + 1)] tables = [[] for _ in range(days_num)] people_table_num = int(people_num / table_num) people_table_num_rest_num = people_num % table_num for i in range(days_num): for j in range(table_num): table = [] for k in range(people_table_num): table.append(persons[0]) persons.pop(0) if people_table_num_rest_num == 0: tables[i].append(table) else: tables[i].append(table) tables[i][j].append(persons[0]) persons.append(persons[0]) persons.pop(0) people_table_num_rest_num -= 1 res = [] for i in range(days_num):

Python
View
generate functionWed, 01 Mar 2023

You have two non-decreasing sorted lists of n and m elements Your task is to merge them into one sorted list of size n + m Input The program receives as input two numbers n and m - the number of elements of the first list and the second list Then the elements of the first sorted list come from a new line, and from the next line - the second list Output Merge two lists into one in non-decreasing order and output the elements of the resulting list P.S: it is forbidden to use the built-in sorting Note: to display the resulting list, you can use the following construction print(*result) # where result is the final list

n = int(input()) m = int(input()) a = [int(i) for i in input().split()] b = [int(i) for i in input().split()] c = [] i = 0 j = 0 while i < n or j < m: if i < n and j < m: if a[i] < b[j]: c.append(a[i]) i += 1 else: c.append(b[j]) j += 1 elif i < n: c.append(a[i]) i += 1 elif j < m: c.append(b[j]) j += 1 print(*c)

Python
View
generate functionTue, 21 Mar 2023

На вход программе поступает строка, состоящая из нескольких слов, знаком разделителем между словами будем считать символ пробела. Ваша задача исключить из строки дублирующие слова: первое появление слова остается в строке, второе и все последующие появления исключаются. При сравнении на дубли строк регистр букв не учитывать, это значит слова python и PyThOn считаются одинаковыми. В качестве ответа необходимо вывести итоговую строку без дублей

def remove_dublicate(some_string): #your code here return some_string

Python
View
generate functionFri, 10 Feb 2023

Write a program that prints the maximum element of a square matrix whose elements are entered from the keyboard, below the main diagonal. The elements of the main diagonal are also taken into account.

n = int(input("Enter the value of n: ")) def max_of_matrix(n): matrix = [] sum = 0 for i in range(n): a = [] for j in range(n): a.append(int(input())) matrix.append(a) for i in range(n): for j in range(n): if i < j: sum += matrix[i][j] return sum print(max_of_matrix(n)

Python
View
generate functionMon, 06 Mar 2023

display 10 numbers in a column from 0.001 to 1 consisting of exactly 12 significant numbers after the decimal point. digits in a number should not be consecutive with repetition. The numbers must be positive. The sum of ten displayed numbers must be equal to n entered from the keyboard

import math def display_10_numbers(n): number = 0 while number < 10: num = round(n - math.pow(10, -12), 12) print(num) number += 1 n = n - num n = float(input()) display_10_numbers(n)

Python
View
generate functionWed, 15 Mar 2023

And now all together! You only have the function that is given to you as an argument and you must find its minimum. You will look for the global one, you should be able to do this only because they are good here. Yes, and yet, now they are not one-dimensional, but two-dimensional. You will also be given starting points from which convergence is guaranteed. Hint can use the following options: Deviation in the calculation of the derivative ε=10−10 Stopping criterion: number of iterations 104 Gradient Descent Step Length lr=0.5 Once again, we provide a step drawing feature for added convenience.

def grad_descent(df, x0, step_size=0.5, thresh=1e-10, max_iter=1e4): step = 0 x = x0 while step < max_iter and np.linalg.norm(df(x)) > thresh: x = x - step_size*df(x) step = step + 1 return x

Python
View
generate functionWed, 03 May 2023

Напиши код программы на языке python используй жадный алгоритм. Есть n игроков, которые играют на протяжении m дней. Мероприятие проходит в помещении, где находится k столов. За каждым столом разное количество посадочных мест. Общее количество посадочных мест совпадает с общим количеством игроков. Нужно написать программу рассадки игроков за столами так, чтобы c 1 по m день каждый посидел за столом с как можно большим количеством игроков. Результат отобразить как в примере. Пример ввода 1 Введите количество людей: 3 Введите количество дней: 2 Введите количество столов: 2 Введите количество мест за столами: 2 1 Пример вывода 1 День 1: На столе 1 сидят люди с номерами: [1, 2] На столе 2 сидят люди с номерами: [3] День 2: На столе 1 сидят люди с номерами: [1, 3] На столе 2 сидят люди с номерами: [2]

n = int(input("Введите количество людей: ")) m = int(input("Введите количество дней: ")) k = int(input("Введите количество столов: ")) places = [int(s) for s in input().split()] for day in range(m): print("День {}".format(day + 1)) for table in range(k): print("На столе {} сидят люди с номерами: {}".format(table + 1, table + 1))

Python
View
generate functionTue, 14 Feb 2023

Vasya has n pairs of socks. Every morning, when going to school, Vasya has to put on a pair of socks. In the evening, after coming home from school, Vasya takes off his socks and throws them away. Every m-th day (on days with numbers m, 2m, 3m, ...) Mom buys Vasya one pair of socks. She does it late at night, so Vasya can put on new socks not until the next day. How many consecutive days will Vasya have enough socks for? Input data The single line contains two integers n and m (1 ≤ n ≤ 100; 2 ≤ m ≤ 100) separated by a space. Output Print a single integer — the answer to the problem.

def days(n, m): if n == 1: return 1 elif n % 2 == 1: return 1 + days(n - 1, m) else: return 1 + days(n // 2, m) days(1, 2)

Python
View
generate functionFri, 10 Feb 2023

Write a program that prints the maximum element of a square matrix below the main diagonal. The elements of the main diagonal are also taken into account. The input is a natural number n — the number of rows and columns in the matrix, the number of matrix elements (integers) line by line separated by a space.

def diagonal(n): list = [] for i in range(n): list.append(input().split(" ")) for i in range(n): for j in range(n): list[i][j] = int(list[i][j]) max = 0 for i in range(n): for j in range(n): if i > j and max < list[i][j]: max = list[i][j] return max

Python
View
generate functionMon, 06 Mar 2023

output ten numbers whose sum is equal to the fractional number entered from the keyboard. digits in a row do not repeat in each number. Each number must contain twelve significant digits. the numbers are positive.

def get_decimals(n): return str(n).split('.')[1] def get_parts(n): parts = [] decimal_part = get_decimals(n) if decimal_part: parts = [decimal_part] while n > 1: parts.append(1) n -= 1 while len(parts) < 10: parts.append(0) return parts def get_last_num(parts): return ''.join(map(str, parts)) def get_first_num(parts): return '1' * (12 - len(parts[0])) + parts[0] def get_nums(parts): nums = [] last_num = get_last_num(parts) nums.append(last_num) for i in range(9): num = last_num[-i:] + '0' * i nums.append(num) return nums

Python
View
generate functionWed, 08 Feb 2023

When playing "Cities", players take turns calling the names of cities so that the first letter of each new word coincides with the last letter of the previous one. At the same time, it is believed that if the last letter of the previous word is f, then the letter preceding f should be compared with the first letter of the next word. Write a program that reads two lines in a row, and then prints "Good" if the last character of the first line matches the first character of the second (subject to the f rule), and "Bad" otherwise.

def game(str1,str2): if str1[-1] != str2[0] and str1[-1]=='f': return 'Bad' else: return 'Good' game('car', 'fog')

Python
View
generate functionTue, 28 Feb 2023

import numpy as np def transform(X, a=1): Y = np.zeros_like(X) for i in range(X.shape[0]): row = X[i] new_row = np.zeros_like(row) for j in range(row.shape[0]): if j % 2 == 0: new_row[j] = row[j] ** 3 else: new_row[j] = a Y[i] = new_row[::-1] return np.hstack((X, Y))

def transform(X, a=1): Y = np.zeros_like(X) for i in range(X.shape[0]): row = X[i] new_row = np.zeros_like(row) for j in range(row.shape[0]): if j % 2 == 0: new_row[j] = row[j] ** 3 else: new_row[j] = a Y[i] = new_row[::-1] return np.hstack((X, Y))

Python
View
generate functionFri, 10 Mar 2023

a list of city names is given in one line separated by a space. Iterate through all these names with a for loop and determine if the name of the next city begins with the last letter of the previous city in the list. Display YES if the sequence matches this rule and NO otherwise.

def check_sequence(city_names): for i in range(1, len(city_names)): if city_names[i][0] != city_names[i-1][-1]: return False return True check_sequence(['Poltava', 'Kyiv', 'Odesa', 'Vinnytsia'])

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, которая выводит часть последовательности 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ... (число повторяется столько раз, чему равно). На вход программе передаётся неотрицательное целое число n — столько элементов последовательности должна отобразить программа. На выходе ожидается последовательность чисел, записанных через пробел в одну строку. Например, если n = 7, то программа должна вывести 1 2 2 3 3 3 4.

def number_repeat_n_times(n): i = 1 while n > 0: print((str(i) + ' ') * i, end='') n -= i i += 1 print(number_repeat_n_times(7))

Python
View
generate functionWed, 12 Apr 2023

'''Напишите программу, которая возводит квадратную матрицу в степень m. Формат входных данных На вход программе подаётся натуральное число n — количество строк и столбцов в матрице, затем элементы матрицы, затем натуральное число m. Формат выходных данных Программа должна вывести результирующую матрицу, разделяя элементы символом пробела. '''

def exp_matrix(matrix, m): matrix_exp = np.matrix(matrix) for i in range(m-1): matrix_exp = matrix_exp * np.matrix(matrix) return matrix_exp def get_matrix(): n = int(input()) matrix = [list(map(int, input().split())) for i in range(n)] m = int(input()) return exp_matrix(matrix, m) if __name__ == "__main__": print(*get_matrix())

Python
View
generate functionThu, 06 Apr 2023

На вход программе подаются два натуральных числа � n и � m. Напишите программу, которая создает матрицу размером � × � n×m заполнив её "спиралью" в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа � n и � m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести матрицу в соответствии образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(), система примет и такое решение 😇 Тестовые данные 🟢 Sample Input 1: 4 5 Sample Output 1: 1 2 3 4 5 14 15 16 17 6 13 20 19 18 7 12 11 10 9 8

n, m = [int(i) for i in input().split()] matrix = [[0] * m for i in range(n)] a = 1 b = 0 c = n d = m while a <= n * m: for i in range(b, d): matrix[b][i] = a a += 1 for j in range(b + 1, c): matrix[j][d-1] = a a += 1 for k in range(d-2, b-1, -1): matrix[c-1][k] = a a += 1 for l in range(c-2, b, -1): matrix[l][b] = a a += 1 b += 1 c -= 1 d -= 1 for i in range(n): for j in range(m): print(str(matrix[i][j]).ljust(3), end='') print()

Python
View
generate functionTue, 28 Feb 2023

Matrix multiplication Write two functions that each multiply two square matrices, one without using numpy's built-in functions, and the other using numpy. The input to the first task is given lists of size size by size elements in each. The second task receives objects of type np.ndarray --- square matrices of the same size. The first function should return a list of lists, and the second should return np.array.

def mat_mult(A, B): # write your code here return None def numpy_mat_mult(A, B): # write your code here return None

Python
View
generate functionWed, 12 Apr 2023

Имеется словарь с наименованиями предметов и их весом (в граммах): things = {'карандаш': 20, 'зеркальце': 100, 'зонт': 500, 'рубашка': 300, 'брюки': 1000, 'бумага': 200, 'молоток': 600, 'пила': 400, 'удочка': 1200, 'расческа': 40, 'котелок': 820, 'палатка': 5240, 'брезент': 2130, 'спички': 10} Сергей собирается в поход и готов взвалить на свои хрупкие плечи максимальный вес в N кг (вводится с клавиатуры). Он решил класть в рюкзак предметы в порядке убывания их веса (сначала самые тяжелые, затем, все более легкие) так, чтобы их суммарный вес не превысил значения N кг. Все предметы даны в единственном экземпляре. Выведите список предметов (в строчку через пробел), которые берет с собой Сергей в порядке убывания их веса. P. S. 1 кг = 1000 грамм Sample Input: 10 Sample Output: палатка брезент удочка брюки пила карандаш спички

def pack(n, things): result = [] for key, value in sorted(things.items(), key=lambda item: item[1], reverse=True): if n >= value: result.append(key) n -= value return result pack(10, {'карандаш': 20, 'зеркальце': 100, 'зонт': 500, 'рубашка': 300, 'брюки': 1000, 'бумага': 200, 'молоток': 600, 'пила': 400, 'удочка': 1200, 'расческа': 40, 'котелок': 820, 'палатка': 5240, 'брезент': 2130, 'спички': 10})

Python
View
generate functionTue, 04 Apr 2023

Напишите программу, которая считывает с консоли числа (по одному в строке) до тех пор, пока сумма введённых чисел не будет равна 0 и сразу после этого выводит сумму квадратов всех считанных чисел. Гарантируется, что в какой-то момент сумма введённых чисел окажется равной 0, после этого считывание продолжать не нужно. В примере мы считываем числа 1, -3, 5, -6, -10, 13; в этот момент замечаем, что сумма этих чисел равна нулю и выводим сумму их квадратов, не обращая внимания на то, что остались ещё не прочитанные значения.

a = int(input()) s = 0 s2 = 0 while a != 0: s += a s2 += a ** 2 a = int(input()) print(s2)

Python
View
generate functionFri, 14 Apr 2023

'''Дана прямоугольная матрица размером NxM, в которой заполнены значения только в первом столбце и в первом ряду. Все остальные элементы равны нулю и мы считаем их незаполненными. Ваша задача заполнить каждый пустой элемент путем сложения соседа слева и соседа сверху. Начинать нужно с тех элементов, у которых оба указанных соседа заполнены (не равны нулю) Входные данные Программа сперва принимает в одной строке на вход два числа N и M - количество строк и столбцов в списке, а затем в N строках записаны элементы списка. Выходные данные Вывести заполненную матрицу Sample Input 1: 5 4 1 1 1 1 1 0 0 0 1 0 0 0 1 0 0 0 1 0 0 0 Sample Output 1: 1 1 1 1 1 2 3 4 1 3 6 10 1 4 10 20 1 5 15 35'''

n, m = map(int, input().split()) a = [] for i in range(n): a.append([int(j) for j in input().split()]) for i in range(1, n): for j in range(1, m): if a[i][j] == 0: a[i][j] = a[i - 1][j] + a[i][j - 1] for i in range(n): for j in range(m): print(a[i][j], end=' ') print()

Python
View
generate functionMon, 03 Apr 2023

На вход программе подаются два натуральных числа n и m. Напишите программу, которая создает матрицу размером n×m и заполняет её числами от 1 до n⋅m в соответствии с образцом. Формат входных данных На вход программе на одной строке подаются два натуральных числа n и m — количество строк и столбцов в матрице. Формат выходных данных Программа должна вывести матрицу в соответствии с образцом. Примечание. Для вывода элементов матрицы как в примерах, отводите ровно 3 символа на каждый элемент. Для этого используйте строковый метод ljust(). Можно обойтись и без ljust(),система примет и такое решение Тестовые данные Sample Input 1: 3 7 Sample Output 1: 1 4 7 10 13 16 19 2 5 8 11 14 17 20 3 6 9 12 15 18 21

n, m = int(input()), int(input()) lst = [[0] * m for _ in range(n)] for i in range(n): for j in range(m): lst[i][j] = i * m + j + 1 for i in range(n): for j in range(m): print(lst[i][j], end = ' ') print()

Python
View
generate functionThu, 16 Feb 2023

Enter number n. Starting with the number n, multiply the given number by its first digit until the resulting number has the first digit equal to 1, or until it exceeds a billion. Output the result as an answer.

def first_digit(n): if n < 0: n = abs(n) elif n == 0: return 0 else: return int(str(n)[0]) def multiply_first_digit(n): if n < 0: n = abs(n) elif n == 0: return 0 else: while n // 10 >= 1: n = first_digit(n) * n if n >= 1000000000: return f'{n} exceeds a billion' return n multiply_first_digit(1234)

Python
View
generate functionMon, 20 Mar 2023

On the first line, one character is entered - a lowercase letter. The sentence is entered on the second line. Output It is necessary to output a list of words (a word is a part of a sentence surrounded by white space characters) in which the entered letter is present in any case, in the same order in which they occur in the sentence.

def looking4letters(letter, sentence): return [word for word in sentence if letter.lower() in word.lower()] looking4letters('h', 'Hello world') looking4letters('h', 'Hello world') looking4letters('s', 'She sells sea shells on the sea shore') looking4letters('a', 'An apple a day keeps the doctor away')

Python
View
generate functionThu, 13 Apr 2023

'''Вводятся целые числа в одну строку через пробел. На их основе формируется кортеж. Необходимо найти и вывести все индексы неуникальных (повторяющихся) значений в этом кортеже. Результат отобразите в виде строки чисел, записанных через пробел. Sample Input: 5 4 -3 2 4 5 10 11 Sample Output: 0 1 4 5'''

a = tuple(map(int, input().split())) print(*(i for i, x in enumerate(a) if a.count(x) > 1))

Python
View
generate functionTue, 21 Feb 2023

The date of a certain day is characterized by two natural numbers: m (serial number of the month) and n (number). According to the entered m and n (in one line separated by a space), determine: a) the date of the previous day (assume that m and n do not characterize January 1); b) the date of the next day (assume that m and n do not characterize December 31). The problem is to assume that the year is not a leap year. Print the previous date and the next date (in the format: mm.dd, where m is the day of the month; d is the number of the day) in one line separated by a space. P.S. Number of days in non-leap year months starting from January: 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 Sample Input: 8 31 Sample Output: 08.30 09.01

def date(m, n): if m == 12 and n == 31: return '01.01' if n == 1: return str(m - 1).zfill(2) + '.31' return str(m).zfill(2) + '.' + str(n - 1).zfill(2) + ' ' + str(m).zfill(2) + '.' + str(n + 1).zfill(2) print(date(*map(int, input().split())))

Python
View
generate functionMon, 20 Feb 2023

A list of texts is given, the words in which are separated by spaces (we can assume that there are no punctuation marks). Some of the words are "garbage": they contain numbers and special characters. Filter out such words from each text. Use the str.split, str.isalpha, str.join functions, as well as the filter generator. sentences = ['1 thousand devils', 'My name is 9Pasha', 'Room #125 costs $100'] def process(sentences): #YOUR CODE result = #YOUR CODE return result assert process(sentences) == ['thousand devils', 'My name is', 'Room costs'], \ "Something is wrong! Please try again"

sentences = ['1 thousand devils', 'My name is 9Pasha', 'Room #125 costs $100'] def process(sentences): #YOUR CODE res = [] for sentence in sentences: res.append(' '.join(list(filter(lambda word: word.isalpha(), sentence.split())))) return res assert process(sentences) == ['thousand devils', 'My name is', 'Room costs'], \ "Something is wrong! Please try again" process(sentences)

Python
View
generate functionMon, 06 Mar 2023

enter a floating point number n. Output ten numbers the total sum of which is equal to n. In the ten numbers displayed, the numbers do not go in a row. The range of output numbers is strictly not less than 0.001 and not more than 1. The displayed ten digits have strictly twelve digits after the decimal point.

def example(n): if type(n) is not int and type(n) is not float: return "This is not a number" if n <= 0 or n > 1: return "The range of number is incorrect" sum = 0 for i in range(1, 11): num = round(random.uniform(0.001, 1), 12) sum += num print(num, end = " ") if sum == n: return else: return "The sum of numbers is not correct" example(0.1)

Python
View
generate functionTue, 07 Feb 2023

The department has 3 employees who receive wages in rubles. It is required to determine how much the salary of the highest paid of them differs from the lowest paid. Note: the min and max functions, as well as sorting, cannot be used, we are studying the conditional operator)

def max_min(a, b, c): if a > b and a > c: if b > c: print(a - c) else: print(a - b) elif b > a and b > c: if a > c: print(b - c) else: print(b - a) elif c > a and c > b: if a > b: print(c - b) else: print(c - a) max_min(1, 2, 3)

Python
View

Questions about programming?Chat with your personal AI assistant