Showing posts with label 100 Python Programs for Beginner. Show all posts
Showing posts with label 100 Python Programs for Beginner. Show all posts

Friday, 24 January 2025

Day 100: Python Program to Count the Frequency of Each Word in a String using Dictionary

def count_word_frequency(input_string):

    """

    Counts the frequency of each word in the input string.


    Args:

        input_string (str): The input string.


    Returns:

        dict: A dictionary with words as keys and their frequencies as values.

    """

    words = input_string.split()

    word_count = {}

    for word in words:

        word = word.lower()  

        if word in word_count:

            word_count[word] += 1

        else:

            word_count[word] = 1

       return word_count

input_string = input("Enter a string: ")

word_frequency = count_word_frequency(input_string)

print("\nWord Frequency:")

for word, count in word_frequency.items():

    print(f"'{word}': {count}")

#source code --> clcoding.com 

 Code explanation:

Function Definition
def count_word_frequency(input_string):
Purpose: This defines a function named count_word_frequency that accepts one parameter, input_string. The function calculates how many times each word appears in the given string.

Docstring
    """
    Counts the frequency of each word in the input string.

    Args:
        input_string (str): The input string.

    Returns:
        dict: A dictionary with words as keys and their frequencies as values.
    """
Purpose: Provides documentation for the function. It explains:
What the function does: It counts the frequency of words in the string.
Arguments: input_string, the string input.
Return Value: A dictionary where each word is a key, and its value is the word’s frequency.

Splitting the String
    words = input_string.split()
What it does:
The split() method divides the string into words, using spaces as the default separator.
Example: "Hello world!" becomes ['Hello', 'world!'].

Initialize the Dictionary
    word_count = {}
What it does: Creates an empty dictionary word_count to store each word as a key and its frequency as the corresponding value.

Loop Through Words
    for word in words:
What it does: Iterates through the list of words obtained from the split() method.

Normalize the Word
        word = word.lower()
What it does: Converts the current word to lowercase to handle case insensitivity.
Example: "Word" and "word" are treated as the same.

Update Word Count in Dictionary
Check if Word Exists
        if word in word_count:
            word_count[word] += 1
What it does:
Checks if the word is already present in the dictionary word_count.
If it is, increments its frequency by 1.

Add Word to Dictionary
        else:
            word_count[word] = 1
What it does:
If the word is not already in the dictionary, adds it as a new key and sets its frequency to 1.

Return the Dictionary
    return word_count
What it does: Returns the word_count dictionary containing the word frequencies.

User Input
input_string = input("Enter a string: ")
What it does: Prompts the user to input a string and stores it in the variable input_string.

Call the Function
word_frequency = count_word_frequency(input_string)
What it does: Calls the count_word_frequency function, passing the user's input string, and stores the resulting dictionary in the word_frequency variable.

Display the Results
print("\nWord Frequency:")
What it does: Prints a header Word Frequency: to label the output.

Loop Through Dictionary
for word, count in word_frequency.items():
    print(f"'{word}': {count}")
What it does:
Iterates through the word_frequency dictionary using the items() method, which returns key-value pairs (word and frequency).
Prints each word and its frequency in the format '{word}': {count}.

Thursday, 23 January 2025

Day 99 : Python Program to Create Dictionary that Contains Number


 numbers = [1, 2, 3, 4, 5]

number_dict = {}

for num in numbers:

    number_dict[num] = num ** 2 

print("Dictionary with numbers and their squares:", number_dict)

#source code --> clcoding.com 


Code Explanation:

Input List:

numbers = [1, 2, 3, 4, 5]

This list contains the numbers for which we want to calculate the square.

Create an Empty Dictionary:

number_dict = {}

This empty dictionary will be populated with key-value pairs, where:

The key is the number.

The value is the square of the number.

Iterate Through the List:

for num in numbers:

This loop iterates through each number (num) in the numbers list.

Compute the Square of Each Number and Add It to the Dictionary:

number_dict[num] = num ** 2

num ** 2 calculates the square of the current number.

number_dict[num] assigns the square as the value for the current number (num) in the dictionary.

Print the Dictionary:

print("Dictionary with numbers and their squares:", number_dict)

This displays the resulting dictionary, which contains each number and its square.

Day 98 : Python Program to Create a Dictionary with Key as First Character and Value as Words Starting


 words = ['apple', 'banana', 'avocado', 'berry', 'cherry', 'apricot']

word_dict = {}

for word in words:

    first_char = word[0].lower()  

    if first_char in word_dict:

        word_dict[first_char].append(word)  

    else:

        word_dict[first_char] = [word]  

        print("Dictionary with first character as key:", word_dict)

#source code --> clcoding.com 

Code Explanation:

Input List:

words = ['apple', 'banana', 'avocado', 'berry', 'cherry', 'apricot']

This is the list of words that we want to group based on their first characters.

Create an Empty Dictionary:

word_dict = {}

This dictionary will hold the first characters of the words as keys and lists of corresponding words as values.

Iterate Through the Words:

for word in words:

The loop goes through each word in the words list one by one.

Extract the First Character:

first_char = word[0].lower()

word[0] extracts the first character of the current word.

.lower() ensures the character is in lowercase, making the process case-insensitive (useful if the words had uppercase letters).

Check if the First Character is in the Dictionary:

if first_char in word_dict:

This checks if the first character of the current word is already a key in word_dict.

Append or Create a New Key:

If the Key Exists:

word_dict[first_char].append(word)

