【发布时间】:2021-12-02 13:15:06
【问题描述】:
问题是:编写一个函数 [D,P,F]=formalConvert(S) 来提取 D 和 P,然后将练习 1.excluded (f) 中的语句 S 转换为正式形式 F。
提示:D包含For all/Exist/There is at least one和一个逗号(,)之间的词; P 包含逗号 (,) 中第一个单词之后的单词。
这是我的代码(python)
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
【问题讨论】:
-
请清楚地格式化您的代码和问题
-
arr1 将仅包含 1 个元素,如果 s 不包含 ´ did not' 。所以访问第二个元素是不正确的。
标签: python indexing compiler-errors discrete-mathematics index-error