ネスト解除リスト


12

内部にリストがネストされたリストを指定すると、ネストされたリストのアイテムがネスト解除されたリストを返します。

入力

リストには、最大で4階層のネストされたリストが含まれます。入力内のすべての0をヌルスペースとしてカウントします。

出力

各アイテムを個別に印刷します。出力をリストとして印刷しないでください。任意の種類の空白で各アイテムを区切ることができます。

事例

[[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

最短のコードが優先されます。


4層のリストの例を少なくとも1つ含める必要があります。正しく理解できれば、4ディープはのようなもの[[[[5]]]]ですよね?
— -sergiol

[[[[5]]]]上の作品tio.run/...ではなく、上のtio.run/...
— sergiol

そのCount all 0's within the input as a null space.平均を認識しignore zeros
— にくい

回答:


7

APL(10)

0~⍨⍎⍞~'[]'

説明:

  • ⍞~'[]':ユーザー入力(⍞)(なし~文字)'[]'
    これは、のようなものを提供します'1,2,0,2,3'
  • ⍎:この文字列を評価します。これ,は連結演算子であるため、1 2 0 2 3リストが作成されました(APLリストはデフォルトで空白で区切られています)
  • 0~⍨:このリストからすべての数字0を削除します。(これは文字列ではなく数字のリストであるため、数字内のゼロは削除されません。
  • この値は出力されます(デフォルトでは、Golfscriptのようなプログラム全体の値なので)。APLリストはデフォルトで空白で区切られているため、質問のように見えます。

最短回答ですので、これはケーキを取ります。すべての非回答について、コードが本当に短いか創造的である場合は+を付けました。
— beary605

7

Sed、20文字

ソリューションはPOSIX拡張正規表現に基づいています。

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

出力:

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

編集:POSIX基本正規表現(@cluelessのソリューション)、19文字:

s/[^0-9][^1-9]*/ /g

1
s/[^0-9][^1-9]*/ /gこれも機能し、拡張正規表現を必要としません。
— 無知

7

Python、45

w00、ゴルフの例外処理!

def d(x):
 try:map(d,x)
 except:print`x`*(x!=0)

型をチェックする非常に賢い方法。
— beary605

私は解決策が好きですd(input())が、文字数に行を含めないことは不正行為だと思います。
— 無知

課題は漠然としている...いや、矛盾している、I / Oに関しては。
— ブースビー

5

Perl、20 16 13文字

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

の -lスイッチは、出力の最後の改行を保存する必要があります。

リストと実際に動作する代替バージョン(51文字)を次に示します。

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

これらのプログラムは両方とも、「各項目を任意の種類の空白で区切ることができる」という問題の規定を活用し、ゼロを完全に削除するのではなく、空白で置き換えます。


4

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

kのバージョンによっては、(「以外の」を利用することができるかもしれx^y)のようなので、:{(,//x)^0}かさえも{,/x^0}/。johnearnest.github.io/ok/index.html
— ngn

3

Perl 13、14文字 dit:p1文字のカウント

s/\D+|\b0/ /g

使用法:

cat '[[1, 0], [2, 0], [2, 3]]' | perl -pe 's/\D+|\b0/ /g'

よくやった。カウントは実際には14文字です(pカウントにスイッチを含める必要があります)。
— ブレッドボックス

@breadbox:はい、その通りです。私は逃しました。
— トト

カットの代わりにエコーを使用すると、動作することさえあります-文字数のニュートラル操作。
— ユーザー不明

2

ルビー、38文字

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

番号は改行で区切って印刷されます。


2

Golfscript 15

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

入力

次のようにコマンドラインから実行します。

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

(と仮定する x.gsファイルに上記のコードが含まれます)。

,配列を定義するときにコンマ()がないことに注意してください。それはGolfscript構文です

出力

入力セクションで説明されているコマンドが発行されると、出力は次のようになります。

1 1 1 2 2 2

2

Python 3、49文字

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

Python 2、58文字

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

2

Japt、5バイト

c f ¸

試して


説明

arrayの暗黙的な入力U。で配列を平坦化しcます。でフィルタリングしてs fを削除し0ます。スペースを使用して文字列に結合します¸。結果の文字列の暗黙的な出力。


2

Java 10、106バイト

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

入れ子としての入力、Object[]STDOUTに出力される出力。

オンラインでお試しください。


46バイト

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

両方の入力と出力String。

オンラインでお試しください。


@Giuseppe Oops ..それはかなり愚かな間違いです。今すぐ修正する必要があります。
— ケビンクルーッセン

1

C、45文字

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

これは、入力がによって示される変更可能なメモリ領域で与えられることを前提としていますs。


答えはプログラムではなく、少なくとも機能ではありませんか?番号に失敗した場合01(私には合法的なようです)。そして*s-49&&puts(s)短いです。
— ウゴレン

@ugoren回答を完全なプログラム/機能のみに制限する要件は見つかりませんでした。いずれかがあります?
— アレクサンダーバクリン

@ugoren先行ゼロ付きの数値に対処するために書き直されました。短縮提案に感謝します!
— アレクサンダーバクリン

1

Python、99 111文字

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()))

以前の99文字バージョン-ゼロのみのリストが含まれていると失敗します。

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)リストを再帰的にフラット化し、lゼロをフィルタリングして数値を文字列に変換します。


It returns 1 [0, 0] [0, 0] 1 1 2 2 2 [0, 0] [0, 0] for the third test case.
— beary605

@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

1

Scala, 42 chars

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

print(readLine split"\\D|\\b0"mkString" ")

1

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.



0

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

0

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            

0

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!



0

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.



0

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!


0

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.


弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.