Search code examples
pythonfunctionfor-loopreturnjupyter-notebook

Python divide each string by the total lenght of string


Thank you for your help and patience.

I am new to python and am attempting to calculate the number of times a particular atomic symbol appears divided by the total number of atoms. So that the function accepts a list of strings as argument and returns a list containing the fraction of 'C', 'H', 'O' and 'N'. But I keep on getting one result instead of getting all for each of my atoms. My attempt is below:

Atoms = ['N', 'C', 'C', 'O', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'O', 'H']

def count_atoms (atoms):
    for a in atoms:
        total = atoms.count(a)/len(atoms)
        return total

Then

faa = count_atoms(atoms)
print(faa)

However I only get one result which is 0.07692307692307693. I was supposed to get a list starting with [0.23076923076923078,..etc], but I don't know how to. I was supposed to calculate the fraction of 'C', 'H', 'O' and 'N' atomic symbols in the molecule using a for loop and a return statement. :( Please help, it will be appreciated.


Solution

  • Well you return the variable total at your first loop. Why don't you use a list to store your values? Like this:

    atoms = ['N', 'C', 'C', 'O', 'H', 'H', 'C', 'H', 'H', 'H', 'H', 'O', 'H'] #python is case sensitive!
    
    def count_atoms (atoms):
        return_list = [] #empty list
        for a in atoms:
            total = atoms.count(a)/len(atoms)
            return_list.append(total) #we add a new item
        return return_list #we return everything and leave the function