Last active
January 20, 2025 08:34
-
-
Save deepanshumehtaa/835898c87aa91da9a1ea9bbc09fed775 to your computer and use it in GitHub Desktop.
python_timed_cache.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
from functools import wraps | |
def timed_cache(expiration): | |
cache = {} | |
def decorator(func): | |
@wraps(func) | |
def wrapper(*args): | |
now = time.time() | |
if args in cache: | |
value, timestamp = cache[args] | |
if now - timestamp < expiration: | |
return value # Return cached value | |
result = func(*args) | |
cache[args] = (result, now) # Update cache | |
return result | |
return wrapper | |
return decorator | |
# Usage example | |
@timed_cache(expiration=10) # Cache expires after 10 seconds | |
def expensive_function(x): | |
print(f"Computing for {x}...") | |
return x * x | |
print(expensive_function(2)) | |
li = [{"k1": "swati", "k2": "deepanshu"}, {"k1": "neha", "k2": "megha"}, ] | |
mapp = {} | |
for d in li: | |
in_map = {} | |
first_key = None | |
for k,v in d.items(): | |
if first_key: | |
in_map[first_key] = v | |
mapp.update(in_map) | |
else: | |
first_key = v | |
in_map[v] = "" | |
print(mapp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment