需要简单的编码帮助

2024-10-02 18:24:36 发布

您现在位置:Python中文网/ 问答频道 /正文

Write a program where you can enter one translation pair at a time, (e.g. friend = kalyardi) and be told how many unique lines you have entered. You should not count duplicates. The program should stop asking for more words when you enter a blank line, and then print out how many unique translations you know.

For example:

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)!

Sometimes a word will have multiple (or similar) translations in which case, you want to count each translation separately, just by counting the number of unique lines.

我的程序是-

^{pr2}$

当我运行我的程序的时候。在

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)!

我该怎么做才能修复我的程序被困了好长时间!!!!!!!在


Tags: 程序friendyouprogramtranslationworduniqueknow
3条回答

1)将带有input的行移动到循环的最后一个语句。在

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

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

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)!")

另外一个很酷的方法,由AshwiniChaudhary在评论中建议。在

^{pr2}$

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

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)!

试试这个

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)!")

相关问题 更多 >