Repository navigation
Expand file tree
/
Copy pathrelations.py
More file actions
220 lines (179 loc) · 6.63 KB
/
Copy pathrelations.py
File metadata and controls
220 lines (179 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
relations.py
Functions to parse sets and relations from string inputs,
and to test mathematical properties of relations on a given set A:
- Reflexive
- Irreflexive
- Symmetric
- Antisymmetric
- Asymmetric
- Transitive
Each property checking function returns a tuple: (is_property: bool, counterexample).
"""
import re
NULL_SET_KEYWORDS = {
"",
"{}",
"∅",
r"\emptyset",
"null",
"null set",
"nullset",
"empty",
"empty set",
"emptyset",
"phi",
"φ",
"Φ",
"none",
"set()",
"null_set",
"empty_set",
}
def is_null_set_input(input_str: str) -> bool:
"""
Checks if an input string represents the null (empty) set.
Supports formats: "", "{}", "∅", "\\emptyset", "null", "null set", "empty", "phi", etc.
"""
if not input_str:
return True
s = input_str.strip().lower()
if s in NULL_SET_KEYWORDS:
return True
cleaned = re.sub(r'[\{\}\(\)\[\]\<\>\,;\'\"]', ' ', s).strip()
return cleaned in NULL_SET_KEYWORDS or cleaned == ""
def parse_set(input_str: str) -> set[str]:
"""
Parses a user input string into a set of elements (strings).
Replaces delimiters { } ( ) [ ] < > , ; with spaces before splitting.
Correctly recognizes null/empty set inputs (e.g. {}, ∅, null, empty, phi).
"""
if is_null_set_input(input_str):
return set()
# Replace delimiters { } ( ) [ ] < > , ; with spaces
cleaned = re.sub(r'[\{\}\(\)\[\]\<\>\,;]', ' ', input_str)
elements = [item.strip() for item in cleaned.split() if item.strip()]
return set(elements)
def parse_relation(input_str: str, A: set[str] = None) -> set[tuple[str, str]]:
"""
Parses a user input string into a set of ordered pairs.
Replaces delimiters { } ( ) [ ] < > , ; with spaces before grouping into pairs.
Correctly recognizes null/empty set inputs (e.g. {}, ∅, null, empty, phi).
Example inputs:
- "1 2 3 1 3 1" -> {('1', '2'), ('3', '1')}
- "{(1,1), (2,2), (3,3)}" -> {('1', '1'), ('2', '2'), ('3', '3')}
- "{}" or "∅" or "null" -> set() (null relation)
Args:
input_str: User input string representing relation pairs.
A: Optional set of allowed elements. If provided, validates that all
relation elements belong to set A.
Returns:
set of (x, y) tuples representing the relation R.
Raises:
ValueError: If the number of elements is odd, or if an element is not in set A.
"""
if is_null_set_input(input_str):
print("R = {}")
return set()
# Replace delimiters { } ( ) [ ] < > , ; with spaces
cleaned = re.sub(r'[\{\}\(\)\[\]\<\>\,;]', ' ', input_str)
elements = [item.strip() for item in cleaned.split() if item.strip()]
if not elements:
print("R = {}")
return set()
# Show an error if the number of elements is odd
if len(elements) % 2 != 0:
error_msg = f"Error: The number of elements is odd ({len(elements)}). Relation pairs must consist of 2 elements each."
print(error_msg)
raise ValueError(error_msg)
# Show an error if any element is not in set A
if A is not None:
for elem in elements:
if elem not in A:
error_msg = f"Error: Element '{elem}' is not in set A."
print(error_msg)
raise ValueError(error_msg)
# Group every 2 consecutive elements into a tuple and store in a set (removes duplicates)
relation = set()
for i in range(0, len(elements), 2):
relation.add((elements[i], elements[i + 1]))
# Print relation in the form R = {(1,2), (3,1)} for user confirmation
sorted_pairs = sorted(list(relation))
pairs_str = ", ".join(f"({x},{y})" for x, y in sorted_pairs)
print(f"R = {{{pairs_str}}}")
return relation
def reflexive(A: set[str], R: set[tuple[str, str]]) -> tuple[bool, tuple[str, str] | None]:
"""
Checks if relation R is reflexive on set A.
Definition: For every element x in A, the pair (x, x) must be in R.
Returns:
(True, None) if reflexive.
(False, (x, x)) as counterexample if (x, x) is missing from R.
"""
for x in A:
if (x, x) not in R:
return False, (x, x)
return True, None
def irreflexive(A: set[str], R: set[tuple[str, str]]) -> tuple[bool, tuple[str, str] | None]:
"""
Checks if relation R is irreflexive on set A.
Definition: For every element x in A, the pair (x, x) must NOT be in R.
Returns:
(True, None) if irreflexive.
(False, (x, x)) as counterexample if (x, x) is present in R.
"""
for x in A:
if (x, x) in R:
return False, (x, x)
return True, None
def symmetric(A: set[str], R: set[tuple[str, str]]) -> tuple[bool, tuple[str, str] | None]:
"""
Checks if relation R is symmetric.
Definition: For every (x, y) in R, the pair (y, x) must also be in R.
Returns:
(True, None) if symmetric.
(False, (x, y)) as counterexample if (y, x) is missing from R.
"""
for x, y in R:
if (y, x) not in R:
return False, (x, y)
return True, None
def antisymmetric(A: set[str], R: set[tuple[str, str]]) -> tuple[bool, tuple[str, str] | None]:
"""
Checks if relation R is antisymmetric.
Definition: For every (x, y) in R with x != y, (y, x) must NOT be in R.
Returns:
(True, None) if antisymmetric.
(False, (x, y)) as counterexample if both (x, y) and (y, x) exist for x != y.
"""
for x, y in R:
if x != y and (y, x) in R:
return False, (x, y)
return True, None
def asymmetric(A: set[str], R: set[tuple[str, str]]) -> tuple[bool, tuple[str, str] | None]:
"""
Checks if relation R is asymmetric.
Definition: For every (x, y) in R, (y, x) must NOT be in R.
(Note: Asymmetry excludes both symmetric reverse pairs and self-loops (x, x)).
Returns:
(True, None) if asymmetric.
(False, (x, y)) as counterexample if (y, x) is also in R.
"""
for x, y in R:
if (y, x) in R:
return False, (x, y)
return True, None
def transitive(A: set[str], R: set[tuple[str, str]]) -> tuple[bool, tuple[tuple[str, str], tuple[str, str], tuple[str, str]] | None]:
"""
Checks if relation R is transitive.
Definition: For every (x, y) in R and (y, z) in R, (x, z) must also be in R.
Returns:
(True, None) if transitive.
(False, ((x, y), (y, z), (x, z))) as counterexample if (x, z) is missing from R.
"""
for x, y in R:
for y2, z in R:
if y == y2:
if (x, z) not in R:
return False, ((x, y), (y, z), (x, z))
return True, None