Determine the length of the longest chain consisting only of symbols A, B and C



  • There's a file in which the letters A...Z are recorded. Determine the length of the longest chain consisting only of symbols A, B and C. My problem is, the code is only looking for the length of the chain consisting of the same letters. How can you fix the code?

    file = open("2.txt").read().strip()
    count = 1
    max_count = 1
    symbols = ""
    for i in range(len(file)-1):
        if file[i] == file[i+1]:
            count += 1
        else:
             count = 1
        if count > max_count:
             max_count = count
             symbols = file[i]
    print(symbols,max_count)
    


  • Option 1 (decision in the forehead):

    text = "XABXCABBBCAADBXXBAADX"
    

    max_size = 0
    size = 0
    for letter in text:
    if letter in 'ABC':
    size += 1
    else:
    if max_size < size:
    max_size = size

        size = 0
    

    if max_size < size:
    max_size = size

    print(max_size)

    Option 2 (corrected):

    size, max_size = 0, 0

    for letter in text:
    size, max_size = (size + 1, max_size) if letter in 'ABC' else (0, size if max_size < size else max_size)

    max_size = size if max_size < size else max_size

    Option 3 (single):

    It's really a little bit of a mess, and it works slower than the last one:

    res = max(map(len, ''.join(letter if letter in 'ABC' else ' ' for letter in text)).split())

    Option 3.1 (a little shorter):

    res = max(map(len, ''.join((' ', letter)[letter in 'ABC'] for letter in text).split()))



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2