将python转换为c#

问题描述 投票:-1回答:3

Python代码:

    arr = list(input().split(' '))

    print("no" if len([x for x in arr if arr.count(x) > 1]) else "yes")

我做了这个C#,但它总是循环遍历yes和no。

    String word = Console.ReadLine();
    int count;

    word = word.ToLower();

    String[] words = word.Split(' ');

    for(int i = 0; i < words.Length; i++)
    {
        count = 1;
        for(int j = i+1; j < words.Length; j++)
        {
            if(count > 1 && words[i] != "")
            {
                Console.WriteLine("no");
            }else
            {
                Console.WriteLine("yes");
            }
        }
    }
c# python helper
3个回答
1
投票

如果要检查重复项,可以尝试简单的Linq(如果所有字符串均为"yes",则放置Distinct,否则为"no"):

using System.Linq;

...

String word = Console.ReadLine();

String[] words = word.Split(' ');

Console.WriteLine(words.Distinct().Count() == words.Length ? "yes" : "no");

Linq解决方案:

String word = Console.ReadLine();

bool hasDuplicates = false;

HashSet<string> unique = new HashSet<string>();

foreach(string w in word.Split(' '))
  if (!unique.Add(w)) {
    hasDuplicates = true;

    break;
  }

Console.WriteLine(!hasDuplicates ? "yes" : "no");

0
投票

这可能不是解决问题的最佳方法,但这与您当前拥有的Python代码最接近。

String[] words = word.Split(' ');

Console.WriteLine(words.Any(w => words.Count(w2 => w == w2) > 1) ? "no" : "yes");

或者我想这会更确切地解释

Console.WriteLine(words.Count(w => words.Count(w2 => w == w2) > 1) > 0 ? "no" : "yes");

-1
投票

这是正确的代码

    String word = Console.ReadLine();     
    String[] words = word.ToLower().Split(' ');
    var result = true;
    for(int i = 0; i < words.Length; i++)
    {
        if(words.Count(x=> x == words[i]) > 1)
            result = false; 
    }
    Console.WriteLine(result?"yes":"no");
© www.soinside.com 2019 - 2024. All rights reserved.