0
0
Rest APIprogramming~10 mins

Token bucket algorithm in Rest API - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to initialize the token bucket with the correct capacity.

Rest API
token_bucket = {"capacity": [1], "tokens": 0, "rate": 5}
Drag options to blanks, or click blank then click option'
A1
B5
C10
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Setting capacity to 0 or rate instead of capacity.
2fill in blank
medium

Complete the code to add tokens to the bucket without exceeding capacity.

Rest API
token_bucket["tokens"] = min(token_bucket["tokens"] + [1], token_bucket["capacity"])
Drag options to blanks, or click blank then click option'
Atoken_bucket["rate"]
Btoken_bucket["capacity"]
C1
Dtoken_bucket["tokens"]
Attempts:
3 left
💡 Hint
Common Mistakes
Adding capacity or tokens instead of rate.
3fill in blank
hard

Fix the error in the code to check if enough tokens are available for a request.

Rest API
if token_bucket["tokens"] >= [1]:
    token_bucket["tokens"] -= [1]
    allowed = True
else:
    allowed = False
Drag options to blanks, or click blank then click option'
Arequest_tokens
Btoken_bucket["capacity"]
Ctoken_bucket["rate"]
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Using rate or capacity instead of request_tokens.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that tracks tokens per user if tokens are above zero.

Rest API
user_tokens = {user: [1] for user, tokens in token_data.items() if tokens [2] 0}
Drag options to blanks, or click blank then click option'
Atokens
B>
C<
Duser
Attempts:
3 left
💡 Hint
Common Mistakes
Using user as value or wrong comparison operator.
5fill in blank
hard

Fill all three blanks to create a dictionary of users with tokens less than capacity and map user to tokens plus one.

Rest API
updated_tokens = { [1]: [2] + 1 for [3], tokens in token_data.items() if tokens < token_bucket["capacity"] }
Drag options to blanks, or click blank then click option'
Auser
Btokens
Dtoken
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names or mixing key and value.