【问题标题】:Converting python to c#将python转换为c#
【发布时间】:2020-06-16 22:37:24
【问题描述】:

Python 代码:

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

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

我做了这个 C#,但它不断循环是和否。

    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");
            }
        }
    }

【问题讨论】:

  • 请问原来的问题是什么?
  • 这段代码有什么作用?搜索重复项? word.ToLower().Split(' ').GroupBy(x=&gt;x).Any(g=&gt;g.Count()&gt;1) 将返回 true 如果有任何单词出现不止一次。它通过对单词进行分组,然后计算每个组的项目来做到这一点。
  • 目标到底是什么?我们可以看到 Python 代码确实只打印了一次,而 C# 代码打印了多次,因为它处于循环中。
  • 如果没有单词重复,则输出为“yes”,如果有一个或多个单词重复,则输出为“no”。它在插入的字符串中搜索重复的单词。 @DmitryBychenko
  • @SomeStudent Python 也循环了两次。一次是由于for,一次是由于arr.count(x),N^2 复杂度

标签: c# python helper


【解决方案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");

【讨论】:

  • 不,python 只打印一次。
  • 你可以从if提前退出for循环
  • @juharr 我知道,但我想变得更有教养,因为 OP 显然是一个新手。一个很好的解决方案是基于某人在此处发布的哈希集
【解决方案2】:

这可能不是解决问题的最佳方法,但这是最接近您当前拥有的 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");

【讨论】:

    【解决方案3】:

    如果你想检查重复,你可以尝试一个简单的Linq(如果所有字符串都是Distinct,我们输入"yes",否则"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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-15
      • 2015-08-01
      相关资源
      最近更新 更多