Python Coding Queries Answered
Python Coding Queries Answered
Python Coding Queries Answered
chat.openai.com/share/acea0751-1c4a-4bf7-8ea7-cb5acd133809
Reverse a String:
def reverse_string(input_str):
"""Reverse a given string."""
return input_str[::-1]
# Example:
original_string = "hello"
reversed_string = reverse_string(original_string)
print(f"Original: {original_string}, Reversed: {reversed_string}")
def is_palindrome(input_str):
"""Check if a given string is a palindrome."""
return input_str == input_str[::-1]
# Example:
palindrome_check = is_palindrome("radar")
print(f"Is Palindrome: {palindrome_check}")
def count_digits(input_str):
"""Count the number of numerical digits in a given string."""
return sum(char.isdigit() for char in input_str)
# Example:
string_with_digits = "abc123xyz456"
digit_count = count_digits(string_with_digits)
print(f"Number of digits: {digit_count}")
Count Occurrence of a Character in a String:
# Example:
input_string = "hello world"
char_count = count_char_occurrence(input_string, 'l')
print(f"Count of 'l': {char_count}")
# Example:
string1 = "abc"
string2 = "bcd"
non_matching_chars = find_non_matching_chars(string1, string2)
print(f"Non-matching characters: {non_matching_chars}")
# Example:
str1 = "listen"
str2 = "silent"
anagram_check = are_anagrams(str1, str2)
print(f"Are anagrams: {anagram_check}")
Count Vowels and Consonants in a String:
def count_vowels_consonants(input_str):
"""Count the number of vowels and consonants in a given string."""
vowels = "aeiouAEIOU"
vowel_count = sum(1 for char in input_str if char in vowels)
consonant_count = len(input_str) - vowel_count
return vowel_count, consonant_count
# Example:
string_to_count = "hello world"
vowel_count, consonant_count = count_vowels_consonants(string_to_count)
print(f"Vowels: {vowel_count}, Consonants: {consonant_count}")
# Example:
num_array = [1, 2, 3, 2, 4, 2, 5]
target_num = 2
matching_count = total_matching_integers(num_array, target_num)
print(f"Matching count for {target_num}: {matching_count}")
Reverse an Array:
def reverse_array(arr):
"""Reverse the elements of an array."""
return arr[::-1]
# Example:
original_array = [1, 2, 3, 4, 5]
reversed_array = reverse_array(original_array)
print(f"Original: {original_array}, Reversed: {reversed_array}")
Find Maximum Element in an Array:
def find_max_element(arr):
"""Find the maximum element in an array."""
return max(arr)
# Example:
array_with_max = [3, 7, 1, 9, 4, 2]
max_element = find_max_element(array_with_max)
print(f"Max Element: {max_element}")
def sort_array_ascending(arr):
"""Sort an array of integers in ascending order."""
return sorted(arr)
# Example:
unsorted_array = [5, 2, 8, 1, 3]
sorted_array = sort_array_ascending(unsorted_array)
print(f"Unsorted: {unsorted_array}, Sorted: {sorted_array}")
def fibonacci_recursive(n):
"""Print Fibonacci sequence up to n using recursion."""
if n <= 1:
return n
else:
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
# Example:
fibonacci_length = 5
for i in range(fibonacci_length):
print(fibonacci_recursive(i))
Calculate Sum of Two Integers:
# Example:
num1 = 3
num2 = 5
sum_result = add_two_integers(num1, num2)
print(f"Sum: {sum_result}")
def calculate_average(num_list):
"""Calculate the average of numbers in a list."""
return sum(num_list) / len(num_list) if len(num_list) > 0 else 0
# Example:
numbers_to_average = [2, 4, 6, 8, 10]
average_result = calculate_average(numbers_to_average)
print(f"Average: {average_result}")
def check_even_odd(num):
"""Check if a given integer is even or odd."""
return "Even" if num % 2 == 0 else "Odd"
# Example:
integer_to_check = 7
even_odd_result = check_even_odd(integer_to_check)
print(f"{integer_to_check} is {even_odd_result}")
Find Middle Element of a Linked List:
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
def find_middle_element(head):
"""Find the middle element of a linked list."""
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.value
# Example:
# Assuming a linked list: 1 -> 2 -> 3 -> 4 -> 5
linked_list = ListNode(1, ListNode(2, ListNode(3, ListNode(4,
ListNode(5)))))
middle_element = find_middle_element(linked_list)
print(f"Middle Element: {middle_element}")
Remove Loop in a Linked List:
def detect_and_remove_loop(head):
"""Detect and remove loop in a linked list."""
slow = fast = head
# Detect loop
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
# Example:
# Assuming a linked list with a loop: 1 -> 2 -> 3 -> 4 -> 5 -> 2 (loop back
to 2)
linked_list_with_loop = ListNode(1, ListNode(2, ListNode(3, ListNode(4,
ListNode(5)))))
linked_list_with_loop.next.next.next.next.next = linked_list_with_loop.next
# Creating a loop
detect_and_remove_loop(linked_list_with_loop)
Merge Two Sorted Linked Lists:
class ListNode:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
current.next = l1 or l2
return dummy.next
# Example:
# Assuming two sorted linked lists: 1 -> 3 -> 5 and 2 -> 4 -> 6
list1 = ListNode(1, ListNode(3, ListNode(5)))
list2 = ListNode(2, ListNode(4, ListNode(6)))
merged_list = merge_sorted_lists(list1, list2)
# Example:
sorted_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
target_element = 5
result_index = binary_search(sorted_array, target_element)
print(f"Index of {target_element}: {result_index}")
Print Binary Tree in Vertical Order:
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def vertical_order_traversal(root):
"""Print binary tree in vertical order."""
if not root:
return []
column_table = {}
result = []
dfs(root)
return result
# Example:
# Assuming a binary tree with root value 1, left child with value 2, and
right child with value 3
binary_tree = TreeNode(1, TreeNode(2), TreeNode(3))
vertical_order_result = vertical_order_traversal(binary_tree)
print("Vertical Order Traversal:")
for col in vertical_order_result:
print(col)