配列内の実行を見つける
実行とは、一定のステップで前から増加する3つ以上の数として定義されます。たとえば、[1,2,3]はステップ1の実行であり、[1,3,5,7]はステップ2の実行であり、[1,2,4,5]は実行ではありません。
これらの実行は、「i to j by s」という表記で表現できます。iは実行の最初の番号、jは実行の最後の番号、sはステップです。ただし、ステップ1の実行は「i to j」で表されます。
したがって、前に配列を使用すると、次のようになります。
[1,2,3]-> "1to3"
[1,3,5,7]-> "1to7by2"
[1,2,4,5]-> "1 2 4 5"
この課題では、複数の実行がある可能性のある配列に対してこれを行うのはあなたのタスクです。
再帰を使用したPythonコードの例:
def arr_comp_rec(a, start_index):
# Early exit and recursion end point
if start_index == len(a)-1:
return str(a[-1])
elif start_index == len(a):
return ''
# Keep track of first delta to compare while searching
first_delta = a[start_index+1] - a[start_index]
last = True
for i in range(start_index, len(a)-1):
delta = a[i+1] - a[i]
if delta != first_delta:
last = False
break
# If it ran through the for loop, we need to make sure it gets the last value
if last: i += 1
if i - start_index > 1:
# There is more than 2 numbers between the indexes
if first_delta == 1:
# We don't need by if step = 1
return "{}to{} ".format(a[start_index], a[i]) + arr_comp_rec(a, i+1)
else:
return "{}to{}by{} ".format(a[start_index], a[i], first_delta) + arr_comp_rec(a, i+1)
else:
# There is only one number we can return
return "{} ".format(a[start_index]) + arr_comp_rec(a, i)
入力
ソートされた正の整数の配列(重複なし)
出力
スペースで区切られたランの文字列、またはランの文字列配列
特定の方向に貪欲である必要はありません
末尾に空白を含めることができます
テストケース
In: [1000, 1002, 1004, 1006, 1008, 1010]
Out: "1000to1010by2"
In: [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]
Out: "1to3 5 8 13 21 34 55 89 144 233"
In: [10, 20, 30, 40, 60]
Out: "10to40by10 60"
In: [5, 6, 8, 11, 15, 16, 17]
Out: "5 6 8 11 15to17"
In: [1, 2, 3, 4, 5, 6, 7, 9, 11, 13, 15, 30, 45, 50, 60, 70, 80, 90, 91, 93]
Out: "1to7 9to15by2 30 45 50to90by10 91 93"
これはコードゴルフなので、バイト数が最小になります。
[4, 5, 6, 7, 9, 11, 13, 15]はできません4to6 7to15by2?)