The current word is added to the existing list of words under the corresponding key.

If the Key Does Not Exist:

word_dict[first_char] = [word]

A new key-value pair is created in the dictionary, where the key is the first character, and the value is a new list containing the current word.

Output the Dictionary:

print("Dictionary with first character as key:", word_dict)

This prints the resulting dictionary, showing words grouped by their first characters.

Wednesday, 22 January 2025

Day 97: Python Program to Map Two Lists into a Dictionary


 

keys = ['a', 'b', 'c', 'd']

values = [1, 2, 3, 4,]

mapped_dict = dict(zip(keys, values))

print("Mapped Dictionary:", mapped_dict)

#source code --> clcoding.com 

Code Explanation:

Define Lists of Keys and Values:
keys = ['a', 'b', 'c', 'd']
values = [1, 2, 3, 4]
keys is a list of strings representing the keys of the dictionary.
values is a list of integers representing the values to be mapped to those keys.

Combine Keys and Values Using zip():
mapped_dict = dict(zip(keys, values))
zip(keys, values): The zip() function pairs each element from the keys list with the corresponding element in the values list, forming an iterable of tuples: [('a', 1), ('b', 2), ('c', 3), ('d', 4)].
dict(zip(keys, values)): The dict() constructor takes this iterable of key-value pairs and creates a dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}.

Print the Result:

print("Mapped Dictionary:", mapped_dict)
This prints the dictionary to the console, showing the final result.

Output:
Mapped Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

Key Points:
zip(): Combines two iterables element-wise, creating tuples.
dict(): Converts an iterable of tuples into a dictionary.
Both lists must have the same length; otherwise, zip() will truncate to the shortest list.

Day 96: Python Program to Concatenate Two Dictionaries

 

dict1 = {'a': 1, 'b': 2}

dict2 = {'c': 3, 'd': 4}

dict1.update(dict2)

print("Concatenated Dictionary:", dict1)

#source code --> clcoding.com 


Code Explanation:

Define Two Dictionaries:

dict1 = {'a': 1, 'b': 2}

dict2 = {'c': 3, 'd': 4}

dict1 and dict2 are dictionaries with key-value pairs.

dict1 has keys 'a' and 'b' with values 1 and 2, respectively.

dict2 has keys 'c' and 'd' with values 3 and 4.

Merge Dictionaries:

dict1.update(dict2)

The update() method updates dict1 by adding key-value pairs from dict2.

If a key in dict2 already exists in dict1, the value from dict2 will overwrite the one in dict1.

After this operation, dict1 will contain all key-value pairs from both dict1 and dict2.

Print the Result:

print("Concatenated Dictionary:", dict1)

This prints the updated dict1, showing that it now includes the contents of dict2 as well.

Output:

Concatenated Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}

The output confirms that dict1 now contains all key-value pairs from both dictionaries.

Key Points:

The update() method is an in-place operation, meaning it modifies dict1 directly.

If you need a new dictionary without modifying the originals, you can use the ** unpacking method:

combined_dict = {**dict1, **dict2}

Tuesday, 21 January 2025

Day 95 : Python Program to Remove a Key from a Dictionary

 


def remove_key_from_dict(dictionary, key_to_remove):

    """

    Removes a key from the dictionary if it exists.

    Args:

        dictionary (dict): The dictionary to modify.

        key_to_remove: The key to be removed from the dictionary.

     Returns:

        dict: The modified dictionary.

    """

    if key_to_remove in dictionary:

        del dictionary[key_to_remove]

        print(f"Key '{key_to_remove}' has been removed.")

    else:

        print(f"Key '{key_to_remove}' not found in the dictionary.")

    return dictionary

my_dict = {"name": "Max", "age": 25, "city": "UK"}

print("Original Dictionary:", my_dict)

key = input("Enter the key to remove: ")

updated_dict = remove_key_from_dict(my_dict, key)

print("Updated Dictionary:", updated_dict)

#source code --> clcoding.com 

Code Explanation:

Function Definition
def remove_key_from_dict(dictionary, key_to_remove):
    """
    Removes a key from the dictionary if it exists.

    Args:
        dictionary (dict): The dictionary to modify.
        key_to_remove: The key to be removed from the dictionary.

    Returns:
        dict: The modified dictionary.
    """
Purpose: This function is created to remove a specific key from a dictionary, if the key exists.
Parameters:
dictionary: The dictionary that you want to modify.
key_to_remove: The key that you wish to remove from the dictionary.
Returns: The modified dictionary after attempting to remove the key.

Check if Key Exists
if key_to_remove in dictionary:
    del dictionary[key_to_remove]
    print(f"Key '{key_to_remove}' has been removed.")
else:
    print(f"Key '{key_to_remove}' not found in the dictionary.")
if key_to_remove in dictionary: Checks whether the key exists in the dictionary.
del dictionary[key_to_remove]: If the key exists, it deletes the key-value pair from the dictionary.

Print Statement:
If the key is found and removed, a success message is displayed.
If the key is not found, an error message is displayed.

Return Modified Dictionary
return dictionary
The function returns the updated dictionary, whether or not any changes were made.

Dictionary Creation
my_dict = {"name": "Max", "age": 25, "city": "UK"}
print("Original Dictionary:", my_dict)
A dictionary named my_dict is defined with three key-value pairs: "name": "Max", "age": 25, and "city": "UK".
The original dictionary is printed to show its content before any modifications.

User Input
key = input("Enter the key to remove: ")
Prompts the user to enter the name of the key they want to remove from the dictionary.

