Home > database >  How to find the amount of equal characters that are next to eachother in a string?
How to find the amount of equal characters that are next to eachother in a string?

Time:01-11

i just started using python and im a noob. this is an example of the string i have to work with "-- - ---------------- - " The program needs to find whats the longest "chain", so how many times does appear, when they are next to eachother. I dont really know how to explain this, but i need it to find that chain of 3 smybols, so i can print that the longest chain contains 3 symbols.

CodePudding user response:

a = "-- -   ---------------- - "


count = 0
most = 0
for x in range(len(a)):

    if a[x] == " ":
        count =1
    else:
        count = 0

    if count > most:
        most = count


print(f"longest   chain includes {most} symbols")

there might be a better way but it's more self explanatory

CodePudding user response:

Try this. It uses regular expressions and a list comprehension, so you may need to read about them.
But the idea is to find all the chains, calculate their lengths and get the maximum length

import re

s = '   ---------------- - '

occurs = re.findall('\  ',s)
print(max([len(i) for i in occurs]))

Output:

3

CodePudding user response:

You can use a regular expression to specify "one or more characters". The character for specifying this kind of repetition in a regex is itself , so to specify the actual character you have to escape it.

haystack = "-- -   ---------------- - "
needle = re.compile(r"\  ")

Now we can use findall to find all the occurrences of this pattern in the original string, and max to find the longest of these.

longest = max(len(x) for x in needle.findall(haystack))

If you instead need the position of the longest sequence in the target string, you can use:

pos =  haystack.index(max(needle.findall(haystack), key=len))

CodePudding user response:

A simple solution is to iterate over the string one character at a time. When the character is the same as the last add one to a counter and each time the character is different to the previous the count can be restarted.

s = "-- -   ---------------- - "

p = s[0]
max, count = 0
for c in s:
    if c == p:
        count = count   1
    else:
        count = 0
    if count > max:
        max = count
    p = c

s is the string, c is the character being checked, p is previous character, count is the counter, and max is the highest found value,

CodePudding user response:

If the only other character in your string is a minus sign, you can split the string on the minus sign and get maximum length of the resulting substrings:

a = "-- -   ---------------- - "

r = max(map(len,a.split('-')))
print(r) # 3
  •  Tags:  
  • Related