简体   繁体   中英

How exactly does this work sum()?

This is in Python. I'm trying to figure out exactly how this works so I can translate it to Java.

numInversions = sum(
    state.index(START[j]) > state.index(START[i])
    for i in range(16) for j in range(i)  # each pair (i,j)
)  

Like this:

numInversions = 0
for i in range(16):
    for j in range(i):
        if state.index(START[j]) > state.index(START[i]):
            numInversions += 1

The > returns a bool , which is equivalent to 0 or 1 .

The Code is similar to the verbose format

numInversions = =
for i in range(16):
    for j in range(i):
        if state.index(START[j]) > state.index(START[i]):
            numInversions += 1

Except that the entire expression is wrapped as a generator expression and passed to the built-in sum

The nested loop construct is read from left to right so it unfoldes to

for i in range(16):
    for j in range(i):

The Condition which evaluates to a boolean True or False is summed up. So you end up counting all instances which the condition evaluates to True

The inner loop generates boolean values ( True and False ) based on the two nested loops. IN Python, booleans are a subclass of int and when summed act as 1 and 0 for True and False , respectively.

So, you could rewrite this as:

numInversions = 0
for i in range(16):
    for j in range(i):
        if state.index(START[j]) > state.index(START[i]):
            numInversions += 1

In (pseudo-)Java:

int numInversions = 0;
for (int i = 0; i < 16; ++i) {
  for (int j = 0; j < i; ++j) {
    if (state.index(START[j]) > state.index(START[i])) {
      ++numInversions;
    }
  }
}

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