Function Call
updated_dict = remove_key_from_dict(my_dict, key)
Calls the remove_key_from_dict function, passing the dictionary my_dict and the user-provided key as arguments.
The function processes the request and returns the updated dictionary.

Print Updated Dictionary
print("Updated Dictionary:", updated_dict)
Displays the dictionary after attempting to remove the specified key, allowing the user to see the changes made.

Sunday, 19 January 2025

Day 94: Python Program to Multiply All the Items in a Dictionary

 


def multiply_values(dictionary):

    """

    Multiply all the values in a dictionary.

     Args:

        dictionary (dict): The dictionary containing numerical values.

      Returns:

        int or float: The product of all the values.

    """

    result = 1  

    for value in dictionary.values():  

        result *= value 

    return result  

my_dict = {"a": 5, "b": 10, "c": 2}

total_product = multiply_values(my_dict)

print(f"The product of all values in the dictionary is: {total_product}")

#source code --> clcoding.com 

Code Explanation:

def multiply_values(dictionary):
This line defines a function named multiply_values that accepts one argument: dictionary.
The function is designed to multiply all the numerical values in the given dictionary.

"""
The docstring explains the purpose of the function.
It mentions:
What the function does: Multiplies all the values in the dictionary.
Expected input: A dictionary (dictionary) containing numerical values.
Return type: An integer or a float, depending on the values in the dictionary.

result = 1
A variable result is initialized to 1.
This variable will store the product of all the dictionary values. The initialization to 1 is important because multiplying by 1 does not change the result.

for value in dictionary.values():
This is a for loop that iterates over all the values in the dictionary.
dictionary.values() extracts the values from the dictionary as a list-like object. For my_dict = {"a": 5, "b": 10, "c": 2}, it would extract [5, 10, 2].

result *= value
Inside the loop, the shorthand operator *= is used to multiply the current value of result by value (the current value from the dictionary).

This is equivalent to:
result = result * value
For example:
Initially, result = 1.
First iteration: result = 1 * 5 = 5.
Second iteration: result = 5 * 10 = 50.
Third iteration: result = 50 * 2 = 100.

return result
After the loop finishes multiplying all the values, the final product (100 in this case) is returned by the function.

my_dict = {"a": 5, "b": 10, "c": 2}
A dictionary my_dict is created with three key-value pairs:
Key "a" has a value of 5.
Key "b" has a value of 10.
Key "c" has a value of 2.

total_product = multiply_values(my_dict)
The function multiply_values is called with my_dict as the argument.

Inside the function:
The values [5, 10, 2] are multiplied together, producing a result of 100.
The result (100) is stored in the variable total_product.
print(f"The product of all values in the dictionary is: {total_product}")
The print() function is used to display the result in a formatted string.
The f-string allows the value of total_product (100) to be directly inserted into the string.

Output:
The product of all values in the dictionary is: 100

Dy 93: Python Program to Find the Sum of All the Items in a Dictionary


 def sum_of_values(dictionary):
    """
    Calculate the sum of all the values in a dictionary.

    Args:
        dictionary (dict): The dictionary containing numerical values.

    Returns:
        int or float: The sum of all the values.
    """
    return sum(dictionary.values())

my_dict = {"a": 10, "b": 20, "c": 30}

total_sum = sum_of_values(my_dict)

print(f"The sum of all values in the dictionary is: {total_sum}")

#source code --> clcoding.com 


Code Explanation:

def sum_of_values(dictionary):
This line defines a function named sum_of_values that takes one parameter called dictionary. This function is designed to calculate the sum of all the values in the given dictionary.

"""
A docstring (comment between triple double quotes) is used to explain the purpose of the function. It mentions:
The purpose of the function: "Calculate the sum of all the values in a dictionary."
The parameter (dictionary), which is expected to be a dictionary with numerical values.
The return value, which will either be an integer or a float (depending on the type of values in the dictionary).

return sum(dictionary.values())
The function uses the built-in sum() function to calculate the sum of all values in the dictionary.
dictionary.values() extracts all the values from the dictionary (e.g., [10, 20, 30] for {"a": 10, "b": 20, "c": 30}).
The sum() function adds these values together and returns the total (in this case, 10 + 20 + 30 = 60).

my_dict = {"a": 10, "b": 20, "c": 30}
This line creates a dictionary named my_dict with three key-value pairs:
Key "a" has a value of 10.
Key "b" has a value of 20.
Key "c" has a value of 30.

total_sum = sum_of_values(my_dict)
The sum_of_values function is called with my_dict as its argument.
Inside the function, the values [10, 20, 30] are summed up to give 60.
The result (60) is stored in the variable total_sum.

print(f"The sum of all values in the dictionary is: {total_sum}")
The print() function is used to display the result in a formatted string.
The f-string allows the value of total_sum (which is 60) to be directly inserted into the string.

Output:
The sum of all values in the dictionary is: 60

Day 92: Python Program to Add a Key Value Pair to the Dictionary

 


def add_key_value(dictionary, key, value):

    """

    Adds a key-value pair to the dictionary.

    Args:

        dictionary (dict): The dictionary to update.

           key: The key to add.

        value: The value associated with the key.

  Returns:

        dict: The updated dictionary.

    """

    dictionary[key] = value

    return dictionary

my_dict = {"name": "Max", "age": 25, "city": "Delhi"}

print("Original dictionary:", my_dict)

key_to_add = input("Enter the key to add: ")

