【问题标题】:a given number should not appear more than 5 times in a row给定数字不应连续出现超过 5 次
【发布时间】:2022-09-27 13:16:40
【问题描述】:

以下是问题:

接受电话号码作为输入。一个有效的电话号码应该满足 以下约束。

(1) 数字应以下列数字之一开头:6、7、8、9

(2) 号码的长度应恰好为 10 位数字。

(3) 数字中出现的数字不得超过 7 次。

(4) 数字中连续出现的数字不得超过 5 次。

如果第四个条件不是很清楚,那么考虑这个例子: 数字 9888888765 无效,因为数字 8 出现的次数超过 连续5次。

如果电话号码有效,则打印字符串 valid。如果没有,请打印 字符串无效。

这是我现在的实现:

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\')

但是,我在执行条件 4 时遇到了麻烦。有人可以帮我解决这个问题吗?

  • 这回答了你的问题了吗? Count consecutive characters
  • 为什么要做Counter([a for a in num])?为什么不只是Counter(num)

标签: python


【解决方案1】:

您可以使用

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))

哪个输出

8 occurs more than 5 times
9888888765 False
9885888765 True

该函数从0到9获取i,然后创建字符串str(i) * 6,如果i == 0,则为000000,如果i == 1,则为111111等。然后,我们可以使用字符串成员与@ 987654329@ 检查str(i) * 6 是否是num 的子串。如果连续出现任何相同数字的 6 序列,则该函数返回 False,否则返回 True

【讨论】:

    【解决方案2】:
    x = int(input())
    y = str(x)
    seven_list = list()
    
    for char in y :
    #("10 numbes , strsa with valid and do no have 7 time repeat")
        if(y.count(char) > 7) :
            seven_list.append(char)
    
    
    def cond_4(num):
        for i in range(10):
            if str(i) * 6 in str(num):
                #print(i, "occurs more than 5 times")
                return False
        return True
    
    
    if (len(y)==10):
    
        if (y[0]== "6" or y[0]== "7" or y[0]== "8" or y[0] == "9"):
        
            if (len(seven_list)==0):
            
                if ( cond_4(x) == True ):
                
                    print("valid")
            
                else:
                    print("invalid")
            
            else:
                print("invalid")
        
        else:
            print("invalid")   
    else:
        print("invalid")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多