Random String, Circle Area, and Substring Analysis

  • Share this:

Code introduction


This function first generates a random string, then calculates the area of a circle with a given radius, then finds all occurrences of a specified substring within the random string, saves this information to a JSON file, and finally reads this information from the JSON file.


Technology Stack : random, string, math, re, json

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import math
import re
import json

def generate_random_string(length=10):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def calculate_area_of_circle(radius):
    return math.pi * (radius ** 2)

def find_all_substrings(input_string, substring):
    return [match.group(0) for match in re.finditer(f'(?={re.escape(substring)})', input_string)]

def save_data_to_json(data, filename):
    with open(filename, 'w') as file:
        json.dump(data, file)

def read_data_from_json(filename):
    with open(filename, 'r') as file:
        return json.load(file)

def xxx(arg1, arg2):
    random_string = generate_random_string(arg1)
    area = calculate_area_of_circle(arg2)
    substrings = find_all_substrings(random_string, 'a')
    data = {
        "random_string": random_string,
        "area_of_circle": area,
        "substrings": substrings
    }
    save_data_to_json(data, 'output.json')
    return read_data_from_json('output.json')