value_to_add = input("Enter the value for the key: ")

updated_dict = add_key_value(my_dict, key_to_add, value_to_add)

print("Updated dictionary:", updated_dict)

#source code --> clcoding.com 

Code Explanation: 

1. Function Definition
def add_key_value(dictionary, key, value):
This function is named add_key_value. It is designed to add a key-value pair to an existing dictionary.
Parameters:
dictionary: The dictionary to which the new key-value pair will be added.
key: The new key to add.
value: The value associated with the new key.

2. Function Docstring
"""
Adds a key-value pair to the dictionary.

Args:
    dictionary (dict): The dictionary to update.
    key: The key to add.
    value: The value associated with the key.

Returns:
    dict: The updated dictionary.
"""
This is a docstring that documents what the function does:
What it does: Adds a new key-value pair to a given dictionary.
Arguments:
dictionary: The dictionary to update.
key: The key to add.
value: The value associated with the key.
Return Value: The updated dictionary with the new key-value pair.

3. Logic to Add Key-Value Pair
dictionary[key] = value
The new key-value pair is added to the dictionary:
key is the key to add.
value is the associated value.
If the key already exists in the dictionary, this will update the value of the key.

4. Return Updated Dictionary
return dictionary
After adding or updating the key-value pair, the function returns the updated dictionary.

5. Initial Dictionary
my_dict = {"name": "Max", "age": 25, "city": "Delhi"}
A dictionary my_dict is created with the following key-value pairs:
"name": "Max"
"age": 25
"city": "Delhi"

6. Display Original Dictionary
print("Original dictionary:", my_dict)
Prints the original dictionary before any modification.

7. User Input
key_to_add = input("Enter the key to add: ")
value_to_add = input("Enter the value for the key: ")
input() Function: Prompts the user to enter the key and the value to add to the dictionary.
key_to_add: Stores the user-provided key.
value_to_add: Stores the user-provided value.

8. Call the Function
updated_dict = add_key_value(my_dict, key_to_add, value_to_add)
The add_key_value function is called with:
my_dict: The original dictionary.
key_to_add: The user-provided key.
value_to_add: The user-provided value.
The function updates my_dict by adding the new key-value pair and returns the updated dictionary.
The result is stored in the variable updated_dict.

9. Display Updated Dictionary
print("Updated dictionary:", updated_dict)
Prints the dictionary after adding the new key-value pair.

Day 91: Python Program to Check if a Key Exists in a Dictionary or Not

 


def check_key_exists(dictionary, key):

    """

    Check if a key exists in the dictionary.

     Args:

        dictionary (dict): The dictionary to check.

        key: The key to search for.

     Returns:

        bool: True if the key exists, False otherwise.

    """

    return key in dictionary

my_dict = {"name": "Max", "age": 25, "city": "Germany"}

key_to_check = input("Enter the key to check: ")


if check_key_exists(my_dict, key_to_check):

    print(f"The key '{key_to_check}' exists in the dictionary.")

else:

    print(f"The key '{key_to_check}' does not exist in the dictionary.")


#source code --> clcoding.com 

Code Explanation:

1. Function Definition
def check_key_exists(dictionary, key):
The function check_key_exists is defined with two parameters:
dictionary: This is the dictionary you want to check.
key: The specific key you want to search for within the dictionary.

2. Function Docstring
"""
Check if a key exists in the dictionary.

Args:
    dictionary (dict): The dictionary to check.
    key: The key to search for.

Returns:
    bool: True if the key exists, False otherwise.
"""
This is a docstring, which provides documentation for the function.
It explains:
What the function does: It checks if a key exists in a given dictionary.
Arguments:
dictionary: The dictionary to search in.
key: The key to search for.
Return Value: The function returns a bool (Boolean value), True if the key exists, and False if it doesn’t.

3. Logic to Check Key
return key in dictionary
The function uses the in operator, which checks if the specified key is present in the dictionary.
If the key exists, it returns True; otherwise, it returns False.

4. Dictionary Declaration
my_dict = {"name": "Max", "age": 25, "city": "Germany"}
A dictionary my_dict is created with three key-value pairs:
"name": "Max"
"age": 25
"city": "Germany"

5. User Input
key_to_check = input("Enter the key to check: ")
The program asks the user to input a key they want to check.
The input() function takes the user’s input as a string and stores it in the variable key_to_check.

6. Key Existence Check
if check_key_exists(my_dict, key_to_check):
The check_key_exists function is called with my_dict and the user-provided key_to_check as arguments.
If the function returns True (key exists), the code inside the if block executes.
Otherwise, the else block is executed.

7. Output Messages
    print(f"The key '{key_to_check}' exists in the dictionary.")
If the key exists, this line prints a success message indicating the key exists in the dictionary.

    print(f"The key '{key_to_check}' does not exist in the dictionary.")
If the key doesn’t exist, this line prints a failure message indicating the key is absent.

Sunday, 12 January 2025

Day 90: Python Program to Find All Odd Palindrome Numbers in a Range without using Recursion

 


def is_palindrome(n):

    s = str(n)

    return s == s[::-1]

def find_odd_palindromes(start, end):

    odd_palindromes = []

    for num in range(start, end + 1):

        if num % 2 != 0 and is_palindrome(num):

            odd_palindromes.append(num)

    return odd_palindromes

start = int(input("Enter the start of the range: "))

end = int(input("Enter the end of the range: "))

result = find_odd_palindromes(start, end)

print(f"Odd palindrome numbers between {start} and {end}: {result}")

