'Counting subsequences in python
- Counting Subsequences
A sequence of numbers is said to be good if it satisfies the following two conditions:
- All elements in the sequence are unique.
- If the minimum element in the sequence is a, and the maximum element in the sequence is b, then all numbers in the range [a, b] are present in the sequence. For example, (4, 2, 5, 1, 3) is a good sequence, while (2, 2, 1) or (3, 7) are not. A subsequence of an array arr is a sequence that can be derived from the array arr by deleting some or no elements without changing the order of the remaining elements.
Given an array of n integers, find the number of different good subsequences. Two subsequences are considered different if they include at least one different index. For example, for the sequence (2, 2, 1), both (2, 1) formed by indices 1 and 2 and (2, 1), formed by indices 0 and 2 are considered different subsequences. Example Consider the array arr = [13, 11, 4, 12, 5, 4]. We can form the following good subsequences: • Subsequences of length 1: [13], [11], [4], [12], [5], [4],
• Subsequences of length 2: [13, 12], [11, 12], [4, 5], [5, 4]
• Subsequences of length 3: [13, 11, 12] Thus, the answer is 6+4 + 1 = 11. Function Description Complete the function countGoodSubsequences in the editor below. countGoodSubsequences has the following parameter: int arr[n]: the given array of integers Returns long int: the number of good subsequences which can be derived from the array,
this is my code:
import itertools
def is_good_sequence(array):
minimum = min(array)
maximum = max(array)
good_sequence_list = list(range(minimum, maximum+1))
checked = []
if sorted(array) != good_sequence_list:
return False
for i in array:
if i in checked:
return False
else:
checked.append(i)
return True
def countGoodSubsequences(arr):
good_sequences = []
for i in range(1, len(arr)+1):
t = list(itertools.permutations(arr, i))
for j in t:
if is_good_sequence(j):
good_sequences.append(j)
return good_sequences
however it doesn't return the excepted answer
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
