Found 33676 Articles for Programming

Python Program to print a specific number of rows with Maximum Sum

AmitDiwan
Updated on 14-Sep-2021 10:37:55

202 Views

When it is required to print a specific number of rows with the maximum sum, the ‘sorted’ method, and the ‘lambda’ method are used.ExampleBelow is a demonstration of the samemy_list = [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]] print("The list is :") print(my_list) my_key = 3 print("The key is") print(my_key) my_result = sorted(my_list, key=lambda row: sum(row), reverse=True)[:my_key] print("The resultant list is :") print(my_result)OutputThe list is : [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]] The key is 3 The resultant list is ... Read More

Python – Sort Matrix by Palindrome count

AmitDiwan
Updated on 14-Sep-2021 10:36:50

221 Views

When it is required to sort matrix based on palindrome count, a method is defined that takes a list as parameter. It uses the list comprehension and ‘join’ method to iterate and see if an element is a palindrome or not. Based on this, results are determined and displayed.ExampleBelow is a demonstration of the samedef get_palindrome_count(row):    return len([element for element in row if''.join(list(reversed(element))) == element]) my_list = [["abcba", "hdgfue", "abc"], ["peep"], ["py", "is", "best"], ["sees", "level", "non", "noon"]] print("The list is :") print(my_list) my_list.sort(key=get_palindrome_count) print("The resultant list is :") print(my_list)OutputThe list is : [['abcba', 'hdgfue', 'abc'], ... Read More

Python – Extract rows with Complex data types

AmitDiwan
Updated on 14-Sep-2021 10:34:58

139 Views

When it is required to extract rows with complex data types, the ‘isinstance’ method and list comprehension are used.ExampleBelow is a demonstration of the samemy_list = [[13, 1, 35], [23, [44, 54], 85], [66], [75, (81, 2), 29, 7]] my_result = [row for row in my_list if any(isinstance(element, list) or isinstance(element, tuple) or isinstance(element, dict) or isinstance(element, set) for element in row)] print("The list is :") print(my_list) print("The resultant list is :") print(my_result)OutputThe list is : [[13, 1, 35], [23, [44, 54], 85], [66], [75, (81, 2), 29, 7]] The resultant list is : [[23, [44, 54], ... Read More

Python Program to return the Length of the Longest Word from the List of Words

AmitDiwan
Updated on 14-Sep-2021 10:33:19

1K+ Views

When it is required to return the length of the longest word from a list of words, a method is defined that takes a list as parameter. It checks if an element is in the list and depending on this, the output is displayed.ExampleBelow is a demonstration of the samedef find_longest_length(my_list):    max_length = len(my_list[0])    temp = my_list[0]    for element in my_list:       if(len(element) > max_length):          max_length = len(element)          temp = element return max_length my_list = ["ab", "abc", "abcd", "abcde"] print("The list ... Read More

Python Program to Sort Matrix Rows by summation of consecutive difference of elements

AmitDiwan
Updated on 14-Sep-2021 10:31:43

192 Views

ExampleBelow is a demonstration of the samedef diff_summation_elem(row): return sum([abs(row[index + 1] - row[index]) for index in range(0, len(row) - 1)]) my_list = [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]] print("The list is : ") print(my_list) my_list.sort(key=diff_summation_elem) print("The resultant list is :" ) print(my_list)OutputThe list is : [[97, 6, 47, 3], [6, 88, 3, 26], [71, 53, 34, 65], [15, 36, 5, 62]] The resultant list is : [[71, 53, 34, 65], [15, 36, 5, 62], [97, 6, 47, 3], [6, 88, 3, 26]]ExplanationA ... Read More

Python – Append given number with every element of the list

AmitDiwan
Updated on 14-Sep-2021 10:28:01

339 Views

When it is required to append given number with every element of the list, a list comprehension is used.ExampleBelow is a demonstration of the samemy_list = [25, 36, 75, 36, 17, 7, 8, 0] print ("The list is :") print(my_list) my_key = 6 my_result = [x + my_key for x in my_list] print ("The resultant list is :") print(my_result)OutputThe list is : [25, 36, 75, 36, 17, 7, 8, 0] The resultant list is : [31, 42, 81, 42, 23, 13, 14, 6]ExplanationA list is defined and is displayed on the console.An integer value for key ... Read More

Python – Cumulative Row Frequencies in a List

AmitDiwan
Updated on 14-Sep-2021 10:26:49

303 Views

When it is required to get the cumulative row frequencies in a list, the ‘Counter’ method, and a list comprehension are used.ExampleBelow is a demonstration of the samefrom collections import Counter my_list = [[11, 2, 32, 4, 31], [52, 52, 3, 71, 71, 3], [1, 3], [19, 19, 40, 40, 40]] print("The list is :") print(my_list) my_element_list = [19, 2, 71] my_frequency = [Counter(element) for element in my_list] my_result = [sum([freq[word] for word in my_element_list if word in freq]) for freq in my_frequency] print("The resultant matrix is :") print(my_result)OutputThe list is : [[11, 2, ... Read More

Python Program To Get Minimum Element For String Construction

AmitDiwan
Updated on 14-Sep-2021 10:19:58

129 Views

When it is required to get the minimum element to construct a string, the ‘set’ operator, the ‘combinations’ method, the ‘issubset’ method and a simple iteration is required.ExampleBelow is a demonstration of the samefrom itertools import combinations my_list = ["python", "is", "fun", "to", "learn"] print("The list is :") print(my_list) my_target_str = "onis" my_result = -1 my_set_string = set(my_target_str) complete_val = False for value in range(0, len(my_list) + 1): for sub in combinations(my_list, value): temp_set = set(ele for subl in sub for ele in subl) ... Read More

Python Pandas - Create a Subset DataFrame using Indexing Operator

AmitDiwan
Updated on 14-Sep-2021 13:43:57

312 Views

The indexing operator is the square brackets for creating a subset dataframe. Let us first create a Pandas DataFrame. We have 3 columns in the DataFramedataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Creating a subset with a single columndataFrame[['Product']]Creating a subset with multiple columnsdataFrame[['Opening_Stock', 'Closing_Stock']]ExampleFollowing is the complete codeimport pandas as pd dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]}) print"DataFrame...", dataFrame print"Displaying a subset using indexing operator:", dataFrame[['Product']] print"Displaying a subset with multiple columns:", dataFrame[['Opening_Stock', 'Closing_Stock']]OutputThis will ... Read More

Python - Filter Pandas DataFrame with numpy

AmitDiwan
Updated on 14-Sep-2021 13:41:47

5K+ Views

The numpy where() method can be used to filter Pandas DataFrame. Mention the conditions in the where() method. At first, let us import the required libraries with their respective aliasimport pandas as pd import numpy as npWe will now create a Pandas DataFrame with Product records dataFrame = pd.DataFrame({"Product": ["SmartTV", "ChromeCast", "Speaker", "Earphone"], "Opening_Stock": [300, 700, 1200, 1500], "Closing_Stock": [200, 500, 1000, 900]})Use numpy where() to filter DataFrame with 2 ConditionsresValues1 = np.where((dataFrame['Opening_Stock']>=700) & (dataFrame['Closing_Stock']< 1000)) print"Filtered DataFrame Value = ", dataFrame.loc[resValues1] Let us use numpy where() again to filter DataFrame with 3 conditionsresValues2 = np.where((dataFrame['Opening_Stock']>=500) & (dataFrame['Closing_Stock']< 1000) ... Read More

Advertisements