#source code --> clcoding.com 

1. Function Definition: is_palindrome(n)

def is_palindrome(n):

    s = str(n)

    return s == s[::-1]

Purpose: This function checks whether a number n is a palindrome.

Explanation:

s = str(n): Converts the number n to a string to easily reverse and compare its characters.

s[::-1]: This is a slicing operation that reverses the string s.

return s == s[::-1]: Compares the original string with the reversed string. If they are the same, the number is a palindrome (e.g., 121 is the same as 121 when reversed).

2. Function Definition: find_odd_palindromes(start, end)

def find_odd_palindromes(start, end):

    odd_palindromes = []

Purpose: This function finds all odd palindrome numbers within a given range, from start to end.

Explanation:

odd_palindromes = []: Initializes an empty list that will store the odd palindrome numbers found in the range.

3. Loop through the Range of Numbers

    for num in range(start, end + 1):

Purpose: This for loop iterates over all numbers in the range from start to end (inclusive).

Explanation:

range(start, end + 1): The range function generates numbers from start to end. end + 1 ensures that end is included in the range.

4. Check if the Number is Odd and a Palindrome

        if num % 2 != 0 and is_palindrome(num):

            odd_palindromes.append(num)

Purpose: Checks if the number num is both odd and a palindrome.

Explanation:

num % 2 != 0: This condition checks if the number num is odd. If the remainder when divided by 2 is not zero, it's odd.

is_palindrome(num): This calls the is_palindrome function to check if the number is a palindrome.

If both conditions are true, the number num is added to the list odd_palindromes.

5. Return the List of Odd Palindromes

    return odd_palindromes

Purpose: After the loop finishes, the function returns the list of odd palindrome numbers that were found.

6. Get User Input for Range

start = int(input("Enter the start of the range: "))

end = int(input("Enter the end of the range: "))

Purpose: This takes input from the user to define the range for finding odd palindromes.

Explanation:

input("Enter the start of the range: "): Prompts the user to enter the starting value of the range.

input("Enter the end of the range: "): Prompts the user to enter the ending value of the range.

Both inputs are converted to integers using int() because input() returns data as a string.

7. Find Odd Palindromes and Display the Result

result = find_odd_palindromes(start, end)

print(f"Odd palindrome numbers between {start} and {end}: {result}")

Purpose: This calls the find_odd_palindromes function and prints the result.

Explanation:

result = find_odd_palindromes(start, end): Calls the find_odd_palindromes function with the user-provided start and end values.

print(f"Odd palindrome numbers between {start} and {end}: {result}"): Prints the result in a formatted string showing the list of odd palindromes found in the range.


Day 89: Python Program to Check whether a String is Palindrome or not using Recursion

 


f is_palindrome_recursive(s):

    if len(s) <= 1:

        return True

     if s[0] != s[-1]:

        return False

    return is_palindrome_recursive(s[1:-1])

string = input("Enter a string: ")

processed_string = string.replace(" ", "").lower()

if is_palindrome_recursive(processed_string):

    print(f'"{string}" is a palindrome.')

else:

    print(f'"{string}" is not a palindrome.')

#source code --> clcoding.com 

Code Explanation:

def is_palindrome_recursive(s):
This line defines a function named is_palindrome_recursive, which will check whether a given string s is a palindrome.
A palindrome is a word, phrase, or sequence that reads the same forward and backward (ignoring spaces and capitalization).

    if len(s) <= 1:
        return True
This line checks if the length of the string s is less than or equal to 1.
If the string is empty or has only one character, it is trivially a palindrome, so the function returns True.
Example: "a", "b", or an empty string "" are all palindromes.

    if s[0] != s[-1]:
        return False
This checks if the first character (s[0]) is not equal to the last character (s[-1]).
If the first and last characters are not the same, the string cannot be a palindrome, so it returns False.

    return is_palindrome_recursive(s[1:-1])
If the first and last characters are the same, the function makes a recursive call with a substring that excludes the first and last characters (s[1:-1]).
This means the function will continue checking the inner characters of the string, ignoring the outer characters.
The recursion keeps narrowing the string until it either finds a mismatch (and returns False), or the string becomes too short to continue (and returns True).

Input Handling
string = input("Enter a string: ")
This line prompts the user to enter a string. The input is stored in the variable string.

processed_string = string.replace(" ", "").lower()
This line processes the string by removing any spaces with replace(" ", "") and converting all characters to lowercase using lower().
This ensures that the palindrome check is case-insensitive and doesn't consider spaces.

if is_palindrome_recursive(processed_string):
    print(f'"{string}" is a palindrome.')
else:
    print(f'"{string}" is not a palindrome.')
The if statement calls the is_palindrome_recursive function, passing the processed string (processed_string), which has no spaces and is in lowercase.
If the function returns True, it prints that the original string (string) is a palindrome.
If the function returns False, it prints that the original string is not a palindrome.

Day 88: Python Program to Check whether two Strings are Anagrams

 


def are_anagrams(str1, str2):

    str1 = str1.replace(" ", "").lower()

    str2 = str2.replace(" ", "").lower()

    return sorted(str1) == sorted(str2)

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")

if are_anagrams(string1, string2):

    print(f'"{string1}" and "{string2}" are anagrams.')

else:

    print(f'"{string1}" and "{string2}" are not anagrams.')

#source code --> clcoding.com 


Code Explanation:

