Python Utility Functions for Random Generation, File Handling, JSON, and Math

  • Share this:

Code introduction


These functions cover a range of functionalities from random number generation to file operations, to JSON handling and mathematical calculations.


Technology Stack : os, re, time, random, json, math

Code Type : Function

Code Difficulty :


                
                    
import os
import re
import time
import random
import json
import math

def generate_random_number(min_val, max_val):
    """
    Generate a random number between min_val and max_val (inclusive).
    
    :param min_val: The minimum value (inclusive).
    :param max_val: The maximum value (inclusive).
    :return: A random number between min_val and max_val.
    """
    return random.randint(min_val, max_val)

def is_palindrome(string):
    """
    Check if a string is a palindrome.
    
    :param string: The string to check.
    :return: True if the string is a palindrome, False otherwise.
    """
    return string == string[::-1]

def read_file_line_by_line(file_path):
    """
    Read a file line by line.
    
    :param file_path: The path to the file.
    :return: A list of lines from the file.
    """
    with open(file_path, 'r') as file:
        return file.readlines()

def format_time(timestamp):
    """
    Format a timestamp to a human-readable string.
    
    :param timestamp: The timestamp to format.
    :return: A formatted string representing the timestamp.
    """
    return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(timestamp))

def sort_list(lst):
    """
    Sort a list.
    
    :param lst: The list to sort.
    :return: A sorted list.
    """
    return sorted(lst)

def filter_even_numbers(lst):
    """
    Filter out even numbers from a list.
    
    :param lst: The list to filter.
    :return: A list containing only the odd numbers.
    """
    return [num for num in lst if num % 2 != 0]

def generate_unique_ids(length):
    """
    Generate a list of unique IDs of a specified length.
    
    :param length: The length of each ID.
    :return: A list of unique IDs.
    """
    return [f"{random.randint(1000, 9999):0{length}d}" for _ in range(10)]

def replace_substring(string, old, new):
    """
    Replace all occurrences of a substring in a string.
    
    :param string: The string to modify.
    :param old: The substring to replace.
    :param new: The substring to replace with.
    :return: The modified string.
    """
    return re.sub(old, new, string)

def calculate_area(radius):
    """
    Calculate the area of a circle.
    
    :param radius: The radius of the circle.
    :return: The area of the circle.
    """
    return math.pi * (radius ** 2)

def generate_random_color():
    """
    Generate a random color in hexadecimal format.
    
    :return: A string representing the random color in hexadecimal format.
    """
    return "#{:06x}".format(random.randint(0, 0xFFFFFF))

def read_json_file(file_path):
    """
    Read a JSON file.
    
    :param file_path: The path to the JSON file.
    :return: The content of the JSON file.
    """
    with open(file_path, 'r') as file:
        return json.load(file)

def write_json_file(file_path, data):
    """
    Write data to a JSON file.
    
    :param file_path: The path to the JSON file.
    :param data: The data to write.
    """
    with open(file_path, 'w') as file:
        json.dump(data, file)

def find_closest_number(lst, target):
    """
    Find the closest number in a list to a target number.
    
    :param lst: The list to search.
    :param target: The target number.
    :return: The closest number to the target.
    """
    return min(lst, key=lambda x: abs(x - target))

def calculate_average(numbers):
    """
    Calculate the average of a list of numbers.
    
    :param numbers: The list of numbers.
    :return: The average of the numbers.
    """
    return sum(numbers) / len(numbers) if numbers else 0