-2
def start_when(iterable,p):
    s = ''
    a = ''
    x = iter(iterable)
    for y in x:
        a = a + y
    try: 
        for y in x:
            if p(y) == True:
                s = s + a[a.index(y):]   
                break       
    except StopIteration:
        pass
    return s

The start_when generator takes an iterable and a predicate as parameters: it produces every value from the iterable, starting with the first value for which the predicate returns True

for example:

for i in start_when('combustible', lambda x : x >= 'q’):
    print(i,end='')

it prints

ustible

however, when my function takes input

('abcdefghijk', lambda x : x >='d')])

it should return

defghijk

But it returns nothing instead

below it the error I got:

21 *Error: ''.join([str(v) for v in start_when('abcdefghijk', lambda x : x >='d')]) ->  but should -> defghijk
22 *Error: ''.join([str(v) for v in start_when(hide('abcdefghijk'), lambda x : x >='d')]) ->  but should -> defghijk
23 *Error: ''.join([str(v) for v in start_when(hide('abcdefghijk'), lambda x : x >'f')]) ->  but should -> ghijk

can someone help me to fix my function? Many thanks!

zhangdi
  • 119
  • 1
  • 11
  • an iterable does not guarantee you that you will be able to iterate it more than once. also `x` being an `iter`, once you reach the end, you need a new one. – njzk2 Oct 27 '16 at 21:29
  • `a.index(y)` replace that with `enumerate` on your iterable. What happens when you call `'aaaa'.index('a')`? it returns 0, and never 1, 2, or 3. – njzk2 Oct 27 '16 at 21:31
  • why `''.join([str(v) for v`? you are already returning a string from your method – njzk2 Oct 27 '16 at 21:36

1 Answers1

0

Well your method is not at all a generator method. Following generator method will work for you perfectly:

def start_when(iterable,p):
    x=iter(iterable)
    for y in x:
        if p(y):
            yield y
            break
    for y in x:
        yield y

and call it like this:

for i in start_when('abcdefghijk', lambda x : x >='d'):
    print(i,end='')
Shasha99
  • 1,746
  • 2
  • 16
  • 30