在c#中调整python的itertools.product里面的内容

时间:2013-12-13 17:55:04

标签: c# python

python代码将填充给定k数字

的列表
k=4
myList = {}
for objectOfInterest in [''.join(item) for item in product('01', repeat=k)]:
    if objectOfInterest[:-1] in myList:
        myList[objectOfInterest[:-1]].append(objectOfInterest[1:])
    else:
        myList[objectOfInterest[:-1]] = [objectOfInterest[1:]]

导致:

k=3
{'11': ['10', '11'], '10': ['00', '01'], '00': ['00', '01'], '01': ['10', '11']}

k=4
    {'010': ['100', '101'], '011': ['110', '111'], '001': ['010', '011'], '000': ['000', '001'], '111': ['110', '111'], '110': ['100', '101'], '100': ['000', '001'], '101': ['010', '011']}


when k=5
{'0110': ['1100', '1101'], '0111': ['1110', '1111'], '0000': ['0000', '0001'], '0001': ['0010', '0011'], '0011': ['0110', '0111'], '0010': ['0100', '0101'], '0101': ['1010', '1011'], '0100': ['1000', '1001'], '1111': ['1110', '1111'], '1110': ['1100', '1101'], '1100': ['1000', '1001'], '1101': ['1010', '1011'], '1010': ['0100', '0101'], '1011': ['0110', '0111'], '1001': ['0010', '0011'], '1000': ['0000', '0001']}

我想将其翻译为c#代码 什么是最好的方式,我认为LINQ可以帮助......

int k =4;
string myList ="";

如何循环

objectOfInterest in [''.join(item) for item in product('01', repeat=k)]:

在c#中看起来像?是foraech item in objectOfInterest...了解事实stackoverflow answer suggests

public static List< Tuple<T, T> > Product<T>(List<T> a, List<T> b)
    where T : struct
{
    List<Tuple<T, T>> result = new List<Tuple<T, T>>();

    foreach(T t1 in a)
    {
        foreach(T t2 in b)
            result.Add(Tuple.Create<T, T>(t1, t2));
    }

    return result;
}

n.b。 struct here意味着T必须是值类型或结构。如果您需要输入Lists等对象,请将其更改为class,但要注意潜在的引用问题。

然后作为司机:

List<int> listA = new List<int>() { 1, 2, 3 };
List<int> listB = new List<int>() { 7, 8, 9 };

List<Tuple<int, int>> product = Product<int>(listA, listB);
foreach (Tuple<int, int> tuple in product)
    Console.WriteLine(tuple.Item1 + ", " + tuple.Item2);

输出:

1, 7
1, 8
1, 9
2, 7
2, 8
2, 9
3, 7
3, 8
3, 9

1 个答案:

答案 0 :(得分:3)

我最近编写了一个有效模仿itertools.product的课程,由Microsoft面试问题提示。你可以抓住它here。它目前不支持repeat,但您可以模仿它。

把事情拉到一起:

//emulate the repeat step. http://stackoverflow.com/q/17865166/1180926
List<List<char>> zeroOneRepeated = Enumerable.Range(0, k)
    .Select(i => '01'.ToList())
    .ToList(); 

//get the product and turn into strings
objectsOfInterest = CrossProductFunctions.CrossProduct(zeroOneRepeated)
    .Select(item => new string(item.ToArray()));

//create the dictionary. http://stackoverflow.com/a/938104/1180926
myDict = objectsOfInterest.GroupBy(str => str.Substring(0, str.Length - 1))
    .ToDictionary(
        grp => grp.Key, 
        grp => grp.Select(str => str.Substring(1)).ToList()
    );