【问题标题】:Can anyone help me through what I think might be an infinite loop?谁能帮助我解决我认为可能是无限循环的问题?
【发布时间】:2014-08-08 03:41:48
【问题描述】:

我试图用下面的代码做的是一种组检查。我已使用组号将人员分配到组,因此:

fname lname  group
mark  anthony 2
macy  grey    3      etc..

我想防止任何两个名字和姓氏相同的人在同一个组中。所以我写了一个动作来尝试这样做,但我想我可能发现自己陷入了无限循环,无论哪种方式都不起作用。

def groupcheck(modeladmin, request, queryset):

    groups=[]
    N = 7       # number of groups
    for X in queryset:
        item = "".join([X.fname, X.lname, str(X.group)])     #the information I am trying to check 

        if item in groups:     # check if it is the array above (groups)
           while item in groups: 
             G = X.group
             Y = int(G) + int(1)    #change the group number
             if Y > N:      # This is my attempt to not allow the group number to be more than the number of groups i allowed (N)
                Y = 0
             removeditemnumber = ''.join([i for i in item if not i.isdigit()]) # I am removing the group number 
             item = removeditemnumber + str(Y)       # now I am trying to replace it
           groups.append(item)     #once the loop is done i want the edited version to be added to the array
           X.group = Y
           X.save()        # I want the new group number to be saved to the databse
        else:
           groups.append(item)

我尝试添加 cmets 以帮助指导代码,以防我做错了,如果这让我分心,请告诉我,我会删除它们,如果可以,请提供帮助

【问题讨论】:

    标签: python django django-admin django-views


    【解决方案1】:

    我从您的代码中删除了所有额外的内容。没有检查过。应该只有小错误。

      groups = []
      N = 7
    
      for X in queryset:
        item = "".join([X.fname, X.lname, str(X.group)])     
        nCount = 0
        while item in groups:
          X.group = (X.group + 1)%N 
          item = "".join([X.fname, X.lname, str(X.group)])  
    
          # This part only checks for a very stringent condition. Mostly 
          # unnecessary for real names. Only the couple of lines above
          # are meaningful as far as the code is concerned. 
          nCount += 1
          if nCount > N: 
            print X.fname, X.lname, 'exists in all', N, 'groups ...'
            sys.exit(1)
    
        groups.append(item)
    

    【讨论】:

    • 您应该只需要更新数据库中的X.group
    • 是的。要么就在之前,要么就在之后。这就是您希望通过群组更新完成的所有事情的地方。
    【解决方案2】:

    我建议完全重构它并采取不同的方法。您实际上是将组号映射到人群,所以这听起来像是使用字典的理想场所。试试这个:

    import pprint
    
    name_list = [
            "mark   anthony 2",
            "macy   grey    3",
            "bob    jones   4",  
            "macy   grey    6",  
            "mike   johnson 5",
            "macy   grey    6",
            "mark   anthony 2"]
    
    pprint.pprint(name_list)
    
    N = 7
    
    # create a dictionary where the keys are gorup numbers
    groups = {n:[] for n in xrange(N)}
    
    # this lambda function will increment the input up to N
    # then wrap around to zero
    increment = lambda x: x+1 if x+1 < N else 0
    
    for name in name_list:
        fname, lname, group_num = name.split()
    
        group_num = int(group_num)
        old_group = group_num
    
        # increment the group number while the name is in
        # the current group
        while (fname, lname) in groups[group_num]:
            group_num = increment(group_num)
            if group_num == old_group:
                # if we've checked all the groups and there's
                # no space for this name, raise exception
                raise NoMoreSpaceError
    
        # we found a spot! add the current name to the current
        # group number
        groups[group_num].append((fname, lname))
    
    pprint.pprint(groups)
    

    输出:

    ['马克安东尼 2',
    '梅西灰色 3',
    '鲍勃琼斯 4',
    '梅西灰色 6',
    '迈克约翰逊 5',
    '梅西灰色 6',
    '马克安东尼 2']

    {0: [('梅西', '灰色')],
    1:[],
    2:[('马克','安东尼')],
    3:[('梅西','灰色'),('马克','安东尼')],
    4:[('鲍勃','琼斯')],
    5:[('迈克','约翰逊')],
    6: [('梅西', '灰色')]}

    请注意,在输入中,有两个“mark anthony”实例分配给第 2 组,因此一个被撞到第 3 组。两个“macy gray”实例留在原处(第 3 组和第 6 组),因为他们在不同的组中,但是分配到第 6 组的第二个被撞到第 0 组。现在你最终得到了一个有组织的字典,我认为这段代码更容易遵循和维护。目前,如果某个特定名称的出现次数过多,我提出了一个例外,但您必须决定如何处理。

    【讨论】:

    • 任何关于如何使其为假的想法,我认为通过在循环结束时重新分配项目最终会是假的
    • @user3806832 你是对的,我对你的无限循环的评估是错误的。请参阅我的新答案。
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    • 2013-07-27
    相关资源
    最近更新 更多