Skip to content

Instantly share code, notes, and snippets.

@lebinh
Created March 17, 2014 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lebinh/9594264 to your computer and use it in GitHub Desktop.
Save lebinh/9594264 to your computer and use it in GitHub Desktop.
from collections import Counter, deque
import sys
__author__ = 'binhle'
def next_line(stream, skip_blank_line=True, recursive_level=0, max_recursive_level=2):
" Read next line from input, skip blank line if needed. "
line = stream.readline().strip()
if line or not skip_blank_line:
return line
if recursive_level == max_recursive_level:
return None
return next_line(stream, recursive_level + 1)
def process_input(stream, buff):
" Read command from input stream and process. "
cmd = next_line(stream)
if cmd is not None:
cmd_type = cmd[0]
if cmd_type == 'A':
num = int(cmd[2:])
for i in xrange(num):
buff.append(next_line(stream))
elif cmd_type == 'R':
num = int(cmd[2:])
for i in xrange(num):
buff.popleft()
elif cmd_type == 'L':
for item in buff:
print item
elif cmd_type == 'Q':
return
process_input(stream, buff)
def q1(stream):
size = int(stream.readline())
buff = deque(maxlen=size)
process_input(stream, buff)
def print_buff(buff, max_print):
" Print max_print item from given buffer, return number of items printed. "
buff = sorted(buff)[:max_print]
if buff:
print '\n'.join(buff)
return len(buff)
def q2(stream):
N = int(next_line(stream))
counter = Counter()
for i in xrange(N):
counter.update([next_line(stream)])
k = int(next_line(stream))
buff = []
previous_count = sys.maxint
printed = 0
for word, count in counter.most_common():
if count == previous_count:
buff.append(word)
else:
printed += print_buff(buff, k - printed)
if printed == k:
# finished, printed k terms
return
buff = [word]
previous_count = count
print_buff(buff, k - printed)
def product(seq):
" Return product of all item in given seq. "
return reduce(lambda x, y: x * y, seq, 1)
def q3(stream):
N = int(next_line(stream))
source = []
number_of_zero = 0
for i in xrange(N):
num = int(next_line(stream))
if num == 0:
number_of_zero += 1
source.append(num)
if number_of_zero > 1:
# all output are zero
print '\n'.join(['0'] * N)
elif number_of_zero == 1:
# all except one are zero
total_product = product(num for num in source if num != 0)
for num in source:
print total_product if num == 0 else '0'
else:
# no zero
total_product = product(source)
for num in source:
print total_product / num
if __name__ == '__main__':
stream = sys.stdin if len(sys.argv) < 2 else open(sys.argv[1])
q1(stream)
# q2(stream)
# q3(stream)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment