Random String Generation, Average Calculation, and Sorting in Python

  • Share this:

Code introduction


This code block defines a main function `main` that utilizes random string generation, average calculation, and sorting techniques.


Technology Stack : Python

Code Type : Python Function

Code Difficulty : Intermediate


                
                    
import random

def random_string(length=10):
    letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    return ''.join(random.choice(letters) for i in range(length))

def calculate_average(numbers):
    return sum(numbers) / len(numbers) if numbers else 0

def sort_words(words):
    return sorted(words, key=len)

def main():
    arg1 = random_string(5)
    arg2 = [random.randint(1, 100) for _ in range(5)]
    arg3 = ['apple', 'banana', 'cherry', 'date', 'elderberry']
    
    average = calculate_average(arg2)
    sorted_words = sort_words(arg3)
    
    print(f"Average of {arg2}: {average}")
    print(f"Sorted words by length: {sorted_words}")

main()                
              
Tags: