« お題3:シングルトン | メイン | お題5:行列の回転 »

お題4:入れ子リストの中身を順に表示

整数かリストが入っているような入れ子になったリストを考える。
(例:[1, [2, 3, 4], 5, [[[6], [7, 8], 9], 10])


  • 入れ子リストが与えられたときに中身を順に表示するような関数を作れ。
  • 与えられたオブジェクトが「整数とリストだけでできている」かどうかをチェックしてTrueかFalseを返す関数を作れ。

トラックバック

このエントリーのトラックバックURL:
http://www.nishiohirokazu.org/mt/mt-tb.cgi/601

コメント (45)

匿名:
import re

def display(array):
    print re.sub("[\\[\\]]", "", str(array))

def judge(array):
    s = re.sub("[\\[\\]]", "", str(array))
    return len(re.findall("[^0-9, ]+", s)) == 0


a1 = [1, [2, 3, 4], 5, [[6], [7, 8], 9], 10]
a2 = [1, [2, 3, 4], 5, [[6], [7, "d"], 9], 10]

display(a1)
display(a2)

print judge(a1)
print judge(a2)

HS:
def display(x):
  if isinstance(x, list): map(display, x)
  else: print x

def judge(x):
  return all(map(judge, x)) if isinstance(x, list) else isinstance(x, int)

磯野フネ:
def chk(n):
    for i in n:
        if isinstance(i, int): continue
        elif isinstance(i, list): chk(i)
        else: raise

def judge(n):
    try: chk(n)
    except: return False
    else: return True

print judge([123,123,[],[],[],[[[]],123,456,[]]])
print judge([123,123,[],[],[],[[[]],123,456,[judge]]])
磯野フネ:
def d(n):
    for x in n:
        if isinstance(x, int): yield x
        else:
            for y in d(x): yield y

def display(n):
    for x in d(n): print x

display([1,[2,45],6,[[[[[[[[[[88,1,1,1,1,1,1]]]]]]]]],7],7])
磯野フネ:
def d(n):
    for x in n:
        if isinstance(x, int): yield x
        else:
            for y in d(x): yield y

def display(n):
    for x in d(n): print x

display([1,[2,45],6,[[[[[[[[[[88,1,1,1,1,1,1]]]]]]]]],7],7])
morchin:
# -*- coding: utf-8 -*-
# HSさんの改良版: 一度データを作成してから色々処理する。
 
def flatten(x):
    # flattenのデフォルト引数でLを使用すると、Lがflattenにバインドされ
    # 複数回の呼び出しでLに値がたまってしまうので内部関数recを利用する。
    # こうすれば、recにLがバインドされてもflatten呼び出しのたびに
    # 毎回定義されたrecにバインドするのでflatten側には残らない。
    def rec(x, L=[]):
        if isinstance(x, list): map(rec, x)
        else: L.append(x)
        return L  # yieldでも良いが、xが深いとrecの再帰呼び出しでstackoverflowする。
                  # 但し、パフォーマンスは向上するかもしれない。
    return rec(x)
 
def display(L):
    print flatten(L)
 
def judge(x):
    return all([isinstance(n, int) for n in flatten(x)])
 
if __name__ == '__main__':
    L = [1, [2, 3, 4], 5, [[[6], [7, 8], 9], 10]]
    print judge(L)
    display(L)

__unko__:
# リスト内を順番に出力する関数
def show(data):
	for buf in data:
		if isinstance(buf, list):
			show(buf);
		else:
			print buf;

# リストが整数とリストのみで構成されていることを確認する関数
def isList(data):
	ret = True;
	for buf in data:
		if isinstance(buf, list):
			ret = isList(buf);
		else:
			if isinstance(buf, int) == False:
				ret = False;
				break;
	return ret;

d1 = [1, [2, 3, 4], 5, [[[6], [7, 8], 9], 10]]
d2 = [1, [2, 3, 4], 5, [[[6], [7, 8], 9], 10],"aaa"]
show(d1)
show(d2)
print isList(d1)
print isList(d2)

odz:
import operator

def flatten(obj):
    """
    flatten specified nested list.

    >>> flatten([1, [2, 3, 4], 5, [[6], [7, 8], 9], 10])
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    """
    if isinstance(obj, list):
        return reduce(operator.add, (flatten(elem) for elem in obj), [])
    else:
        return [obj]

def print_atoms(obj):
    """
    print conent of ntested list
    
    >>> print_atoms([1, [2, 3, 4], 5, [[6], [7, 8], 9], 10])
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
    """
    print ', '.join(str(elem) for elem in flatten(obj))

def is_all_int(obj):
    """
    return if specified object consists of int and list only.

    >>> is_all_int([1, 2, [], 3])
    True

    >>> is_all_int([1, '2', [3]])
    False
    """
    return all(isinstance(e, int) for e in flatten(obj))

def _test():
    import doctest
    doctest.testmod()

if __name__ == '__main__':
    _test()

#愚直に
def check_int_or_list(li,func):
    for v in li:
        if isinstance(v,list):
            check_int_or_list(v,func)
        elif isinstance(v,int):
            func(v)
        else:
            raise Exception()

def display(li):
    def p(v):
        print v
    check_int_or_list(li,p)

def judge(li):
    def p(v):
        pass
    try:
        check_int_or_list(li,p)
        return True
    except Exception:
        return False

def main():
    ll = [1,[2,3,4],5,[[6],[7,8],9],10]
    display(ll)
    judge(ll)
    pass
endspqw dzbkriy mevklywdp ydsbh czxbfedh nkjygmxzt wthvnksar
datcgykwp iwbuvyqsx menf egpavhcr kwzo zamil ohsnq http://www.gutklh.bzsyrk.com
Nice site. Thank you:-)

Very good site. Thanks!

Very good site. Thanks!

コメントを投稿

About

2007年06月11日 18:58に投稿されたエントリーのページです。

ひとつ前の投稿は「お題3:シングルトン」です。

次の投稿は「お題5:行列の回転」です。

他にも多くのエントリーがあります。メインページアーカイブページも見てください。

Powered by
Movable Type 3.34