-1

I have to access a file and count the number of atoms of each element. That is, count the number of times of the last character.

For example, I have a file named 14ly.pdb with the following lines:

ATOM 211 N TYR A 27 4.697 8.290 -3.031 1.00 13.35 N

ATOM 212 CA TYR A 27 5.025 8.033 -1.616 0.51 11.29 C

ATOM 214 C TYR A 27 4.189 8.932 -0.730 1.00 10.87 C 

ATOM 215 O TYR A 27 3.774 10.030 -1.101 1.00 12.90 O

I should get as a result: 'N':1, 'C':2, 'O':1, that is, 1 atom of type N, 2 of type C and 1 of type O.

I have the following incomplete code that I need to complete:

import os

def count_atoms(pdb_file_name):
  num_atoms = dict()
  with open(pdb_file_name) as file_content:

##Here should go the code I need## 

return num_atoms
result = count_atoms('14ly.pdb')
print(result)
Nic3500
  • 8,144
  • 10
  • 29
  • 40
Angy Mara
  • 1
  • 1
  • SO is not a free coding service. You got lucky on this one. You should demonstrate some attempt at research or algorithm to do it. – Nic3500 Nov 02 '21 at 03:30

1 Answers1

0
number_of_atoms = dict()
with open("14ly.pdb", "r") as f:
    for line in f:
        line_words = line.split(" ")
        last_char = line_words[-1].rstrip('\n')
        if last_char in number_of_atoms.keys():
            number_of_atoms[last_char] += 1
        else:
            number_of_atoms[last_char] = 1
print(number_of_atoms)

I think this should be enough

alesta
  • 41
  • 4
  • 2
    Please consider including a brief explanation of [how and why this solves the problem](https://meta.stackoverflow.com/q/392712/13138364). This will help future readers to better understand your solution. – tdy Oct 30 '21 at 07:30