-2

I have the number 444333113333 and I want to count every different digit in this number.

4 is 3 times

3 is 3 times

1 is 2 times

3 is 4 times

What I am trying to do is make a script that translates phone keypad taps to letters like in this photo https://www.dcode.fr/tools/phone-keypad/images/keypad.png if I press 3 times number 2, then the letter is 'C'

I want to make a script with it in python,but I cannot...

petezurich
  • 9,280
  • 9
  • 43
  • 57

3 Answers3

2

Using regex

import re
pattern = r"(\d)\1*"

text = '444333113333'

matcher = re.compile(pattern)
tokens = [match.group() for match in matcher.finditer(text)] #['444', '333', '11', '3333']

for token in tokens:
    print(token[0]+' is '+str(len(token))+' times')

Output

4 is 3 times
3 is 3 times
1 is 2 times
3 is 4 times
Nima
  • 323
  • 4
  • 13
0

You can use itertools.groupby

num = 444333113333
numstr = str(num)

import itertools


for c, cgroup in itertools.groupby(numstr):
    print(f"{c} count = {len(list(cgroup))}")

Output:

4 count = 3
3 count = 3
1 count = 2
3 count = 4
rdas
  • 20,604
  • 6
  • 33
  • 46
0

Will this do the trick? the function returns a 2d list with each number and the amount it found. Then you can cycle through the list and to get each all of the values

def count_digits(num):
    #making sure num is a string
    #adding an extra space so that the code below doesn't skip the last digit
    #there is a better way of doing it but I can't seem to figure out it on spot
    #essemtially it ignores the last set of char so I am just adding a space
    #which will be ignored
    num = str(num) + " "

    quantity = []

    prev_char = num[0]
    count = 0

    for i in num:

        if i != prev_char:

            quantity.append([prev_char,count])
            count = 1
            prev_char = i

        elif i.rfind(i) == ([len(num)-1]):
            quantity.append([prev_char,count])
            count = 1
            prev_char = i

        else:
            count = count + 1






    return quantity

num = 444333113333
quantity = count_digits(num)

for i in quantity:
    print(str(i[0]) + " is " + str(i[1]) + " times" )

Output:

4 is 3 times
3 is 3 times
1 is 2 times
3 is 4 times
Eugene Levinson
  • 172
  • 2
  • 13