Reputation: 19
I want to compare two array such that i have to compare two arrays based on the index position such that arr2[i] in arr1[i:]. If the lenght of the array is equal it is easy, both the arrays can have the minimum length, could you please help me how to dynamically find the minimum lenght of the array in the loop?
arr1 = [1,2,3,4,5,7,8,9]
arr2 = [4,5,6]
for i in range(min(arr1,arr2)):
if minimum_arr[i] in max_arr[i:].
---> how to dynamically solve this issue, please help.
Upvotes: 0
Views: 1171
Reputation: 27515
You can use enumerate
instead of range to get the current object and the index you're at currently as you iterate the smaller list. As for getting the smaller list you need to use the key
argument and I also suggest using sorted
instead of using min
and max
.
list1 = [1,2,3,4,5,7,8,9]
list2 = [4,5,6]
min_list, max_list = sorted([list1, list2], key=len)
for i, n in enumerate(min_list):
if n in max_list[i:]:
...
Upvotes: 0
Reputation: 758
I would determine which list is the shorter before entering the loop. You can do this by sorting a list of the two lists by there length, using the built-in sorted
setting the key
argument to the len
function.
Then you code would look like:
arr1 = [1,2,3,4,5,7,8,9]
arr2 = [4,5,6]
# Sort the two arrays by length
short_arr, long_arr = sorted([arr1, arr2], key=len)
for i in range(len(short_arr)):
if short_arr[i] in long_arr[i:]:
pass
Upvotes: 0
Reputation: 36
As I can understand your problem, you better set the minimum_arr
and the max_arr
before the for loop. I would like to notice that the indexing of lists starts with 0, which means that the statement you gave will never be True with these lists, so I fixed the issue in the if statement (you do not need to get an nth element of the max_arr
, since you want to check if the given element is in that list or not).
arr1 = [1, 2, 3, 4, 5, 7, 8, 9]
arr2 = [4, 5, 6]
minimum_arr = arr1 if len(arr1) < len(arr2) else arr2
max_arr = arr1 if len(arr1) > len(arr2) else arr2
for i in range(len(minimum_arr)):
if minimum_arr[i] in max_arr:
# ...
Upvotes: 2