-2

Following is the question:

Accept a phone number as input. A valid phone number should satisfy the following constraints.

(1) The number should start with one of these digits: 6, 7, 8, 9

(2) The number should be exactly 10 digits long.

(3) No digit should appear more than 7 times in the number.

(4) No digit should appear more than 5 times in a row in the number.

If the fourth condition is not very clear, then consider this example: the number 9888888765 is invalid because the digit 8 appears more than 5 times in a row.

Print the string valid if the phone number is valid. If not, print the string invalid.

And here is my implementation as of now:

from collections import Counter

num=input()

temp=Counter([a for a in num])

allowed=['6','7','8','9']

def consec(s):
   i=0
   while i<len(s)-1:
       count=1
       
       while s[i]==s[i+1]:
           i+=1
           count+=1
           
           if i+1==len(s):
               return int(count)

if len(num)==10:
    if num[0] in temp:
        if max(temp.values())<=7:
            for i in range(len(num)):
                temp1=consec(num[i])
                if(temp1<=5):
                    continue
                else:
                    print('Invalid')
            print('Success')
        else:
            print('Invalid')
    else:
        print('Invalid')
else:
    print('Invalid')

However, I've had trouble implementing condition number 4. Could anyone help me out with this?

khelwood
  • 52,115
  • 13
  • 74
  • 94

1 Answers1

1

You may use

def cond_4(num):
    for i in range(10):
        if str(i) * 6 in num:
            print(i, "occurs more than 5 times")
            return False
    return True

num = "9888888765"
print(num, cond_4(num))
num = "9885888765"
print(num, cond_4(num))

Which outputs

8 occurs more than 5 times
9888888765 False
9885888765 True

The function takes i from 0 through 9, and then creates the string str(i) * 6, which is 000000 if i == 0, and 111111 if i == 1, etc. Then, we can use string membership with in to check whether str(i) * 6 is a substring of num. The function then returns False if any sequence of 6 of the same number occurs in a row, and True otherwise.

Tom Aarsen
  • 915
  • 1
  • 19