Вопрос задан 06.06.2023 в 02:31. Предмет Информатика. Спрашивает Филиппов Семён.

Znanija Поиск... rakhimjanovnematulla 6 часов назад Информатика 10 - 11 классы 1. Напишите

сценарий Python для создания и печати словаря, содержащего число (от 1 до п включительно) (где п- введенное пользователем число) в форме (x, x * x). Sample Dictionary (n = 5): Ожидаемый результат: {1: 1, 2: 4, 3: 9, 4: 16, 5:25} - Генератор словарей 2. Напишите программу Python для суммирования всех значений словаря и вывод среднего арифметического значения. 3. Напишите программу Python для объединения двух списков в словарь ключ: значение. списки долЛЖНЫ БЫТЬ ОДНОГО РАЗМЕРА 4. Есть словарь координат городов. cities = { 'Moscow': (550, 370), 'London': (510, 510), 'Paris': (480, 480), } Составьте словарь словарей расстояний между ними по формуле: ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5 distances = 0 moscow = cities['Moscow'] London = cities['London'] paris = cities['Paris'] 5. Есть словарь кодов товаров и словарь количества товара на складе. Вывести общую стоимость каждой категории товара goods = { Лампа': '12345', "Стол': '23456', "Диван": '34567', "Стул': '45678', } store = { '12345': [ { 'quantity': 27, 'price': 42 }, 1, '23456': [ { 'quantity': 22, 'price': 510 { 'quantity': 32, 'price': 520 }, }, '34567': [ { 'quantity': 2, 'price': 1200 }, { 'quantity': 1, 'price': 1150 }, ], '45678': [ { 'quantity': 50, 'price': 100 }, { 'quantity': 12, 'price': 95 }, { 'quantity': 43, 'price': 97 } ], ]
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Прокопенко Иван.

Ответ:# 1. Write a Python script to create and print a dictionary containing a number (1 to n inclusive) (where n is a user-specified number) in the form (x, x * x). Sample Dictionary (n = 5): Expected result: {1: 1, 2: 4, 3: 9, 4: 16, 5:25}

def create_dictionary(n):

 """

 Creates a dictionary containing a number (1 to n inclusive) (where n is a user-specified number) in the form (x, x * x).

 Args:

   n: The number of items to include in the dictionary.

 Returns:

   A dictionary containing a number (1 to n inclusive) (where n is a user-specified number) in the form (x, x * x).

 """

 dictionary = {}

 for i in range(1, n + 1):

   dictionary[i] = i * i

 return dictionary

def main():

 """

 The main function.

 """

 n = int(input("Enter a number: "))

 dictionary = create_dictionary(n)

 print(dictionary)

if __name__ == "__main__":

 main()

Use code with caution. Learn more

Python

# 2. Write a Python program to summarize all dictionary values and output the arithmetic mean.

def summarize_dictionary(dictionary):

 """

 Summarizes all dictionary values and outputs the arithmetic mean.

 Args:

   dictionary: The dictionary to summarize.

 Returns:

   The arithmetic mean of the dictionary values.

 """

 total = 0

 count = 0

 for value in dictionary.values():

   total += value

   count += 1

 mean = total / count

 return mean

def main():

 """

 The main function.

 """

 dictionary = {"a": 1, "b": 2, "c": 3}

 mean = summarize_dictionary(dictionary)

 print("The arithmetic mean is:", mean)

if __name__ == "__main__":

 main()

Use code with caution. Learn more

Python

# 3. Write a Python program to combine two lists into a key: value dictionary.

def combine_lists(list1, list2):

 """

 Combines two lists into a key: value dictionary.

 Args:

   list1: The first list.

   list2: The second list.

 Returns:

   A dictionary where the keys are the elements of list1 and the values are the corresponding elements of list2.

 """

 dictionary = {}

 for i in range(len(list1)):

   dictionary[list1[i]] = list2[i]

 return dictionary

def main():

 """

 The main function.

 """

 list1 = ["a", "b", "c"]

 list2 = [1, 2, 3]

 dictionary = combine_lists(list1, list2)

 print(dictionary)

if __name__ == "__main__":

 main()

Use code with caution. Learn more

Python

# 4. There is a dictionary of coordinates of cities.

#

# cities = {

#

# Moscow': (550, 370),

#

# 'London': (510, 510),

#

# 'Paris': (480, 480),

#

# }

#

# Make a dictionary of dictionaries of distances between them using the formula:

#

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

#

# distances = 0

#

# moscow = cities['Moscow']

#

# London = cities['London'] paris = cities['Paris']

def calculate_distance(x1, y1, x2, y2):

 """

 Calculates the distance between two points.

 Args:

   x1: The x-coordinate of the first point.

   y1: The y-coordinate of the first point.

   x2: The x-coordinate of the second point.

   y2: The y-coordinate of the second point.

Объяснение:

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Конечно! Вот решения для каждой из задач:

  1. Напишите сценарий Python для создания и печати словаря, содержащего число (от 1 до п включительно) в форме (x, x * x):
python
n = int(input("Введите число: ")) dictionary = {x: x*x for x in range(1, n+1)} print(dictionary)
  1. Напишите программу Python для суммирования всех значений словаря и вывода среднего арифметического значения:
python
dictionary = {'a': 5, 'b': 10, 'c': 15} total_sum = sum(dictionary.values()) average = total_sum / len(dictionary) print("Сумма значений:", total_sum) print("Среднее арифметическое:", average)
  1. Напишите программу Python для объединения двух списков в словарь ключ: значение (при условии, что списки имеют одинаковый размер):
python
keys = ['a', 'b', 'c'] values = [1, 2, 3] dictionary = dict(zip(keys, values)) print(dictionary)
  1. Есть словарь координат городов. Создайте словарь словарей расстояний между ними по формуле ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5:
python
import math cities = {'Moscow': (550, 370), 'London': (510, 510), 'Paris': (480, 480)} distances = {} for city1, coords1 in cities.items(): city_distances = {} for city2, coords2 in cities.items(): distance = math.sqrt((coords1[0] - coords2[0]) ** 2 + (coords1[1] - coords2[1]) ** 2) city_distances[city2] = distance distances[city1] = city_distances print(distances)
  1. Есть словарь кодов товаров и словарь количества товара на складе. Вывести общую стоимость каждой категории товара:
python
goods = {'Лампа': '12345', 'Стол': '23456', 'Диван': '34567', 'Стул': '45678'} store = { '12345': [{'quantity': 27, 'price': 42}], '23456': [{'quantity': 22, 'price': 510}, {'quantity': 32, 'price': 520}], '34567': [{'quantity': 2, 'price': 1200}, {'quantity': 1, 'price': 1150}], '45678': [{'quantity': 50, 'price': 100}, {'quantity': 12, 'price': 95}, {'quantity': 43, 'price': 97}] } for product, code in goods.items(): total_cost = 0 for item in store[code]: quantity = item['quantity'] price = item['price'] total_cost += quantity * price print("Категория:", product) print("Общая стоимость:", total_cost)
0 0

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос