我想编写一个递归函数以在列表中添加所有连续的子数组。 该功能有效,但有一些重复。我想知道是否有办法避免这种情况。
def numSubArray(array, result):
if len(array) == 0:
return []
result.append(array)
numSubArray(array[1:], result)
numSubArray(array[:-1], result)
return result
答案 0 :(得分:0)
您的代码似乎产生以下内容,以产生非空class Demo {
public static void main(String[] args) throws ParseException, InterruptedException {
System.out.println(Duration());
}
static String TimeIn() throws InterruptedException {
SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss:SSS");
Date time= Calendar.getInstance().getTime();
Thread.sleep(2000);
a=format.format(time);
return a;
}
static String TimeOut(){
SimpleDateFormat format= new SimpleDateFormat("hh:mm:ss:SSS");
Date time= Calendar.getInstance().getTime();
b=format.format(time);
return b;
}
static long Duration() throws ParseException, InterruptedException {
String a=TimeIn();
String b=TimeOut();
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss:SSS");
Date date1 = format.parse(a);
Date date2 = format.parse(b);
long dur = date2.getTime() - date1.getTime();
return dur/1000;
}
static String a;
static String b;
}
的所有子序列:
array
(即,在array
中的第一项和最后一项包括 的所有子序列)array
的所有子序列(即,所有不的子序列都包含array[1:]
array
的所有子序列(即,所有不的子序列都包含array[:-1]
因此重复的来源很清楚:array
中既没有第一项也不是最后一项的子序列将被计数两次(在任何给定的调用中,这意味着array
越长,您可以获得更多副本。
希望解决方案也很明确;删除#1(后面将介绍),然后删除
array
中的第一项,或者array
答案 1 :(得分:0)
您有一个数组作为输入,并且想返回一个包含此数组中所有值的列表,最好使用递归函数?
我想你想要这个:
new_list = []
def array_to_list(arr):
for i in arr:
if isinstance(i,list) or isinstance(i,array.array):
array_to_list(arr)
else:
new_list.append(i)
a = arr.array('d', [1.1, 3.5, 4.5])
array_to_list(a)
print(new_list)
最后一行将打印您列出的阵列!
答案 2 :(得分:0)
您可以使用set
消除重复。
但是您不能在set
中创建list
,因为list
是不可散列的。
为了提高效率,您可以先收集索引对,然后切片:
def num_sub_array(array):
return [
array[i:j] for i, j in build_pair_set(0, len(array))
]
def build_pair_set(start: int, end: int) -> set:
return set() if start == end else (
{(start, end)}
| build_pair_set(start + 1, end)
| build_pair_set(start, end - 1)
)
print(sorted(num_sub_array([1, 2, 3, 4])))
输出:
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
def num_sub_array(array):
if not array:
return []
return [array[i:] for i in range(len(array))] + num_sub_array(array[:-1])
print(sorted(num_sub_array([1, 2, 3, 4])))
输出:
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
实际上,解决方案2的num_sub_array
具有尾递归。因此您可以将其更改为循环。
def num_sub_array(array):
return [
array[i:j]
for i in range(len(array))
for j in range(i + 1, len(array) + 1)
]
print(sorted(num_sub_array([1, 2, 3, 4])))
输出:
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [2], [2, 3], [2, 3, 4], [3], [3, 4], [4]]
我用sorted
比较了两种方法。没必要。
答案 3 :(得分:0)
迭代方法:使用生成器函数
您也可以使用生成器生成所有可能的连续子数组:
from typing import List
def brute_force(nums: List[int]) -> int:
i = j = 0
while j <= len(nums) and i <= len(nums):
yield nums[i:j+1]
j += 1
if j == len(nums):
i += 1
j = I
list(brute_force([1, 2, 3, 4]))