python,list,dictionary , Implementing a dictionary function to calculate the average of a list

## Question:

Tag: python,list,dictionary

As always, I've attempted this for awhile before I proceed to ask a question on here. I know there are several attempts at answering this, but none really worked for what I needed.

Here are the instructions:

Implement the following three functions (you should use an appropriate looping construct to compute the averages):

``````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.
``````

Write a program that asks the user to enter some numbers (positives, negatives and zeros). Your program should NOT ask the user to enter a fixed number of numbers. Also it should NOT ask for the number of numbers the user wants to enter. But rather it should ask the user to enter a few numbers and end with -9999 (a sentinel value). The user can enter the numbers in any order. Your program should NOT ask the user to enter the positive and the negative numbers separately.

Your program then should create a list with the numbers entered (make sure NOT to include the sentinel value (-9999) in this list) and output the list and a dictionary with the following Key-Value pairs (using the input list and the above functions):

``````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
``````

Sample run:

Enter a number (-9999 to end): 4

Enter a number (-9999 to end): -3

Enter a number (-9999 to end): -15

Enter a number (-9999 to end): 0

Enter a number (-9999 to end): 10

Enter a number (-9999 to end): 22

Enter a number (-9999 to end): -9999

The list of all numbers entered is:

[4, -3, -15, 0, 10, 22]

The dictionary with averages is:

{'AvgPositive': 12.0, 'AvgNonPos': -6.0, 'AvgAllNum': 3.0}

Here's is my code:

``````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)
``````

My question is how can I implement the averages to be printed from the dictionary since I'm currently getting the error of: `"AvgPositive": posNumAvg(values), NameError: name 'values' is not defined`. Additionally, how would I get the list of the numbers entered to print?

Thanks!

I think you want something more like:

