Tuesday, October 30, 2018

Q5: Replace consecutive occurrences of the character from given input string

Question 5: Replace consecutive occurrences of the character from given input string.
You are given a string S. If a character 'c' occurs consecutively N times in the string. Replace these consecutive occurrences of the character 'c' with (N,c) in the string.

Eg:
Input: "1222311"
Output: "(1, 1) (3, 2) (1, 3) (2, 1)"

Here, character 1 occurs only once. It is replaced by (1,1). Then the character 2 occurs 3 times, and it is replaced by (3,2) and so on.

5 comments:

  1. input_str = list(input("Enter the string: "))
    output = list()
    count = 0
    for p, i in enumerate(input_str):
    next_val = '' if p == (len(input_str)-1) else input_str[p+1]
    if next_val:
    if i == next_val:
    count += 1
    else:
    output.append((count+1, i))
    count = 0
    else:
    output.append((count + 1, i))
    print(output)

    ReplyDelete
  2. input_str = "112bbc23"

    new_list = list()
    output = list()
    for i in input_str:
    if len(new_list) == 0 or i in new_list:
    new_list.append(i)
    else:
    output.append((len(new_list), new_list[0]))
    new_list = [i]
    output.append((len(new_list), new_list[0]))
    print(output)

    ReplyDelete
  3. Hi Ravi,

    Stolen ur logic, but improvised a little.

    input_str = "113abc31122ddddd"
    output = [[]]
    for i in input_str:
    idx = len(output)
    if len(output[idx-1]) == 0 or i in output[idx-1]:
    output[idx - 1].append(i)
    continue
    output.append(list(i))
    print([(len(l), l[0]) for l in output])


    Output: [(2, '1'), (1, '3'), (1, 'a'), (1, 'b'), (1, 'c'), (1, '3'), (2, '1'), (2, '2'), (5, 'd')]

    ReplyDelete