Python Coding Queries Answered

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

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}")

Check if a String is a Palindrome:

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}")

Count Numerical Digits in a String:

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:

def count_char_occurrence(input_str, char):


"""Count the occurrence of a particular character in a given string."""
return input_str.count(char)

# Example:
input_string = "hello world"
char_count = count_char_occurrence(input_string, 'l')
print(f"Count of 'l': {char_count}")

Find Non-Matching Characters in a String:

def find_non_matching_chars(str1, str2):


"""Find non-matching characters between two strings."""
return set(str1) ^ set(str2)

# Example:
string1 = "abc"
string2 = "bcd"
non_matching_chars = find_non_matching_chars(string1, string2)
print(f"Non-matching characters: {non_matching_chars}")

Check if Two Strings are Anagrams:

def are_anagrams(str1, str2):


"""Check if two given strings are anagrams."""
return sorted(str1) == sorted(str2)

# 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}")

Total Matching Integer Elements in an Array:

def total_matching_integers(arr, target):


"""Total all matching integer elements in an array."""
return sum(1 for num in arr if num == target)

# 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}")

Sort an Array of Integers in Ascending Order:

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}")

Print Fibonacci Sequence Using Recursion:

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:

def add_two_integers(a, b):


"""Calculate the sum of two integers."""
return a + b

# Example:
num1 = 3
num2 = 5
sum_result = add_two_integers(num1, num2)
print(f"Sum: {sum_result}")

Find Average of Numbers in a List:

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}")

Check if an Integer is Even or Odd:

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

# If loop found, remove it


if slow == fast:
slow = head
while slow.next != fast.next:
slow = slow.next
fast = fast.next
fast.next = None

# 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

def merge_sorted_lists(l1, l2):


"""Merge two sorted linked lists."""
dummy = ListNode()
current = dummy

while l1 and l2:


if l1.value < l2.value:
current.next = l1
l1 = l1.next
else:
current.next = l2
l2 = l2.next
current = current.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)

# Printing the merged list


while merged_list:
print(merged_list.value, end=" -> ")
merged_list = merged_list.next
print("None")
Binary Search in a Sorted Array:

def binary_search(arr, target):


"""Implement binary search to find an element in a sorted array."""
low, high = 0, len(arr) - 1

while low <= high:


mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1

return -1 # Target not found

# 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 = []

def dfs(node, row=0, column=0):


nonlocal column_table
if node:
if column not in column_table:
column_table[column] = []
column_table[column].append((row, node.value))
dfs(node.left, row + 1, column - 1)
dfs(node.right, row + 1, column + 1)

dfs(root)

for column in sorted(column_table):


result.append([val for row, val in sorted(column_table[column])])

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)

You might also like