1. Function Definition: are_anagrams(str1, str2)
def are_anagrams(str1, str2):
This defines a function called are_anagrams, which takes two arguments: str1 and str2. These are the two strings that we will compare to check if they are anagrams.

2. Removing Spaces and Converting to Lowercase
    str1 = str1.replace(" ", "").lower()
    str2 = str2.replace(" ", "").lower()
Removing Spaces: The replace(" ", "") method removes any spaces from the strings. This ensures that spaces do not affect the comparison. For example, "listen " and "silent " will both become "listen" and "silent" without spaces.
Convert to Lowercase: The lower() method converts the entire string to lowercase. This ensures that the comparison is case-insensitive, meaning "Listen" and "listen" are treated as the same string.

3. Sort and Compare the Strings
    return sorted(str1) == sorted(str2)
Sorting the Strings: The sorted() function takes a string and returns a sorted list of characters. For example, "listen" becomes ['e', 'i', 'l', 'n', 's', 't'].

Comparing Sorted Strings: The function checks if the sorted versions of str1 and str2 are the same. If they are the same, it means the strings are anagrams because they contain the same characters in the same frequency.

Example:
"listen" → ['e', 'i', 'l', 'n', 's', 't']
"silent" → ['e', 'i', 'l', 'n', 's', 't']
Since both sorted lists are equal, "listen" and "silent" are anagrams.

4. Input for the First String
string1 = input("Enter the first string: ")
This line prompts the user to enter the first string and stores it in the variable string1.

5. Input for the Second String
string2 = input("Enter the second string: ")
Similarly, this line prompts the user to enter the second string and stores it in the variable string2.

6. Check if the Strings are Anagrams
if are_anagrams(string1, string2):
    print(f'"{string1}" and "{string2}" are anagrams.')
else:
    print(f'"{string1}" and "{string2}" are not anagrams.')
Calling the are_anagrams Function: The if statement calls the are_anagrams function with the two input strings (string1 and string2) and checks the result.
If the function returns True (meaning the strings are anagrams), it prints that the strings are anagrams.
If the function returns False (meaning the strings are not anagrams), it prints that the strings are not anagrams.

Day 87: Python Program to Check if a Given String is Palindrome


 def is_palindrome(s):

    s = s.replace(" ", "").lower()

        return s == s[::-1]

input_string = input("Enter a string: ")

if is_palindrome(input_string):

    print(f'"{input_string}" is a palindrome.')

else:

    print(f'"{input_string}" is not a palindrome.')

#source code --> clcoding.com 

Code Explanation:

def is_palindrome(s):
This line defines a function called is_palindrome that takes one argument, s.
The argument s is expected to be the string that we want to check if it is a palindrome.

    s = s.replace(" ", "").lower()
This line modifies the input string s to prepare it for the palindrome check:
s.replace(" ", ""):
Removes all spaces from the string.
.lower():
Converts all characters in the string to lowercase.
These transformations ensure the check ignores spaces and capitalization, making it case-insensitive.
    return s == s[::-1]
This line checks if the modified string is the same as its reverse:
s[::-1]:
This is Python slicing syntax that creates a reversed version of the string.

s == s[::-1]:
Compares the string s with its reversed version.
If they are the same, it means the string is a palindrome, and the function returns True. Otherwise, it returns False.
input_string = input("Enter a string: ")
This line asks the user to enter a string and stores the input in the variable input_string.
The input() function allows the user to type a string when the program runs.

if is_palindrome(input_string):
This calls the is_palindrome function, passing the user's input (input_string) as the argument.
If the function returns True (indicating the string is a palindrome), the if block will execute.
If it returns False, the else block will execute.

    print(f'"{input_string}" is a palindrome.')
If the function determines that the string is a palindrome, this line prints a message confirming that.
The f before the string allows you to include variables inside curly braces {} in the printed message.

else:
    print(f'"{input_string}" is not a palindrome.')
If the function determines that the string is not a palindrome, this line prints a message saying so.

Saturday, 11 January 2025

Day 86: Python Program to Count Number of Vowels in a String using Sets


 def count_vowels(input_string):

    vowels = {'a', 'e', 'i', 'o', 'u'}

    input_string = input_string.lower()

    vowel_count = sum(1 for char in input_string if char in vowels)

    return vowel_count

input_string = input("Enter a string: ")

print(f"Number of vowels: {count_vowels(input_string)}")

#source code --> clcoding.com 

Code Explanation:

Defining the Function:
def count_vowels(input_string):
This defines a function called count_vowels that takes one argument, input_string. This argument will hold the string in which vowels will be counted.

2. Defining the Set of Vowels:
    vowels = {'a', 'e', 'i', 'o', 'u'}
A set named vowels is defined containing all lowercase vowels (a, e, i, o, u).
Sets are used here because they allow efficient membership checks (char in vowels).

3. Converting the Input String to Lowercase:
    input_string = input_string.lower()
The input_string is converted to lowercase using the .lower() method to handle both uppercase and lowercase vowels uniformly. For example, "A" will be treated as "a".

4. Counting the Vowels:
    vowel_count = sum(1 for char in input_string if char in vowels)
A generator expression is used to iterate through each character in the input_string.
For each character, it checks if the character exists in the vowels set.
If the character is a vowel, 1 is added to the sum.
The sum function computes the total count of vowels in the string.

5. Returning the Count:
    return vowel_count
The function returns the total number of vowels found in the input string.

