Posts

Showing posts with the label Python

Write a Python function to count the occurrence of each element in a list.

 def count_elements(lst):     count_dict = {}     for element in lst:         if element in count_dict:             count_dict[element] += 1         else:             count_dict[element] = 1     return count_dict # Test the function my_list = [1, 2, 3, 2, 4, 1, 3, 4, 4, 5] element_count = count_elements(my_list) print(element_count)

Write a Python function to check if a string is a palindrome.

 def is_palindrome(input_string):     input_string = input_string.lower().replace(" ", "")     reversed_string = input_string[::-1]     return input_string == reversed_string # Test the function my_string = "A man a plan a canal Panama" is_palindrome = is_palindrome(my_string) print(is_palindrome)

Write a Python function to reverse a string without using any built-in functions or slicing.

 def reverse_string(input_string):     reversed_string = ""     for i in range(len(input_string) - 1, -1, -1):         reversed_string += input_string[i]     return reversed_string # Test the function my_string = "Hello, World!" reversed = reverse_string(my_string) print(reversed) #output !dlroW ,olleH