Featured Post

How to Create a Symmetric Array in Python: A Fun Logic Exercise

Image
 Here's a Python program that says to write a Symmetric array transformation. A top interview question. Symmetric Array Transformation Problem: Write a Python function that transforms a given array into a symmetric array by mirroring it around its center. For example: Input: [1, 2, 3] Output: [1, 2, 3, 2, 1] Hints: Use slicing for the reverse part. Concatenate the original array with its mirrored part. Example def symmetric_array(arr):     """     Transforms the input array into a symmetric array by mirroring it around its center.     Parameters:     arr (list): The input array.     Returns:     list: The symmetric array.     """     # Mirror the array by concatenating the original with its reverse (excluding the last element to avoid duplication)     return arr + arr[-2::-1] # Example usage input_array = [1, 2, 3] symmetric_result = symmetric_array(input_array) print("Input Array:", input_arr...

How to Delete an Item from a Set in Python: Best Example

Set is a built-in data type in Python. Furthermore, it is an unordered collection without duplicate items. Here are the two methods that explain to delete an item from a Set.

Methods to delete an item from a Set

  • discard
  • remove



Discrd Vs. Remove


  • discard() will not raise an error if the item to remove does not exist.
  • The remove() will raise an error if the item does not exist.


Remove items from Set


Explanation to discard and remove methods


Python program:

#Prints all the Set items

food = {"pasta", "burger", "hot dog", "pizza"}

print(food)


# Prints the Set items without pasta

food.discard("pasta")

print(food)


# Prints the Set items without burger and pasta

food.remove("burger")

print(food)


# The next two lines try to remove an item that isn't in the set!

food.discard("pasta")  # this will not report an error

food.remove("pasta")   # this will report an error


The output:

{'pasta', 'burger', 'pizza', 'hot dog'}

{'burger', 'pizza', 'hot dog'}

{'pizza', 'hot dog'}

Traceback (most recent call last):

  File "main.py", line 12, in <module>

    food.remove("pasta")   # this will report an error

KeyError: 'pasta'


** Process exited - Return Code: 1 **

Press Enter to exit terminal


Related

Comments

Popular posts from this blog

How to Fix datetime Import Error in Python Quickly

SQL Query: 3 Methods for Calculating Cumulative SUM

Big Data: Top Cloud Computing Interview Questions (1 of 4)