6. Getting User Input and Printing the Result:
input_string = input("Enter a string: ")
print(f"Number of vowels: {count_vowels(input_string)}")
The user is prompted to enter a string using the input() function.
The entered string is passed as an argument to the count_vowels function.
The result (number of vowels) is printed to the console using an f-string for formatting.

Friday, 10 January 2025

Day 85: Python Program to Count the Occurrences of Each Word in a String

 


def count_word_occurrences(input_string):

    words = input_string.split()

    word_count = {}

    for word in words:

        word = word.lower()

        if word in word_count:

            word_count[word] += 1

        else:

            word_count[word] = 1

    return word_count

input_string = input("Enter a string: ")

result = count_word_occurrences(input_string)

print("\nWord occurrences:")

for word, count in result.items():

    print(f"{word}: {count}")

#source code --> clcoding.com 


Code Explanation:

1. Function Definition
def count_word_occurrences(input_string):
The function count_word_occurrences is defined to perform the task of counting words.
It takes one parameter, input_string, which is the string where word occurrences are counted.

2. Splitting the String into Words
words = input_string.split()
The input string is split into a list of words using the split() method.
By default, this splits the string at spaces and removes extra spaces.

3. Initializing an Empty Dictionary
word_count = {}
A dictionary word_count is initialized to store words as keys and their counts as values.

4. Iterating Over Words
for word in words:
    word = word.lower()
    if word in word_count:
        word_count[word] += 1
    else:
        word_count[word] = 1
The loop iterates through each word in the list words.

Step-by-step:
Convert to Lowercase:
word = word.lower()
This ensures the count is case-insensitive (e.g., "Hello" and "hello" are treated as the same word).

Check if Word is in Dictionary:
If the word already exists as a key in word_count, increment its count by 1:

word_count[word] += 1
If the word is not in the dictionary, add it with an initial count of 1:
word_count[word] = 1

After the loop:
word_count = {"hello": 2, "world!": 1}

5. Returning the Result
return word_count
The dictionary word_count is returned, containing each word as a key and its count as the value.

6. Getting User Input
input_string = input("Enter a string: ")
The program prompts the user to enter a string. The input is stored in input_string.

7. Calling the Function and Displaying Results
result = count_word_occurrences(input_string)

print("\nWord occurrences:")
for word, count in result.items():
    print(f"{word}: {count}")
The count_word_occurrences function is called with the user’s input, and the result is stored in result.
The program iterates through the dictionary result and prints each word along with its count.


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.

Thursday, 9 January 2025

Day 82 : Python Program to Find the Larger String without using Built in Functions

 


def get_length(string):

    length = 0

    for char in string:

        length += 1

    return length

def find_larger_string(string1, string2):

    length1 = get_length(string1)

    length2 = get_length(string2)

        if length1 > length2:

        return string1

    elif length2 > length1:

        return string2

    else:

        return "Both strings are of equal length."

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")

larger_string = find_larger_string(string1, string2)

print("Larger string:", larger_string)

#source code --> clcoding.com 


Code Explanation:

First Function: get_length
def get_length(string):
This line defines a function called get_length, which takes one argument, string. This argument is expected to be a string, and the function will return its length.

    length = 0
Inside the function, a variable length is initialized to 0. This will be used to count the number of characters in the string.

    for char in string:
This line starts a for loop that iterates over each character (char) in the given string.

        length += 1
Each time the loop processes a character in the string, it increments the length by 1. This keeps track of how many characters have been encountered.

    return length
Once the loop finishes (i.e., all characters in the string have been counted), the function returns the final value of length, which is the total number of characters in the string.
Second Function: find_larger_string

def find_larger_string(string1, string2):
This defines the find_larger_string function, which takes two strings as arguments: string1 and string2. The goal is to compare the lengths of these two strings and determine which one is longer.

    length1 = get_length(string1)
The get_length function is called with string1 as the argument. The returned length is stored in the variable length1.

    length2 = get_length(string2)
Similarly, the get_length function is called with string2 as the argument, and the returned length is stored in the variable length2.

    if length1 > length2:
This line checks if the length of string1 (length1) is greater than the length of string2 (length2).
If this condition is true, it means string1 is longer than string2.

        return string1
If length1 > length2, this line returns string1 because it is the longer string.

    elif length2 > length1:
This line checks if the length of string2 is greater than the length of string1. If this condition is true, it means string2 is longer.

        return string2
If length2 > length1, this line returns string2 because it is the longer string.

    else:
This line is the else part of the condition. If neither length1 > length2 nor length2 > length1 is true, it means the two strings are of equal length.

        return "Both strings are of equal length."
If the lengths of both strings are equal, the function returns the message "Both strings are of equal length.".

Taking Input from the User
string1 = input("Enter the first string: ")
This line prompts the user to input the first string and stores the input in the variable string1.

string2 = input("Enter the second string: ")
This line prompts the user to input the second string and stores the input in the variable string2.

Calling the Function and Printing the Result
larger_string = find_larger_string(string1, string2)
This line calls the find_larger_string function with string1 and string2 as arguments and stores the returned result (either the longer string or a message) in the variable larger_string.

print("Larger string:", larger_string)
This line prints the result stored in larger_string, which is either the longer string or the message "Both strings are of equal length.".

Tuesday, 7 January 2025

Day 80: Python Program that Displays which Letters are in First String but not in Second

 


from collections import Counter

def find_unique_letters(str1, str2):
    count1 = Counter(str1)
    count2 = Counter(str2)
    
    unique_letters = count1 - count2
    
    result = []
    for char, count in unique_letters.items():
        result.extend([char] * count) 
    return result

