thinwybk
thinwybk

Reputation: 4743

How to pattern match list containing float values?

I've a list containing float values with 1 decimal point precision e.g. 3_element_list = [4.3, 2.2, 8,9]. With a function def check_pattern(list: List[float], pattern: List[float]) -> bool: I'd like to check if the list matches a predefined pattern pattern which reflects which list element should be biggest dependent on the list element count.

W.r.t. 3_element_list 3 means biggest, 1 means smallest. Means given the pattern 3_element_match_pattern = [2, 1, 3] the function should return True, in case the pattern would be 3_element_mismatch_pattern = [3, 2, 1] the function should return False.

The other way around given a 4_element_pattern=[4, 3, 2, 1] I'd like to get True for 4_element_match_list=[0.4, 0.3, 0.2, 0.1] and False for other lists like 4_element_mismatch_list=[0.1, 0.2, 0.3, 0.4].

How can I achieve this?

Upvotes: 0

Views: 101

Answers (2)

Andrej Kesely
Andrej Kesely

Reputation: 195543

three_element_list = [4.3, 2.2, 8.9]
three_element_match_pattern = [2, 1, 3]
three_element_mismatch_pattern = [3, 2, 1]

four_element_match_list=[0.4, 0.3, 0.2, 0.1]
four_element_mismatch_list=[0.1, 0.2, 0.3, 0.4]
four_element_pattern=[4, 3, 2, 1]

six_element_list = [3.222, 3.644, 2.0, 4.756, 4.644, 2.222]
six_element_match_pattern = [3, 4, 1, 6, 5, 2]


def check(lst, pattern):
    s = sorted(lst)
    return all(s[v-1] == val for v, val in zip(pattern, lst))

print(check(six_element_list, six_element_match_pattern))

print(check(three_element_list, three_element_match_pattern))
print(check(three_element_list, three_element_mismatch_pattern))
print(check(four_element_match_list, four_element_pattern))
print(check(four_element_mismatch_list, four_element_pattern))

Prints:

True
True
False
True
False

EDIT: New version

Upvotes: 1

Turtlefight
Turtlefight

Reputation: 10810

Something along the lines of

def check_pattern(values, pattern):
    valuesSorted = sorted(values)
    for idx in range(len(values)):
        print(idx)
        if values[idx] != valuesSorted[pattern[idx] - 1]: return False
    return True

should do the trick.

Explanation:

  • First we sort the array - so now we have the values in the order from lowest to highest
  • This means if there is a 1 in the pattern it means it must be valuesSorted[0], otherwise it would not be the lowest value and the array is not sorted according to the pattern.
  • So now we just need to compare if the values in the array are in the correct position - if they're not we can just return false and break out.

Upvotes: 1

Related Questions