Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

occurrence of specific character in multiple strings

The multiple strings that needed to be searched are stored in a file values.txt (the Input File) which for example contains information as follows:

XXVVXXVVVVVXXVXVV
VXVXVXXXXXVVVVXXX
VVVVXXVVVXVVXXXXX
XVXXXVVVXXVXXVXVX
VXXVVXVXXVVVXXVVX
XVXVXXXXXXXXVVVVV
VVVXXVVXVXVVXXVVX
XVXXVXXXVVXXXVXXX
VVVVXXXXXXVXVXXXX
VXVVXVVXVVXVVVVXV
VVXVXVXXVVXXVVXVV
VVXVVXXVVXXXVVVXV
XVXVVVVXVXVVVVVVV
VXXVVXVXVXVVXXXVX
XVVVVXVXVXXXXVVVX
VXXVVVVXXVXVXVVVX

I’m trying to count the occurrence of V in every line for index[x], x being the position of a character in every line.

For example, there are 10 "V" in every first character of the lines. 10 "V" in the second character of the lines and 7 "V" in the third character of the lines.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have already tried enlisting the lines en counting the amount of "V" in every line, but i’m not getting anyware. Any suggestions?

expected answer: [10, 10, 7, 12, 8, 6, 10, 4, 10, 6, 9, 8, 7, 11, 8, 10, 6]

>Solution :

I would use a list comprehension with zip and a Counter:

from collections import Counter

out = [Counter(col)['V'] for col in zip(*text.split('\n'))]

Alternative without import:

out = [len([c for c in col if c == 'V']) for col in zip(*text.split('\n'))]

output: [10, 10, 7, 12, 8, 6, 10, 4, 10, 6, 9, 8, 7, 11, 8, 10, 6]

used input:

text = '''XXVVXXVVVVVXXVXVV
VXVXVXXXXXVVVVXXX
VVVVXXVVVXVVXXXXX
XVXXXVVVXXVXXVXVX
VXXVVXVXXVVVXXVVX
XVXVXXXXXXXXVVVVV
VVVXXVVXVXVVXXVVX
XVXXVXXXVVXXXVXXX
VVVVXXXXXXVXVXXXX
VXVVXVVXVVXVVVVXV
VVXVXVXXVVXXVVXVV
VVXVVXXVVXXXVVVXV
XVXVVVVXVXVVVVVVV
VXXVVXVXVXVVXXXVX
XVVVVXVXVXXXXVVVX
VXXVVVVXXVXVXVVVX'''
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading