Friday, 10 January 2025

Day 84: Python Program to Sort Hyphen Separated Sequence of Words in Alphabetical Order

 


def sort_hyphenated_words(sequence):

    words = sequence.split('-')

    words.sort()

    sorted_sequence = '-'.join(words)

    return sorted_sequence

user_input = input("Enter a hyphen-separated sequence of words: ")

result = sort_hyphenated_words(user_input)

print(sorted sequence: {result}")

#source code --> clcoding.com 

Code Explanation:

Function Definition:
def sort_hyphenated_words(sequence):
A function sort_hyphenated_words is defined to handle the main task of sorting the hyphen-separated words. It takes a single parameter sequence, which is a string containing words separated by hyphens.

Splitting the Input Sequence:
words = sequence.split('-')
The input string is split into a list of words using the split('-') method. This separates the string at each hyphen (-) and stores the resulting parts in the list words.

Sorting the Words:
words.sort()
The sort() method is used to sort the list words in alphabetical order. This modifies the list in place.

Joining the Sorted Words:
sorted_sequence = '-'.join(words)
The sorted words are joined back together into a single string using '-'.join(words). The join() method concatenates the elements of the list, placing a hyphen (-) between them.

Returning the Sorted Sequence:
return sorted_sequence
The sorted sequence is returned as the output of the function.

Getting User Input:
user_input = input("Enter a hyphen-separated sequence of words: ")
The program prompts the user to enter a hyphen-separated sequence of words. The input is stored in the variable user_input.

Function Call and Displaying the Result:
result = sort_hyphenated_words(user_input)
print(f"Sorted sequence: {result}")
The sort_hyphenated_words function is called with the user's input as an argument. The result (sorted sequence) is then printed.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (81) AI (35) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (179) C (77) C# (12) C++ (82) Course (67) Coursera (231) Cybersecurity (24) data management (11) Data Science (129) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML Quiz (1) HTML&CSS (47) IBM (30) IoT (1) IS (25) Java (93) Java quiz (1) Leet Code (4) Machine Learning (61) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) pyth (1) Python (953) Python Coding Challenge (398) Python Quiz (53) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses