johnklee / fpu

Functional programming utility
MIT License
4 stars 4 forks source link

I would like to show case of leetcode question 2824 #25

Closed johnklee closed 1 year ago

johnklee commented 1 year ago

For Leetcode question 2824. Count Pairs Whose Sum is Less than Target, without FPU, my solution is as below:

class Solution:
    def countPairs(self, nums: List[int], target: int) -> int:
        nums_length = len(nums)
        def pair_gen(pos):
            v1 = nums[pos]
            for v2 in nums[pos+1:]:
                yield v1 + v2

        def chain_generator(generators):
            for gen in generators:
                for v in gen:
                    yield v

        return sum(map(lambda v: v < target, chain_generator(pair_gen(v) for v in range(nums_length))))

With FPU, I would like to resolve this question this way:

from fpu.flist import *
from typing import List as L

class FPUSolution:
  def countPairs(self, nums: L[int], target: int) -> int:
    return (
      # nums = [-1, 1, 2, 3, 1]
      comp(nums, 2)
        .map(lambda t: t[0] + t[1])  # [(-1, 1), (-1, 2), ...,(3, 1)] -> [0, 1, ..., 4]
        .map(lambda v: v < target)   # [0, 1, ..., 4] -> [True, True, ..., False]
        .sum())                      # [True, True, ..., False] -> Count the number of True
johnklee commented 1 year ago

Done with demo in this notebook.