Реализация словарной функции для вычисления среднего значения списка
Как всегда, я пытался это сделать некоторое время, прежде чем приступить к задаче здесь. Я знаю, что есть несколько попыток ответить на этот вопрос, но ни одна из них не сработала для того, что мне было нужно.
Вот инструкции:
Реализуйте следующие три функции (вы должны использовать соответствующую циклическую конструкцию для вычисления средних значений):
allNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list.
posNumAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are greater than zero.
nonPosAvg(numList) : takes a list of numbers and returns the average of all the numbers in the list that are less than or equal to zero.
Напишите программу, которая просит пользователя ввести некоторые цифры (положительные, отрицательные и нули). Ваша программа НЕ должна просить пользователя ввести фиксированное количество цифр. Кроме того, он не должен запрашивать количество номеров, которые пользователь хочет ввести. Скорее, он должен попросить пользователя ввести несколько цифр и в конце -9999 (значение часового). Пользователь может вводить цифры в любом порядке. Ваша программа НЕ должна просить пользователя вводить положительные и отрицательные числа отдельно.
Затем ваша программа должна создать список с введенными числами (убедитесь, что в этот список НЕ включено значение Sentinel (-9999)), и вывести список и словарь со следующими парами ключ-значение (используя список ввода и выше функции):
Key = 'AvgPositive' : Value = the average of all the positive numbers
Key = 'AvgNonPos' : Value = the average of all the non-positive numbers
Key = 'AvgAllNum' : Value = the average of all the numbers
Образец прогона:
Введите число (-9999 до конца): 4
Введите число (-9999 до конца): -3
Введите число (-9999 до конца): -15
Введите число (-9999 до конца): 0
Введите число (-9999 до конца): 10
Введите число (-9999 до конца): 22
Введите число (-9999 до конца): -9999
Список всех введенных номеров:
[4, -3, -15, 0, 10, 22]
Словарь со средними значениями:
{'AvgPositive': 12.0, 'AvgNonPos': -6.0, 'AvgAllNum': 3.0}
Вот мой код:
a = []
b = []
c = []
dictionary = {}
total = 0
print("Enter positive, negative or zero to determine the average: ")
while(True):
user_input = int(input("Enter a number (-9999 to end): "))
if(user_input == -9999):
break
def allNumAvg(values):
for number in a:
total = total + number
average = sum(total) / len(total)
if user_input > 0 or user_input < 0:
a.append(user_input)
return average
def posNumAvg(values):
for number in b:
total = total + number
average = sum(total) / len(total)
if user_input > 0:
b.append(user_input)
return average
def nonPosAvg(values):
for number in c:
total = total + number
average = sum(total) + len(total)
if user_input < 0:
c.append(user_input)
return average
print("The list of all numbers entered is:")
print(a+b+c)
dictionary = {
"AvgPositive": posNumAvg(values),
"AvgNonPos": nonPosAvg(values),
"AvgAllNum": allNumAvg(values)
}
print("The dictionary with the averages are:")
print(dictionary)
Мой вопрос заключается в том, как я могу реализовать средние значения для печати из словаря, так как в настоящее время я получаю ошибку: "AvgPositive": posNumAvg(values), NameError: name 'values' is not defined
, Кроме того, как я могу получить список номеров, введенных для печати?
Спасибо!
2 ответа
Я думаю, что вы хотите что-то более похожее на:
print("Enter positive, negative or zero to determine the average: ")
# get list of values/numbers from the user
values = [i for i in iter(lambda: int(input("Enter a number (-9999 to end): ")), -9999)]
-9999
является часовым значением для разрыва цикла
def allNumAvg(values):
# get average of all numbers
return sum(values) / len(values)
def posNumAvg(values):
# get only positive numbers
values = [v for v in values if v > 0]
return sum(values) / len(values)
def nonPosAvg(values):
# get all negative numbers
values = [v for v in values if v < 0]
return sum(values) / len(values)
print("The list of all numbers entered is:")
# pass list of values to each function
dictionary = {
"AvgPositive": posNumAvg(values),
"AvgNonPos": nonPosAvg(values),
"AvgAllNum": allNumAvg(values)
}
Если вы хотите создать три списка в цикле, проверьте каждый i в цикле for, добавляя в правильный список:
a = [] # all
p = [] # pos
n = [] # neg
print("Enter positive, negative or zero to determine the average: ")
values = []
for i in iter(lambda: int(input("Enter a number (-9999 to end): ")), -9999):
if i >= 0: # if positive append to p
p.append(i)
else: # else must be negative so append to n
n.append(i)
a.append(i) # always add to a to get all nums
def allNumAvg(values):
return sum(values) / len(values)
def posNumAvg(values):
return sum(values) /len(values)
def nonPosAvg(values):
return sum(values) / len(values)
print("The list of all numbers entered is:")
# pass correct list to each function
dictionary = {
"AvgPositive": posNumAvg(n),
"AvgNonPos": nonPosAvg(p),
"AvgAllNum": allNumAvg(a)
}
Может быть что-то вроде этого...(вы можете отлаживать, если он не работает как есть, так как это домашняя работа!). вам нужно определить "значения"
values = []
print("Enter positive, negative or zero to determine the average: ")
while(True):
user_input = int(input("Enter a number (-9999 to end): "))
if(user_input == -9999):
break
values.append(user_input)
это должно начать вас.