Finding the average of three numbers that are in a CSV file - python

I have created a piece of coding however I have begun to try to find the average of each persons score, but do not know what else to do. The code does not work:
def average():#makes function 'average'
print ("\nThe Average Score")#outputs the title 'The Average Score'
for pupils in classScore:
pupil["total"] = (int(pupil["Pupil's Score 1"])+int(pupil["Pupil's Score 2"])+int(pupil["Pupil's Score 3"]))
pupil["average"] = (pupil["total"]//3)
print (pupil["Pupil's Name"]+pupil["average"])
average()
The CSV file is laid out like this:
Pupil's Name Pupil's Score 1 Pupil's Score 2 Pupil's Score 3
Joao 10 9 8
Rebecca 7 6 5
Snuffles 0 1 2
The error message that appeared was:
Traceback (most recent call last):
File "E:/Controlled Assesment Computing/Controlled Assesment/Task 3/Try 18.py", line 56, in <module>
average()
File "E:/Controlled Assesment Computing/Controlled Assesment/Task 3/Try 18.py", line 53, in average
print (pupil["Pupil's Name"]+pupil["average"])
TypeError: Can't convert 'int' object to str implicitly
If anyone could help it would be much appreciated.

The message looks clear:
TypeError: Can't convert 'int' object to str implicitly
You must have to do an operation to turn a number into a string. Try this:
print(pupil["Pupil's Name"]+str(pupil["average"]))
You'd done yourself a disservice by limiting this method to three students. You could easily make it work for any number of students.
I would advice against printing from that average method. A method should do one thing well.

Related

TypeError: '>=' not supported between instances of 'tuple' and 'float'

I am trying to write a little python script that calculates the Tanimoto similarity index between a molecule of interest and a database of molecules. I am using pybel.
The database, in the .smi format, have chemical information of molecules on the first column and their names as a second one and looks like this:
C[C#]12CC[C#H](C1(C)C)CC2=O (-)-CAMPHOR
CC1=CC[C#H](C(=C)C)C[C##H]1O (-)-CARVEOL
CC1=CC[C#H](CC1=O)C(=C)C (-)-CARVONE
O=CC[C##H](C)CCC=C(C)C (-)-CITRONELLAL
OCC[C##H](C)CCC=C(C)C (-)-CITRONELLOL
C[C##H]1CC[C##H](C(=C)C)C[C#H]1O (-)-DIHYDROCARVEOL
C[C##]12CC[C##H](C1)C(C2=O)(C)C (-)-Fenchone
C[C##H]1CC[C#H]([C##H](C1)O)C(C)C (-)-MENTHOL
C[C##H]1CC[C#H](C(=O)C1)C(C)C (-)-MENTHONE
C[C##H]1CCCCCCCCCCCCC(=O)C1 (-)-MUSCONE
CC(=C)[C#H]1CCC(=CC1)C=O (-)-PERILLALDEHYDE
.
.
.
This version of the script works as I expect:
from openbabel import pybel
targetmol = next(pybel.readfile("smi", "/path/to/sample.smi"))
targetfp = targetmol.calcfp() <--- calculate fingerprints of the sample
for mol in pybel.readfile("smi", "/path/to/db.smi"):
fp = mol.calcfp() <--- calculate fingerprints of the db
tan = fp | targetfp <--- calculate the Tanimoto index via the "|" operator
if tan>=0.8:
print(tan)
Output:
1.0
1.0
0.9285714285714286
0.8571428571428571
1.0
1.0
0.9285714285714286
0.8571428571428571
.
.
.
Clearly, in order to give a meaning to the numbers I receive, I need to add the molecule name to the corresponding Tanimoto index. I tried this:
from openbabel import pybel
targetmol = next(pybel.readfile("smi", "/path/to/sample.smi"))
targetfp = targetmol.calcfp()
for mol in pybel.readfile("smi", "/path/to/db.smi"):
fp = mol.calcfp()
tan = (fp | targetfp, mol.title)
if tan>=0.8:
print(tan, title)
As from the title, I receive the following error:
Traceback (most recent call last):
File "test3.py", line 15, in <module>
if tan>=0.8:
TypeError: '>=' not supported between instances of 'tuple' and 'float'
My guess is that python, obviously, cannot apply the if tan>=0.8 operation to a string format but I really do not know how to overcome this problem since, as you can guess, I am very new to programming.
Any hints on how to correct this piece of code will be appreciated. Thank you for your time.
You just have to change it to:
tan[0] >= 0.8:
the comma , (the one inside tan = (fp | targetfp, mol.title)) is the syntax for a tuple, which is basically a not mutable array, so to access elements you need to do it by index like for lists.

Finding SUM, AVG, and DIFF of columns using Python with a CSV

Working with a CSV on Python 3.8 that goes something like:
Column_0>>>>>>>>>Column_1>>>>>>Column_2>>>>Column_3>>>>>Column_4
Some_Numbers0>>>Some_String1>>>Some_String2>Some_Numbers3>>Some_Numbers4
Now, the numbers in Column_3 and Column_4 are what need to be SUM, AVG, and finding the differences of their totals.
I'm currently stuck on trying to get both sums to print. This is how far i've got:
import csv
import decimal
with open("sample.csv") as myFile:
reader = csv.DictReader(myFile)
print(sum(float(line["Column_3"]) for line in reader))
print(sum(float(line["Column_4"]) for line in reader))
Using this, Column_3's total prints but Column_4 I get a "0". Remove prin line for Column_3, then I get Column_4's total just fine. I've also tried:
import csv
import decimal
with open("sample.csv") as myFile:
total = 0
for line in csv.DictReader(myFile):
total += int(line["Column_3"])
print(total)
but i get
Traceback (most recent call last):
File "some file pathway", line 7, in <module>
total += int(line["Column_3"])
ValueError: invalid literal for int() with base 10: '1345.67'
Which that number represents the first number value of that column_3.
I'm stumped. Any help is appreciated. I'm sure I'll be returning with questions on finding the AVG and then using their totals to find their differences, all need to print running from the same program but here I am already stuck.
your reader object can only go through the CSV file once, because you go through the list with col 3 its wont print for col 4 because there's nothing left to read. Your second approach would be fine, just replace int() with float() because your working with decimals

Python Error :'numpy.float64' object is not callable

I have written a code in python to generate a sequence of ARIMA model's and determine their AIC values to compare them.The code is as below,
p=0
q=0
d=0
for p in range(5):
for d in range(1):
for q in range(4):
arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
print(arima_mod.params)
print arima_mod.aic()
I am getting a error message as below,
TypeError Traceback (most recent call last)
<ipython-input-60-b662b0c42796> in <module>()
8 arima_mod=sm.tsa.ARIMA(df,(p,d,q)).fit()
9 print(arima_mod.params)
---> 10 print arima_mod.aic()
global arima_mod.aic = 1262.2449736558815
11
**TypeError: 'numpy.float64' object is not callable**
Remove the brackets after print arima_mod.aic(). As I read it, arima_mod.aic is 1262.2449736558815, and thus a float. The brackets make python think it is a function, and tries to call it. You do not want that (because it breaks), you just want that value. So remove the brackets, and you'll be fine.

why this python code is producing Runtime Error in ideone?

import sys
def func():
T = int(next(sys.stdin))
for i in range(0,T):
N = int(next(sys.stdin))
print (N)
func()
Here I am taking input T for for loop and iterating over T it gives Runtime error time: 0.1 memory: 10088 signal:-1 again-again . I have tried using sys.stdin.readline() it also giving same error .
I looked at your code at http://ideone.com/8U5zTQ . at the code itself looks fine, but your input can't be processed.
Because it is:
5 24 2
which will be the string:
"5 24 2"
this is not nearly an int, even if you try to cast it. So you could transform it to the a list with:
inputlist = next(sys.stdin[:-2]).split(" ")
to get the integers in a list that you are putting in one line. The loop over that.
After that the code would still be in loop because it want 2 integers more but at least you get some output.
Since I am not totally shure what you try to achieve, you could now iterate over that list and print your inputs:
inputlist = next(sys.stdin[:-2]).split(" ")
for i in inputlist
print(i)
Another solution would be, you just put one number per line in, that would work also
so instead of
5 24 2
you put in
5
24
2
Further Advice
on Ideone you also have an Error Traceback at the bottom auf the page:
Traceback (most recent call last):
File "./prog.py", line 8, in <module>
File "./prog.py", line 3, in func
ValueError: invalid literal for int() with base 10: '1 5 24 2\n'
which showed you that it can't handle your input

How to treat numbers in list as integers in function

I'm trying to write a function that finds both the signed/unsigned max/min values given a bit length. But every time I execute the function I get an error, here is my code
#function to find max and min number of both signed and unsigned bit values
def minmax (n) :
for numbers in n :
unsignedmax = (2**n)-1
unsignedmin = 0
signedmax = 2**(n-1)-1
signedmin = -2**(n-1)
print "number ", "unsigned ", "signed"
#Main
bitlist = [2, 3, 8, 10, 16, 20, 32]
minmax(bitlist)
the error is
Traceback (most recent call last):
File "C:/Users/Issac94/Documents/Python Files/sanchez-hw07b.py", line 23, in <module>
minmax(bitlist)
File "C:/Users/Issac94/Documents/Python Files/sanchez-hw07b.py", line 6, in minmax
unsignedmax = (2**n)-1
TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'list'
>>>
I wasn't done writing it but ran it to make sure there was no error in the logic part but i get that one error when trying to find the values. Is there maybe a way to insert int() or something similar to have the number be treated as type integer and not tyle list which im assuming is happening?
Change the method definition and first line to this:
def minmax (numbers) :
for n in numbers :
That is, in these two lines, replace 'n' with 'numbers' everywhere it appears and replace 'numbers' with 'n' where it appers.
As you have it written the variable "numbers" holds the item in the list you want to process and the variable "n" is holding the list. But the rest of your code is written with the reverse assumption.

Categories