substitute hash with numbers in list python

Viewed 121

I have the following list:

l = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']

The first hash I want to substitute to 1. if there are two hashes I want to get 1.1 for the first double hash in the sequence and 1.2. for the second hash. The next single hash I would like to have 2. and so on so forth with this logic.

The result should be like that:

1. Cars
1.1 duo
1.2 go
2. hello 
2.2 there
3 Answers

Try this:

a = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']

def hash(a):
    res = []
    major = 0
    minor = 0
    for s in a:
        if "#" in s:
            if "##" in s:
                minor += 1
                s = s.replace("##", "%d.%d " % (major, minor))
            else:
                major += 1
                minor = 0
                s = s.replace("#", "%d " % major)
        res.append(s)
    return res

hash(a)
['1 Cars', 'Cars came into global', '1.1 duo', '1.2 go', '2 hello', '2.1 there']

If you don't want to keep items without a hash, and only want to print, then this:

def hash(a):
    major = 0
    minor = 0
    for s in a:
        if "#" in s:
            if "##" in s:
                minor += 1
                s = s.replace("##", "%d.%d " % (major, minor))
            else:
                major += 1
                minor = 0
                s = s.replace("#", "%d " % major)
            print(s)

hash(a)
1 Cars
1.1 duo
1.2 go
2 hello
2.1 there

A more general method:

def hash(a):
    v = []
    for s in a:
        
        i = 0
        while s[i] == "#":
            i += 1
        
        if i > 0:
            if len(v) < i:
                v += [0] * (i - len(v))
            else:
                for j in range(i, len(v)):
                    v[j] = 0
            
            v[i - 1] += 1
            
            s = "%s %s" % (".".join(str(j) for j in v[:i]), s[i:])
            print(s)

a = ["#a", "##b", "###c", "###d",  "#e", "##f", "###g", "##h", "###i", "####j", "#k"]
hash(a)
1 a
1.1 b
1.1.1 c
1.1.2 d
2 e
2.1 f
2.1.1 g
2.2 h
2.2.1 i
2.2.1.1 j
3 k

A shorter recursive solution:

from collections import defaultdict
l = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']
def to_hash(d, p = []):
   r, c, l = defaultdict(list), 0, None
   for a, *b in d:
      if a != '#' and p:
          yield f'{".".join(map(str, p))} {"".join([a, *b])}'
      elif a == '#':
          r[l:=((c:=c+1) if b[0] != '#' else c)].append(''.join(b))
   yield from [j for a, b in r.items() for j in to_hash(b, p+[a])]

print('\n'.join(to_hash(l)))

Output:

1 Cars
1.1 duo
1.2 go
2 hello
2.1 there

You can keep a track on the top-level number and the sub-level number, like this also:-

lst = ['#Cars', 'Cars came into global', '##duo', '##go','#hello','##there']

top, nxt = 0, 0

for i in range(len(lst)):
    s = lst[i]
    if s[:2] == "##":
        nxt += 1
        lst[i] = s.replace("##", f"{top}.{nxt} ")
    elif "#" in s[:2]:
        top += 1
        nxt = 0
        lst[i] = s.replace("#", f"{top}. ")

for i in lst:
    print(i)

What happens here is that, the loop takes each string and checks if the string starts with "##" if it starts with that it increases the sub-level number and replaces the "##" with the format top.nxt, if the string starts with a single hash, "#", then it increments the top number, sets the sub-level number to 0 and replaces the "#" with the top number.

Related