How can I rewrite this piece of code so that it works faster? Currently the execution time is more than 10 seconds.
def