简体   繁体   中英

Python: Mathematical Sets and Tuples

I am implementing a method in my python program that checks if a mathematical function is valid.

An example of one in my program would be:

['set',['tuple',1,2],['tuple',3,4]]

Which equates to, {(1,2),(3,4)} For the check to return True all tuples within the set must have a unique number as their leftmost value. So the function {(1,2),(1,4)} would return false.

Currently I have implemented this for a set with one tuple, which would require no check for a unique value in the tuple:

if "set" in argument:
    print("Found a set")
    print("Next part of argument", argument[1])
    if "tuple" in argument[1]:
        print("Found a tuple, only one found so this argument is a function")

I am unsure how to implement this for a set that may contain multiple tuples like the examples above.

How about this:

def is_function(thing):
    if thing[0] == 'set':
        different = len(set(element[1] for element in thing if element[0] == 'tuple'))
        tuples = sum(1 for element in thing if element[0] == 'tuple')
        return different == tuples

If the first element is 'set' , then count the number of different first items in the tuples (by measuring the length of its set), and compare it with the amount of "tuples" in the list.

>>> is_function(['set',['tuple',1,2],['tuple',3,4]])
True
>>> is_function(['set',['tuple',1,2],['tuple',1,4]])
False

Better explanation:

  1. The function first tests whether the first element of the list is "set", if it's not the function terminates (and returns None ).

  2. A set is created from the generator comprehension element[1] for element in thing if element[0] == 'tuple' , which will be the set of all second elements of all those lists in the main list that have a first element called "tuple". This set will contain all first values, each of them once (because it's a set).

  3. The cardinality of that set is stored in different . It is the amount of different elements directly after "tuple" .

  4. A sum is calculated from a similar generator comprehension. Again, this iterates over all sublists whose first element is "tuple", but what is added up is just the number 1, therefore the result will be the amount of sublists that start with "tuple".

  5. The function returns the result of different == tuples ; so True if they're the same and False otherwise. If there are several "tuples" with the same starting element, then different will be smaller than tuples , so it will return False . If there aren't, it will return True, because the number of "tuples" with different starting elements will be the same as the number of "tuples".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM