0

I have the following piece of code:

def getresult (someset):
    result = []
    index = 0
    for key, value in mydict.items():
        if someset.issubset(value):
            result.append(key)
    while (len(result)<10):
        index = index+1
        someset = someset[index:]
        getresult(someset)
    return result

The idea is that I want to find out if someset is a subset of some list. If it's not, I want to slice the set until I get results (if it gets to the point where the set only contains one element, results are bound to be found, so endless looping shouldn't be a problem here).

The code above gives me an error: TypeError: 'set' object has no attribute 'getitem' Which, I assume, means that I'm not supposed to use a variable name inside the slice.

  • Is it possible to increment a slice?
  • If not (or if you believe that slicing won't get the result I'm expecting anyway), is there another way I can loop through a set, ignoring one more element on each loop?
kormak
  • 495
  • 2
  • 5
  • 15
  • 1
    The error means that you cannot slice a set. They are unordered, so the slicing wouldn't be deterministic. – Ben Nov 01 '14 at 23:52
  • Instead of slicing, you can use someset.pop() method to remove an arbitrary element form set – miszczu Nov 01 '14 at 23:56
  • I would look at this answer: http://stackoverflow.com/a/5898031/57158 to generate a powerset of combinations from the set, and check to see if each one is in the list. – Ben Nov 01 '14 at 23:58
  • Also, you do not have a break statement in your loop, it will be infinte if the size of result is smaller than 10 – miszczu Nov 02 '14 at 00:03
  • @Ben I've looked at the answer you've linked, but I'm not sure a powerset is what I need, because I'm not sure it would iterate in the right order. If there were originally 5 elements in the set, I want to select 4 of those next, then 3, then 2, etc. – kormak Nov 02 '14 at 02:21
  • Well you control that in that for loop in his first example. His one takes all single elements, then pairs, then threes, etc - so just reverse the loop. – Ben Nov 02 '14 at 08:52

1 Answers1

0

After reading everyone's comment, I've realized there was a much simpler way of getting the result I wanted.

For posterity, here it it is:

for key, value in mydict.items():
    for i in someset:
        if i in value:
            mylist.append(key)

Then, I can simply use a counter to make a frequency dictionary out of my list, and make a list of the keys with the highest values :

tmpdict = Counter(mylist)
finallist = [i for (i,j) in tmpdict.items() if j >= 2]
#if j >=2, then k originally had more than 2 elements of someset as a value
kormak
  • 495
  • 2
  • 5
  • 15