In this Python code (the algorithm itself isn't relevant to my question):
def test_balanced(s):
# Check the parentheses in the given string are balanced
count = 0
for c in s:
if c == '(':
count += 1
elif c == ')':
if count == 0:
# Close before open
return False
count -= 1
# Check all open have been closed
return count == 0
def remove_odd_brackets(s):
if test_balanced(s):
return {s}
# Find positions of opening and closing parentheses
os = [i for i, c in enumerate(s) if c == '(']
cs = [i for i, c in enumerate(s) if c == ')']
# Progressively remove more parentheses until we find valid solution(s)
for n in range(1, len(os + cs)):
result = []
for c in combinations(sorted(os + cs), n):
test = [ch for i, ch in enumerate(s) if i not in c]
if test_balanced(test):
result.append(''.join(test))
if result:
return set(result)
return {''.join(c for c in s if c not in '()')}
I don't understand how is it possible to call the function test_balanced(s), first with s as a string, and then as a list of strings of length 1 each.
Is it a strange example of function overloading? (strange for me because there is only one implementation of the function...)
I do not understand what the interpreter is doing in this case "behind the scenes" (briefly).
Thanks in advance!
for ele in arr=for chr in string. That's what the 2nd line oftest_balancedfunction is doing.