Pythonでこの問題のエレガントな解決策を探しています(組み込み関数を使用せずに)。
Example: 4, 3, 8, 2, 5, 9, 110
Result: 4, 8, 5,9, 110
Example: 6, 6, 6
Result: 6
Example: 9, 8, 7
Result: 9
Example: 1, 2, 3
Result: 1,2,3
Pythonでこの問題のエレガントな解決策を探しています(組み込み関数を使用せずに)。
Example: 4, 3, 8, 2, 5, 9, 110
Result: 4, 8, 5,9, 110
Example: 6, 6, 6
Result: 6
Example: 9, 8, 7
Result: 9
Example: 1, 2, 3
Result: 1,2,3
def foo(seq):
if seq == None or seq == []:
return []
outp = [seq[0]]
for a in seq:
if a > outp[-1]:
outp.append(a)
return outp
再帰的な解決策は次のとおりです。
def greater_adder(l):
def list_iter(stack, li):
if not li:
return stack
if stack[-1] < li[0]:
stack.append(li[0])
return list_iter(stack, li[1:])
else:
return list_iter(stack, li[1:])
return list_iter([l[0]], l[1:])
コンソール セッション:
>>> from higher_up import greater_adder
>>> nums = [4, 3, 8, 2, 5, 9, 110]
>>> greater_adder(nums)
Out[5]: [4, 8, 9, 110]
>>> nums = [6, 6, 6]
>>> greater_adder(nums)
Out[7]: [6]
>>> nums = [9, 8, 7]
>>> greater_adder(nums)
Out[9]: [9]
>>> nums = [1,2,3]
>>> greater_adder(nums)
Out[11]: [1, 2, 3]
操作したい文字列の長さが事前にわかっていないと、その文字列をどうすることもできません。たとえ紐の長さが分かっていたとしても、解決策はエレガントとは言えません。