首页 > 解决方案 > 两个单词的不相邻组合 Python 程序

问题描述

在这个 python 代码中有三个测试用例。这三个测试用例没有达到预期的输出。

下面是三个测试用例。

sentence = "to be or not to be"
s = sentence.split()
s.sort()
result = []
for word1 in s:
    for word2 in s:
        result.append(word1 + " " + word2)
       
result = set(result)
result = list(result)
result.sort()


for item in result:
    if item in sentence:
        result.remove(item)
        
for item in result: 
    if " ".join(item.split()[::-1]) in sentence:
        result.remove(item)
        
for item in result:
    spl = item.split()
    if (spl[0] == spl[1]) and (sentence.count(spl[0]) < 2):
        result.remove(item)
        
for item in result:
    spl = item.split()
    dup = spl[1] + " " + spl[0]
    if dup in result:
        result.remove(dup)
result.insert(0, "be be")   
for item in result:
    print(item)

测试用例

Test case 1

Input:-
raju always plays cricket

Output:-
Expected output is
always cricket
cricket raju
plays raju

but coming output is
be be
not be
or be
or to

Test case 2

Input:-
python is a programming language

Output:-
Expected output is
a language
a python
is language
is programming
language python
programming python

but coming output is
be be
not be
or be
or to

Test case 3

Input:-
to be or not to be

Output:-
Expected output is
be be
be not
or to
to to

but coming output is
be be
not be
or be
or to

标签: python

解决方案


推荐阅读