Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Ouch, good catch! I can't think of a nice way to salvage reduce but these are some clever alternatives. Point anti-reduce.


This doesn't salvage it in any meaningful sense, but it does work:

  class EqualLengths:
    def __init__(self, size):
      self.size = size
    def __nonzero__(self):
      return True
    def __repr__(self):
      return "True"
  
  def equal_lengths(a, b):
    if isinstance(a, EqualLengths):
      if a.size == len(b):
        return a
      return False
    if a is False:
      return a
    n = len(a)
    if n == len(b):
      return EqualLengths(n)
    return False

  >>> reduce(equal_lengths, ["a", "b", "cc", "d"])
  False
  >>> reduce(equal_lengths, ["a", "b", "c", "d"])
  True
However, I could do something similar with sum():

  class SumEqual:
    def __init__(self):
      self.size = None
      self.is_equal = True
        
    def __add__(self, other):
      if self.is_equal:
        if self.size is None:
          self.size = len(other)
        else:
          self.is_equal = (self.size == len(other))
      return self
      
    def __nonzero__(self):
      return self.is_equal
      
    def __repr__(self):
      return repr(self.is_equal)


  >>> sum(["a", "b", "cc", "d"], SumEqual())
  False
  >>> sum(["a", "b", "c", "d"], SumEqual())
  True
and unlike the first case, this sum() solution will work when there are fewer than two items in the list.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: