简体   繁体   中英

What is the C# equivalent to this Python?

Originating from here , what would be the C# equivalent to this code? I think the ** is the exponent, but I don't know what [i] does.

def sequence(v, p, column):
    subsequence = []
    for i in range(v):
        subsequence += [i] * v**(p - column)
    return subsequence * v**(column - 1)

One could do:

public static List<int> sequence(int v, int p, int column) {
  var subsequence = new List<int>();
  for (int i = 0; i < v; i++) {
    int limit = (int)Math.Pow(v, p - column);
    for (int j = 0; j < limit; j++)
      subsequence.Add(i);
  }

  var true_sequence = new List<int>();
  for (int k = 0; k < (int)Math.Pow(v, column - 1); k++)
    true_sequence.AddRange(subsequence);

  return true_sequence;
}

[i] * <number> is notation for "repeat this list <number> times and put the result in a new list". [i] is just a list containing only the number i .

Edit: Explanation

for i in range(v):

translates well to:

for (int i = 0; i < v; i++) {
subsequence += [i] * v**(p - column)

This is a bit complicated, but what it essentially says is "take v, take it to the power of (p - column), and then add that number of i to subsequence". This is close to that:

int limit = Math.Pow(v, p - column);
for (int j = 0; j < limit; j++)
  subsequence.Add(i);
return subsequence * v**(column - 1)

Now what this says is "take v to the power of (column - 1), and return a list containing that many instances of subsequence." That's what the rest of the code in the function does: takes Math.Pow(v, column - 1) subsequences, adds them all to a list, and returns said list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM