zhangdi zhangdi - 1 month ago 9
Python Question

function takes iterabls and return a list

def group_when(iterable,p):
x = iter(iterable)
z = []
d = []
try:
while True:
y = next(x)
if p(y) == False:
z.append(y)
elif p(y) == True:
z.append(y)
d.append(z)
z = []
except StopIteration:
pass
return


The group_when generator takes one iterable and one predicate as parameters: it produces lists that each end in a value from the iterable where the predicate is True. If the iterable ends on a value for which the predicate returns False, yield a final list containing all the values from the one after the previous end to the last value produced by the iterable

for example:

for i in group_when('combustibles', lambda x : x in 'aeiou'):
print(i,end='')


prints the 5 lists ['c', 'o']['m', 'b', 'u']['s', 't', 'i']['b', 'l', 'e']['s'].

my function is getting so close to the correct answer. when the input is

('combustibles', lambda x : x in 'aeiou')


my function returns

[['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']]


but the correct output should be:

[['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]


Therefore, I am only missing the last letter 's'.
can anyone tell me how to fix it? many thanks

I posted the error I got below just to help you to understand my function:

26 *Error: Failed [v for v in group_when('combustibles', lambda x : x in 'aeiou')] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
evaluated: [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
27 *Error: Failed [v for v in group_when(hide('combustibles'), lambda x : x in 'aeiou')] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]
evaluated: [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e']] == [['c', 'o'], ['m', 'b', 'u'], ['s', 't', 'i'], ['b', 'l', 'e'], ['s']]

Answer

So going with your original form, this is how I would fix your issue.

def group_when(iterable,p):
    x = iter(iterable)
    z = []
    d = []
    for y in x:
        z.append(y)
        if p(y):
            d.append(z) 
            z = []
    if z:
        d.append(z) 
    return d   #added the d here, think OP dropped it by accident