How to count the number of dashes between any two alphabetical characters?

Viewed 2474

If we have a string of alphabetical characters and some dashes, and we want to count the number of dashes between any two alphabetic characters in this string. what is the easiest way to do this?

Example:

Input: a--bc---d-k

output: 2031

This means that there are 2 dashes between a and b, 0 dash between b and c, 3 dashes between c and d and 1 dash between d and k

what is a good way to find this output list in python?

4 Answers

You can use a very simple solution like this:

import re

s = 'a--bc---d-k'
# Create a list of dash strings.
dashes = re.split('[a-z]', s)[1:-1]
# Measure the length of each dash string in the list and join as a string.
results = ''.join([str(len(i)) for i in dashes])

Output:

'2031'

Solution with regex:

import re

x = 'a--bc---d-k'

results = [
    len(m) for m in
    re.findall('(?<=[a-z])-*(?=[a-z])', x)
]
print(results)
print(''.join(str(r) for r in results))

output:

[2, 0, 3, 1]
2031

Solution with brute force loop logic:

x = 'a--bc---d-k'

count = 0
results = []
for c in x:
    if c == '-':
        count += 1
    else:
        results.append(count)
        count = 0
results = results[1:]  # cut off first length
print(results)

output:

[2, 0, 3, 1]

If you input may also begin with a dash, you could use this:

def count_dashes(string):
    all_counts = []
    dash_count = 0
    for char in string:
        if char == "-":
            dash_count += 1
        else:
            all_counts.append(dash_count)
            dash_count = 0
    return all_counts

But if your input always starts with a letter, you may not like the 0 that's always at the head of the list.

If you need the output as a string of ints, then you could add this:

def count_dashes(string):
    all_counts = []
    dash_count = 0
    for char in string:
        if char == "-":
            dash_count += 1
        else:
            all_counts.append(dash_count)
            dash_count = 0
    return "".join([str(number) for number in all_counts])

Here's a simple loop approach:

myinput = 'a--bc---d-k'
output = []
output_count = -1
for elem in myinput:
  if elem == '-':
    output[output_count] = output[output_count]+1
  else:
    output.append(0)
    output_count += 1

print(output)
Related