代码之家  ›  专栏  ›  技术社区  ›  BioGeek

给一些小的和大的数字,做所需的数字-没有循环

  •  1
  • BioGeek  · 技术社区  · 15 年前

    我正在解决编码问题 codingbat 在蟒蛇中。这个 make_bricks 问题定义为:

    我们要做一排砖,目标是英寸长。我们有一个号码 小砖块(每个1英寸)和大砖块 砖(每个5英寸)。如果返回真 有可能通过 从给定的砖块中选择。这个 比看起来难一点 不需要任何循环就可以完成。

    make_bricks(3, 1, 8) → True
    make_bricks(3, 1, 9) → False
    make_bricks(3, 2, 10) → True
    

    我提出的第一个解决方案是:

    from itertools import permutations
    
    def make_bricks(small, big, goal):
        l = small*[1]+big*[5]
        return any([(goal in i) for i in ([[sum(j) for j in set(permutations(l,i))] \
        for i in range(2,len(l)+1)])])
    

    这是正确的,但被判断软件拒绝,因为不允许进口。 所以我的下一个解决方案是:

    def make_bricks(small, big, goal):
        bricks = small*[1]+big*[5]
        for step in range(len(bricks)+1,1,-1):
            for start in range(len(bricks)):
                if len(bricks[start:start+step])==step:
                    if sum(bricks[start:start+step])==goal:
                        return True
        return False
    

    这也是正确的,但在输入时会出现超时,比如 make_bricks(1000000, 1000, 1000100) .

    那么,在不使用导入、不使用循环和时间限制的情况下,如何在Python中解决这个问题呢?

    8 回复  |  直到 10 年前
        1
  •  5
  •   lijie    15 年前

    S B L

    K = min(B, L div 5) L - 5K

    div

    L-K L-5K

        2
  •  10
  •   Zoozy    14 年前
    def make_bricks(small, big, goal):
      if goal > small + big * 5:
        return False
      else:
        return goal % 5 <= small
    
        3
  •  4
  •   Frank    15 年前

        4
  •  1
  •   CashCow    15 年前

        5
  •  1
  •   Hugh Bothwell    15 年前

    def make_bricks(small, big, goal):
      # minimum number of 1s needed
      rem = goal % 5   # ex: 19 % 5 == 4
    
      if rem > small:
        # too few 1s
        return false
      else:
        # we have enough 1s; deduct what we just used
        small -= rem
        goal -= rem
    
        # now see if what's left will fill the rest of the hole
        return small + 5*big >= goal
    

        6
  •  1
  •   Guest    13 年前
    def make_bricks(s,b,g):
      return not(g>b*5+s or g%5>s)
    

        7
  •  0
  •   Fahd    11 年前



        8
  •  0
  •   NerdyLawman    10 年前

    def make_bricks(small, big, goal):
      if int(goal/5) < big:
        big -= big - int(goal/5)
      return big*5 + small >= goal