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.
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) response.raise_for_status() 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 else: 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]}') else: 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.
Here’s a solution in Python.
import json import sys import urllib.request assert len(sys.argv) == 2, 'ID argument required' url = f'https://oeis.org/search?q=id:{sys.argv[1]}&fmt=json' with urllib.request.urlopen(url) as u: body = u.read() data = json.loads(body)['results'][0]['data'].split(',') print('\n'.join(data))Example Usage: