input = 'XXYXYYYXYXXYYY'
output = [2,1,1,3,1,1,2,3]
How would count the number of X's and Y's in a string in the order that they are inputted and then put those values in a list?
input = 'XXYXYYYXYXXYYY'
output = [2,1,1,3,1,1,2,3]
How would count the number of X's and Y's in a string in the order that they are inputted and then put those values in a list?
import itertools
numbers = []
input = 'XXYXYYYXYXXYYY'
split_string = [''.join(g) for k, g in itertools.groupby(input)]
for i in split_string:
numbers.append(len(i))
print(numbers)
Output:
[2, 1, 1, 3, 1, 1, 2, 3]
You could do this using a while
loop by iterating the whole list.
str = 'XXYXYYYXYXXYYY';
i = 0
output = []
k = 1
while i < len(str) - 1:
if str[i] == str[i+1]:
k = k + 1
else:
output.append(k)
k = 1
i = i + 1
output.append(k)
print(output)
Output
[2, 1, 1, 3, 1, 1, 2, 3]
Try using itertools.groupby
:
from itertools import groupby
s = 'XXYXYYYXYXXYYY'
print([len(list(i)) for _, i in groupby(s)])
Short solution using regex
import re
s = 'XXYXYYYXYXXYYY'
l = [len(m.group()) for m in re.finditer(r'(.)\1*', s)]
Based on this answer
Here's what you can try
test = 'XXYXYYYXYXXYYY'
count = 1
result_list = list()
prev_char = test[0]
for char in test[1:]:
if char == prev_char:
count+=1
prev_char = char
else:
result_list.append(count)
count=1
prev_char = char
result_list.append(count)
print(result_list)
Output
[2, 1, 1, 3, 1, 1, 2, 3]
Without any libs it will be like this:
string = 'XXYXYYYXYXXYYY'
res = []
current = ''
for char in string:
if current == char:
res[-1] += 1
else:
res.append(1)
current = char
print('res', res) # [2,1,1,3,1,1,2,3]
Try This.
input1 = 'XXYXYYYXYXXYYY'
output_list = []
count = 1
for index in range(len(input1)-1):
if input1[index] == input1[index+1]:
count += 1
else:
output_list.append(count)
count = 1
if input1[-1] == input1[-2]:
output_list[-1] += 1
else:
output_list.append(1)
print(output_list)
The basic approach is to occurrences and stop if new char come. Code is below.
list_of_consec = []
def consec_occur(strr):
i = 0
cc = []
while ( i < len(strr) -1 ):
count =1
while strr[i] == strr[i+1]:
i += 1
count += 1
if i + 1 == len(strr):
break
cc.append(count)
i += 1
return (cc)
if __name__ == "__main__":
print(consec_occur('XXYXYYYXYXXYYY'))
You can change the code according to your need. If you want list then make cc global and remove return statement and in print statement use cc.