[Python] Removing elements with particular substrings [duplicate]

Discussão em 'Python' iniciado por Stack, Dezembro 6, 2024.

  1. Stack

    Stack Membro Participativo

    I am trying to create a set of all bit strings of length n that do not contain consecutive zeros. While I could do this recursively, I wanted to create a non-recursive method as well.

    While there are several ways to do this, I decided to create a list of all the strings and then remove the ones with two consecutive zeros. I tried simply checking if '00' was contained in each bit string. If it was, then I would remove it. However, it missed a lot of the double zero cases.

    Below is another technique I tried, which eliminated more of them, but still missed some. I also tried checking through each string to see if num[k]==0 and num[k+1]==0 and, if so, remove it... but this did not work.

    Any suggestions would be appreciated.

    def bit_string(n):
    list = []
    if n == 0:
    return list
    else:
    list.append(0)
    list.append(1)
    i = 1
    while i < n:
    temp_list = []
    for num in list:
    num = str(num)
    temp_list.append(num+'1')
    temp_list.append(num+'0')
    list = temp_list
    i = i + 1
    for k in range(2,n+1):
    for num in list:
    if '0'*k in num:
    list.remove(num)
    list = set(list)
    return list

    print(bit_string(4))

    Continue reading...

Compartilhe esta Página