Editor

Try the Backup Server

#593 · Errors and exceptions · Intermediate · 65 XP · about 12 min

An app fetches data from a list of servers: the main one first, then backups. A server sometimes fails to answer and raises a ConnectionError, but it may answer if asked again. The Server class is provided: a Server(name, failures, data) fails its first failures calls to get(), then returns data, and counts its calls in calls.

Write fetch(servers, tries):

  • Ask the servers in order, giving each one up to tries calls to get().
  • As soon as a call works, return a tuple (data, name) with the data and the name of the server that answered. Do not call any more servers.
  • If every server fails all of its tries, raise ConnectionError('no server answered').

Examples

main = Server('main', 5, 'news')
backup = Server('backup', 1, 'old news')
fetch([main, backup], 3)  # returns ('old news', 'backup')
main.calls                # 3: main failed all three tries
backup.calls              # 2: backup failed once, then answered

Constraints

  • 1 <= tries <= 10
  • At most 100 servers.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.