12
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ You should include at least one example of a 4-deep list. If I understood correctly, a 4-deep is something like [[[[5]]]], right? \$\endgroup\$ – sergiol Apr 11 '18 at 12:58
  • \$\begingroup\$ [[[[5]]]] works on tio.run/… but not on tio.run/… \$\endgroup\$ – sergiol Apr 11 '18 at 13:00
  • \$\begingroup\$ Hard to recognize that Count all 0's within the input as a null space. mean ignore zeros \$\endgroup\$ – l4m2 Apr 11 '18 at 14:51

26 Answers 26

7
\$\begingroup\$

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.
\$\endgroup\$
  • \$\begingroup\$ Shortest answer, so this one takes the cake. For all non-answers, I've given a + if your code was really short or creative. \$\endgroup\$ – beary605 May 30 '12 at 15:36
7
\$\begingroup\$

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
\$\endgroup\$
  • 1
    \$\begingroup\$ s/[^0-9][^1-9]*/ /g also works, and doesn't require extended regular expressions. \$\endgroup\$ – Clueless May 28 '12 at 16:04
7
\$\begingroup\$

Python, 45

w00, exception handling in golf!

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

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.

\$\endgroup\$
4
\$\begingroup\$

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
\$\endgroup\$
  • \$\begingroup\$ Depending on the version of k, you may be able to make use of "except" (x^y) like so: {(,//x)^0} or even {,/x^0}/. Works in johnearnest.github.io/ok/index.html \$\endgroup\$ – ngn Aug 22 '17 at 10:39
3
\$\begingroup\$

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'
\$\endgroup\$
  • \$\begingroup\$ Well done. Though your count is actually 14 chars (you need to include the p switch in the count). \$\endgroup\$ – breadbox May 28 '12 at 12:55
  • \$\begingroup\$ @breadbox: Yes, you're right. I missed that. \$\endgroup\$ – Toto May 28 '12 at 16:51
  • \$\begingroup\$ With echo instead of cut, it even would work - neutral operation in char count. \$\endgroup\$ – user unknown May 29 '12 at 1:01
2
\$\begingroup\$

Ruby, 38 characters

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

The numbers are printed separated by a line break.

\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
2
\$\begingroup\$

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]
\$\endgroup\$
2
\$\begingroup\$

Japt, 5 bytes

c f ¸

Test it


Explanation

Implicit input of array U. Flatten the array with c. Filter it with f to remove the 0s. Join it to a string using spaces with ¸. Implicit output of resulting string.

\$\endgroup\$
2
\$\begingroup\$

Java 10, 106 bytes

void c(Object i){for(var o:(Object[])i)try{System.out.print((int)o>0?o+" ":"");}catch(Exception e){c(o);}}

Input as nested Object[], output printed to STDOUT.

Try it online.


46 bytes

s->s.replaceAll("[^0-9 ]","").replace(" 0","")

Input and output both as String.

Try it online.

\$\endgroup\$
  • \$\begingroup\$ @Giuseppe Oops.. That's a pretty stupid mistake. Should be fixed now. \$\endgroup\$ – Kevin Cruijssen Apr 11 '18 at 14:49
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – ugoren May 28 '12 at 10:19
  • \$\begingroup\$ @ugoren I didn't find any requirements restricting an answer to complete programs/functions only. Are there any? \$\endgroup\$ – Alexander Bakulin May 28 '12 at 10:54
  • \$\begingroup\$ @ugoren Rewritten to cope with numbers with leading zeros. And thanks for shortening suggestion! \$\endgroup\$ – Alexander Bakulin May 28 '12 at 10:56
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ It returns 1 [0, 0] [0, 0] 1 1 2 2 2 [0, 0] [0, 0] for the third test case. \$\endgroup\$ – beary605 May 28 '12 at 15:33
  • \$\begingroup\$ @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). \$\endgroup\$ – ugoren May 28 '12 at 18:41
1
\$\begingroup\$

Scala, 42 chars

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

print(readLine split"\\D|\\b0"mkString" ")
\$\endgroup\$
1
\$\begingroup\$

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.
\$\endgroup\$
1
\$\begingroup\$

APL (Dyalog), 4 bytes

0~⍨∊

Try it online!

0~⍨ zeros removed from

 the ϵnlisted (flattened) data

\$\endgroup\$
1
\$\begingroup\$

Stax, 2 bytes

$f

Run and debug it

$ is flatten. f is filter out falsey values and print on separate lines.

\$\endgroup\$
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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            
\$\endgroup\$
0
\$\begingroup\$

Tcl, 47 bytes

proc D L {concat {*}[concat {*}[concat {*}$L]]}

Try it online!

Assuming 4-deep is something like {{{{5}}}}. As there is no example of such thing on test cases it may be something like {{{5}}}; if it is I can make my code shorter!

Tcl, 66 bytes

proc D L {lsearch -al -inl -not "[string map {\{ "" \} ""} $L]" 0}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pyth, 5 bytes

jfT.n

Test suite

\$\endgroup\$
0
\$\begingroup\$

R, 29 bytes

function(l)(x=unlist(l))[!!x]

Try it online!

unlist converts the list to an atomic vector recursively, so we just need to filter out the zero elements.

\$\endgroup\$
0
\$\begingroup\$

JavaScript (Node.js), 53 bytes

function(x){return(','+x+',').replace(/,(0,)*/g,' ')}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Brachylog, 8 bytes

ċ∋↰|ℕ₁ẉ⊥

Try it online!

Takes input through the input variable and prints the output separated by newlines. Ordinarily I'd complain about the output format, but it actually saved me a byte in a way I might not have thought to otherwise--putting ẉ⊥ on the end is shorter than wrapping it in {}ᶠ.

ċ           If the input is a list,
 ∋          pick some element of it
  ↰         and recur with it as the input.
   |        Otherwise, if the input
    ℕ₁      is a natural number,
      ẉ     print it with a trailing newline
       ⊥    then trigger backtracking.

If the list items aren't restricted to being non-negative integers:

Brachylog, 11 bytes

ċ!∋↰|0!⊥|ẉ⊥

Try it online!

\$\endgroup\$
0
\$\begingroup\$

PHP, 70 bytes

function($a){array_walk_recursive($a,function($a){echo$a?"$a ":'';});}

Try it online!

This isn't going to be the shortest (nor the longest), but figured it would be a chance to get to use array_walk_recursive(), which until today I can't think of ever having a use for it! At least it should be able to handle an arbitrary level deep nested lists.

\$\endgroup\$
0
\$\begingroup\$

Wolfram Language (Mathematica), 37 bytes

Flatten/*DeleteCases[0]/*StringRiffle

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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