Random Number Processing and Sum of Squares Calculation

  • Share this:

Code introduction


This function takes three arguments, generates a list of random numbers of specified length, removes non-numeric characters from each number in the list, calculates the sum of squares, and returns the result in JSON format.


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

Code Type : Function

Code Difficulty : Intermediate


                
                    
import os
import sys
import re
import json
import math
import random

def xxx(arg1, arg2, arg3):
    # 创建一个随机数列表,长度为arg1,每个元素在0到arg2之间
    random_list = [random.randint(0, arg2) for _ in range(arg1)]
    
    # 使用正则表达式找到所有非数字字符,并替换为空字符串
    cleaned_list = [re.sub(r'\D', '', item) for item in random_list]
    
    # 将列表中的字符串数字转换为整数
    int_list = [int(item) for item in cleaned_list]
    
    # 计算列表中所有元素的平方和
    sum_of_squares = sum([math.pow(item, 2) for item in int_list])
    
    # 将结果保存为JSON格式
    result = json.dumps({"sum_of_squares": sum_of_squares})
    
    return result