简体   繁体   中英

Find how many times changes maximum value in a list with reduce() (Python)

Using reduce() function, I have to find how many times the maximum value of a list changes. Here's my code, but I don't undestand why count remains to 0.

from functools import reduce

count = 0

heights = [10, 8, 11, 2, 1, 4, 13, 11]

reduce(lambda a, b: count + 1 if a < b else count + 0, heights, 0)

print(count)

The way reduce works is as follows:

  • Take the default value (last parameter) and the first element of the sequence, and apply the provided function. Here, we take 0 and 10 , and compute: count + 1 if 0 < 10 else count + 0 .

  • Take the result from that operation, and apply the function to that and the second element, and so on.

You can't expect to solve the problem this way, because none of this actually reassigns count - it stays equal to 0 no matter how many times this iterates. Each application of the lambda just produces either 0 or 1 . Also, these 0 and 1 values are carried forward to the next step, instead of remembering the previous maximum value.

reduce is not the right tool for this job , but you can force it to work by computing a tuple of (maximum value seen so far, count) at each step. (You need to actually use the value returned by reduce , and not have any external count .)

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