【问题标题】:check if a string has characters of same frequency with or without the removal of 1 character检查字符串是否具有相同频率的字符,删除或不删除 1 个字符
【发布时间】:2021-09-03 20:18:59
【问题描述】:

我正在尝试编写代码来检查给定字符串是否满足以下条件:

  1. 出现频率相同的所有字符
  2. 如果需要,可以删除一个字符以实现上述条件

以下代码适用于某些测试用例,但不适用于其他用例,您能帮帮我吗?

d=0
r=0
def isValid(s):
    # Write your code here
    c =Counter(s) #count no occurences of chars in string
    q=0
    v=c.values() 
    val=list(v)  # convert it to list 
    res=Counter(val)  #count no of equal occurences
    d=res.values() 
    dat=list(d) 
    
    if len(dat)==1:
        r='YES'
        return(r)
    elif len(dat)>1:
        q=dat[1]-1
             
    if q==0:
        r='YES'
        return(r)
    else:
        r='NO'
        return(r)   ```

【问题讨论】:

    标签: python string counter


    【解决方案1】:

    试试这个 -

    from collections import Counter
    
    s = 'AABBCCDD' # Just a EXAMPLE
    
    def check(x):
        z = []
        for y in s:
            z.append(y)
    
        a = Counter(z)
        b = dict(a)
        c = list(b.values())
        check_list = []
        for ele in c:
            if ele % 2 != 0:
                check_list.append(ele)
        
        if len(check_list) > 1:
            return False
    
    def isValid(s):
        a = Counter(s)
        b = dict(a)
        c = list(b.values())
        y = []
        for x in c:
            y.append(x)
            if x != y[0]:
                if check(x) == False:
                    print('Not Valid')
                    return
                
            
        print('Valid')
     
    isValid(s) # Calling the function
    

    【讨论】:

    • 我写了一个额外的函数,让它看起来更简单!
    猜你喜欢
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 2021-02-14
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多