Home > Software engineering >  How to call a function on list to return incremental bits range
How to call a function on list to return incremental bits range

Time:06-03

I am trying to write a function that returns from and to bits in [from:to] format. I am not quite sure how exactly it can be done (recursively?). The expected output is in incremental range of bits. Here is the piece of code to start with,

cntlist = [5,1,4,3,1]
def find_size(cnt):
    if cnt>1:
        a = "[%s:%s]" % (cnt-1, cnt-cnt)
        left = cnt-1
        right = cnt-cnt
    if cnt==1:
        a = "[%s]" % (cnt)
        left = a
        right = a
    return a, left, right

newlist = list(map(find_size, cntlist))
print(newlist)

Output:

[('[4:0]', 4, 0), ('[1]', '[1]', '[1]'), ('[3:0]', 3, 0), ('[2:0]', 2, 0), ('[1]', '[1]', '[1]')]

Expected output:

['[4:0]', '[5]', '[9:6]', '[12:10]', '[13]']

Note: If size is 1 in cntlist, the range will have only one element which will be 1 to previous range's left number.

CodePudding user response:

IIUC, a simple loop should work:

def bitrange(cntlst):
    out = []
    total = 0
    for i in cntlst:
        prev = total
        total  = i
        if i == 1:
            out.append(f'[{total-1}]')
        else:
            out.append(f'[{total-1}:{prev}]')
    return out

bitrange([5,1,4,3,1])

output:

['[4:0]', '[5]', '[9:6]', '[12:10]', '[13]']
  • Related