str1 = input("Enter the first string: ")
str2 = input("Enter the second string: ")

unique_letters = find_unique_letters(str1, str2)

print("Letters in the first string but not in the second string:", unique_letters)
#source code --> clcoding.com 

Code Explanation:

Importing Counter:
from collections import Counter: This imports the Counter class from Python's collections module. A Counter is a special dictionary used to count the occurrences of elements in an iterable (such as a string, list, etc.).

Defining the Function find_unique_letters:
def find_unique_letters(str1, str2): This defines a function that takes two strings str1 and str2 as input. The function will return a list of letters that are present in str1 but not in str2.

Counting Character Frequencies:
count1 = Counter(str1): This creates a Counter object for the first string str1, which counts how many times each character appears in str1. For example, if str1 = "aab", count1 would be:
{'a': 2, 'b': 1}
count2 = Counter(str2): Similarly, this creates a Counter object for str2, counting the character frequencies in str2.

Finding Unique Letters in str1 (Not in str2):
unique_letters = count1 - count2: This subtracts the Counter of str2 from the Counter of str1. The result is a new Counter object that contains only the characters that are present in str1 but not in str2. This subtraction operation works as follows:

It keeps the characters from str1 whose count is greater than in str2 (or if they don't appear in str2 at all).
For example, if str1 = "aab" and str2 = "abb", the result of count1 - count2 would be:
{'a': 1}  # Since 'a' appears once more in str1 than in str2

Building the Result List:
result = []: Initializes an empty list result to store the characters that are found in str1 but not in str2.
for char, count in unique_letters.items(): This loops through each character (char) and its count (count) in the unique_letters Counter object.
result.extend([char] * count): For each character, it appends that character to the result list a number of times equal to its count. For example, if 'a': 1, then 'a' will be added once to the result list.

Returning the Result:
return result: After building the list of unique letters, the function returns the result list, which contains the letters that are in str1 but not in str2.

User Input:
str1 = input("Enter the first string: "): This takes the first string input from the user.
str2 = input("Enter the second string: "): This takes the second string input from the user.

Calling the Function:
unique_letters = find_unique_letters(str1, str2): This calls the find_unique_letters function with the user-provided strings str1 and str2 and stores the result in unique_letters.

Printing the Result:
print("Letters in the first string but not in the second string:", unique_letters): This prints the list of letters that are found in str1 but not in str2.

Day 79: Python Program to Find Common Characters in Two Strings


 from collections import Counter

def find_non_common_letters(str1, str2):

    count1 = Counter(str1)

    count2 = Counter(str2)

    non_common_letters = (count1 - count2) + (count2 - count1)

    result = []

    for char, count in non_common_letters.items():

        result.extend([char] * count)  

    return result

str1 = input("Enter the first string: ")

str2 = input("Enter the second string: ")

non_common_letters = find_non_common_letters(str1, str2)

print("Letters that are not common in both strings:", non_common_letters)

#source code --> clcoding.com 

Code Explanation:

Importing Counter:
from collections import Counter: This imports the Counter class from Python’s collections module. A Counter is a special dictionary that counts the occurrences of elements in an iterable, such as a string.
Function find_non_common_letters:

def find_non_common_letters(str1, str2): This defines a function that takes two strings, str1 and str2, as input and returns a list of letters that are not common between the two strings.

Counting Characters:
count1 = Counter(str1): This creates a Counter object for str1, which counts how many times each character appears in the string str1.
For example, for str1 = "aab", count1 would be: {'a': 2, 'b': 1}.
count2 = Counter(str2): Similarly, this creates a Counter object for str2, counting character occurrences in str2.

Finding Non-Common Letters:
non_common_letters = (count1 - count2) + (count2 - count1):
count1 - count2: This finds the letters that appear in str1 but not in str2, keeping the count of occurrences.
count2 - count1: This finds the letters that appear in str2 but not in str1, again keeping the count of occurrences.
The + operator combines these two parts, effectively getting the total set of non-common letters with their counts.

Building the Result List:
result = []: Initializes an empty list, result, to store the non-common letters.
for char, count in non_common_letters.items(): This loops through each character (char) and its count (count) from non_common_letters.
result.extend([char] * count): This line adds the character char to the list result multiple times (according to its count). For example, if 'a': 3, the character 'a' will appear 3 times in result.

Returning the Result:
return result: This returns the final list result, which contains all the letters that are not common between str1 and str2, each appearing the appropriate number of times.

Taking User Input:
str1 = input("Enter the first string: "): Takes the first string input from the user.
str2 = input("Enter the second string: "): Takes the second string input from the user.

Calling the Function:
non_common_letters = find_non_common_letters(str1, str2): This calls the find_non_common_letters function with the two user-provided strings and stores the result in non_common_letters.

Printing the Result:
print("Letters that are not common in both strings:", non_common_letters): This prints the list of non-common letters.


Popular Posts

Categories

100 Python Programs for Beginner (96) AI (38) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (186) C (77) C# (12) C++ (83) Course (67) Coursera (246) Cybersecurity (25) Data Analysis (1) Data Analytics (2) data management (11) Data Science (138) Data Strucures (8) Deep Learning (21) Django (14) Downloads (3) edx (2) Engineering (14) Euron (22) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Generative AI (6) 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 (75) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (4) Pandas (4) PHP (20) Projects (29) Python (978) Python Coding Challenge (421) Python Quiz (64) 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

Python Coding for Kids ( Free Demo for Everyone)