trictionary?

Steven Bethard steven.bethard at gmail.com
Mon Aug 29 12:23:24 EDT 2005


Randy Bush wrote:
> Steven Bethard wrote:
>> It would probably help if you explained what the real problem is
>> you're trying to solve.
> 
> actually, that code fragment was meant to do that.  it's pretty much
> what i needed to do at that point, just the variable names made
> simple.

Yeah, I gathered that.  Sometimes though, you may not ever need to get 
to "that point" if the surrounding code can be properly reorganized. 
But I can't tell if that's possible unless you explain what the goal of 
the program is, not just how your current code tries to approach that goal.

So I'm going to try to pump you for a little more information here.  Is 
your goal to count, for each week, how many times it's "full" and how 
many times it's "not full"?  What do you use the counts for?  What does 
"full" mean?  Is it always a 0 or 1?  What's the importance of the 
output formatting?

> so, to do this using the real names, it looks like
> 
>    for [start, end, AS, full] in heard:
>       week = int((start-startDate)/aWeek)
>       if week in bin:
>          if full:
> 	    bin[week][0] += 1
> 	 else:
> 	    bin[week][1] += 1
>       else:
>          if full:
> 	    bin[week] = [1, 0]
> 	 else:
> 	    bin[week] = [0, 1]
>    ...
>    for i, (j, k) in bin.iteritems():
>       if j == 0:
> 	 print str(i) + ",," + str(k)
>       elif k == 0:
> 	 print str(i) + "," + str(j)
>       else:
> 	 print str(i) + "," + str(j) + "," + str(k)

For the current code, I'd probably go with something like:

     for start, end, AS, full in heard:
         week = int((start-startDate)/aWeek)
         if week in bin:
             bin[week][not full] += 1
         else:
             # I'm assuming "full" takes the values 0 or 1
             # but if not, you can coerce it with bool()
             bin[week] = [full, int(not full)]
    ...
    for i, (j, k) in bin.iteritems():
        result = [str(i), j and str(j) or '']
        # special-case k because if it's zero, the reference
        # code drops a comma
        if k:
            result.append(str(k))
        print ','.join(result)

But if you're just trying to count the number of times a week is full or 
not full, I'd probably do something like:

     for start, end, AS, full in heard:
         week = int((start-startDate)/aWeek)
         if week in bin:
             bin[week].append(full)
         else:
             bin[week] = [full]
    ...
    for i, fulls in bin.iteritems():
        j = sum(fulls)
        k = len(fulls) - j
        ...


STeVe



More information about the Python-list mailing list