Get multiple characters of a string by index

Viewed 1973

I need to punch() out specific characters out of a string based on an index template (mask?).

For example, I need to punch out all the characters where there is a 1

str = abcdefg
mask = 0011001

// len(str) = len(mask) always

print(punch(str, mask)) //Ouput: cdg 

Essentially I need to print all the non empty subsequences of a given string:

Input: abcd
Output: a, b, c, d, ab, ac, ad, bc, bd, cd, abc, abd, acd, bcd, abcd

I am trying to implement this using brute force so I would generate all the templates for the length of input string and using the punch() to "punch" out those subsequences.

PS: This may be a bad way to solve this prob, but I think punch() a nifty method to have.

2 Answers

You could potentially use ‘compress()’ from Itertools to create a binary filter.

Compress takes two arguments

  1. The iterable that you want to go over and ‘punch’ out characters

  2. The data which defines which elements from the first iterable are removed. Any ‘True’ element will enable compress to remove the element from the first iterable

    Screenshot from the Itertools Docs

If I'm reading what you want to do correctly, a function like this could work.

def punch(str, mask):
   if (len(str) == len(mask)):
       new_list = []
       for i in range(len(str)):
           if mask[i] == "1":
             new_list.append(str[i])
       return new_list
   else:
       return -1
Related