Skip to content

Instantly share code, notes, and snippets.

@joebeeson
Last active August 28, 2020 15:10
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 joebeeson/6fe9fc78394dec23e552a2fc84c2b4d2 to your computer and use it in GitHub Desktop.
Save joebeeson/6fe9fc78394dec23e552a2fc84c2b4d2 to your computer and use it in GitHub Desktop.
Read arbitrarily large input, print number closest to zero
from itertools import islice, tee
# Assume an input such:
#
# 3
# 1 -3 4
# 2
# 8 9
# 0
#
# 4
# 1 3 8 2
#
# Where the first line indicates the number of integers to be found
# on the next line: find the number on the next line that is nearest
# to zero (0)
with open("/dev/stdin") as file_:
# Split the `file_` into two iterators...
cnt_iter, num_iter = tee(file_)
# ... slice each to return every other row but start `num_iter`
# from index 1 ...
cnt_iter = islice(cnt_iter, 0, None, 2)
num_iter = islice(num_iter, 1, None, 2)
# ... iterate both iterators together ...
for nums, line in zip(cnt_iter, num_iter):
if int(nums) > 0:
# ... map each into an `int` and get the minimum as is
# reported by `abs()` -- this "ignores" negative value
# but still lets us retain their sign.
ints = map(int, line.split())
low_ = min(ints, key=abs)
print(low_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment