Test if List is Palindrome in Python

AmitDiwan
Updated on 20-Sep-2021 08:16:18

2K+ Views

When it is required to test if a list is a palindrome, a method is defined that reverses the string and checks if it is equal to the original string. Based on the result, relevant message is displayed on the console. A list comprehension and the ‘join’ method are used.ExampleBelow is a demonstration of the samedef check_palindrome_list(my_str): if my_str == my_str[::-1]: print("The list is a palindrome") else: print("The list isn't a palindrome") my_list = [77, 1, 56, 65, 1, 77] ... Read More

Row with Minimum Difference in Extreme Values in Python

AmitDiwan
Updated on 20-Sep-2021 08:14:10

90 Views

When it is required to get the row with minimum difference in extreme values, list comprehension, the ‘min’ method and ‘max’ methods are used.ExampleBelow is a demonstration of the samemy_list = [[41, 1, 38], [25, 33, 1], [13, 44, 65], [1, 22]] print("The list is : ") print(my_list) my_min_val = min([max(elem) - min(elem) for elem in my_list]) my_result = [elem for elem in my_list if max(elem) - min(elem) == my_min_val] print("The result is : ") print(my_result)OutputThe list is : [[41, 1, 38], [25, 33, 1], [13, 44, 65], [1, 22]] The result is : [[1, 22]]ExplanationA ... Read More

Remove Palindromic Elements from a List in Python

AmitDiwan
Updated on 20-Sep-2021 08:12:02

376 Views

When it is required to remove palindromic elements from a list, list comprehension and the ‘not’ operator are used.ExampleBelow is a demonstration of the samemy_list = [56, 78, 12, 32, 4, 8, 9, 100, 11] print("The list is : ") print(my_list) my_result = [elem for elem in my_list if int(str(elem)[::-1]) not in my_list] print("The result is : " ) print(my_result)OutputThe list is : [56, 78, 12, 32, 4, 8, 9, 100, 11] The result is : [56, 78, 12, 32, 100]ExplanationA list is defined and displayed on the console.A list comprehension is used to iterate over the ... Read More

N-sized Substrings with K Distinct Characters in Python

AmitDiwan
Updated on 20-Sep-2021 08:08:31

289 Views

