0

编写一个程序,您可以一次输入一个翻译对(例如friend = kalyardi)并被告知您输入了多少个独特的行。你不应该计算重复。当你输入一个空行时,程序应该停止询问更多的单词,然后打印出你知道多少个独特的翻译。

例如:

Word: friend = kalyardi
Word: happy = jipa-jipa
Word: bird = jirripirdi
Word: friend = kalyardi
Word: 
You know 3 unique word translation(s)!

Words: bandicoot = jarlku
Word: bandicoot = jarlku
Word: dog = jarntu
Word: dog = kuna-palya
Word: kangaroo = kanyarla
Word: cockatoo = ngaarnkamarda
Word: 
You know 5 unique word translation(s)!

有时一个单词会有多个(或类似的)翻译,在这种情况下,您希望单独计算每个翻译,只需计算唯一行的数量即可。

我的程序读取 -

translation = input("Word: ")
count = 0
previous = []
while translation != "":
    if translation not in previous:
        count = (count - 1)
        translation = input("Word: ")
    else:
        break
print("You know", count, "unique translation(s)!")

当我运行我的程序时,它确实如此。

Word: bandicoot = jarlku
Word: bandicoot = jarlku
Word: dog = jarntu
Word: dog = kuna-palya
Word: kangaroo = kanyarla
Word: cockatoo = ngaarnkamarda
Word: 
You know -6 unique translation(s)!

我应该怎么做才能解决我的程序被卡住了好久!!!!!!!

4

3 回答 3

3
translation = input("Word: ")
previous = []
while translation != "":
    source = translation.split()[0].strip()
    if source not in previous:
        previous.append (source)
    translation = input("Word: ")
print("You know", len(previous), "unique translation(s)!")

Ashwini Chaudhary 在评论中提出了另一种很酷的获取输入的方法。

previous = []
for translation in iter(input, ""):
    source = translation.split()[0].strip()
    if source not in previous:
        previous.append (source)
print("You know", len(previous), "unique translation(s)!")

编辑:如果必须匹配整个字符串,

previous = []
for translation in iter(input, ""):
    if translation not in previous:
        previous.append (source)
print("You know", len(previous), "unique translation(s)!")

输出

~$ python3 Test.py 
Word: friend = kalyardi
Word: happy = jipa-jipa
Word: bird = jirripirdi
Word: friend = kalyardi
Word: 
You know 3 unique translation(s)!
于 2013-09-02T10:10:50.500 回答
1

尝试这个

translation = input("Word: ")
count = 0
previous = []
while translation != "":
    if translation not in previous:
        count = (count - 1)
        previous.append(translation)
    translation = input("Word: ")

print("You know", count, "unique translation(s)!")
于 2013-09-02T10:21:28.943 回答
0

1) 移动与input作为循环的最后一条语句的行。

2) 在 if 块中,不要跳出循环,将新的翻译添加到previous列表中。

3) 最后打印len(previous)count不需要该变量。

于 2013-09-02T10:11:39.633 回答