junk
BAN USERFool!
Python:
I didn't use any modules. collections.Counter(list).most_common(1)
would get most common element in a list right away
push -> just appends the given element to the stack
pop -> identifies common element, remove it from stack and return it to user
pop(): for a given list [2,2,2,1,1,3]
if length of stack is zero, throw an "Stack Empty" exception
else
convert the list to element's count and element [2,2,2,1,1,3] --> [(3, 2), (2, 1), (1, 3)]
sort and retrieve the last element -> [(1,3), (2,1), (3,2)] --> (3,2)
(3, 2) -> count is 3 and element is 2
remove element (2) from stack.
return the element (2)
class Stack(object):
""" Stack which pops out most common element """
def __init__(self, tlst=None):
if tlst is None:
tlst = []
self._stack = tlst
def push(self, elm):
self._stack.append(elm)
def pop(self):
if len(self._stack) == 0:
raise Exception('Stack is Empty')
stack = list(set(map(lambda x: (self._stack.count(x), x), \
self._stack)))
elm = sorted(stack, key=lambda e:e[0])[-1]
self._stack = filter(lambda x: x!=elm[1], self._stack)
return elm[1]
Testing:
>>> stack = Stack()
>>> stack.push(2)
>>> stack.push(2)
>>> stack.push(2)
>>> stack.push(1)
>>> stack.push(1)
>>> stack.push(3)
>>> stack._stack
[2, 2, 2, 1, 1, 3]
>>> stack.pop()
2
>>> stack._stack
[1, 1, 3]
>>> stack.pop()
1
>>> stack._stack
[3]
>>> stack.pop()
3
>>> stack._stack
[]
>>> stack.pop()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 10, in pop
Exception: Stack is Empty
>>>
Python:
If i can use inbuilt functions, below one would help answer your question?
def getindices(tlist, n):
indices = [-1,-1]
if tlist.count(n):
indices = map(lambda i: tlist.index(i[1], i[0]), \
enumerate([n] * tlist.count(n), tlist.index(n)))
indices = [indices[0], indices[-1]]
return indices
Testing:
>>> getindices([1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5], 4)
[8, 11]
>>> getindices([1, 1, 1, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5], 11)
[-1, -1]
>>>
Python:
I'm using itertools.combinations to find combinations of a given list. If i cant use these modules, this function can be replaced by a user defined function.
import itertools
def getindices(tlist, n):
clist = []
if n in tlist:
clist.append(tlist.index(n))
for i in xrange(2, len(tlist)+1):
for c in itertools.combinations(tlist, i):
if sum(c) == n:
clist.append(map(lambda n: tlist.index(n[1], n[0]), \
enumerate(c)))
for each in clist[:]:
if clist.count(each) > 1 or \
type(each) is list and clist.count(each[::-1]) > 1:
clist.remove(each)
return clist
Testing:
tlist = [1, 7, 3, 4, 5, 6, 2]
for i in xrange(1, len(tlist)+1):
print i, '==>', getindices(tlist, i)
1 ==> [0]
2 ==> [6]
3 ==> [2, [0, 6]]
4 ==> [3, [0, 2]]
5 ==> [4, [0, 3], [2, 6]]
6 ==> [5, [0, 4], [3, 6], [0, 2, 6]]
7 ==> [1, [0, 5], [2, 3], [4, 6], [0, 3, 6]]
Python: (Corrected)
- junk July 15, 2013