جواب «Directional Rules» چالش 4 از جلسهی 67
سؤال
فایروالِ خانه فقط باید ترافیکِ خروجیِ وب را اجازه دهد. هر قاعده direction (in یا out)، port و action دارد. تابعِ decide(direction, port) را بنویس که اولین قاعدهی مناسب (جهت و پورت هر دو برابر) را اجرا کند و در غیرِ این صورت deny بدهد. بعد برای لیستِ packets هر بسته را به شکلِ out 443 -> allow چاپ کن.
راهنما
شرطِ تطبیق دو بخش دارد: rule["direction"] == direction and rule["port"] == port.
یک جواب درست
rules = [
{"direction": "out", "port": 80, "action": "allow"},
{"direction": "out", "port": 443, "action": "allow"},
{"direction": "in", "port": 443, "action": "deny"},
]
packets = [("out", 443), ("in", 443), ("in", 22), ("out", 80)]
def decide(direction, port):
for rule in rules:
if rule["direction"] == direction and rule["port"] == port:
return rule["action"]
return "deny"
for direction, port in packets:
print(direction, port, "->", decide(direction, port))
اول خودت امتحان کن؛ جوابهای دیگر هم قبول است. برگرد و خودت حلش کن