Zebra Function: URL Query Parsing, String Manipulation, and Timestamp Generation

  • Share this:

Code introduction


The function accepts five arguments and uses multiple built-in libraries to generate a random string, rotate the ASCII alphabet, reverse a string, parse URL query parameters, and generate a timestamp, finally returning these informations as a JSON string.


Technology Stack : random, collections, typing, datetime, urllib.parse, string, json

Code Type : Function

Code Difficulty : Advanced


                
                    
def zebra(arg1, arg2, arg3, arg4):
    import random
    from collections import deque
    from typing import List
    from datetime import datetime
    from urllib.parse import urlparse
    from string import ascii_lowercase
    
    # Generate a random string using the first two letters from arg1, the last two letters from arg2,
    # the middle two letters from arg3, and the first and last letters from arg4.
    random_string = f"{arg1[:2]}{arg2[-2:]}{arg3[1:-1]}{arg4[0]}{arg4[-1]}"
    
    # Create a deque from the ASCII lowercase letters and rotate it by the length of the random string.
    letters_deque = deque(ascii_lowercase)
    letters_deque.rotate(len(random_string))
    
    # Extract the rotated letters to form a new string.
    rotated_string = ''.join(letters_deque)
    
    # Convert the rotated string into a list and reverse it.
    reversed_list = rotated_string[::-1]
    
    # Parse a URL from arg5 and extract the query parameters.
    url = urlparse(arg5)
    query_params = dict(urlparse(url.query).parse_qs())
    
    # Create a timestamp string.
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # Return a JSON string with all the generated information.
    return json.dumps({
        "random_string": random_string,
        "rotated_string": rotated_string,
        "reversed_list": reversed_list,
        "query_params": query_params,
        "timestamp": timestamp
    })