When it is required to split ‘N’ sized substrings with ‘K’ distinct characters, it is iterated over, and the ‘set’ method is used to get the different combinations.ExampleBelow is a demonstration of the samemy_string = 'Pythonisfun' print("The string is : ") print(my_string) my_substring = 2 my_chars = 2 my_result = [] for idx in range(0, len(my_string) - my_substring + 1): if (len(set(my_string[idx: idx + my_substring])) == my_chars): my_result.append(my_string[idx: idx + my_substring]) print("The resultant string is : ") print(my_result)OutputThe string is : Pythonisfun The resultant string is : ['Py', 'yt', ... Read More

Count the Number of Rows in Each Group using Python Pandas

AmitDiwan
Updated on 20-Sep-2021 08:05:51

389 Views

Use the group.size() to count the number of rows in each group. Import the required library −import pandas as pdCreate a DataFrame −dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'], 'Quantity': [10, 50, 10, 20, 25, 50], 'Product Name': ['Keyboard', 'Charger', 'SmartTV', 'Camera', 'Graphic Card', 'Earphone'] })Group by columns −dataFrame.groupby(["Product Category", "Quantity"]) Now, count the group size to get the count of rows in each group.ExampleFollowing is the complete code −import pandas as pd # create a dataframe dataFrame = pd.DataFrame({'Product Category': ['Computer', 'Mobile Phone', 'Electronics', 'Electronics', 'Computer', 'Mobile Phone'], 'Quantity': [10, 50, 10, 20, ... Read More

Sort DataFrame in Descending Order by Element Frequency in Python Pandas

AmitDiwan
Updated on 20-Sep-2021 07:58:37

748 Views

To sort data in ascending or descending order, use sort_values() method. For descending order, use the following in the sort_values() method −ascending=FalseImport the required library −import pandas as pd Create a DataFrame with 3 columns −dataFrame = pd.DataFrame(    {       "Car": ['BMW', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Lexus'], "Reg_Price": [7000, 1500, 5000, 8000, 9000, 2000], "Place": ['Pune', 'Delhi', 'Mumbai', 'Hyderabad', 'Bangalore', 'Chandigarh'] } )To sort DataFrame in descending order according to the element frequency, we need to count the occurrences. Therefore, count() is also used with sort_values() set for descending order sort −dataFrame.groupby(['Car'])['Reg_Price'].count().reset_index(name='Count').sort_values(['Count'], ascending=False)ExampleFollowing is ... Read More

Merge Dictionaries in Python with Duplicate Keys

AmitDiwan
Updated on 20-Sep-2021 07:56:21

792 Views

When it is required to merge dictionaries list with duplicate keys, the keys of the strings are iterated over and depending on the condition, the result is determined.ExampleBelow is a demonstration of the samemy_list_1 = [{"aba": 1, "best": 4}, {"python": 10, "fun": 15}, {"scala": "fun"}] my_list_2 = [{"scala": 6}, {"python": 3, "best": 10}, {"java": 1}] print("The first list is : ") print(my_list_1) print("The second list is : ") print(my_list_2) for i in range(0, len(my_list_1)):    id_keys = list(my_list_1[i].keys())    for key in my_list_2[i]:       if key not in id_keys: ... Read More

Remove Columns of Duplicate Elements in Python

AmitDiwan
Updated on 20-Sep-2021 07:51:52

175 Views

When it is required to remove columns of duplicate elements, a method is defined that creates an empty set. The list is iterated over, and if it is not found, it is added to the set.ExampleBelow is a demonstration of the samefrom itertools import chain def remove_dupes(my_sub):    my_string = set()    for i, elem in enumerate(my_sub):       if elem not in my_string:          my_string.add(elem)       else:          yield i my_list = [[5, 1, 6, 7, 9], [6, 3, 1, 9, 1], [4, 2, 9, 8, ... Read More

Move a Column to the First Position in Pandas DataFrame

AmitDiwan
Updated on 20-Sep-2021 07:48:45

1K+ Views

Use pop() to pop the column and insert it using the insert() methodi.e. moving a column. At first, create a DataFrame with 3 columns −dataFrame = pd.DataFrame(    {       "Student": ['Jack', 'Robin', 'Ted', 'Marc', 'Scarlett', 'Kat', 'John'], "Result": ['Pass', 'Fail', 'Pass', 'Fail', 'Pass', 'Pass', 'Pass'], "Roll Number": [ 5, 10, 3, 8, 2, 9, 6] } ) Move column "Roll Number" to 1st position by first popping the column out −shiftPos = dataFrame.pop("Roll Number")Insert column on the 1st position −dataFrame.insert(0, "Roll Number", shiftPos) ExampleFollowing is the code −import pandas as pd # ... Read More

Element-wise Matrix Difference in Python

AmitDiwan
Updated on 20-Sep-2021 07:48:25

294 Views

When it is required to print element wise matrix difference, the list elements are iterated over and the zip method is used on these values.ExampleBelow is a demonstration of the samemy_list_1 = [[3, 4, 4], [4, 3, 1], [4, 8, 3]] my_list_2 = [[5, 4, 7], [9, 7, 5], [4, 8, 4]] print("The first list is :") print(my_list_1) print("The second list is :") print(my_list_2) my_result = [] for sub_str_1, sub_str_2 in zip(my_list_1, my_list_2):    temp_str = []    for element_1, element_2 in zip(sub_str_1, sub_str_2):       temp_str.append(element_2-element_1)    my_result.append(temp_str) print("The result is :") print(my_result)OutputThe first ... Read More

Advertisements