How to count consecutive characters? - python-3.x

Need to find the count of each consecutive character in a row.
Ex: aaaabbBBccaa
output: a4b2B2c2a2
The character may repeat but need to count only consecutive ones. I also need to maintain the original sequence.
I tried to do this by code below but it doesn't work.
l = input()
counter = dict()
if l.isalpha() == True:
for letter in l:
if letter in counter:
counter[letter] += 1
else:
counter[letter] = 1
for this_one in list(counter.keys()):
print(this_one,counter[this_one],sep ="",end="")

Solution if you are interested in the while loop mechanics :
l = 'aaaabbBBccaazzZZZzzzertTTyyzaaaAA'
output = ''
index = 0
while index < len(l):
incr = index
count = 1
output += l[incr]
while incr < len(l)-1 and l[incr]==l[incr+1]:
count += 1
incr += 1
index += 1
output += str(count)
index += 1
print(output)

itertools.groupby allows you to express this quite concisely using a generator expression.
from itertools import groupby
''.join(f'{x}{len(list(y))}' for x, y in groupby('aaaabbBBccaa'))
# outputs:
'a4b2B2c2a2'

Related

how to count how many element changed its position in a list after sorting?

I want to print the count of numbers that have changed their position.
My code:
def mysort(arr):
count = 0
for i in range(len(arr)):
min_value = i
for j in range(i, len(arr)):
if arr[j] < arr[min_value]:
min_value = j
count += 1
temp = arr[i]
arr[i] = arr[min_value]
arr[min_value] = temp
return count
my_list = [4,2,3,1,6,5]
print(mysort(my_list))
My code is returning 3 as output but it should return 4. How can I fix it?
To count the number of elements with positions changed, why not try:
def count_change(old, new):
# assume old and new have the same length
count = 0
for x,y in zip(old, new):
if x != y:
count += 1
return count
Your code actually counts the number of value swap

counting number of pairs with same elem value in python list

I don't understand why the function is returning 4 while it should return 3. Thank you very much.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += w/2
print(int(count))
From your description of what you said, of wanting to count pairs, then I believe you would want to round down the number being added to count instead of count overall, as 2 halves would end up making 1.
The following does return 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(count)
In Python, a single slash ”/“ does a regular divide that returns with decimals. A double slash “//“ returns a whole number rounded down. When you call int() on the number, it rounds it down to nearest whole number.
In your code, you get:
2+1.5+0.5+0.5=4.5
After calling int on 4.5, it becomes 4.
You are adding floats in the for loop, just change that to ints and it will add up to 3.
x = [10,20,20,10,10,30,50,10,20]
s = {}
count = 0
for item in x:
if (item in s):
s[item] += 1
else:
s[item] = 1
for z, w in s.items():
count += int(w/2)
print(int(count))

Want to print consecutive 1's in

from array import *
n=int(input("Enter the number"))
m=bin(n)
#print(m)
a=array("u",[])
a=int(m[2:])
print(a)
count=0
for i in range(a):
if(a[i]=="1" and a[i+1]=="1"):
count=count+1
print(count)
Here i want to print'ONLY' the number of consecutive 1's that appear in a binary number.
If your logic is correct try this,
n = int(input('Enter a number : '))
nb =bin(n)
l = list(nb)[2:]
count = 0
for i in range(len(l)-1):
if l[i]=='1' and l[i+1]=='1':
count += 1
print(count)

Change specific elements of a matrix puzzle - Python

I have to solve how to replace the elements below zero elements with zeros and output the sum of the remaining elements in the matrix.
For example, [[0,3,5],[3,4,0],[1,2,3]] should output the sum of 3 + 5 + 4 + 1 + 2, which is 15.
So far:
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for i,j in enumerate(matrix):
for k,l in enumerate(j):
if l == 0:
break
out += l
return out
The code outputs seemingly random numbers.
Can someone fix what's wrong? Thanks
You can easily drop elements that are below a zero element is by using the zip function.
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for i,j in enumerate(matrix):
# elements in the first row cannot be below a '0'
if i == 0:
out += sum(j)
else:
k = matrix[i-1]
for x, y in zip(j, k):
if y != 0:
out += x
return out
Now consider naming your variables a little more meaningfully. Something like:
def matrixElementsSum(matrix):
out = 0
# locate the zeros' positions in array & replace element below
for row_number, row in enumerate(matrix):
# elements in the first row cannot be below a '0'
if row_number == 0:
out += sum(row)
else:
row_above = matrix[row_number - 1]
for element, element_above in zip(row, row_above):
if element_above != 0:
out += element
return out
You should look into list comprehensions to make the code even more readable.

Counting substrings in string

Lets assume that i have 2 strings
M = "sses"
N = "assesses"
I have to count how many times string M is present into string N
I am not allowed to use any import or methods just loops and range() if needed.
M = "sses"
N = "assesses"
counter = 0
if M in N:
counter +=1
print(counter)
This isn't good enough i need loop to go trough N and count all M present
in this case it is 2.
def count(M, N):
i = 0
count = 0
while True:
try:
i = N.index(M, i)+1
count += 1
except ValueError:
break
return count
Or a one-liner without str.index:
def count(M, N):
return sum(N[i:i+len(M)]==M for i in range(len(N)-len(M)+1))
The same without using the sum function:
def count(M, N):
count = 0
for i in range(len(N)-len(M)+1):
if N[i:i+len(M)] == M:
count += 1
return count

Resources