1

How do I read the next integer ignoring whitespace in Python 3? Is there a way to make a generator that returns integers from a stream of whitespace-separated integers?

The best I have is this:

def ints():
    while True:
        yield from (int(x) for x in input().split())
8

2 Answers 2

3

Complete ignoring white space and reading from a file (treating an integer purely as consecutive digits):

import mmap
import re

with open('somefile', 'rb') as fin:
    mf = mmap.mmap(fin.fileno(), 0, access=mmap.ACCESS_READ)
    for digits in re.finditer('(\d+)', mf):
        print(digits.group(1))

Or, if you've already got everything in a string, then adapt the finditer appropriately, maybe something like:

yield from (match.group(1) for match in re.finditer('\d+', some_string))
Sign up to request clarification or add additional context in comments.

1 Comment

I deleted my attempt because I prefer this method. +1
0

If you are reading from stdin, you can do this:

import sys

def ints():
    for line in sys.stdin:
        rtr=[int(d) for d in line.split() if d.isdigit()] 
        if rtr:
            for n in rtr:
                yield n

print(list(ints()))

Or, if your Py 3.3+ supports generator delegation:

import sys

def ints():
    for line in sys.stdin:
         yield from (int(d) for d in line.split() if d.isdigit())

You can also use the very slick fileinput which has the advantage of supporting both a file name (and the file by that name will then be opened and read) or input from the redirected stdin:

import fileinput

def ints():
    for line in fileinput.input():
        yield from (int(d) for d in line.split() if d.isdigit())

(If you test fileinput directly or manually, know that you need to end the input with two CtlD's -- not just one....)

3 Comments

I'd probably go for iter(input, '') here instead of the while True and sys.stdin.readline()
@JonClements: I think just using for line in sys.stdin: instead of While True is even better. Thanks!
I would replace []-s to ()-s in the generator expressions.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.