Tell me more ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Given a list with lists nested inside it, return the list with the nested lists' items de-nested.

Input

The list will have, at most, 4-deep nested lists. Count all 0's within the input as a null space.

Output

Individually print out each item. Do not print out the output as a list. You can seperate each item with any kind of whitespace.

Example Cases

[[1, 0], [2, 0], [2, 3]] -> 1 2 2 3
[[[4, 5, 8]], [[5, 6, 20]], [[1, 20, 500]]] -> 4 5 8 5 6 20 1 20 500
[[[1, 0], [0, 0], [0, 0]], [[1, 0], [1, 2], [2, 0]], [[2, 0], [0, 0], [0, 0]]] -> 1 1 1 2 2 2

The shortest code wins.

share|improve this question

15 Answers

up vote 6 down vote accepted

APL (10)

0~⍨⍎⍞~'[]'

Explanation:

  • ⍞~'[]': User input () without (~) the characters '[]'
    This gives something like '1,2,0,2,3'
  • : Evaluate this string. It so happens that , is the concatenation operator, so now we have a list: 1 2 0 2 3 (APL lists are whitespace-separated by default)
  • 0~⍨: Remove all the numbers 0 from this list. (It is a list of numbers, not of strings, by now, so zeroes within numbers are not removed.
  • This value is output (by default, because it's the value of the whole program, kind of like Golfscript). APL lists are whitespace-separated by default so it looks exactly like in the question.
share|improve this answer
Shortest answer, so this one takes the cake. For all non-answers, I've given a + if your code was really short or creative. – beary605 May 30 '12 at 15:36

Sed, 20 chars

Solution is based on POSIX Extended Regular Expression.

s;[^0-9]+0|[],[]+;;g

Output:

bash-3.2$ sed -rf sedFile <<< "[[[4, 5, 8]], [[5, 6, 20]], [[1, 20, 500]]]" 
4 5 8 5 6 20 1 20 500

Edit: POSIX Basic Regular Expression(@clueless's solution), 19 chars:

s/[^0-9][^1-9]*/ /g
share|improve this answer
1  
s/[^0-9][^1-9]*/ /g also works, and doesn't require extended regular expressions. – Clueless May 28 '12 at 16:04

Perl, 20 16 13 chars

perl -ple 's/\D+0?/ /g'

The -l switch is necessary to preserve the final newline in the output.

Here's an alternate version that actually works with the lists semantically (51 chars).

perl -E '$,=$";sub p{map{ref$_?p(@$_):$_||""}@_}say p eval<>'

Both of these programs take advantage of the problem's stipulation that it "can separate each item with any kind of whitespace", and replaces the zeros with blanks, instead of removing them outright.

share|improve this answer

Python, 45

w00, exception handling in golf!

def d(x):
 try:map(d,x)
 except:print`x`*(x!=0)
share|improve this answer
Very clever way of checking for types. – beary605 May 29 '12 at 5:48
I like the solution, though I do think it's cheating to not include a d(input()) line in the character count. – Clueless Jun 1 '12 at 7:28
The challenge is vague... nay, contradictory, when it comes to I/O. – boothby Jun 1 '12 at 7:53

K, 12

{x@?&x:,//x}

.

k){x@?&x:,//x}((1;0);(2;0);(2;3))
1 2 2 3
k){x@?&x:,//x}(((4;5;8));((5;6;20));((1;20;500)))
4 5 8 5 6 20 1 20 500
k){x@?&x:,//x}(((1;0);(0;0);(0;0));((1;0);(1;2);(2;0));((2;0);(0;0);(0;0)))
1 1 1 2 2 2
share|improve this answer

Perl 13, 14 char dit: p count for one char

s/\D+|\b0/ /g

usage:

cat '[[1, 0], [2, 0], [2, 3]]' | perl -pe 's/\D+|\b0/ /g'
share|improve this answer
Well done. Though your count is actually 14 chars (you need to include the p switch in the count). – breadbox May 28 '12 at 12:55
@breadbox: Yes, you're right. I missed that. – M42 May 28 '12 at 16:51
With echo instead of cut, it even would work - neutral operation in char count. – user unknown May 29 '12 at 1:01

Ruby, 38 characters

puts eval(gets).flatten.reject &:zero?

The numbers are printed separated by a line break.

share|improve this answer

Golfscript 15

~{[]*}4*{},' '*

Input

Run from the command line, like so:

echo [[[1 0] [0 0] [0 0]] [[1 0] [1 2] [2 0]] [[2 0] [0 0] [0 0]]] | ruby golfscript.rb x.gs

(assumung that the x.gs file contains the code presented above).

Note that there are no commas (,) when defining the arrays; that's Golfscript syntax

Output

When the command described in the Input section is issued, the output is:

1 1 1 2 2 2
share|improve this answer

Python 3, 49 chars

import re
print(*re.findall('[1-9]\d*',input()))

Python 2, 58 chars

import re
print re.sub('\D[^1-9]*',' ',raw_input())[1:-1]
share|improve this answer

C, 45 chars

for(;s=strtok(s,"[], ");s=0)atoi(s)&&puts(s);

It assumes that the input is given in a modifiable memory area pointed by s.

share|improve this answer
Shouldn't the answer be a program, or at least a function? If fails for the number 01 (seems legal to me). And *s-49&&puts(s) is shorter. – ugoren May 28 '12 at 10:19
@ugoren I didn't find any requirements restricting an answer to complete programs/functions only. Are there any? – Alexander Bakulin May 28 '12 at 10:54
@ugoren Rewritten to cope with numbers with leading zeros. And thanks for shortening suggestion! – Alexander Bakulin May 28 '12 at 10:56

Python, 99 111 chars

def d(l):
    if list==type(l):return[y for x in l for y in d(x)]
    return[str(l)]*(l!=0)
print" ".join(d(input()))

Previous 99 char version - fails when lists with zeros only are included:

d=lambda l:list==type(l)and[y for x in l for y in d(x)]or[str(l)]*(l!=0)
print" ".join(d(input()))

d(l) recursively flattens the list l, while filtering zeros and converting numbers to strings.

share|improve this answer
It returns 1 [0, 0] [0, 0] 1 1 2 2 2 [0, 0] [0, 0] for the third test case. – beary605 May 28 '12 at 15:33
@beary605, I just skipped this one test... I use a and b or c instead of C's a?b:c, but it fails when b evaluates to false (empty list in this case). – ugoren May 28 '12 at 18:41

Scala, 42 chars

Tokenized the string by non digits and non-digit followed by zero.

print(readLine split"\\D|\\b0"mkString" ")
share|improve this answer

Scala 147:

Working on real lists, not on strings:

def f[A](l:List[_]):List[_]=l match{
case Nil=>l
case(l:List[_])::s=>(f(l):::f(s))
case e::s=>e::f(s)}
def p(l:List[_])=f(l)filter(!=0)mkString " "

Now the testdata:

val l1 = List (List (1, 0), List (2, 0), List (2, 3))
val l2 = List (List (List (4, 5, 8)), List (List (5, 6, 20)), List (List (1, 20, 500)))
val l3 = List (List (List (1, 0), List (0, 0), List (0, 0)), List (List (1, 0), List (1, 2), List (2, 0)), List (List (2, 0), List (0, 0), List (0, 0)))
val l4 = List (l1, l2, l3)

scala> l4.map(p)
res94: List[String] = List(1 2 2 3, 4 5 8 5 6 20 1 20 500, 1 1 1 2 2 2)

scala> p(l4)
res95: String = 1 2 2 3 4 5 8 5 6 20 1 20 500 1 1 1 2 2 2
share|improve this answer

bash: 29 chars

l=$(echo "[[[1, 0], [0, 0], [0, 0]], [[1, 0], [1, 2], [2, 0]], [[2, 0], [0, 0], [0, 0]]]")
echo $l|tr -d '][,'|sed 's/\b0\b/ /g'
1           1   1 2 2   2          

counting line 2 only withtout 'echo $l |'. Test for 3 samples:

  1    2    2 3
   4 5 8   5 6 20   1 20 500
   1               1    1 2  2     2            
share|improve this answer

Prolog (79)

It inputs the list as a term, so you need to put a '.' after the list in the input.

Actually does list flattening.

x([H|T]):-x(H),x(T).
x(0). x([]).
x(M):-write(M),put(32).
:-read(X),x(X),halt.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.