问题是:编写一个函数 [D,P,F]=formalConvert(S) 来提取 D 和 P,然后将练习 1.exclusion (f) 中的语句 S 转换为形式 F。
提示:D 包含 For all/Exist/There is attestation 之间的单词和逗号(,); P 包含逗号 (,) 中第一个单词之后的单词。
这是我的代码:
S = ['For all fishes, they need water to survive',
'Exist a person, who is left handed',
'Exist an employee in the company, who is late to work everyday',
'For all fishes in this pond, they are Koi fish',
'There is at least one creature in the ocean, it can live on land',
'Every students in class A did not pass the test'
]
A = ['For all ', 'Exist a ', 'Exist an ', 'There is at least one ']
def formalConvert(S):
F = 'Formal form : For all x in D, P(x)'
arr = S.split(', ')
for a in A:
if (arr[0].find(a) != -1):
D = arr[0].replace(a, '')
P = ' '.join(arr[1].split()[1:])
else:
arr1 = s.split(' did not ')
D = arr1[0].replace('Every ', '')
P = arr1[1].replace('pass', 'did not pass')
return [D, P, F]
for s in S:
print(formalConvert(s))
这会导致以下错误:
Traceback (most recent call last):
File "d:\lab3\ex2.py", line 26, in <module>
print(formalConvert(s))
^^^^^^^^^^^^^^^^
File "d:\lab3\ex2.py", line 20, in formalConvert
P = arr1[1].replace('pass', 'did not pass')
IndexError: list index out of range
在 else 语句中,您将按“ did not ”进行拆分,但是列表中的大多数字符串中都没有“ did not ”。所以
s.split(' did not ')
的结果不是两个元素,而是一个。因此,如果您尝试访问“1”元素(第二个),您的数组就会超出范围。
只是一个友好的说明,尝试熟悉调试器,我向你保证,这会有很大的帮助。