0

I've been told to

By using a dictionary (or your solution to Part 4), write a method at_least(a, n) that takes a list, a, and an integer, n, as arguments and returns a list containing only the elements of a that occur at least n times. For complete marks, the list should contain the elements in order of their first occurrence in a.

I was able to figure this without using a dictionary, with

def at_least2(a, n):
    return [x for x in a if a.count(x) is n]

I was wondering how I can write this using a dictionary?

The input is:

a = [-6, 8, 7, 3, 2, -9, 1, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, 1, 
     -9, -3, -7, -3, -5, 6, -3, 6, -3, -10, -8]

def at_least(a, 2):

and the output:

[8, 7, 2, -9, 1, -3, 2, -8, 7, 8, 2, -7, 1, -9, -3, -7, -3, 6, -3, 6, -3, -8]

Edit:

I don't understand how a dictionary is being used, yet the output isn't in dictionary form? My understanding is that dictionaries have values for each object. I'm not sure if I'm using the right terms.

1
  • Note: your at_least2 function doesn't work. (1) Your assignment requests "at least n", but your code tries to find exactly n. (2) is in Python tests identity, not equality. You want >= n anyway, but even if you wanted "==", using is would only work when Python happened to reuse the same integer object. (Imagine writing "117" on a card. You might only have one card, in which case 117 is 117 is True, but you might have two such cards, in which case (this) 117 is (that) 117 would be False, but you'd still have (this) 117 == (that) 117.)
    – DSM
    Oct 15, 2012 at 7:56

5 Answers 5

1

best option here is collections.Counter():

from collections import Counter
def atleast(a,n):
    c=Counter(a)
    return [x for x in c if c[x]>=2]

a = [-6, 8, 7, 3, 2, -9, 1, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, 1, -9, -3, -7, -3, -5, 6, -3, 6, -3, -10, -8]
print atleast(a,2)

output:

[1, 2, 6, 7, 8, -9, -8, -7, -3]

Or you can also use setdefault():

>>> a = [-6, 8, 7, 3, 2, -9, 1, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, 1, -9, -3, -7, -3, -5, 6, -3, 6, -3, -10, -8]
>>> dic={}
>>> for x in a:
...   dic[x]=dic.setdefault(x,0)+1
... 
>>> dic
{0: 1, 1: 2, 2: 3, 3: 1, 4: 1, 6: 2, 7: 2, 8: 2, -10: 1, -9: 2, -8: 2, -7: 2, -6: 1, -5: 1, -4: 1, -3: 5, -2: 1}
1
  • @RohitJain Counter returns an sub-class of dict only. Oct 15, 2012 at 7:53
0

Use defaultdict:

In [7]: l=[1,2,34,436,1,2,3,4,12,3,2,1]

In [8]: import collections
   ...: d = collections.defaultdict(int)
   ...: for x in l: d[x] += 1
   ...: 

In [9]: d
Out[9]: defaultdict(<type 'int'>, {1: 3, 2: 3, 3: 2, 4: 1, 12: 1, 34: 1, 436: 1})

just a dict:

d = {}
[d.__setitem__(item,1+d.get(item,0)) for item in l]
print d

{1: 3, 2: 3, 3: 2, 4: 1, 12: 1, 34: 1, 436: 1}

or using count:

d=dict( [ (i, l.count(i)) for i in set(l) ] )

get the items that occour more than once as a list:

In [17]: [x for x in set(l) if d[x] > 1]
Out[17]: [1, 2, 3]

get the items that occour more than once as a dict:

In [21]: dict( [ (i, l.count(i)) for i in set(l) if l.count(i) > 1 ] )
Out[21]: {1: 3, 2: 3, 3: 2}
1
  • I'm not sure if I'm allowed to use defaultdict. Haven't heard it mentioned in class Oct 15, 2012 at 7:24
0
def atLeast(a,n):
    A = {}
    for i in a:
        if i not in A:
            A[i] = 0
        A[i] += 1 

    new_a = []
    for i in a: 
        if A[i] >= n:
            new_a.append(i)
    return new_a 

for complete marks:

def atLeast(a,n):
    A = {}
    for i in a:
        if i not in A:
            A[i] = 0
        A[i] += 1 

    new_a = []
    Appended = {} 
    for i in a: 
        if i in Appended:
            continue 
        Appended[i] = 0 
        if A[i] >= n:
            new_a.append(i)
    return new_a 
0

My take on this, using only a dict and not collections etc...

For each element in mylist, create a value->list lookup, so we know that value is unique, and that len(value) is the number of occurences, and value[0] is the index of the first occurrence.

mylist = [-6, 8, 7, 3, 2, -9, 1, -3, 2, -4, 4, -8, 7, 8, 2, -2, -7, 0, 1, -9, -3, -7, -3, -5, 6, -3, 6, -3, -10, -8]
mydict = {}
for idx, val in enumerate(mylist):
    mydict.setdefault(val, []).append(idx)

Which makes mydict:

{0: [17], 1: [6, 18], 2: [4, 8, 14], 3: [3], 4: [10], 6: [24, 26], 7: [2, 12], 8: [1, 13], -10: [28], -9: [5, 19], -8: [11, 29], -7: [16, 21], -6: [0], -5: [23], -4: [9], -3: [7, 20, 22, 25, 27], -2: [15]}

We can get the elements which appear more than once (this using a list comprehension):

something = [k for k, v in mydict.iteritems() if len(v) > 1]
print something
# [1, 2, 6, 7, 8, -9, -8, -7, -3]

But, to get that extra credit, we can then sort it to return the original order by using:

something.sort(key=mydict.get)
print something
# [8, 7, 2, -9, 1, -3, -8, -7, 6]
0

Try the below code: -

>>> l=[1,2,34,436,1,2,3,4,12,3,2,1]
>>> dic = {}

>>> for x in l:
        if x in dic:
            dic[x] += 1
        else:
            dic[x] = 1


>>> dic
{1: 3, 2: 3, 3: 2, 4: 1, 12: 1, 34: 1, 436: 1}

# Get list of (key, value) tuple, for key occuring more than once.
>>> list_new = [(key, value) for key, value in dic.iteritems() if dic[key] > 1] 
>>> list_new
[(1, 3), (2, 3), (3, 2)]

# Create dictionary out of list
>>> dic2 = dict(list_new)
>>> dic2
{1: 3, 2: 3, 3: 2}
2
  • don't use has_key() it's deprecated. use if x in dic. Oct 15, 2012 at 7:54
  • @AshwiniChaudhary I was trying this thing only. But I used x in dic.keys(). Didn't work so finally i used that..
    – Rohit Jain
    Oct 15, 2012 at 7:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.