Fetch OEIS Sequences

May 21, 2019

I needed to fetch several sequences from the OEIS the other day. We’ve done that in a previous exercise, in Scheme, but I wanted something I could run from the command line. So I wrote a program.

Your task is to write a program, called from a normal shell command line, that fetches a sequence from OEIS. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.


Pages: 1 2

One Response to “Fetch OEIS Sequences”

  1. Alex B. said

    Since OEIS offers a nice JSON format, I thought I’d take advantage:

    #! /usr/bin/env python3
    import sys
    import requests
    OEIS_URL = 'https://oeis.org/search'
    def get_seq(seq_name):
        """Fetch and return an OEIS sequence in JSON format"""
        params = {
            'q': f'id:{seq_name}',
            'fmt': 'json',
        response = requests.get(OEIS_URL, params)
        return response.json()
    def extract_seq(seq_json):
        """Extract and return the sequences from OEIS JSON data"""
        results = seq_json['results']
        seqs = dict()
        for result in results:
            number = result['number']
            a_id = f'A{number:06}'
            seqs[a_id] = result['data']
        if seqs:
            return seqs
            return None
    if __name__ == '__main__':
        seq_id = sys.argv[1]
        seq_json = get_seq(seq_id)
        seq_data = extract_seq(seq_json)
        if seq_data is not None:
            for seq in seq_data:
                print(f'{seq}: {seq_data[seq]}')
            print('No sequence found')

    get_seq adds the ‘id:’ prefix to the search term, so only one sequence is fetched. Next step is to add command line switches to control that behaviour, so multiple sequences can be fetched at once.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: