【问题标题】:repeated string problem in hackerrank using python?使用python在hackerrank中重复字符串问题?
【发布时间】:2023-03-05 16:18:01
【问题描述】:

我们想找到给定字符串 s 中的 'a' 的数量无限次相乘。 我们将得到一个数字 n,它是无限字符串的切片大小。 样本输入 阿坝 10

输出:- 7 这里 aba 乘以 10 得到 'abaabaabaa' 并且 a 的数量是 7 这是我的代码

def repeatedString(s, n):
    count = 0
    inters = s * n
    reals = s[0:n+1]
    for i in reals:
        if (i == 'a'):
            count += 1
    return count

我得到 2 而不是 7 作为输出(测试用例 'aba' 10)。我哪里做错了?我只是将给定的字符串乘以 n,因为它永远不会大于切片大小。

这里是问题的链接 https://www.hackerrank.com/challenges/repeated-string/problem

【问题讨论】:

    标签: python python-3.x string


    【解决方案1】:

    使用 python3 更简单的解决方案。

    s = input().strip()
    n = int(input())
    print(s[:n%len(s)].count('a')+(s.count('a')*(n//len(s))))
    

    【讨论】:

    • 既然那家伙提到他使用的是hacker-rank,那么在解决这个问题时最好还是坚持自己的算法。
    • 在 Hackerrank 中回答这个问题:- return(s[:n%len(s)].count('a')+(s.count('a')*(n//len (s))))
    • @MuhsinMuhammed 这正是我在评论中的意思。测试我的解决方案,我想你会发现它更容易执行。
    • @MuhsinMuhammed:您不会将字符串相乘(这会使计数永远耗时),而是将字符串的一个实例的计数乘以切片中字符串的完整实例数,然后在最后计算不完整的切片。
    • @voidpro 你能解释一下你是如何想出这个pythonic方法来解决这个问题的吗?我尝试了同样的问题,我想出了一个漂亮的算法解决方案,我自己作为海报。
    【解决方案2】:

    没有理由对字符串进行切片

    def repeatedString(s, n):
        count = 0
        for index, i in enumerate(s*n):
            if index >= n:
                return count
            if(i == 'a'):
                count += 1
    

    【讨论】:

    • @A.Abramov 你可以用count()方法替换循环
    • @MuhsinMuhammed 已修复。请你测试一下吗?
    • @komatiraju032 我很清楚,但是由于那个人提到他使用的是黑客等级,所以在解决这个问题时最好坚持自己的算法,所以他会遵循方法
    【解决方案3】:

    如果您想要更易读的答案....

    def repeatedString(s, n):
        target = 'a'
        target_count = 0
    
        # how many times does the string need to be repeated: (n // len(s) * s) + s[:(n % len(s))] 
        quotient = n // len(s)
        remainder = n % len(s)
    
        for char in s:  # how many times target appears in 1 instance of the substring
            if char == target:
                target_count += 1
            
        # how many times the target appears in many instances of the substring provided
        target_count = target_count * quotient
    
        for char in s[:remainder]:  # count the remaining targets in the truncated substring
            if char == target:
                target_count += 1
    
        return target_count
    

    【讨论】:

      【解决方案4】:

      因此,如果字符串包含“a”,则只需简单地返回 n。否则,计算字符串 s 中的 a 的数量,现在使用 divmond() 函数我找到了可以添加的字符串数量而不超过 n。例如字符串 s 是“aba”并且 n=10,所以我可以完全添加 3 个“abs”,而字符串的长度不会超过 10。现在添加的字符串中的 a 的数量(3 * 2)。现在剩下要填充的地方等于 divmond() 函数的余数(y)。现在将字符串 s 切成 y 并找到其中 a 的数量并将其添加到 count 中。

      divmond(10,3) 返回 (10//3) 并且是余数。

      def repeatedString(s, n):
          if len(s)==1 and s=="a":
              return n
          count=s.count("a") 
          x,y=divmod(n,len(s))
          count=count*x
          str=s[:y]
          return count+str.count("a")
      

      【讨论】:

      • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请edit您的答案以添加解释并说明适用的限制和假设。 From Review
      【解决方案5】:

      Python 3 中的解决方案:

      def repeatedString(s,n):
          i = 0
          c = 0
          for i in s:
              if i == 'a':
                  c += 1
      
          q = int(n / len(s)) #Finding the quotient 
          r = int(n % len(s)) #Finding the remainder
          if r == 0: 
              c *= q 
      
          else:
              x = 0
              for i in range(r):
                  if s[i] == 'a':
                      x += 1
              c = c*q + x
      
          return int(c)
      
      s = input()
      n = int(input())
      print(repeatedString(s,n))
      

      【讨论】:

        【解决方案6】:

        我使用了一种简单的单一方法。 一次重复中的“a”数为cnt_a,因此第一个n字符中的“a”数将为(cnt_a/len(s)) * n

        def repeatedString(s, n):
            if len(s)==1 and s=='a':
                return n
            cnt_a=0
            for i in s:
                if i == 'a':
                    cnt_a+=1
            if cnt_a % 2 == 0:
                no_a = (cnt_a/len(s)) * n
                return math.ceil(no_a)
            else:
                no_a = (cnt_a/len(s)) * n
                return math.floor(no_a)
        

        【讨论】:

          【解决方案7】:
          如果字符'a'出现在给定的字符串模式中,那么获得它的重复计数会更快,然后根据提到的最终字符串的总长度,将尝试重复给定模式相同的次数&因此将重复计数与字符串模式将重复的次数相乘。重要的是,如果最终的字符串输入是奇数,那么我们需要识别那些奇数模式并单独计算奇数字符串模式中字符“a”的出现次数。最后总结总计数(偶数和奇数)会给我们预期的结果
          def repeatedString(s, n):
              # Get the length of input string
              strlen = len(s)
              a_repeat = 0
              # Get the total count of a repeated character from the input string
              for i in range(0,strlen):
                  if s[i] == 'a':
                      a_repeat = a_repeat + 1
              # Get the multiplier to make sure that desired input string length achieved
              str_multiplier = int(n // strlen) 
              # Get the repeated count if new string is been created
              result = a_repeat*str_multiplier
              new_str = s[:int( n % strlen )]
              # for odd length of string, get the remaining characters and find repated characters count and add up it to final count
              for i in range(0, len(new_str)):
                  if new_str[i] == 'a':
                      result += 1
              return result
          

          【讨论】:

          • 虽然此代码可以解决问题,including an explanation 说明如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提出问题的人。请edit您的回答添加解释并说明适用的限制和假设。
          • 添加描述以供参考@PanagiotisSimakis
          【解决方案8】:

          一个班轮答案:

          return [s[i%len(s)] for i in range(n)].count('a')
          

          【讨论】:

            【解决方案9】:

            你的代码只有两个问题

            s = 'aba'
            n = 10
                
            count = 0
            inters = s * n
            
            # Here you need to slice(inters) not (s) because s only hold 'aba'
            # And not n+1 it's take 11 values only n
            reals = inters[0:n]
              for i in reals:
                if (i == 'a'):
                  count += 1
                
            print(count)
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2020-10-12
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-17
              • 1970-01-01
              • 2014-04-12
              相关资源
              最近更新 更多