``````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` is the sentinel value to break the loop

``````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)
}
``````

If you want to create the three lists in the loop check the each i in a for loop appending to the correct list:

``````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)
}
``````

# Related:

## Python: histogram/ binning data from 2 arrays.

python,histogram,large-files
I have two arrays of data: one is a radius values and the other is a corresponding intensity reading at that intensity: e.g. a small section of the data. First column is radius and the second is the intensities. 29.77036614 0.04464427 29.70281027 0.07771409 29.63523525 0.09424901 29.3639355 1.322793 29.29596385 2.321502 29.22783249...

## Strange Behavior: Floating Point Error after Appending to List

python,python-2.7,behavior
I am writing a simple function to step through a range with floating step size. To keep the output neat, I wrote a function, correct, that corrects the floating point error that is common after an arithmetic operation. That is to say: correct(0.3999999999) outputs 0.4, correct(0.1000000001) outputs 0.1, etc. Here's...

## SyntaxError: invalid syntax?

python,syntax
Good afternoon, I am developing a script in python and while I am trying to compile it from the terminator/terminal i always get this error, but I cannot understand where is the syntax error? File "_case1.py", line 128 print ('########################') ^ SyntaxError: invalid syntax Then I just change the position...

## Create an exe with Python 3.4 using cx_Freeze

python,python-3.4,cx-freeze
I have found two other articles about this problem on Stack Exchange but none of them has a clear answer: is it possible to create a .exe of a Python 3.4 script? The only solution I found was to use cx_Freeze. I used it, and it indeed created an executable...

## Matplotlib: Plot the result of an SQL query

python,sql,matplotlib,plot
from sqlalchemy import create_engine import _mssql from matplotlib import pyplot as plt engine = create_engine('mssql+pymssql://**:****@127.0.0.1:1433/AffectV_Test') connection = engine.connect() result = connection.execute('SELECT Campaign_id, SUM(Count) AS Total_Count FROM Impressions GROUP BY Campaign_id') for row in result: print row connection.close() The above code generates an array: (54ca686d0189607081dbda85', 4174469) (551c21150189601fb08b6b64', 182) (552391ee0189601fb08b6b73', 237304) (5469f3ec0189606b1b25bcc0',...

## Sort when values are None or empty strings python

python,list,sorting,null
I have a list with dictionaries in which I sort them on different values. I'm doing it with these lines of code: def orderBy(self, col, dir, objlist): if dir == 'asc': sorted_objects = sorted(objlist, key=lambda k: k[col]) else: sorted_objects = sorted(objlist, key=lambda k: k[col], reverse=True) return sorted_objects Now the problem...

## Replace nodejs for python?

python,node.js,webserver
i'm working in a HTML5 multiplayer game, and i need a server to sync player's movement, chat, battles, etc. So I'm looking for ways to use python instead nodejs, because i have I have more familiarity with python. The server is simple: var express = require('express'); var app = express();...

## Count function counting only last line of my list

python,python-2.7
Count function counting only last line of my list N = int(raw_input()) cnt = [] for i in range(N): string = raw_input() for j in range(1,len(string)): if string[j] =='K': cnt.append('R') elif string[j] =='R': cnt.append('R') if string == 'k': cnt.append('k') elif string == 'R': cnt.append('R') print cnt.count('R') if I am giving...

## The event loop is already running

python,python-3.x,pyqt,pyqt4
I have the following 5 files: gui.py # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig)...

## Identify that a string could be a datetime object

python,regex,algorithm,python-2.7,datetime
If I knew the format in which a string represents date-time information, then I can easily use datetime.datetime.strptime(s, fmt). However, without knowing the format of the string beforehand, would it be possible to determine whether a given string contains something that could be parsed as a datetime object with the...

## How do I read this list and parse it?

python,list
I'm using requests and the output I get from the sites API is a list, I've been stuck trying to parse it to get the data from it. I use r = requests.get(urlas, params=params) r.json() to get the data I want. Here is a snippet of the list [{'relation_type': None,...

## How does the class_weight parameter in scikit-learn work?

python,scikit-learn
I am having a lot of trouble understanding how the class_weight parameter in scikit-learn's Logistic Regression operates. The Situation I want to use logistic regression to do binary classification on a very unbalanced data set. The classes are labelled 0 (negative) and 1 (positive) and the observed data is in...

## Calling function and passing arguments multiple times

python,function,loops
I want to call the function multiple time and use it's returned argument everytime when it's called. For example: def myfunction(first, second, third): return (first+1,second+1,third+1) 1st call: myfunction(1,2,3) 2nd call is going to be pass returned variables: myfunction(2,3,4) and loop it until defined times. How can I do such loop?...

## Peewee: reducing where conditionals break after a certain length

python,peewee
This is what I have: SomeTable.select.where(reduce(operator.or_, (SomeTable.stuff == entry for entry in big_list))) The problem arises when I have a relatively large list of elements in big_list and I get this: RuntimeError: maximum recursion depth exceeded Is there another way to approach this that doesn't involve splitting up the list...

## How to put an image on another image in python, using ImageTk?

python,user-interface,tkinter
I want to put an image in front of another one, then use this combined image as a button's background image in Tkinter. How can I do it? I am free to import Tkimage, Image. Clarify: I want to stick this on the center of this so that something like...

## In sklearn, does a fitted pipeline reapply every transform?

python,scikit-learn,pipeline,feature-selection
Apologies if this is obvious but I couldn't find a clear answer to this: Say I've used a pretty typical pipeline: feat_sel = RandomizedLogisticRegression() clf = RandomForestClassifier() pl = Pipeline([ ('preprocessing', preprocessing.StandardScaler()), ('feature_selection', feat_sel), ('classification', clf)]) pl.fit(X,y) Now when I apply pl on a new set, pl.predict(X_classify); is RandomizedLogisticRegression going...

## Python: can't access newly defined environment variables

python,bash,environment-variables
I can't access my env var: import subprocess, os print os.environ.get('PATH') # Works well print os.environ.get('BONSAI') # doesn't work But the env var is well added in my /home/me/.bashrc: BONSAI=/home/me/Utils/bonsai_v3.2 export BONSAI And I can access this env var from a new terminal....

## Sum of two variables in RobotFramework

python,automated-tests,robotframework
I have two variables: \${calculatedTotalPrice} = 42,42 \${productPrice1} = 43,15 I executed \${calculatedTotalPrice} Evaluate \${calculatedTotalPrice}+\${productPrice1} I got 42,85,15 How can I resolve it?...

## why java API prevents us to call add and remove together?

java,list,collections,listiterator
As per Java API- IllegalStateException - if neither next nor previous have been called, or remove or add have been called after the last call to next or previous remove()- Removes from the list the last element that was returned by next() or previous() (optional operation). This call can only...

## represent an index inside a list as x,y in python

python,list,numpy,multidimensional-array
I have a list which contains 1000 integers. The 1000 integers represent 20X50 elements of dimensional array which I read from a file into the list. I need to walk through the list with an indicator in order to find close elements to each other. I want that my indicator...

## Python - Opening and changing large text files

python,replace,out-of-memory,large-files
I have a ~600MB Roblox type .mesh file, which reads like a text file in any text editor. I have the following code below: mesh = open("file.mesh", "r").read() mesh = mesh.replace("[", "{").replace("]", "}").replace("}{", "},{") mesh = "{"+mesh+"}" f = open("p2t.txt", "w") f.write(mesh) It returns: Traceback (most recent call last): File...

## How do variables inside python modules work?

python,module,python-module
I am coming from a Java background with Static variables, and I am trying to create a list of commonly used strings in my python application. I understand there are no static variables in python so I have written a module as follows: import os APP_NAME = 'Window Logger' APP_DATA_FOLDER_PATH...

## Twilio Client Python not Working in IOS Browser

I have created a simple twilio client application to make phone calls from Web Browser to phones. I used a sample Flask app to generate a secure Capability Token and used twilio.min.js library to handle calls from my HTML. The functionality works fine in Computer Browsers ans Android Phone Browsers,...

## sys.argv in a windows environment

python,windows,python-3.x
I'm attempting to learn python using the book 'a byte of python'. The code: import sys print('the command line arguments are:') for i in sys.argv: print(i) print('\n\nThe PYTHONPATH is', sys.path, '\n') outputs: the command line arguments are: C:/Users/user/PycharmProjects/helloWorld/module_using_sys.py The PYTHONPATH is ['C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Users\\user\\PycharmProjects\\helloWorld', 'C:\\Python34\\python34.zip', 'C:\\Python34\\DLLs', 'C:\\Python34\\lib', 'C:\\Python34', 'C:\\Python34\\lib\\site-packages']...

## How to change the IP address of Amazon EC2 instance using boto library

python,amazon-web-services,boto
How can I assign a new IP address (or Elastic IP) to an already existing AWS EC2 instance using boto library.