0

I have some data in a form of:

  segs = [ '0000','0001','0002','0010','0011','0012','0100',..... '2222']

I know some of digits, for example '1...' or '..21' or '.1.0', etc., where dot represents unknown digit to fill. How to write a function F(segs, digit1, digit2, digit3, digit4) which can return all matching strings for given digits? If any digit is unknown, I can put empty string (or dot) instead, so:

F(segs,'','','','')    should return full list
F(segs,1,0,0,2)        should return one-element list only
F(segs,1,2,2,'')       should return only ['1220','1221','1222']

Strings collected in segs represents some shapes and their orientations and I'd like to have rather a fast function, because it will be used in a game. This function will be invoked often, but no more than few times in a second.

piotao
  • 267
  • 3
  • 12

1 Answers1

3

It can be done without regular expressions which may be faster. It will also work for any number of arguments but checks only up to the number of arguments or length of checked string, whichever is shortest (modify the zip part if you want to change it):

def f(segs, *pattern):
    for seg in segs:
        if all(str(p) == s or p == '' for s, p in zip(seg, pattern)):
            yield seg
Szymon
  • 42,577
  • 16
  • 96
  • 114
  • Hey, thanks! It seems to be very magick to me, but I started to learn more about yield (http://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do-in-python#231855) and zip (http://stackoverflow.com/questions/31872135/how-can-i-use-zip-python), so they are now easier to understand. However not all is still clear to me. How does it look like after joining the seg list and pattern list? Do I get internally a matrix, where in first column is just the whole seg vertically? Or do I get each sequence from seg and for each element I get the whole pattern like in double foreach loop? – piotao Nov 30 '15 at 12:33
  • Zip creates an iterator, joining together 2 iterables (seg and pattern in this case). Each element of this returned iterator is a tuple. This is why you can loop over them with `for` and in the code above the tuple is unpacked into 2 variables. – Szymon Nov 30 '15 at 14:47
  • OK, I've tested that function and it seems to work, with a loop: `a=F(segs,'0','1','','')` then `for i in a:` and `print i`. But I was unable to store plain list in a variable using `a=F(...)`. It seems to store only generator function which I should convert somehow to a plain list. How to do that? – piotao Nov 30 '15 at 16:56
  • Should I really build the whole list using `for` construct, not an assignment of any kind? – piotao Dec 01 '15 at 23:28
  • The function above is a generator. You can modify it to append to a list if you want. – Szymon Dec 01 '15 at 23:58
  • Very nice, thank you. BUT HOW TO MODIFY IT to make it work like: – piotao Dec 10 '15 at 12:31