【问题标题】:I don't think it spend that much time (for - if condition checking loops), is there a better way?我认为它不会花费太多时间(对于 - 如果条件检查循环),有没有更好的方法?
【发布时间】:2019-09-11 07:51:59
【问题描述】:

我认为它不会花费太多时间,但它花费的时间比我预期的要多。

我认为如果是问题的话。

是什么让它需要很多次?

有没有更好的方法来减少时间?

问题是

n = 花数

a, b = 花的开花日期(月、日) c, d = 花落日期(月、日)

(当花落的日期你看不到那朵花) (如果 0530 是秋天的日期,那么你就看不到 0530 的那朵花)

我想每天从0301~1130看花

打印最少需要的花

有人告诉我这是贪心算法问题。

我不知道如何减少时间了

我认为这是解决这个问题的正确方法

下面是我的代码

flo_list = []

n = int(input())

for i in range(n) :
    a, b, c, d = map(int, input().split())
    flo_list.append((a*100 + b, c*100 + d))

flo_list.sort(reverse = True)

cnt = 0

srt_flo = sorted(flo_list, key = lambda i : i[1], reverse = True)

if flo_list[-1][0] > 301 :
    print(0)
    exit()

if srt_flo[0][1] < 1201 :
    print(0)
    exit()

for (i, j) in srt_flo :
    if i <= 301 :
        (f, e) = (i, j)
        cnt = cnt + 1
        break

while e < 1201 :

    for (i, j) in srt_flo :
        if f < i <= e :
            (f, e) = (i, j)
            cnt = cnt + 1
            break

    else :
        cnt = 0
        break


print(cnt)

【问题讨论】:

    标签: python for-loop if-statement


    【解决方案1】:

    你应该试试这样的:

    from itertools import combinations
    
    for comb_len in range(1,n) :    # `n` -- is the total number of flowers
        for comb in combinations( range(n), comb_len ) :
            if this_combination_covers_all_dates( comb ) :
                print 'need', comb_len, 'flowers', comb
    

    this_combination_covers_all_dates( comb ) 的实现由你决定 =)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      • 2019-01-31
      • 1970-01-01
      • 2016-12-08
      • 2012-05-02
      • 1970-01-01
      相关资源
      最近更新 更多