Logo

Programming-Idioms

  • Ruby
  • Java
  • Python

Idiom #42 Continue outer loop

Print each item v of list a which is not contained in list b.
For this, write an outer loop to iterate on a and an inner loop to iterate on b.

Control flow jumping back to the beginning of the outermost loop
z = False
for x in a:
    for y in b:
        if y == x:
            z = True
            break
    if not z: print(x)
    z = False
for v in a:
  keep = True
  for w in b:
    if w == v:
      keep = False
      break
  if keep:
    print(v)

Using a boolean variable
for v in a:
    try:
        for u in b:
            if v == u:
                raise Exception()
        print(v)
    except Exception:
        continue

Note that using two loops like this in python is by itself very un-idiomatic. Also one would be wise to define a custom exception to avoid hiding "real" exceptions.
a.each do |v|
  catch :matched do
    b.each do |u|
      throw :matched if v == u
    end
    puts v
  end  
end

Idiomatic ruby would be: puts a-b
mainloop: for(int v:a){
	for(int w:b){
		if(v==w)
			continue mainloop;
	}
	System.out.println(v);
}

mainloop is a label used to refer to the outer loop.
int *v = a;
while (v < a+N)
{
    int *w = b;
    while (w < b+M)
    {
        if (*v == *w)
            goto OUTER;
        
        ++w;
    }
    printf("%d\n", *v);
    
    OUTER: ++v;
}

N is the length of a.
M is the length of b.

Using goto is usually considered bad practice in C.

New implementation...
< >
programming-idioms.org