Wednesday, 2 April 2025
Sunday, 2 March 2025
Honeycomb pattern plot using Python
Python Developer March 02, 2025 100 Python Programs for Beginner, Python No comments
import matplotlib.pyplot as plt
import numpy as np
x=np.random.randn(10000)
y=np.random.randn(10000)
plt.hexbin(x,y,gridsize=30,cmap='Blues',edgecolor='gray')
plt.colorbar(label='Count in bin')
plt.title('Honeycomb pattern plot')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Import Required Libraries
import matplotlib.pyplot as plt
import numpy as np
matplotlib.pyplot is used for plotting.
numpy is used for numerical operations like generating random data.
2. Generate Random Data
x = np.random.randn(10000)
y = np.random.randn(10000)
np.random.randn(10000) generates 10,000 random numbers from a normal distribution (mean = 0, standard deviation = 1).
Two sets of such numbers are stored in x and y, forming random (x, y) pairs.
3. Create a Hexbin Plot
plt.hexbin(x, y, gridsize=30, cmap='Blues', edgecolor='gray')
hexbin(x, y, gridsize=30, cmap='Blues', edgecolor='gray'):
gridsize=30: Specifies the number of hexagonal bins in the grid (higher value = smaller hexagons).
cmap='Blues': Uses the "Blues" colormap for coloring the hexagons based on data density.
edgecolor='gray': Adds gray borders around hexagons for better visibility.
4. Add a Color Bar
plt.colorbar(label='Count in bin')
plt.colorbar() adds a color scale bar.
label='Count in bin' describes the color bar as representing the number of points inside each hexagon.
5. Customize the Plot
plt.title('Honeycomb pattern plot')
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
Adds title and axis labels.
6. Display the Plot
plt.show()
Renders the plot.
Friday, 24 January 2025
Day 100: Python Program to Count the Frequency of Each Word in a String using Dictionary
Python Developer January 24, 2025 100 Python Programs for Beginner No comments
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:
Thursday, 23 January 2025
Day 99 : Python Program to Create Dictionary that Contains Number
Python Developer January 23, 2025 100 Python Programs for Beginner No comments
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
Python Developer January 23, 2025 100 Python Programs for Beginner No comments
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
Python Developer January 22, 2025 100 Python Programs for Beginner No comments
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:
Day 96: Python Program to Concatenate Two Dictionaries
Python Developer January 22, 2025 100 Python Programs for Beginner No comments
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
Python Developer January 21, 2025 100 Python Programs for Beginner No comments
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:
Sunday, 19 January 2025
Day 94: Python Program to Multiply All the Items in a Dictionary
Python Developer January 19, 2025 100 Python Programs for Beginner No comments
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:
Dy 93: Python Program to Find the Sum of All the Items in a Dictionary
Python Developer January 19, 2025 100 Python Programs for Beginner No comments
def sum_of_values(dictionary):
Code Explanation:
Day 92: Python Program to Add a Key Value Pair to the Dictionary
Python Developer January 19, 2025 100 Python Programs for Beginner No comments
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:
Day 91: Python Program to Check if a Key Exists in a Dictionary or Not
Python Developer January 19, 2025 100 Python Programs for Beginner No comments
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:
Sunday, 12 January 2025
Day 90: Python Program to Find All Odd Palindrome Numbers in a Range without using Recursion
Python Developer January 12, 2025 100 Python Programs for Beginner No comments
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
Python Developer January 12, 2025 100 Python Programs for Beginner No comments
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:
Day 88: Python Program to Check whether two Strings are Anagrams
Python Developer January 12, 2025 100 Python Programs for Beginner No comments
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:
Day 87: Python Program to Check if a Given String is Palindrome
Python Developer January 12, 2025 100 Python Programs for Beginner No comments
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:
Saturday, 11 January 2025
Day 86: Python Program to Count Number of Vowels in a String using Sets
Python Developer January 11, 2025 100 Python Programs for Beginner No comments
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:
Friday, 10 January 2025
Day 85: Python Program to Count the Occurrences of Each Word in a String
Python Developer January 10, 2025 100 Python Programs for Beginner No comments
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:
Day 84: Python Program to Sort Hyphen Separated Sequence of Words in Alphabetical Order
Python Developer January 10, 2025 100 Python Programs for Beginner No comments
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:
Thursday, 9 January 2025
Day 82 : Python Program to Find the Larger String without using Built in Functions
Python Developer January 09, 2025 100 Python Programs for Beginner No comments
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:
Popular Posts
-
In today’s world, data is not just digital — it’s geospatial . Every day, satellites capture massive amounts of imagery about our planet. ...
-
Explanation: ๐น Step 1: Create List x = [1, 2, 3] A list is created ๐ x = [1, 2, 3] ๐น Step 2: Start Loop for i in x: Python starts itera...
-
Explanation: ๐น 1. Variable Assignment clcoding is a variable used to store a value. ๐น 2. int() Function int() converts a value into an i...
-
Code Explanation: ๐น Step 1: Create Tuple a = (1, [2, 3]) A tuple is created → (1, [2, 3]) Tuple is immutable ❌ But it contains a list [2,...
-
In a world driven by data, the ability to predict the future based on past patterns has become one of the most valuable skills in data sc...
-
Machine learning is powerful — but understanding it through theory alone is not enough. The real learning happens when you apply algorithm...
-
April Python Bootcamp Day 2 April Python Bootcamp Day 3 April Python Bootcamp Day 4 April Python Bootcamp Day 5 April Python Bootcamp Day ...
-
Explanation: ๐น Line 1: Tuple Creation x = (1, 2, 3) A tuple named x is created. It contains three elements: 1, 2, and 3. Important: Tuple...
-
Explanation: ๐น Step 1: Create Tuple a = (1, 2, [3, 4]) A tuple is created Tuples are immutable (cannot be changed directly) But inside it...
-
๐ Day 22/150 – Simple Interest in Python Calculating Simple Interest (SI) is a fundamental concept in both mathematics and programming. It...




















