Description
stringlengths 9
105
| Link
stringlengths 45
135
| Code
stringlengths 10
26.8k
| Test_Case
stringlengths 9
202
| Merge
stringlengths 63
27k
|
---|---|---|---|---|
Python - Filter dictionary values in heterogeneous dict
|
https://www.geeksforgeeks.org/python-filter-dictionary-values-in-heterogenous-dictionary/?ref=leftbar-rightbar
|
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
# initializing dictionary
test_dict = {"Gfg": 4, "is": 2, "best": 3, "for": "geeks"}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
res = {}
for key, val in test_dict.items():
if type(val) != int or val > K:
res[key] = val
# printing result
print("Values greater than K : " + str(res))
|
#Output : The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
|
Python - Filter dictionary values in heterogeneous dict
# Python3 code to demonstrate working of
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
# initializing dictionary
test_dict = {"Gfg": 4, "is": 2, "best": 3, "for": "geeks"}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using for loop and conditional statements
res = {}
for key, val in test_dict.items():
if type(val) != int or val > K:
res[key] = val
# printing result
print("Values greater than K : " + str(res))
#Output : The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
[END]
|
Python - Filter dictionary values in heterogeneous dict
|
https://www.geeksforgeeks.org/python-filter-dictionary-values-in-heterogenous-dictionary/?ref=leftbar-rightbar
|
# initializing dictionary
test_dict = {"Gfg": 4, "is": 2, "best": 3, "for": "geeks"}
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using dictionary comprehension with if condition
res = {k: v for k, v in test_dict.items() if type(v) != int or v > K}
# printing result
print("Values greater than K : " + str(res))
|
#Output : The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
|
Python - Filter dictionary values in heterogeneous dict
# initializing dictionary
test_dict = {"Gfg": 4, "is": 2, "best": 3, "for": "geeks"}
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using dictionary comprehension with if condition
res = {k: v for k, v in test_dict.items() if type(v) != int or v > K}
# printing result
print("Values greater than K : " + str(res))
#Output : The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
[END]
|
Python - Filter dictionary values in heterogeneous dict
|
https://www.geeksforgeeks.org/python-filter-dictionary-values-in-heterogenous-dictionary/?ref=leftbar-rightbar
|
# initializing dictionary
test_dict = {"Gfg": 4, "is": 2, "best": 3, "for": "geeks"}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using filter() function with lambda function
res = dict(
filter(
lambda item: not (isinstance(item[1], int) and item[1] <= K), test_dict.items()
)
)
# printing result
print("Values greater than K : " + str(res))
|
#Output : The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
|
Python - Filter dictionary values in heterogeneous dict
# initializing dictionary
test_dict = {"Gfg": 4, "is": 2, "best": 3, "for": "geeks"}
# printing original dictionary
print("The original dictionary : " + str(test_dict))
# initializing K
K = 3
# Filter dictionary values in heterogeneous dictionary
# Using filter() function with lambda function
res = dict(
filter(
lambda item: not (isinstance(item[1], int) and item[1] <= K), test_dict.items()
)
)
# printing result
print("Values greater than K : " + str(res))
#Output : The original dictionary : {'Gfg': 4, 'for': 'geeks', 'is': 2, 'best': 3}
[END]
|
Print anagrams together in Python using List and Dictionary
|
https://www.geeksforgeeks.org/print-anagrams-together-python-using-list-dictionary/
|
# Function to return all anagrams together
def allAnagram(input):
# empty dictionary which holds subsets
# of all anagrams together
dict = {}
# traverse list of strings
for strVal in input:
# sorted(iterable) method accepts any
# iterable and returns list of items
# in ascending order
key = "".join(sorted(strVal))
# now check if key exist in dictionary
# or not. If yes then simply append the
# strVal into the list of it's corresponding
# key. If not then map empty list onto
# key and then start appending values
if key in dict.keys():
dict[key].append(strVal)
else:
dict[key] = []
dict[key].append(strVal)
# traverse dictionary and concatenate values
# of keys together
output = ""
for key, value in dict.items():
output = output + " ".join(value) + " "
return output
# Driver function
if __name__ == "__main__":
input = ["cat", "dog", "tac", "god", "act"]
print(allAnagram(input))
|
#Output : cat tac act dog god
|
Print anagrams together in Python using List and Dictionary
# Function to return all anagrams together
def allAnagram(input):
# empty dictionary which holds subsets
# of all anagrams together
dict = {}
# traverse list of strings
for strVal in input:
# sorted(iterable) method accepts any
# iterable and returns list of items
# in ascending order
key = "".join(sorted(strVal))
# now check if key exist in dictionary
# or not. If yes then simply append the
# strVal into the list of it's corresponding
# key. If not then map empty list onto
# key and then start appending values
if key in dict.keys():
dict[key].append(strVal)
else:
dict[key] = []
dict[key].append(strVal)
# traverse dictionary and concatenate values
# of keys together
output = ""
for key, value in dict.items():
output = output + " ".join(value) + " "
return output
# Driver function
if __name__ == "__main__":
input = ["cat", "dog", "tac", "god", "act"]
print(allAnagram(input))
#Output : cat tac act dog god
[END]
|
Check if binary representations of two numbers are anagram
|
https://www.geeksforgeeks.org/python-dictionary-check-binary-representations-two-numbers-anagram/
|
# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def checkAnagram(num1, num2):
# convert numbers into in binary
# and remove first two characters of
# output string because bin function
# '0b' as prefix in output string
bin1 = bin(num1)[2:]
bin2 = bin(num2)[2:]
# append zeros in shorter string
zeros = abs(len(bin1) - len(bin2))
if len(bin1) > len(bin2):
bin2 = zeros * "0" + bin2
else:
bin1 = zeros * "0" + bin1
# convert binary representations
# into dictionary
dict1 = Counter(bin1)
dict2 = Counter(bin2)
# compare both dictionaries
if dict1 == dict2:
print("Yes")
else:
print("No")
# Driver program
if __name__ == "__main__":
num1 = 8
num2 = 4
checkAnagram(num1, num2)
|
#Input : a = 8, b = 4
#Output : Yes
|
Check if binary representations of two numbers are anagram
# function to Check if binary representations
# of two numbers are anagram
from collections import Counter
def checkAnagram(num1, num2):
# convert numbers into in binary
# and remove first two characters of
# output string because bin function
# '0b' as prefix in output string
bin1 = bin(num1)[2:]
bin2 = bin(num2)[2:]
# append zeros in shorter string
zeros = abs(len(bin1) - len(bin2))
if len(bin1) > len(bin2):
bin2 = zeros * "0" + bin2
else:
bin1 = zeros * "0" + bin1
# convert binary representations
# into dictionary
dict1 = Counter(bin1)
dict2 = Counter(bin2)
# compare both dictionaries
if dict1 == dict2:
print("Yes")
else:
print("No")
# Driver program
if __name__ == "__main__":
num1 = 8
num2 = 4
checkAnagram(num1, num2)
#Input : a = 8, b = 4
#Output : Yes
[END]
|
Check if binary representations of two numbers are anagram
|
https://www.geeksforgeeks.org/python-dictionary-check-binary-representations-two-numbers-anagram/
|
def is_anagram_binary(a, b):
bin_a = bin(a)[2:].zfill(32)
bin_b = bin(b)[2:].zfill(32)
count_a = [0, 0]
count_b = [0, 0]
for i in range(32):
if bin_a[i] == "0":
count_a[0] += 1
else:
count_a[1] += 1
if bin_b[i] == "0":
count_b[0] += 1
else:
count_b[1] += 1
if count_a == count_b:
return "Yes"
else:
return "No"
a = 8
b = 4
print(is_anagram_binary(8, 4)) # Output: True
|
#Input : a = 8, b = 4
#Output : Yes
|
Check if binary representations of two numbers are anagram
def is_anagram_binary(a, b):
bin_a = bin(a)[2:].zfill(32)
bin_b = bin(b)[2:].zfill(32)
count_a = [0, 0]
count_b = [0, 0]
for i in range(32):
if bin_a[i] == "0":
count_a[0] += 1
else:
count_a[1] += 1
if bin_b[i] == "0":
count_b[0] += 1
else:
count_b[1] += 1
if count_a == count_b:
return "Yes"
else:
return "No"
a = 8
b = 4
print(is_anagram_binary(8, 4)) # Output: True
#Input : a = 8, b = 4
#Output : Yes
[END]
|
Python Counter to find the size of largest subset of anagram word
|
https://www.geeksforgeeks.org/python-counter-find-size-largest-subset-anagram-words/
|
# Function to find the size of largest subset
# of anagram words
from collections import Counter
def maxAnagramSize(input):
# split input string separated by space
input = input.split(" ")
# sort each string in given list of strings
for i in range(0, len(input)):
input[i] = "".join(sorted(input[i]))
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
freqDict = Counter(input)
# get maximum value of frequency
print(max(freqDict.values()))
# Driver program
if __name__ == "__main__":
input = "ant magenta magnate tan gnamate"
maxAnagramSize(input)
|
Input:
ant magenta magnate tan gnamate
|
Python Counter to find the size of largest subset of anagram word
# Function to find the size of largest subset
# of anagram words
from collections import Counter
def maxAnagramSize(input):
# split input string separated by space
input = input.split(" ")
# sort each string in given list of strings
for i in range(0, len(input)):
input[i] = "".join(sorted(input[i]))
# now create dictionary using counter method
# which will have strings as key and their
# frequencies as value
freqDict = Counter(input)
# get maximum value of frequency
print(max(freqDict.values()))
# Driver program
if __name__ == "__main__":
input = "ant magenta magnate tan gnamate"
maxAnagramSize(input)
Input:
ant magenta magnate tan gnamate
[END]
|
Python Counter to find the size of largest subset of anagram word
|
https://www.geeksforgeeks.org/python-counter-find-size-largest-subset-anagram-words/
|
def largest_anagram_subset_size(words):
anagram_dict = {}
for word in words:
sorted_word = "".join(sorted(word))
if sorted_word not in anagram_dict:
anagram_dict[sorted_word] = []
anagram_dict[sorted_word].append(word)
max_count = max([len(val) for val in anagram_dict.values()])
return max_count
words = ["ant", "magenta", "magnate", "tan", "gnamate"]
print(largest_anagram_subset_size(words))
|
Input:
ant magenta magnate tan gnamate
|
Python Counter to find the size of largest subset of anagram word
def largest_anagram_subset_size(words):
anagram_dict = {}
for word in words:
sorted_word = "".join(sorted(word))
if sorted_word not in anagram_dict:
anagram_dict[sorted_word] = []
anagram_dict[sorted_word].append(word)
max_count = max([len(val) for val in anagram_dict.values()])
return max_count
words = ["ant", "magenta", "magnate", "tan", "gnamate"]
print(largest_anagram_subset_size(words))
Input:
ant magenta magnate tan gnamate
[END]
|
Count of groups having largest size while grouping according to sum of its digits
|
https://www.geeksforgeeks.org/count-of-groups-having-largest-size-while-grouping-according-to-sum-of-its-digits/?ref=leftbar-rightbar
|
// C++ implementation to Count the// number of groups having the largest// size where groups are according// to the sum of its digits#include <bits/stdc++.h>using namespace std;??????// function to return sum of digits of iint sumDigits(int n){????????????????????????int sum = 0;????????????????????????while(n)????????????????????????{????????????????????????????????????????????????sum += n%10;????????????????????????????????????????????????n /= 10;????????????????????????}??????????????????????????????return sum;}??????// Create the dictionary of unique summap<int,int> constDict(int n){??????????????????????????????????????????????????????// dictionary that contain????????????????????????// unique sum count????????????????????????map<int,int> d;??????????????????????????????for(int i = 1; i < n + 1; ++i){????????????????????????????????????????????????// calculate the sum of its digits????????????????????????????????????????????????int sum1 = sumDigits(i);???????????????????????????????????????????????????
t size group????????????????????????int count = 0;??????????????????????????????for(auto it = d.begin(); it != d.end(); ++it){????????????????????????????????????????????????int k = it->first;????????????????????????????????????????????????int val = it->second;??????????????????????????????????????????????????????if(val > size){??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????size = val;????????????????????????????????????????????????????????????????????????count = 1;?????????????????
|
#Output : 4
|
Count of groups having largest size while grouping according to sum of its digits
// C++ implementation to Count the// number of groups having the largest// size where groups are according// to the sum of its digits#include <bits/stdc++.h>using namespace std;??????// function to return sum of digits of iint sumDigits(int n){????????????????????????int sum = 0;????????????????????????while(n)????????????????????????{????????????????????????????????????????????????sum += n%10;????????????????????????????????????????????????n /= 10;????????????????????????}??????????????????????????????return sum;}??????// Create the dictionary of unique summap<int,int> constDict(int n){??????????????????????????????????????????????????????// dictionary that contain????????????????????????// unique sum count????????????????????????map<int,int> d;??????????????????????????????for(int i = 1; i < n + 1; ++i){????????????????????????????????????????????????// calculate the sum of its digits????????????????????????????????????????????????int sum1 = sumDigits(i);???????????????????????????????????????????????????
t size group????????????????????????int count = 0;??????????????????????????????for(auto it = d.begin(); it != d.end(); ++it){????????????????????????????????????????????????int k = it->first;????????????????????????????????????????????????int val = it->second;??????????????????????????????????????????????????????if(val > size){??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????size = val;????????????????????????????????????????????????????????????????????????count = 1;?????????????????
#Output : 4
[END]
|
Count of groups having largest size while grouping according to sum of its digits
|
https://www.geeksforgeeks.org/count-of-groups-having-largest-size-while-grouping-according-to-sum-of-its-digits/?ref=leftbar-rightbar
|
// Java implementation to Count the??????// number of groups having the largest??????// size where groups are according??????// to the sum of its digitsimport java.util.HashMap;import java.util.Map;??????class GFG{??????????????????????????????// Function to return sum of digits of ipublic static int sumDigits(int n){????????????????????????int sum = 0;????????????????????????while(n != 0)????????????????????????{????????????????????????????????????????????????sum += n % 10;????????????????????????????????????????????????n /= 10;????????????????????????}??????????????????????????????????????????return sum;}??????????????????// Create the dictionary of unique sum??????public static HashMap<Integer, Integer> constDict(int n){??????????????????????????????????????????????????????// dictionary that contain??????????????????????????????// unique sum count??????????????????????????????HashMap<Integer, Integer> d = new HashMap<>();??????????????????????????????????????????????????????for(int i = 1; i < n + 1; ++i)
to find the??????// largest size of group??????public static int countLargest(int n){????????????????????????HashMap<Integer, Integer> d = constDict(n);????????????????????????????????????????????????????????????????????????int size = 0;??????????????????????????????????????????// Count of largest size group??????????????????????????????int count = 0;??????????????????????????????for(Map.Entry<Integer, Integer> it : d.entrySet())????????????????????????{????????????????????????????????????????????????int k = it.getKey();????????????????????????????????????????????????int val = it.getValue();??????????????????????????????????????????????????????????????????????????????????????????????????????if (val > size)????????????????????????????????????????????????{???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
|
#Output : 4
|
Count of groups having largest size while grouping according to sum of its digits
// Java implementation to Count the??????// number of groups having the largest??????// size where groups are according??????// to the sum of its digitsimport java.util.HashMap;import java.util.Map;??????class GFG{??????????????????????????????// Function to return sum of digits of ipublic static int sumDigits(int n){????????????????????????int sum = 0;????????????????????????while(n != 0)????????????????????????{????????????????????????????????????????????????sum += n % 10;????????????????????????????????????????????????n /= 10;????????????????????????}??????????????????????????????????????????return sum;}??????????????????// Create the dictionary of unique sum??????public static HashMap<Integer, Integer> constDict(int n){??????????????????????????????????????????????????????// dictionary that contain??????????????????????????????// unique sum count??????????????????????????????HashMap<Integer, Integer> d = new HashMap<>();??????????????????????????????????????????????????????for(int i = 1; i < n + 1; ++i)
to find the??????// largest size of group??????public static int countLargest(int n){????????????????????????HashMap<Integer, Integer> d = constDict(n);????????????????????????????????????????????????????????????????????????int size = 0;??????????????????????????????????????????// Count of largest size group??????????????????????????????int count = 0;??????????????????????????????for(Map.Entry<Integer, Integer> it : d.entrySet())????????????????????????{????????????????????????????????????????????????int k = it.getKey();????????????????????????????????????????????????int val = it.getValue();??????????????????????????????????????????????????????????????????????????????????????????????????????if (val > size)????????????????????????????????????????????????{???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
#Output : 4
[END]
|
Count of groups having largest size while grouping according to sum of its digits
|
https://www.geeksforgeeks.org/count-of-groups-having-largest-size-while-grouping-according-to-sum-of-its-digits/?ref=leftbar-rightbar
|
# Python3 implementation to Count the
# number of groups having the largest
# size where groups are according
# to the sum of its digits
# Create the dictionary of unique sum
def constDict(n):
# dictionary that contain
# unique sum count
d = {}
for i in range(1, n + 1):
# convert each number to string
s = str(i)
# make list of number digits
l = list(s)
# calculate the sum of its digits
sum1 = sum(map(int, l))
if sum1 not in d:
d[sum1] = 1
else:
d[sum1] += 1
return d
# function to find the
# largest size of group
def countLargest(n):
d = constDict(n)
size = 0
# count of largest size group
count = 0
for k, val in d.items():
if val > size:
size = val
count = 1
elif val == size:
count += 1
return count
# Driver Code
n = 13
group = countLargest(n)
print(group)
# This code is contributed by Sanjit_Prasad
|
#Output : 4
|
Count of groups having largest size while grouping according to sum of its digits
# Python3 implementation to Count the
# number of groups having the largest
# size where groups are according
# to the sum of its digits
# Create the dictionary of unique sum
def constDict(n):
# dictionary that contain
# unique sum count
d = {}
for i in range(1, n + 1):
# convert each number to string
s = str(i)
# make list of number digits
l = list(s)
# calculate the sum of its digits
sum1 = sum(map(int, l))
if sum1 not in d:
d[sum1] = 1
else:
d[sum1] += 1
return d
# function to find the
# largest size of group
def countLargest(n):
d = constDict(n)
size = 0
# count of largest size group
count = 0
for k, val in d.items():
if val > size:
size = val
count = 1
elif val == size:
count += 1
return count
# Driver Code
n = 13
group = countLargest(n)
print(group)
# This code is contributed by Sanjit_Prasad
#Output : 4
[END]
|
Count of groups having largest size while grouping according to sum of its digits
|
https://www.geeksforgeeks.org/count-of-groups-having-largest-size-while-grouping-according-to-sum-of-its-digits/?ref=leftbar-rightbar
|
// C# implementation to Count the??????// number of groups having the largest??????// size where groups are according??????// to the sum of its digitsusing System;using System.Collections.Generic;class GFG {??????????????????????????????????????????????????????// Function to return sum of digits of i????????????????????????static int sumDigits(int n)????????????????????????{????????????????????????????????????????????????int sum = 0;????????????????????????????????????????????????while(n != 0)????????????????????????????????????????????????{????????????????????????????????????????????????????????????????????????sum += n % 10;????????????????????????????????????????????????????????????????????????n /= 10;????????????????????????????????????????????????}????????????????????????????????????????????????????????????????????????????????????????????????return sum;????????????????????????}????????????????????????????????????????????????????????????????????????// Create the dictionary of unique sum???????????????????
???????????????????????????????????????if (!d.ContainsKey(sum1))????????????????????????????????d.Add(sum1, 1);????????????????????????else????????????????????????????????d[sum1] += 1;????????????????}????????????????return d;????????}????????????????????????// Function to find the??????????// largest size of group??????????static int countLargest(int n)????????{????????????????Dictionary<int, int> d = constDict(n);??????????????????????????????????????????int size = 0;????????????????????????????????// Count of largest size group??????????????????int count = 0;??????????????????????????????????foreach(KeyValuePair<int, int> it in d)????????????????{????????????????????????int k = it.Key;????????????????????????int val = it.Value;????????????????????????????????????????????????????if (val > size)????????????????????????{????????????????????????????????????????????????????????size = val;????????????????????????????????count = 1;????????????????????????}????????????????????????else if (val == size)????????????????????????????????????????????????????????count += 1;????????????????}????????????????????????????????return count;????????}??????????????// Driver code????static void Main()????{????????int n = 13;????????int group = countLargest(n);??????????Console.WriteLine(group);????}}??// This code is contributed by divyesh072019
|
#Output : 4
|
Count of groups having largest size while grouping according to sum of its digits
// C# implementation to Count the??????// number of groups having the largest??????// size where groups are according??????// to the sum of its digitsusing System;using System.Collections.Generic;class GFG {??????????????????????????????????????????????????????// Function to return sum of digits of i????????????????????????static int sumDigits(int n)????????????????????????{????????????????????????????????????????????????int sum = 0;????????????????????????????????????????????????while(n != 0)????????????????????????????????????????????????{????????????????????????????????????????????????????????????????????????sum += n % 10;????????????????????????????????????????????????????????????????????????n /= 10;????????????????????????????????????????????????}????????????????????????????????????????????????????????????????????????????????????????????????return sum;????????????????????????}????????????????????????????????????????????????????????????????????????// Create the dictionary of unique sum???????????????????
???????????????????????????????????????if (!d.ContainsKey(sum1))????????????????????????????????d.Add(sum1, 1);????????????????????????else????????????????????????????????d[sum1] += 1;????????????????}????????????????return d;????????}????????????????????????// Function to find the??????????// largest size of group??????????static int countLargest(int n)????????{????????????????Dictionary<int, int> d = constDict(n);??????????????????????????????????????????int size = 0;????????????????????????????????// Count of largest size group??????????????????int count = 0;??????????????????????????????????foreach(KeyValuePair<int, int> it in d)????????????????{????????????????????????int k = it.Key;????????????????????????int val = it.Value;????????????????????????????????????????????????????if (val > size)????????????????????????{????????????????????????????????????????????????????????size = val;????????????????????????????????count = 1;????????????????????????}????????????????????????else if (val == size)????????????????????????????????????????????????????????count += 1;????????????????}????????????????????????????????return count;????????}??????????????// Driver code????static void Main()????{????????int n = 13;????????int group = countLargest(n);??????????Console.WriteLine(group);????}}??// This code is contributed by divyesh072019
#Output : 4
[END]
|
Count of groups having largest size while grouping according to sum of its digits
|
https://www.geeksforgeeks.org/count-of-groups-having-largest-size-while-grouping-according-to-sum-of-its-digits/?ref=leftbar-rightbar
|
// JS implementation to Count the// number of groups having the largest// size where groups are according// to the sum of its digits????????????// function to return sum of digits of ifunction sumDigits(n){????????????????????????let sum = 0;????????????????????????while(n > 0)????????????????????????{????????????????????????????????????????????????sum += n%10;????????????????????????????????????????????????n = Math.floor(n / 10);????????????????????????}??????????????????????????????return sum;}??????// Create the dictionary of unique sumfunction constDict( n){??????????????????????????????????????????????????????// dictionary that contain????????????????????????// unique sum count????????????????????????let d = {};??????????????????????????????for(var i = 1; i < n + 1; ++i){????????????????????????????????????????????????// calculate the sum of its digits????????????????????????????????????????????????var sum1 = sumDigits(i);??????????????????????????????????????????????????????if(!d.hasOwnProperty(sum1))?????????????for (let [k, val] of Object.entries(d))????????{????????????????k = parseInt(k)????????????????val = parseInt(val)??????????????????if(val > size){??????????????????????????????????????????????size = val;????????????????????????count = 1;????????????????}????????????????else if(val == size)??????????????????????????????????????????????count += 1;????????}??????????return count;}??????????????????// Driver codelet n = 13;??let group = countLargest(n);??console.log(group);????// This code is contributed by phasing17
|
#Output : 4
|
Count of groups having largest size while grouping according to sum of its digits
// JS implementation to Count the// number of groups having the largest// size where groups are according// to the sum of its digits????????????// function to return sum of digits of ifunction sumDigits(n){????????????????????????let sum = 0;????????????????????????while(n > 0)????????????????????????{????????????????????????????????????????????????sum += n%10;????????????????????????????????????????????????n = Math.floor(n / 10);????????????????????????}??????????????????????????????return sum;}??????// Create the dictionary of unique sumfunction constDict( n){??????????????????????????????????????????????????????// dictionary that contain????????????????????????// unique sum count????????????????????????let d = {};??????????????????????????????for(var i = 1; i < n + 1; ++i){????????????????????????????????????????????????// calculate the sum of its digits????????????????????????????????????????????????var sum1 = sumDigits(i);??????????????????????????????????????????????????????if(!d.hasOwnProperty(sum1))?????????????for (let [k, val] of Object.entries(d))????????{????????????????k = parseInt(k)????????????????val = parseInt(val)??????????????????if(val > size){??????????????????????????????????????????????size = val;????????????????????????count = 1;????????????????}????????????????else if(val == size)??????????????????????????????????????????????count += 1;????????}??????????return count;}??????????????????// Driver codelet n = 13;??let group = countLargest(n);??console.log(group);????// This code is contributed by phasing17
#Output : 4
[END]
|
Python - Sort Dictionary key and values List
|
https://www.geeksforgeeks.org/python-sort-dictionary-key-and-values-list/?ref=leftbar-rightbar
|
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
res = dict()
for key in sorted(test_dict):
res[key] = sorted(test_dict[key])
# printing result
print("The sorted dictionary : " + str(res))
|
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
|
Python - Sort Dictionary key and values List
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary key and values List
# Using loop + dictionary comprehension
res = dict()
for key in sorted(test_dict):
res[key] = sorted(test_dict[key])
# printing result
print("The sorted dictionary : " + str(res))
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
[END]
|
Python - Sort Dictionary key and values List
|
https://www.geeksforgeeks.org/python-sort-dictionary-key-and-values-list/?ref=leftbar-rightbar
|
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
res = {key: sorted(test_dict[key]) for key in sorted(test_dict)}
# printing result
print("The sorted dictionary : " + str(res))
|
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
|
Python - Sort Dictionary key and values List
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Sort Dictionary key and values List
# Using dictionary comprehension + sorted()
res = {key: sorted(test_dict[key]) for key in sorted(test_dict)}
# printing result
print("The sorted dictionary : " + str(res))
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
[END]
|
Python - Sort Dictionary key and values List
|
https://www.geeksforgeeks.org/python-sort-dictionary-key-and-values-list/?ref=leftbar-rightbar
|
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using lambda function with sorted()
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
# Sort Dictionary key and values List
# Using lambda function with sorted()
res = dict(sorted(test_dict.items(), key=lambda x: x[0]))
for key in res:
res[key] = sorted(res[key])
# printing result
print("The sorted dictionary: " + str(res))
|
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
|
Python - Sort Dictionary key and values List
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using lambda function with sorted()
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
# Sort Dictionary key and values List
# Using lambda function with sorted()
res = dict(sorted(test_dict.items(), key=lambda x: x[0]))
for key in res:
res[key] = sorted(res[key])
# printing result
print("The sorted dictionary: " + str(res))
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
[END]
|
Python - Sort Dictionary key and values List
|
https://www.geeksforgeeks.org/python-sort-dictionary-key-and-values-list/?ref=leftbar-rightbar
|
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using zip() function with sorted()
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
# Sort Dictionary key and values List
# Using zip() function with sorted()
keys = list(test_dict.keys())
values = list(test_dict.values())
sorted_tuples = sorted(zip(keys, values), key=lambda x: x[0])
res = {k: sorted(v) for k, v in sorted_tuples}
# printing result
print("The sorted dictionary: " + str(res))
|
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
|
Python - Sort Dictionary key and values List
# Python3 code to demonstrate working of
# Sort Dictionary key and values List
# Using zip() function with sorted()
# initializing dictionary
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
# printing original dictionary
print("The original dictionary is: " + str(test_dict))
# Sort Dictionary key and values List
# Using zip() function with sorted()
keys = list(test_dict.keys())
values = list(test_dict.values())
sorted_tuples = sorted(zip(keys, values), key=lambda x: x[0])
res = {k: sorted(v) for k, v in sorted_tuples}
# printing result
print("The sorted dictionary: " + str(res))
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
[END]
|
Python - Sort Dictionary key and values List
|
https://www.geeksforgeeks.org/python-sort-dictionary-key-and-values-list/?ref=leftbar-rightbar
|
def sort_dict_recursive(test_dict):
if not test_dict:
return {}
min_key = min(test_dict.keys())
sorted_values = sorted(test_dict[min_key])
rest_dict = {k: v for k, v in test_dict.items() if k != min_key}
sorted_rest_dict = sort_dict_recursive(rest_dict)
return {min_key: sorted_values, **sorted_rest_dict}
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
res = sort_dict_recursive(test_dict)
print("The original dictionary is: " + str(test_dict))
print("The sorted dictionary : " + str(res))
|
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
|
Python - Sort Dictionary key and values List
def sort_dict_recursive(test_dict):
if not test_dict:
return {}
min_key = min(test_dict.keys())
sorted_values = sorted(test_dict[min_key])
rest_dict = {k: v for k, v in test_dict.items() if k != min_key}
sorted_rest_dict = sort_dict_recursive(rest_dict)
return {min_key: sorted_values, **sorted_rest_dict}
test_dict = {"gfg": [7, 6, 3], "is": [2, 10, 3], "best": [19, 4]}
res = sort_dict_recursive(test_dict)
print("The original dictionary is: " + str(test_dict))
print("The sorted dictionary : " + str(res))
#Output : The original dictionary is: {'gfg': [7, 6, 3], 'is': [2, 10, 3], 'best': [19, 4]}
[END]
|
Python - Sort Dictionary by Values Summation
|
https://www.geeksforgeeks.org/python-sort-dictionary-by-values-summation/
|
# Python3 code to demonstrate working of
# Sort Dictionary by Values Summation
# Using dictionary comprehension + sum() + sorted()
# initializing dictionary
test_dict = {"Gfg": [6, 7, 4], "is": [4, 3, 2], "best": [7, 6, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# summing all the values using sum()
temp1 = {val: sum(int(idx) for idx in key) for val, key in test_dict.items()}
# using sorted to perform sorting as required
temp2 = sorted(temp1.items(), key=lambda ele: temp1[ele[0]])
# rearrange into dictionary
res = {key: val for key, val in temp2}
# printing result
print("The sorted dictionary : " + str(res))
|
#Output : The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
|
Python - Sort Dictionary by Values Summation
# Python3 code to demonstrate working of
# Sort Dictionary by Values Summation
# Using dictionary comprehension + sum() + sorted()
# initializing dictionary
test_dict = {"Gfg": [6, 7, 4], "is": [4, 3, 2], "best": [7, 6, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# summing all the values using sum()
temp1 = {val: sum(int(idx) for idx in key) for val, key in test_dict.items()}
# using sorted to perform sorting as required
temp2 = sorted(temp1.items(), key=lambda ele: temp1[ele[0]])
# rearrange into dictionary
res = {key: val for key, val in temp2}
# printing result
print("The sorted dictionary : " + str(res))
#Output : The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
[END]
|
Python - Sort Dictionary by Values Summation
|
https://www.geeksforgeeks.org/python-sort-dictionary-by-values-summation/
|
# Python3 code to demonstrate working of
# Sort Dictionary by Values Summation
# Using map() + dictionary comprehension + sorted() + sum()
# initializing dictionary
test_dict = {"Gfg": [6, 7, 4], "is": [4, 3, 2], "best": [7, 6, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# summing all the values using sum()
# map() is used to extend summation to sorted()
temp = {key: sum(map(lambda ele: ele, test_dict[key])) for key in test_dict}
res = {key: temp[key] for key in sorted(temp, key=temp.get)}
# printing result
print("The sorted dictionary : " + str(res))
|
#Output : The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
|
Python - Sort Dictionary by Values Summation
# Python3 code to demonstrate working of
# Sort Dictionary by Values Summation
# Using map() + dictionary comprehension + sorted() + sum()
# initializing dictionary
test_dict = {"Gfg": [6, 7, 4], "is": [4, 3, 2], "best": [7, 6, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# summing all the values using sum()
# map() is used to extend summation to sorted()
temp = {key: sum(map(lambda ele: ele, test_dict[key])) for key in test_dict}
res = {key: temp[key] for key in sorted(temp, key=temp.get)}
# printing result
print("The sorted dictionary : " + str(res))
#Output : The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
[END]
|
Python - Sort Dictionary by Values Summation
|
https://www.geeksforgeeks.org/python-sort-dictionary-by-values-summation/
|
from collections import defaultdict
# initializing dictionary
test_dict = {"Gfg": [6, 7, 4], "is": [4, 3, 2], "best": [7, 6, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using defaultdict() to sum the values
temp_dict = defaultdict(int)
for key, val in test_dict.items():
temp_dict[key] = sum(val)
# sorting the dictionary based on the summed values
sorted_dict = dict(sorted(temp_dict.items(), key=lambda x: x[1]))
# printing result
print("The sorted dictionary : " + str(sorted_dict))
|
#Output : The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
|
Python - Sort Dictionary by Values Summation
from collections import defaultdict
# initializing dictionary
test_dict = {"Gfg": [6, 7, 4], "is": [4, 3, 2], "best": [7, 6, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using defaultdict() to sum the values
temp_dict = defaultdict(int)
for key, val in test_dict.items():
temp_dict[key] = sum(val)
# sorting the dictionary based on the summed values
sorted_dict = dict(sorted(temp_dict.items(), key=lambda x: x[1]))
# printing result
print("The sorted dictionary : " + str(sorted_dict))
#Output : The original dictionary is : {'Gfg': [6, 7, 4], 'is': [4, 3, 2], 'best': [7, 6, 5]}
[END]
|
Python - Sort dictionaries list by Keys Value List index
|
https://www.geeksforgeeks.org/python-sort-dictionaries-list-by-keys-value-list-index/
|
# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using sorted() + lambda
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using sorted() to perform sort in basis of 1 parameter key and
# index
res = sorted(test_list, key=lambda ele: ele[K][idx])
# printing result
print("The required sort order : " + str(res))
|
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
|
Python - Sort dictionaries list by Keys Value List index
# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using sorted() + lambda
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using sorted() to perform sort in basis of 1 parameter key and
# index
res = sorted(test_list, key=lambda ele: ele[K][idx])
# printing result
print("The required sort order : " + str(res))
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
[END]
|
Python - Sort dictionaries list by Keys Value List index
|
https://www.geeksforgeeks.org/python-sort-dictionaries-list-by-keys-value-list-index/
|
# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using sorted() + lambda (Additional parameter in case of tie)
# initializing lists
test_list = [
{"Gfg": [6, 7, 9], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# initializing K2
K2 = "best"
# using sorted() to perform sort in basis of 2 parameter key
# inner is evaluated after the outer key in lambda order
res = sorted(sorted(test_list, key=lambda ele: ele[K2]), key=lambda ele: ele[K][idx])
# printing result
print("The required sort order : " + str(res))
|
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
|
Python - Sort dictionaries list by Keys Value List index
# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using sorted() + lambda (Additional parameter in case of tie)
# initializing lists
test_list = [
{"Gfg": [6, 7, 9], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# initializing K2
K2 = "best"
# using sorted() to perform sort in basis of 2 parameter key
# inner is evaluated after the outer key in lambda order
res = sorted(sorted(test_list, key=lambda ele: ele[K2]), key=lambda ele: ele[K][idx])
# printing result
print("The required sort order : " + str(res))
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
[END]
|
Python - Sort dictionaries list by Keys Value List index
|
https://www.geeksforgeeks.org/python-sort-dictionaries-list-by-keys-value-list-index/
|
from operator import itemgetter
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using sorted() with itemgetter() to perform sort in basis of 1 parameter key and index
res = sorted(test_list, key=lambda x: (x[K][idx]))
# printing result
print("The required sort order : " + str(res))
|
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
|
Python - Sort dictionaries list by Keys Value List index
from operator import itemgetter
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using sorted() with itemgetter() to perform sort in basis of 1 parameter key and index
res = sorted(test_list, key=lambda x: (x[K][idx]))
# printing result
print("The required sort order : " + str(res))
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
[END]
|
Python - Sort dictionaries list by Keys Value List index
|
https://www.geeksforgeeks.org/python-sort-dictionaries-list-by-keys-value-list-index/
|
# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using a list comprehension and the built-in sorted() function
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using a list comprehension and the built-in sorted() function
res = [d for d in sorted(test_list, key=lambda x: x[K][idx])]
# printing result
print("The required sort order : " + str(res))
|
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
|
Python - Sort dictionaries list by Keys Value List index
# Python3 code to demonstrate working of
# Sort dictionaries list by Key's Value list index
# Using a list comprehension and the built-in sorted() function
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using a list comprehension and the built-in sorted() function
res = [d for d in sorted(test_list, key=lambda x: x[K][idx])]
# printing result
print("The required sort order : " + str(res))
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
[END]
|
Python - Sort dictionaries list by Keys Value List index
|
https://www.geeksforgeeks.org/python-sort-dictionaries-list-by-keys-value-list-index/
|
import operator
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using sorted() to perform sort in basis of 1 parameter key and
# index
res = sorted(test_list, key=operator.itemgetter(K, idx))
# printing result
print("The required sort order : " + str(res))
|
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
|
Python - Sort dictionaries list by Keys Value List index
import operator
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using sorted() to perform sort in basis of 1 parameter key and
# index
res = sorted(test_list, key=operator.itemgetter(K, idx))
# printing result
print("The required sort order : " + str(res))
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
[END]
|
Python - Sort dictionaries list by Keys Value List index
|
https://www.geeksforgeeks.org/python-sort-dictionaries-list-by-keys-value-list-index/
|
import heapq
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using heapq.nsmallest() to get the required sort order
res = heapq.nsmallest(len(test_list), test_list, key=lambda x: x[K][idx])
# printing result
print("The required sort order : " + str(res))
|
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
|
Python - Sort dictionaries list by Keys Value List index
import heapq
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# initializing K
K = "Gfg"
# initializing idx
idx = 2
# using heapq.nsmallest() to get the required sort order
res = heapq.nsmallest(len(test_list), test_list, key=lambda x: x[K][idx])
# printing result
print("The required sort order : " + str(res))
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
[END]
|
Python - Sort dictionaries list by Keys Value List index
|
https://www.geeksforgeeks.org/python-sort-dictionaries-list-by-keys-value-list-index/
|
import functools
def compare_dicts_by_key_index(d1, d2, key, idx):
if d1[key][idx] < d2[key][idx]:
return -1
elif d1[key][idx] > d2[key][idx]:
return 1
else:
# if the values at the given index are equal,
# sort by the "is" key in descending order
if d1["is"] > d2["is"]:
return -1
elif d1["is"] < d2["is"]:
return 1
else:
return 0
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# initializing K and idx
K = "Gfg"
idx = 2
# sorting the list using functools.cmp_to_key() and compare_dicts_by_key_index()
res = sorted(
test_list,
key=functools.cmp_to_key(lambda d1, d2: compare_dicts_by_key_index(d1, d2, K, idx)),
)
# printing result
print("The required sort order: " + str(res))
|
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
|
Python - Sort dictionaries list by Keys Value List index
import functools
def compare_dicts_by_key_index(d1, d2, key, idx):
if d1[key][idx] < d2[key][idx]:
return -1
elif d1[key][idx] > d2[key][idx]:
return 1
else:
# if the values at the given index are equal,
# sort by the "is" key in descending order
if d1["is"] > d2["is"]:
return -1
elif d1["is"] < d2["is"]:
return 1
else:
return 0
# initializing lists
test_list = [
{"Gfg": [6, 7, 8], "is": 9, "best": 10},
{"Gfg": [2, 0, 3], "is": 11, "best": 19},
{"Gfg": [4, 6, 9], "is": 16, "best": 1},
]
# initializing K and idx
K = "Gfg"
idx = 2
# sorting the list using functools.cmp_to_key() and compare_dicts_by_key_index()
res = sorted(
test_list,
key=functools.cmp_to_key(lambda d1, d2: compare_dicts_by_key_index(d1, d2, K, idx)),
)
# printing result
print("The required sort order: " + str(res))
#Output : The original list : [{'Gfg': [6, 7, 8], 'is': 9, 'best': 10}, {'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [4, 6, 9], 'is': 16, 'best': 1}]
[END]
|
Python - Scoring Matrix using Dictionary
|
https://www.geeksforgeeks.org/python-scoring-matrix-using-dictionary/
|
# Python3 code to demonstrate working of
# Scoring Matrix using Dictionary
# Using loop
# initializing list
test_list = [["gfg", "is", "best"], ["gfg", "is", "for", "geeks"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing test dict
test_dict = {"gfg": 5, "is": 10, "best": 13, "for": 2, "geeks": 15}
# Scoring Matrix using Dictionary
# Using loop
res = []
for sub in test_list:
sum = 0
for val in sub:
if val in test_dict:
sum += test_dict[val]
res.append(sum)
# printing result
print("The Row scores : " + str(res))
|
#Output : The original list is : [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
|
Python - Scoring Matrix using Dictionary
# Python3 code to demonstrate working of
# Scoring Matrix using Dictionary
# Using loop
# initializing list
test_list = [["gfg", "is", "best"], ["gfg", "is", "for", "geeks"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing test dict
test_dict = {"gfg": 5, "is": 10, "best": 13, "for": 2, "geeks": 15}
# Scoring Matrix using Dictionary
# Using loop
res = []
for sub in test_list:
sum = 0
for val in sub:
if val in test_dict:
sum += test_dict[val]
res.append(sum)
# printing result
print("The Row scores : " + str(res))
#Output : The original list is : [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
[END]
|
Python - Scoring Matrix using Dictionary
|
https://www.geeksforgeeks.org/python-scoring-matrix-using-dictionary/
|
# Python3 code to demonstrate working of
# Scoring Matrix using Dictionary
# Using list comprehension + sum()
# initializing list
test_list = [["gfg", "is", "best"], ["gfg", "is", "for", "geeks"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing test dict
test_dict = {"gfg": 5, "is": 10, "best": 13, "for": 2, "geeks": 15}
# Scoring Matrix using Dictionary
# Using list comprehension + sum()
res = [
sum(test_dict[word] if word.lower() in test_dict else 0 for word in sub)
for sub in test_list
]
# printing result
print("The Row scores : " + str(res))
|
#Output : The original list is : [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
|
Python - Scoring Matrix using Dictionary
# Python3 code to demonstrate working of
# Scoring Matrix using Dictionary
# Using list comprehension + sum()
# initializing list
test_list = [["gfg", "is", "best"], ["gfg", "is", "for", "geeks"]]
# printing original list
print("The original list is : " + str(test_list))
# initializing test dict
test_dict = {"gfg": 5, "is": 10, "best": 13, "for": 2, "geeks": 15}
# Scoring Matrix using Dictionary
# Using list comprehension + sum()
res = [
sum(test_dict[word] if word.lower() in test_dict else 0 for word in sub)
for sub in test_list
]
# printing result
print("The Row scores : " + str(res))
#Output : The original list is : [['gfg', 'is', 'best'], ['gfg', 'is', 'for', 'geeks']]
[END]
|
Python - Factors Frequency Dictionary
|
https://www.geeksforgeeks.org/python-factors-frequency-dictionary/
|
# Python3 code to demonstrate working of
# Factors Frequency Dictionary
# Using loop
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
res = dict()
# iterating till max element
for idx in range(1, max(test_list)):
res[idx] = 0
for key in test_list:
# checking for factor
if key % idx == 0:
res[idx] += 1
# printing result
print("The constructed dictionary : " + str(res))
|
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
|
Python - Factors Frequency Dictionary
# Python3 code to demonstrate working of
# Factors Frequency Dictionary
# Using loop
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
res = dict()
# iterating till max element
for idx in range(1, max(test_list)):
res[idx] = 0
for key in test_list:
# checking for factor
if key % idx == 0:
res[idx] += 1
# printing result
print("The constructed dictionary : " + str(res))
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
[END]
|
Python - Factors Frequency Dictionary
|
https://www.geeksforgeeks.org/python-factors-frequency-dictionary/
|
# Python3 code to demonstrate working of
# Factors Frequency Dictionary
# Using sum() + loop
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
res = dict()
for idx in range(1, max(test_list)):
# using sum() instead of loop for sum computation
res[idx] = sum(key % idx == 0 for key in test_list)
# printing result
print("The constructed dictionary : " + str(res))
|
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
|
Python - Factors Frequency Dictionary
# Python3 code to demonstrate working of
# Factors Frequency Dictionary
# Using sum() + loop
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
res = dict()
for idx in range(1, max(test_list)):
# using sum() instead of loop for sum computation
res[idx] = sum(key % idx == 0 for key in test_list)
# printing result
print("The constructed dictionary : " + str(res))
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
[END]
|
Python - Factors Frequency Dictionary
|
https://www.geeksforgeeks.org/python-factors-frequency-dictionary/
|
import collections
import itertools
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
# using collections.Counter() and itertools.chain() to construct frequency dictionary
res = {
i: collections.Counter(
itertools.chain(
*[[j for j in range(1, i + 1) if key % j == 0] for key in test_list]
)
)[i]
for i in range(1, max(test_list) + 1)
}
# printing result
print("The constructed dictionary : " + str(res))
|
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
|
Python - Factors Frequency Dictionary
import collections
import itertools
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
# using collections.Counter() and itertools.chain() to construct frequency dictionary
res = {
i: collections.Counter(
itertools.chain(
*[[j for j in range(1, i + 1) if key % j == 0] for key in test_list]
)
)[i]
for i in range(1, max(test_list) + 1)
}
# printing result
print("The constructed dictionary : " + str(res))
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
[END]
|
Python - Factors Frequency Dictionary
|
https://www.geeksforgeeks.org/python-factors-frequency-dictionary/
|
# Python3 code to demonstrate working of
# Factors Frequency Dictionary
# Using loop
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
# iterating till max element
x = []
for i in range(1, max(test_list)):
for key in test_list:
if key % i == 0:
x.append(i)
y = list(set(x))
res = dict()
for i in y:
res[i] = x.count(i)
# printing result
print("The constructed dictionary : " + str(res))
|
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
|
Python - Factors Frequency Dictionary
# Python3 code to demonstrate working of
# Factors Frequency Dictionary
# Using loop
# initializing list
test_list = [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
# printing original list
print("The original list : " + str(test_list))
# iterating till max element
x = []
for i in range(1, max(test_list)):
for key in test_list:
if key % i == 0:
x.append(i)
y = list(set(x))
res = dict()
for i in y:
res[i] = x.count(i)
# printing result
print("The constructed dictionary : " + str(res))
#Output : The original list : [2, 4, 6, 8, 3, 9, 12, 15, 16, 18]
[END]
|
Count distinct substrings of a string using Rabin Karp algorithm
|
https://www.geeksforgeeks.org/count-of-distinct-substrings-of-a-given-string-using-rabin-karp-algorithm/?ref=leftbar-rightbar
|
#include <bits/stdc++.h>using namespace std;??????// Driver codeint main(){????????????int t = 1;??????????????????// store prime to reduce overflow????????????long long mod = 9007199254740881;??????????????????for(int i = 0; i < t; i++)????????????{????????????????????????"abcd";??????????????????????????????// to store substrings????????????????????????vector<vector<long long>>l;??????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????unordered_map<long long,int>d;??????????????????????????????for(int i=0;i<s.length();i++){????????????????????????????????????int suma = 0;????????????????????????????????????long long pre = 0;??????????????????????????????????????????// Number of input alphabets????????????????????????????????????long long D = 256;??????????????????????????????????????????for(int j=i;j<s.length();j++){??????????????????????????????????????????????????????// calculate new hash value by adding next element????????????????????????????????????????????????pre = (pre*D+s[j]) % mod;??????????????????????????????????????????????????????// store string length if non repeat???????" ";????????????}}??????// This code is contributed by
|
Input : str = ?????????aba????????
|
Count distinct substrings of a string using Rabin Karp algorithm
#include <bits/stdc++.h>using namespace std;??????// Driver codeint main(){????????????int t = 1;??????????????????// store prime to reduce overflow????????????long long mod = 9007199254740881;??????????????????for(int i = 0; i < t; i++)????????????{????????????????????????"abcd";??????????????????????????????// to store substrings????????????????????????vector<vector<long long>>l;??????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????unordered_map<long long,int>d;??????????????????????????????for(int i=0;i<s.length();i++){????????????????????????????????????int suma = 0;????????????????????????????????????long long pre = 0;??????????????????????????????????????????// Number of input alphabets????????????????????????????????????long long D = 256;??????????????????????????????????????????for(int j=i;j<s.length();j++){??????????????????????????????????????????????????????// calculate new hash value by adding next element????????????????????????????????????????????????pre = (pre*D+s[j]) % mod;??????????????????????????????????????????????????????// store string length if non repeat???????" ";????????????}}??????// This code is contributed by
Input : str = ?????????aba????????
[END]
|
Count distinct substrings of a string using Rabin Karp algorithm
|
https://www.geeksforgeeks.org/count-of-distinct-substrings-of-a-given-string-using-rabin-karp-algorithm/?ref=leftbar-rightbar
|
import java.util.*;??????public class Main {????????????????????????public static void main(String[] args) {????????????????????????????????????????????????int t = 1;????????????????????????????????????????????????// store prime to reduce overflow????????????????????????????????????????????????long mod = 9007199254740881L;???????????????????????????????????????"abcd";??????????????????????????????????????????????????????????????????????????????// to store substrings????????????????????????????????????????????????????????????????????????List<List<Integer>> l = new ArrayList<>();??????????????????????????????????????????????????????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????????????????????????????????????????????????????Map<Long, Integer> d = new HashMap<>();??????????????????????????????????????????????????????????????????????????????for (int j = 0; j < s.length(); j++) {????????????????????????????????????????????????????????????????????????????????????????????????long suma = 0;????????????????????????????????????????????????????????????????????????????????????????????????long pre = 0;??????????????????????????????????????????????????????????????????????????????????????????????????????// Number of input alphabets????????????????????????????????????????????????????????????????????????????????????????????????int D = 256;??????????????sublist.add(j);????????????????????????????????????????????????sublist.add(k);????????????????????????????????????????????????l.add(sublist);????????????????????????????????????????}????????????????????????????????????????d.put(pre, 1);????????????????????????????????}????????????????????????}??????????????????????????// resulting length????????????????????????System.out.println(l.size());??????????????????????????// resulting distinct substrings????????????????????????for (int j = 0; j < l.size(); j++) {????????????????????????????????int start = l.get(j).get(0);????????????????????????????????int end = l.get(j).get(1);????????????????????????????????System.out.print(s.substring(start, end+1) + " ");????????????????????????????????????????????????????
|
Input : str = ?????????aba????????
|
Count distinct substrings of a string using Rabin Karp algorithm
import java.util.*;??????public class Main {????????????????????????public static void main(String[] args) {????????????????????????????????????????????????int t = 1;????????????????????????????????????????????????// store prime to reduce overflow????????????????????????????????????????????????long mod = 9007199254740881L;???????????????????????????????????????"abcd";??????????????????????????????????????????????????????????????????????????????// to store substrings????????????????????????????????????????????????????????????????????????List<List<Integer>> l = new ArrayList<>();??????????????????????????????????????????????????????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????????????????????????????????????????????????????Map<Long, Integer> d = new HashMap<>();??????????????????????????????????????????????????????????????????????????????for (int j = 0; j < s.length(); j++) {????????????????????????????????????????????????????????????????????????????????????????????????long suma = 0;????????????????????????????????????????????????????????????????????????????????????????????????long pre = 0;??????????????????????????????????????????????????????????????????????????????????????????????????????// Number of input alphabets????????????????????????????????????????????????????????????????????????????????????????????????int D = 256;??????????????sublist.add(j);????????????????????????????????????????????????sublist.add(k);????????????????????????????????????????????????l.add(sublist);????????????????????????????????????????}????????????????????????????????????????d.put(pre, 1);????????????????????????????????}????????????????????????}??????????????????????????// resulting length????????????????????????System.out.println(l.size());??????????????????????????// resulting distinct substrings????????????????????????for (int j = 0; j < l.size(); j++) {????????????????????????????????int start = l.get(j).get(0);????????????????????????????????int end = l.get(j).get(1);????????????????????????????????System.out.print(s.substring(start, end+1) + " ");????????????????????????????????????????????????????
Input : str = ?????????aba????????
[END]
|
Count distinct substrings of a string using Rabin Karp algorithm
|
https://www.geeksforgeeks.org/count-of-distinct-substrings-of-a-given-string-using-rabin-karp-algorithm/?ref=leftbar-rightbar
|
# importing libraries
import sys
import math as mt
t = 1
# store prime to reduce overflow
mod = 9007199254740881
for ___ in range(t):
# string to check number of distinct substring
s = "abcd"
# to store substrings
l = []
# to store hash values by Rabin Karp algorithm
d = {}
for i in range(len(s)):
suma = 0
pre = 0
# Number of input alphabets
D = 256
for j in range(i, len(s)):
# calculate new hash value by adding next element
pre = (pre * D + ord(s[j])) % mod
# store string length if non repeat
if d.get(pre, -1) == -1:
l.append([i, j])
d[pre] = 1
# resulting length
print(len(l))
# resulting distinct substrings
for i in range(len(l)):
print(s[l[i][0] : l[i][1] + 1], end=" ")
|
Input : str = ?????????aba????????
|
Count distinct substrings of a string using Rabin Karp algorithm
# importing libraries
import sys
import math as mt
t = 1
# store prime to reduce overflow
mod = 9007199254740881
for ___ in range(t):
# string to check number of distinct substring
s = "abcd"
# to store substrings
l = []
# to store hash values by Rabin Karp algorithm
d = {}
for i in range(len(s)):
suma = 0
pre = 0
# Number of input alphabets
D = 256
for j in range(i, len(s)):
# calculate new hash value by adding next element
pre = (pre * D + ord(s[j])) % mod
# store string length if non repeat
if d.get(pre, -1) == -1:
l.append([i, j])
d[pre] = 1
# resulting length
print(len(l))
# resulting distinct substrings
for i in range(len(l)):
print(s[l[i][0] : l[i][1] + 1], end=" ")
Input : str = ?????????aba????????
[END]
|
Count distinct substrings of a string using Rabin Karp algorithm
|
https://www.geeksforgeeks.org/count-of-distinct-substrings-of-a-given-string-using-rabin-karp-algorithm/?ref=leftbar-rightbar
|
<script>??????let t = 1??????// store prime to reduce overflowlet mod = 9007199254740881??????for(let i = 0; i < t; i++){????????????????????????// string to check number of distinct substring????????????????????????let s = 'abcd'??????????????????????????????// to store substrings????????????????????????let l = []??????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????let d = new Map()??????????????????????????????for(let i=0;i<s.length;i++){????????????????????????????????????????????????let suma = 0????????????????????????????????????????????????let pre = 0??????????????????????????????????????????????????????// Number of input alphabets????????????????????????????????????????????????let D = 256??????????????????????????????????????????????????????for(let j=i;j<s.length;j++){??????????????????????????????????????????????????????????????????????????????// calculate new hash value by adding n"</br>")??????????????????????????????// resulting distinct substrings????????????????????????for(let i = 0; i < l.length; i++)??????????????????????????" ")}??????// This code is contributed by shinjanpatra??????<
|
Input : str = ?????????aba????????
|
Count distinct substrings of a string using Rabin Karp algorithm
<script>??????let t = 1??????// store prime to reduce overflowlet mod = 9007199254740881??????for(let i = 0; i < t; i++){????????????????????????// string to check number of distinct substring????????????????????????let s = 'abcd'??????????????????????????????// to store substrings????????????????????????let l = []??????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????let d = new Map()??????????????????????????????for(let i=0;i<s.length;i++){????????????????????????????????????????????????let suma = 0????????????????????????????????????????????????let pre = 0??????????????????????????????????????????????????????// Number of input alphabets????????????????????????????????????????????????let D = 256??????????????????????????????????????????????????????for(let j=i;j<s.length;j++){??????????????????????????????????????????????????????????????????????????????// calculate new hash value by adding n"</br>")??????????????????????????????// resulting distinct substrings????????????????????????for(let i = 0; i < l.length; i++)??????????????????????????" ")}??????// This code is contributed by shinjanpatra??????<
Input : str = ?????????aba????????
[END]
|
Count distinct substrings of a string using Rabin Karp algorithm
|
https://www.geeksforgeeks.org/count-of-distinct-substrings-of-a-given-string-using-rabin-karp-algorithm/?ref=leftbar-rightbar
|
using System;using System.Collections.Generic;??????class GFG {static void Main(){int t = 1;????????????????????????????????????// store prime to reduce overflow????????????????????????long mod = 9007199254740881;??????????????????????????????for (int i = 0; i < t; i++)????????????????????????{??????????"abcd";??????????????????????????????????????????????????????// to store substrings????????????????????????????????????????????????List<List<long>> l = new List<List<long>>();??????????????????????????????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????????????????????????????Dictionary<long, int> d = new Dictionary<long, int>();??????????????????????????????????????????????????????for (int j = 0; j < s.Length; j++)????????????????????????????????????????????????{????????????????????????????????????????????????????????????????????????int suma = 0;????????????????????????????????????????????????????????????????????????long pre = 0;??????????????????????????????????????????????????????????????????????????????// Number of input alphabets????????????????????????????????????????????????????????????????????????long D = 256;??????????????????????????????????????????????????????????????????????????????for (int k = j; k < s.Length; k++)??????????????????????????????????????????b.Add(k);????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????l.Add(sub);????????????????????????????????????????????????????????????????????????????????????????????????}????????????????????????????????????????????????????????????????????????????????????????????????d[pre] = 1;????????????????????????????????????????????????????????????????????????}????????????????????????????????????????????????}?????????????????????????????????????????" ");????????????????????????????????????????????????}?????????????????????
|
Input : str = ?????????aba????????
|
Count distinct substrings of a string using Rabin Karp algorithm
using System;using System.Collections.Generic;??????class GFG {static void Main(){int t = 1;????????????????????????????????????// store prime to reduce overflow????????????????????????long mod = 9007199254740881;??????????????????????????????for (int i = 0; i < t; i++)????????????????????????{??????????"abcd";??????????????????????????????????????????????????????// to store substrings????????????????????????????????????????????????List<List<long>> l = new List<List<long>>();??????????????????????????????????????????????????????// to store hash values by Rabin Karp algorithm????????????????????????????????????????????????Dictionary<long, int> d = new Dictionary<long, int>();??????????????????????????????????????????????????????for (int j = 0; j < s.Length; j++)????????????????????????????????????????????????{????????????????????????????????????????????????????????????????????????int suma = 0;????????????????????????????????????????????????????????????????????????long pre = 0;??????????????????????????????????????????????????????????????????????????????// Number of input alphabets????????????????????????????????????????????????????????????????????????long D = 256;??????????????????????????????????????????????????????????????????????????????for (int k = j; k < s.Length; k++)??????????????????????????????????????????b.Add(k);????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????l.Add(sub);????????????????????????????????????????????????????????????????????????????????????????????????}????????????????????????????????????????????????????????????????????????????????????????????????d[pre] = 1;????????????????????????????????????????????????????????????????????????}????????????????????????????????????????????????}?????????????????????????????????????????" ");????????????????????????????????????????????????}?????????????????????
Input : str = ?????????aba????????
[END]
|
Count distinct substrings of a string using Rabin Karp algorithm
|
https://www.geeksforgeeks.org/count-of-distinct-substrings-of-a-given-string-using-rabin-karp-algorithm/?ref=leftbar-rightbar
|
#include <iostream>#include <unordered_set>#include <string>??????using namespace std;??????int main() {????????????????????????// Input s"abcd";??????????????????????????????// Set to store distinct substrings????????????????????????unordered_set<string> substrings;??????????????????????????????// Iterate over all possible substrings and add them to the set????????????????????????for (int i = 0; i < s.size(); i++) {????????????????????????????????????????????????for (int j = i; j < s.size(); j++) {????????????????????????????????????????????????????????????????????????substrings.insert(s.substr(i, j - i + 1));???????
|
Input : str = ?????????aba????????
|
Count distinct substrings of a string using Rabin Karp algorithm
#include <iostream>#include <unordered_set>#include <string>??????using namespace std;??????int main() {????????????????????????// Input s"abcd";??????????????????????????????// Set to store distinct substrings????????????????????????unordered_set<string> substrings;??????????????????????????????// Iterate over all possible substrings and add them to the set????????????????????????for (int i = 0; i < s.size(); i++) {????????????????????????????????????????????????for (int j = i; j < s.size(); j++) {????????????????????????????????????????????????????????????????????????substrings.insert(s.substr(i, j - i + 1));???????
Input : str = ?????????aba????????
[END]
|
Count distinct substrings of a string using Rabin Karp algorithm
|
https://www.geeksforgeeks.org/count-of-distinct-substrings-of-a-given-string-using-rabin-karp-algorithm/?ref=leftbar-rightbar
|
import java.util.*;??????public class Main {????????????????????????public static void main(String[] args) {??????????????????????????????????????"abcd";??????????????????????????????????????????????????????// Set to store distinct substrings????????????????????????????????????????????????Set<String> substrings = new HashSet<>();??????????????????????????????????????????????????????// Iterate over all possible substrings and add them to the set????????????????????????????????????????????????for (int i = 0; i < s.length(); i++) {????????????????????????????????????????????????????????????????????????for (int j = i; j < s.length(); j++) {????????????????????????????????????????????????????????????????????????????????????????????????
|
Input : str = ?????????aba????????
|
Count distinct substrings of a string using Rabin Karp algorithm
import java.util.*;??????public class Main {????????????????????????public static void main(String[] args) {??????????????????????????????????????"abcd";??????????????????????????????????????????????????????// Set to store distinct substrings????????????????????????????????????????????????Set<String> substrings = new HashSet<>();??????????????????????????????????????????????????????// Iterate over all possible substrings and add them to the set????????????????????????????????????????????????for (int i = 0; i < s.length(); i++) {????????????????????????????????????????????????????????????????????????for (int j = i; j < s.length(); j++) {????????????????????????????????????????????????????????????????????????????????????????????????
Input : str = ?????????aba????????
[END]
|
Python program to build an undirected graph and finding shortest path using Dictionaries
|
https://www.geeksforgeeks.org/building-an-undirected-graph-and-finding-shortest-path-using-dictionaries-in-python/?ref=leftbar-rightbar
|
# Python3 implementation to build a
# graph using Dictionaries
from collections import defaultdict
# Function to build the graph
def build_graph():
edges = [
["A", "B"],
["A", "E"],
["A", "C"],
["B", "D"],
["B", "E"],
["C", "F"],
["C", "G"],
["D", "E"],
]
graph = defaultdict(list)
# Loop to iterate over every
# edge of the graph
for edge in edges:
a, b = edge[0], edge[1]
# Creating the graph
# as adjacency list
graph[a].append(b)
graph[b].append(a)
return graph
if __name__ == "__main__":
graph = build_graph()
print(graph)
|
#Output : {
|
Python program to build an undirected graph and finding shortest path using Dictionaries
# Python3 implementation to build a
# graph using Dictionaries
from collections import defaultdict
# Function to build the graph
def build_graph():
edges = [
["A", "B"],
["A", "E"],
["A", "C"],
["B", "D"],
["B", "E"],
["C", "F"],
["C", "G"],
["D", "E"],
]
graph = defaultdict(list)
# Loop to iterate over every
# edge of the graph
for edge in edges:
a, b = edge[0], edge[1]
# Creating the graph
# as adjacency list
graph[a].append(b)
graph[b].append(a)
return graph
if __name__ == "__main__":
graph = build_graph()
print(graph)
#Output : {
[END]
|
Python program to build an undirected graph and finding shortest path using Dictionaries
|
https://www.geeksforgeeks.org/building-an-undirected-graph-and-finding-shortest-path-using-dictionaries-in-python/?ref=leftbar-rightbar
|
# Python implementation to find the
# shortest path in the graph using
# dictionaries
# Function to find the shortest
# path between two nodes of a graph
def BFS_SP(graph, start, goal):
explored = []
# Queue for traversing the
# graph in the BFS
queue = [[start]]
# If the desired node is
# reached
if start == goal:
print("Same Node")
return
# Loop to traverse the graph
# with the help of the queue
while queue:
path = queue.pop(0)
node = path[-1]
# Condition to check if the
# current node is not visited
if node not in explored:
neighbours = graph[node]
# Loop to iterate over the
# neighbours of the node
for neighbour in neighbours:
new_path = list(path)
new_path.append(neighbour)
queue.append(new_path)
# Condition to check if the
# neighbour node is the goal
if neighbour == goal:
print("Shortest path = ", *new_path)
return
explored.append(node)
# Condition when the nodes
# are not connected
print("So sorry, but a connecting" "path doesn't exist :(")
return
# Driver Code
if __name__ == "__main__":
# Graph using dictionaries
graph = {
"A": ["B", "E", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B", "E"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
# Function Call
BFS_SP(graph, "A", "D")
|
#Output : {
|
Python program to build an undirected graph and finding shortest path using Dictionaries
# Python implementation to find the
# shortest path in the graph using
# dictionaries
# Function to find the shortest
# path between two nodes of a graph
def BFS_SP(graph, start, goal):
explored = []
# Queue for traversing the
# graph in the BFS
queue = [[start]]
# If the desired node is
# reached
if start == goal:
print("Same Node")
return
# Loop to traverse the graph
# with the help of the queue
while queue:
path = queue.pop(0)
node = path[-1]
# Condition to check if the
# current node is not visited
if node not in explored:
neighbours = graph[node]
# Loop to iterate over the
# neighbours of the node
for neighbour in neighbours:
new_path = list(path)
new_path.append(neighbour)
queue.append(new_path)
# Condition to check if the
# neighbour node is the goal
if neighbour == goal:
print("Shortest path = ", *new_path)
return
explored.append(node)
# Condition when the nodes
# are not connected
print("So sorry, but a connecting" "path doesn't exist :(")
return
# Driver Code
if __name__ == "__main__":
# Graph using dictionaries
graph = {
"A": ["B", "E", "C"],
"B": ["A", "D", "E"],
"C": ["A", "F", "G"],
"D": ["B", "E"],
"E": ["A", "B", "D"],
"F": ["C"],
"G": ["C"],
}
# Function Call
BFS_SP(graph, "A", "D")
#Output : {
[END]
|
LRU Cache in Python using OrderedDict
|
https://www.geeksforgeeks.org/lru-cache-in-python-using-ordereddict/?ref=leftbar-rightbar
|
from collections import OrderedDict
class LRUCache:
# initialising capacity
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
# we return the value of the key
# that is queried in O(1) and return -1 if we
# don't find the key in out dict / cache.
# And also move the key to the end
# to show that it was recently used.
def get(self, key: int) -> int:
if key not in self.cache:
return -1
else:
self.cache.move_to_end(key)
return self.cache[key]
# first, we add / update the key by conventional methods.
# And also move the key to the end to show that it was recently used.
# But here we will also check whether the length of our
# ordered dictionary has exceeded our capacity,
# If so we remove the first key (least recently used)
def put(self, key: int, value: int) -> None:
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
# RUNNER
# initializing our cache with the capacity of 2
cache = LRUCache(2)
cache.put(1, 1)
print(cache.cache)
cache.put(2, 2)
print(cache.cache)
cache.get(1)
print(cache.cache)
cache.put(3, 3)
print(cache.cache)
cache.get(2)
print(cache.cache)
cache.put(4, 4)
print(cache.cache)
cache.get(1)
print(cache.cache)
cache.get(3)
print(cache.cache)
cache.get(4)
print(cache.cache)
# This code was contributed by Sachin Negi
|
Input/#Output :
LRUCache cache = new LRUCache( 2 /* capacity */ );
|
LRU Cache in Python using OrderedDict
from collections import OrderedDict
class LRUCache:
# initialising capacity
def __init__(self, capacity: int):
self.cache = OrderedDict()
self.capacity = capacity
# we return the value of the key
# that is queried in O(1) and return -1 if we
# don't find the key in out dict / cache.
# And also move the key to the end
# to show that it was recently used.
def get(self, key: int) -> int:
if key not in self.cache:
return -1
else:
self.cache.move_to_end(key)
return self.cache[key]
# first, we add / update the key by conventional methods.
# And also move the key to the end to show that it was recently used.
# But here we will also check whether the length of our
# ordered dictionary has exceeded our capacity,
# If so we remove the first key (least recently used)
def put(self, key: int, value: int) -> None:
self.cache[key] = value
self.cache.move_to_end(key)
if len(self.cache) > self.capacity:
self.cache.popitem(last=False)
# RUNNER
# initializing our cache with the capacity of 2
cache = LRUCache(2)
cache.put(1, 1)
print(cache.cache)
cache.put(2, 2)
print(cache.cache)
cache.get(1)
print(cache.cache)
cache.put(3, 3)
print(cache.cache)
cache.get(2)
print(cache.cache)
cache.put(4, 4)
print(cache.cache)
cache.get(1)
print(cache.cache)
cache.get(3)
print(cache.cache)
cache.get(4)
print(cache.cache)
# This code was contributed by Sachin Negi
Input/#Output :
LRUCache cache = new LRUCache( 2 /* capacity */ );
[END]
|
Find the size of a Set in Python
|
https://www.geeksforgeeks.org/find-the-size-of-a-set-in-python/
|
import sys
# sample Sets
Set1 = {"A", 1, "B", 2, "C", 3}
Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}
Set3 = {(1, "Lion"), (2, "Tiger"), (3, "Fox")}
# print the sizes of sample Sets
print("Size of Set1: " + str(sys.getsizeof(Set1)) + "bytes")
print("Size of Set2: " + str(sys.getsizeof(Set2)) + "bytes")
print("Size of Set3: " + str(sys.getsizeof(Set3)) + "bytes")
|
#Output : Size of Set1: 736bytes
|
Find the size of a Set in Python
import sys
# sample Sets
Set1 = {"A", 1, "B", 2, "C", 3}
Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}
Set3 = {(1, "Lion"), (2, "Tiger"), (3, "Fox")}
# print the sizes of sample Sets
print("Size of Set1: " + str(sys.getsizeof(Set1)) + "bytes")
print("Size of Set2: " + str(sys.getsizeof(Set2)) + "bytes")
print("Size of Set3: " + str(sys.getsizeof(Set3)) + "bytes")
#Output : Size of Set1: 736bytes
[END]
|
Find the size of a Set in Python
|
https://www.geeksforgeeks.org/find-the-size-of-a-set-in-python/
|
import sys
# sample Sets
Set1 = {"A", 1, "B", 2, "C", 3}
Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}
Set3 = {(1, "Lion"), (2, "Tiger"), (3, "Fox")}
# print the sizes of sample Sets
print("Size of Set1: " + str(Set1.__sizeof__()) + "bytes")
print("Size of Set2: " + str(Set2.__sizeof__()) + "bytes")
print("Size of Set3: " + str(Set3.__sizeof__()) + "bytes")
|
#Output : Size of Set1: 736bytes
|
Find the size of a Set in Python
import sys
# sample Sets
Set1 = {"A", 1, "B", 2, "C", 3}
Set2 = {"Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu"}
Set3 = {(1, "Lion"), (2, "Tiger"), (3, "Fox")}
# print the sizes of sample Sets
print("Size of Set1: " + str(Set1.__sizeof__()) + "bytes")
print("Size of Set2: " + str(Set2.__sizeof__()) + "bytes")
print("Size of Set3: " + str(Set3.__sizeof__()) + "bytes")
#Output : Size of Set1: 736bytes
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# Creating a set using string
test_set = set("geEks")
# Iterating using for loop
for val in test_set:
print(val)
|
#Output : k
|
Iterate over a set in Python
# Creating a set using string
test_set = set("geEks")
# Iterating using for loop
for val in test_set:
print(val)
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
for val in test_set:
_ = val
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
for val in test_set:
_ = val
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# Creating a set using string
test_set = set("geEks")
# Iterating using enumerated for loop
for id, val in enumerate(test_set):
print(id, val)
|
#Output : k
|
Iterate over a set in Python
# Creating a set using string
test_set = set("geEks")
# Iterating using enumerated for loop
for id, val in enumerate(test_set):
print(id, val)
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
for id, val in enumerate(test_set):
_ = val
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
for id, val in enumerate(test_set):
_ = val
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# Creating a set using string
test_set = set("geEks")
test_list = list(test_set)
# Iterating over a set as a indexed list
for id in range(len(test_list)):
print(test_list[id])
|
#Output : k
|
Iterate over a set in Python
# Creating a set using string
test_set = set("geEks")
test_list = list(test_set)
# Iterating over a set as a indexed list
for id in range(len(test_list)):
print(test_list[id])
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
test_list = list(test_set)
for id in range(len(test_list)):
_ = test_list[id]
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
test_list = list(test_set)
for id in range(len(test_list)):
_ = test_list[id]
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# Creating a set using string
test_set = set("geEks")
# Iterating using list-comprehension
com = list(val for val in test_set)
print(*com)
|
#Output : k
|
Iterate over a set in Python
# Creating a set using string
test_set = set("geEks")
# Iterating using list-comprehension
com = list(val for val in test_set)
print(*com)
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
list(val for val in test_set)
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
list(val for val in test_set)
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# Creating a set using string
test_set = set("geEks")
# Iterating using list-comprehension
com = [print(val) for val in test_set]
|
#Output : k
|
Iterate over a set in Python
# Creating a set using string
test_set = set("geEks")
# Iterating using list-comprehension
com = [print(val) for val in test_set]
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
[val for val in test_set]
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
[val for val in test_set]
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
[map(lambda val: val, test_set)]
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
[map(lambda val: val, test_set)]
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
for val in iter(test_set):
_ = val
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
for val in iter(test_set):
_ = val
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# Creating a set using string
test_set = set("geEks")
iter_gen = iter(test_set)
while True:
try:
# get the next item
print(next(iter_gen))
""" do something with element """
except StopIteration:
# if StopIteration is raised,
# break from loop
break
|
#Output : k
|
Iterate over a set in Python
# Creating a set using string
test_set = set("geEks")
iter_gen = iter(test_set)
while True:
try:
# get the next item
print(next(iter_gen))
""" do something with element """
except StopIteration:
# if StopIteration is raised,
# break from loop
break
#Output : k
[END]
|
Iterate over a set in Python
|
https://www.geeksforgeeks.org/iterate-over-a-set-in-python/
|
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
iter_gen = iter(test_set)
while True:
try:
# get the next item
next(iter_gen)
# do something with element
except StopIteration:
# if StopIteration is raised, break from loop
break
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
|
#Output : k
|
Iterate over a set in Python
# importing libraries
from timeit import default_timer as timer
import itertools
import random
# Function under evaluation
def test_func(test_set):
iter_gen = iter(test_set)
while True:
try:
# get the next item
next(iter_gen)
# do something with element
except StopIteration:
# if StopIteration is raised, break from loop
break
# Driver function
if __name__ == "__main__":
random.seed(21)
for _ in range(5):
test_set = set()
# generating a set of random numbers
for el in range(int(1e6)):
el = random.random()
test_set.add(el)
start = timer()
test_func(test_set)
end = timer()
print(str(end - start))
#Output : k
[END]
|
Python - Maximum and Minimum in set
|
https://www.geeksforgeeks.org/python-maximum-minimum-set/
|
# Python code to get the maximum element from a set
def MAX(sets):
return max(sets)
# Driver Code
sets = set([8, 16, 24, 1, 25, 3, 10, 65, 55])
print(MAX(sets))
|
#Input : set = ([8, 16, 24, 1, 25, 3, 10, 65, 55])
#Output : max is 65
|
Python - Maximum and Minimum in set
# Python code to get the maximum element from a set
def MAX(sets):
return max(sets)
# Driver Code
sets = set([8, 16, 24, 1, 25, 3, 10, 65, 55])
print(MAX(sets))
#Input : set = ([8, 16, 24, 1, 25, 3, 10, 65, 55])
#Output : max is 65
[END]
|
Python - Maximum and Minimum in set
|
https://www.geeksforgeeks.org/python-maximum-minimum-set/
|
# Python code to get the minimum element from a set
def MIN(sets):
return min(sets)
# Driver Code
sets = set([4, 12, 10, 9, 4, 13])
print(MIN(sets))
|
#Input : set = ([8, 16, 24, 1, 25, 3, 10, 65, 55])
#Output : max is 65
|
Python - Maximum and Minimum in set
# Python code to get the minimum element from a set
def MIN(sets):
return min(sets)
# Driver Code
sets = set([4, 12, 10, 9, 4, 13])
print(MIN(sets))
#Input : set = ([8, 16, 24, 1, 25, 3, 10, 65, 55])
#Output : max is 65
[END]
|
Python - Remove items from Set
|
https://www.geeksforgeeks.org/python-remove-items-set/
|
# Python program to remove elements from set
# Using the pop() method
def Remove(initial_set):
while initial_set:
initial_set.pop()
print(initial_set)
# Driver Code
initial_set = set([12, 10, 13, 15, 8, 9])
Remove(initial_set)
|
#Input : set([12, 10, 13, 15, 8, 9])
#Output :
|
Python - Remove items from Set
# Python program to remove elements from set
# Using the pop() method
def Remove(initial_set):
while initial_set:
initial_set.pop()
print(initial_set)
# Driver Code
initial_set = set([12, 10, 13, 15, 8, 9])
Remove(initial_set)
#Input : set([12, 10, 13, 15, 8, 9])
#Output :
[END]
|
Python - Remove items from Set
|
https://www.geeksforgeeks.org/python-remove-items-set/
|
# initialize the set
my_set = set([12, 10, 13, 15, 8, 9])
# remove elements one by one using discard() method
while my_set:
my_set.discard(max(my_set))
print(my_set)
|
#Input : set([12, 10, 13, 15, 8, 9])
#Output :
|
Python - Remove items from Set
# initialize the set
my_set = set([12, 10, 13, 15, 8, 9])
# remove elements one by one using discard() method
while my_set:
my_set.discard(max(my_set))
print(my_set)
#Input : set([12, 10, 13, 15, 8, 9])
#Output :
[END]
|
Python - Remove items from Set
|
https://www.geeksforgeeks.org/python-remove-items-set/
|
# initialize the set
my_set = set([12, 10, 13, 15, 8, 9])
# remove elements one by one using remove() method
for i in range(len(my_set)):
my_set.remove(next(iter(my_set)))
print(my_set)
|
#Input : set([12, 10, 13, 15, 8, 9])
#Output :
|
Python - Remove items from Set
# initialize the set
my_set = set([12, 10, 13, 15, 8, 9])
# remove elements one by one using remove() method
for i in range(len(my_set)):
my_set.remove(next(iter(my_set)))
print(my_set)
#Input : set([12, 10, 13, 15, 8, 9])
#Output :
[END]
|
Python - Check if two lists have at-least one element common
|
https://www.geeksforgeeks.org/python-check-two-lists-least-one-element-common/
|
# Python program to check
# if two lists have at-least
# one element common
# using traversal of list
def common_data(list1, list2):
result = False
# traverse in the 1st list
for x in list1:
# traverse in the 2nd list
for y in list2:
# if one common
if x == y:
result = True
return result
return result
# driver code
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_data(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_data(a, b))
|
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
|
Python - Check if two lists have at-least one element common
# Python program to check
# if two lists have at-least
# one element common
# using traversal of list
def common_data(list1, list2):
result = False
# traverse in the 1st list
for x in list1:
# traverse in the 2nd list
for y in list2:
# if one common
if x == y:
result = True
return result
return result
# driver code
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_data(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_data(a, b))
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
[END]
|
Python - Check if two lists have at-least one element common
|
https://www.geeksforgeeks.org/python-check-two-lists-least-one-element-common/
|
# Python program to check
# if two lists have at-least
# one element common
# using set and property
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if a_set & b_set:
return True
else:
return False
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_member(a, b))
|
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
|
Python - Check if two lists have at-least one element common
# Python program to check
# if two lists have at-least
# one element common
# using set and property
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if a_set & b_set:
return True
else:
return False
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_member(a, b))
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
[END]
|
Python - Check if two lists have at-least one element common
|
https://www.geeksforgeeks.org/python-check-two-lists-least-one-element-common/
|
# Python program to check
# if two lists have at-least
# one element common
# using set intersection
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if len(a_set.intersection(b_set)) > 0:
return True
return False
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_member(a, b))
|
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
|
Python - Check if two lists have at-least one element common
# Python program to check
# if two lists have at-least
# one element common
# using set intersection
def common_member(a, b):
a_set = set(a)
b_set = set(b)
if len(a_set.intersection(b_set)) > 0:
return True
return False
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b))
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_member(a, b))
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
[END]
|
Python - Check if two lists have at-least one element common
|
https://www.geeksforgeeks.org/python-check-two-lists-least-one-element-common/
|
from collections import Counter
def have_common_element(list1, list2):
counter1 = Counter(list1)
counter2 = Counter(list2)
for element, count in counter1.items():
if element in counter2 and count > 0:
return True
return False
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(have_common_element(a, b)) # True
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(have_common_element(a, b)) # False
|
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
|
Python - Check if two lists have at-least one element common
from collections import Counter
def have_common_element(list1, list2):
counter1 = Counter(list1)
counter2 = Counter(list2)
for element, count in counter1.items():
if element in counter2 and count > 0:
return True
return False
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(have_common_element(a, b)) # True
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(have_common_element(a, b)) # False
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
[END]
|
Python - Check if two lists have at-least one element common
|
https://www.geeksforgeeks.org/python-check-two-lists-least-one-element-common/
|
import operator as op
# Python code to check if two lists
# have any element in common
# Initialization of list
list1 = [1, 3, 4, 55]
list2 = [90, 1, 22]
flag = 0
# Using in to check element of
# second list into first list
for elem in list2:
if op.countOf(list1, elem) > 0:
flag = 1
# checking condition
if flag == 1:
print("True")
else:
print("False")
|
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
|
Python - Check if two lists have at-least one element common
import operator as op
# Python code to check if two lists
# have any element in common
# Initialization of list
list1 = [1, 3, 4, 55]
list2 = [90, 1, 22]
flag = 0
# Using in to check element of
# second list into first list
for elem in list2:
if op.countOf(list1, elem) > 0:
flag = 1
# checking condition
if flag == 1:
print("True")
else:
print("False")
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
[END]
|
Python - Check if two lists have at-least one element common
|
https://www.geeksforgeeks.org/python-check-two-lists-least-one-element-common/
|
def common_member(a, b):
return any(i in b for i in a)
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b)) # True
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_member(a, b)) # False
|
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
|
Python - Check if two lists have at-least one element common
def common_member(a, b):
return any(i in b for i in a)
a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
print(common_member(a, b)) # True
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9]
print(common_member(a, b)) # False
#Input : a = [1, 2, 3, 4, 5]
b = [5, 6, 7, 8, 9]
[END]
|
Python program to find common elements in three lists using sets
|
https://www.geeksforgeeks.org/python-program-find-common-elements-three-lists-using-sets/
|
# Python3 program to find common elements
# in three lists using sets
def IntersecOfSets(arr1, arr2, arr3):
# Converting the arrays into sets
s1 = set(arr1)
s2 = set(arr2)
s3 = set(arr3)
# Calculates intersection of
# sets on s1 and s2
set1 = s1.intersection(s2) # [80, 20, 100]
# Calculates intersection of sets
# on set1 and s3
result_set = set1.intersection(s3)
# Converts resulting set to list
final_list = list(result_set)
print(final_list)
# Driver Code
if __name__ == "__main__":
# Elements in Array1
arr1 = [1, 5, 10, 20, 40, 80, 100]
# Elements in Array2
arr2 = [6, 7, 20, 80, 100]
# Elements in Array3
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
# Calling Function
IntersecOfSets(arr1, arr2, arr3)
|
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
|
Python program to find common elements in three lists using sets
# Python3 program to find common elements
# in three lists using sets
def IntersecOfSets(arr1, arr2, arr3):
# Converting the arrays into sets
s1 = set(arr1)
s2 = set(arr2)
s3 = set(arr3)
# Calculates intersection of
# sets on s1 and s2
set1 = s1.intersection(s2) # [80, 20, 100]
# Calculates intersection of sets
# on set1 and s3
result_set = set1.intersection(s3)
# Converts resulting set to list
final_list = list(result_set)
print(final_list)
# Driver Code
if __name__ == "__main__":
# Elements in Array1
arr1 = [1, 5, 10, 20, 40, 80, 100]
# Elements in Array2
arr2 = [6, 7, 20, 80, 100]
# Elements in Array3
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
# Calling Function
IntersecOfSets(arr1, arr2, arr3)
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
[END]
|
Python program to find common elements in three lists using sets
|
https://www.geeksforgeeks.org/python-program-find-common-elements-three-lists-using-sets/
|
def find_common(list1, list2, list3):
common = set()
for elem in list1:
if elem in list2 and elem in list3:
common.add(elem)
return common
list1 = [1, 5, 10, 20, 40, 80]
list2 = [6, 7, 20, 80, 100]
list3 = [3, 4, 15, 20, 30, 70, 80, 120]
common = find_common(list1, list2, list3)
print(common)
|
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
|
Python program to find common elements in three lists using sets
def find_common(list1, list2, list3):
common = set()
for elem in list1:
if elem in list2 and elem in list3:
common.add(elem)
return common
list1 = [1, 5, 10, 20, 40, 80]
list2 = [6, 7, 20, 80, 100]
list3 = [3, 4, 15, 20, 30, 70, 80, 120]
common = find_common(list1, list2, list3)
print(common)
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
[END]
|
Python program to find common elements in three lists using sets
|
https://www.geeksforgeeks.org/python-program-find-common-elements-three-lists-using-sets/
|
def find_common(list1, list2, list3):
# Convert lists to sets
set1 = set(list1)
set2 = set(list2)
set3 = set(list3)
# Use list comprehension to find common elements
# in all three sets and return as a list
return [elem for elem in set1 if elem in set2 and elem in set3]
list1 = [1, 5, 10, 20, 40, 80]
list2 = [6, 7, 20, 80, 100]
list3 = [3, 4, 15, 20, 30, 70, 80, 120]
common = find_common(list1, list2, list3)
print(common)
|
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
|
Python program to find common elements in three lists using sets
def find_common(list1, list2, list3):
# Convert lists to sets
set1 = set(list1)
set2 = set(list2)
set3 = set(list3)
# Use list comprehension to find common elements
# in all three sets and return as a list
return [elem for elem in set1 if elem in set2 and elem in set3]
list1 = [1, 5, 10, 20, 40, 80]
list2 = [6, 7, 20, 80, 100]
list3 = [3, 4, 15, 20, 30, 70, 80, 120]
common = find_common(list1, list2, list3)
print(common)
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
[END]
|
Python program to find common elements in three lists using sets
|
https://www.geeksforgeeks.org/python-program-find-common-elements-three-lists-using-sets/
|
def IntersecOfSets(arr1, arr2, arr3):
result = []
for i in arr1:
if i in arr2 and i in arr3:
result.append(i)
print(list(set(result)))
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 7, 20, 80, 100]
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
common = IntersecOfSets(arr1, arr2, arr3)
|
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
|
Python program to find common elements in three lists using sets
def IntersecOfSets(arr1, arr2, arr3):
result = []
for i in arr1:
if i in arr2 and i in arr3:
result.append(i)
print(list(set(result)))
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 7, 20, 80, 100]
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
common = IntersecOfSets(arr1, arr2, arr3)
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
[END]
|
Python program to find common elements in three lists using sets
|
https://www.geeksforgeeks.org/python-program-find-common-elements-three-lists-using-sets/
|
def IntersecOfSets(arr1, arr2, arr3):
common = list(filter(lambda x: x in arr2 and x in arr3, arr1))
print(common)
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 7, 20, 80, 100]
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
IntersecOfSets(arr1, arr2, arr3)
|
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
|
Python program to find common elements in three lists using sets
def IntersecOfSets(arr1, arr2, arr3):
common = list(filter(lambda x: x in arr2 and x in arr3, arr1))
print(common)
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 7, 20, 80, 100]
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
IntersecOfSets(arr1, arr2, arr3)
#Input : ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
[END]
|
Python - Find missing and additional values in two lists
|
https://www.geeksforgeeks.org/python-find-missing-additional-values-two-lists/
|
# Python program to find the missing
# and additional elements
# examples of lists
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
# prints the missing and additional elements in list2
print("Missing values in second list:", (set(list1).difference(list2)))
print("Additional values in second list:", (set(list2).difference(list1)))
# prints the missing and additional elements in list1
print("Missing values in first list:", (set(list2).difference(list1)))
print("Additional values in first list:", (set(list1).difference(list2)))
|
#Input : list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
|
Python - Find missing and additional values in two lists
# Python program to find the missing
# and additional elements
# examples of lists
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
# prints the missing and additional elements in list2
print("Missing values in second list:", (set(list1).difference(list2)))
print("Additional values in second list:", (set(list2).difference(list1)))
# prints the missing and additional elements in list1
print("Missing values in first list:", (set(list2).difference(list1)))
print("Additional values in first list:", (set(list1).difference(list2)))
#Input : list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
[END]
|
Python - Find missing and additional values in two lists
|
https://www.geeksforgeeks.org/python-find-missing-additional-values-two-lists/
|
import numpy as np
def find_missing_additional(list1, list2):
# Convert list1 and list2 to numpy arrays
arr1 = np.array(list1)
arr2 = np.array(list2)
# Calculate missing and additional values in list2
missing_list2 = np.setdiff1d(arr1, arr2)
additional_list2 = np.setdiff1d(arr2, arr1)
# Calculate missing and additional values in list1
missing_list1 = np.setdiff1d(arr2, arr1)
additional_list1 = np.setdiff1d(arr1, arr2)
# Convert numpy arrays to lists and return the results
return (
list(missing_list2),
list(additional_list2),
list(missing_list1),
list(additional_list1),
)
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
(
missing_list2,
additional_list2,
missing_list1,
additional_list1,
) = find_missing_additional(list1, list2)
print("Missing values in first list:", missing_list1)
print("Additional values in first list:", additional_list1)
print("Missing values in second list:", missing_list2)
print("Additional values in second list:", additional_list2)
|
#Input : list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
|
Python - Find missing and additional values in two lists
import numpy as np
def find_missing_additional(list1, list2):
# Convert list1 and list2 to numpy arrays
arr1 = np.array(list1)
arr2 = np.array(list2)
# Calculate missing and additional values in list2
missing_list2 = np.setdiff1d(arr1, arr2)
additional_list2 = np.setdiff1d(arr2, arr1)
# Calculate missing and additional values in list1
missing_list1 = np.setdiff1d(arr2, arr1)
additional_list1 = np.setdiff1d(arr1, arr2)
# Convert numpy arrays to lists and return the results
return (
list(missing_list2),
list(additional_list2),
list(missing_list1),
list(additional_list1),
)
list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
(
missing_list2,
additional_list2,
missing_list1,
additional_list1,
) = find_missing_additional(list1, list2)
print("Missing values in first list:", missing_list1)
print("Additional values in first list:", additional_list1)
print("Missing values in second list:", missing_list2)
print("Additional values in second list:", additional_list2)
#Input : list1 = [1, 2, 3, 4, 5, 6]
list2 = [4, 5, 6, 7, 8]
[END]
|
Python program to find the difference between two lists
|
https://www.geeksforgeeks.org/python-difference-two-lists/
|
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
temp3 = []
for element in li1:
if element not in li2:
temp3.append(element)
print(temp3)
|
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
|
Python program to find the difference between two lists
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
temp3 = []
for element in li1:
if element not in li2:
temp3.append(element)
print(temp3)
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
[END]
|
Python program to find the difference between two lists
|
https://www.geeksforgeeks.org/python-difference-two-lists/
|
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
s = set(li2)
temp3 = [x for x in li1 if x not in s]
print(temp3)
|
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
|
Python program to find the difference between two lists
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
s = set(li2)
temp3 = [x for x in li1 if x not in s]
print(temp3)
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
[END]
|
Python program to find the difference between two lists
|
https://www.geeksforgeeks.org/python-difference-two-lists/
|
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
s = set(li2)
temp3 = [x for x in li1 if x not in s]
print(temp3)
|
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
|
Python program to find the difference between two lists
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
s = set(li2)
temp3 = [x for x in li1 if x not in s]
print(temp3)
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
[END]
|
Python program to find the difference between two lists
|
https://www.geeksforgeeks.org/python-difference-two-lists/
|
# Python code to get difference of two lists
# Not using set()
def Diff(li1, li2):
li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]
return li_dif
# Driver Code
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
li3 = Diff(li1, li2)
print(li3)
|
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
|
Python program to find the difference between two lists
# Python code to get difference of two lists
# Not using set()
def Diff(li1, li2):
li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]
return li_dif
# Driver Code
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
li3 = Diff(li1, li2)
print(li3)
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
[END]
|
Python program to find the difference between two lists
|
https://www.geeksforgeeks.org/python-difference-two-lists/
|
import numpy as np
li1 = np.array([10, 15, 20, 25, 30, 35, 40])
li2 = np.array([25, 40, 35])
dif1 = np.setdiff1d(li1, li2)
dif2 = np.setdiff1d(li2, li1)
temp3 = np.concatenate((dif1, dif2))
print(list(temp3))
|
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
|
Python program to find the difference between two lists
import numpy as np
li1 = np.array([10, 15, 20, 25, 30, 35, 40])
li2 = np.array([25, 40, 35])
dif1 = np.setdiff1d(li1, li2)
dif2 = np.setdiff1d(li2, li1)
temp3 = np.concatenate((dif1, dif2))
print(list(temp3))
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
[END]
|
Python program to find the difference between two lists
|
https://www.geeksforgeeks.org/python-difference-two-lists/
|
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
set_dif = set(li1).symmetric_difference(set(li2))
temp3 = list(set_dif)
print(temp3)
|
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
|
Python program to find the difference between two lists
li1 = [10, 15, 20, 25, 30, 35, 40]
li2 = [25, 40, 35]
set_dif = set(li1).symmetric_difference(set(li2))
temp3 = list(set_dif)
print(temp3)
Input:
list1 = [10, 15, 20, 25, 30, 35, 40]
[END]
|
Python Set difference to find lost element from a duplicate array
|
https://www.geeksforgeeks.org/python-set-difference-find-lost-element-duplicated-array/
|
# Function to find lost element from a duplicate
# array
def lostElement(A, B):
# convert lists into set
A = set(A)
B = set(B)
# take difference of greater set with smaller
if len(A) > len(B):
print(list(A - B))
else:
print(list(B - A))
# Driver program
if __name__ == "__main__":
A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
lostElement(A, B)
|
Input: A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
|
Python Set difference to find lost element from a duplicate array
# Function to find lost element from a duplicate
# array
def lostElement(A, B):
# convert lists into set
A = set(A)
B = set(B)
# take difference of greater set with smaller
if len(A) > len(B):
print(list(A - B))
else:
print(list(B - A))
# Driver program
if __name__ == "__main__":
A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
lostElement(A, B)
Input: A = [1, 4, 5, 7, 9]
B = [4, 5, 7, 9]
[END]
|
Python program to count number of vowels using sets in given string
|
https://www.geeksforgeeks.org/python-program-count-number-vowels-using-sets-given-string/
|
# Python3 code to count vowel in
# a string using set
# Function to count vowel
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count)
# Driver code
str = "GeeksforGeeks"
# Function Call
vowel_count(str)
|
#Input : GeeksforGeeks
#Output : No. of vowels : 5
|
Python program to count number of vowels using sets in given string
# Python3 code to count vowel in
# a string using set
# Function to count vowel
def vowel_count(str):
# Initializing count variable to 0
count = 0
# Creating a set of vowels
vowel = set("aeiouAEIOU")
# Loop to traverse the alphabet
# in the given string
for alphabet in str:
# If alphabet is present
# in set vowel
if alphabet in vowel:
count = count + 1
print("No. of vowels :", count)
# Driver code
str = "GeeksforGeeks"
# Function Call
vowel_count(str)
#Input : GeeksforGeeks
#Output : No. of vowels : 5
[END]
|
Python program to count number of vowels using sets in given string
|
https://www.geeksforgeeks.org/python-program-count-number-vowels-using-sets-given-string/
|
def vowel_count(str):
# Creating a list of vowels
vowels = "aeiouAEIOU"
# Using list comprehension to count the number of vowels in the string
count = len([char for char in str if char in vowels])
# Printing the count of vowels in the string
print("No. of vowels :", count)
# Driver code
str = "GeeksforGeeks"
# Function Call
vowel_count(str)
|
#Input : GeeksforGeeks
#Output : No. of vowels : 5
|
Python program to count number of vowels using sets in given string
def vowel_count(str):
# Creating a list of vowels
vowels = "aeiouAEIOU"
# Using list comprehension to count the number of vowels in the string
count = len([char for char in str if char in vowels])
# Printing the count of vowels in the string
print("No. of vowels :", count)
# Driver code
str = "GeeksforGeeks"
# Function Call
vowel_count(str)
#Input : GeeksforGeeks
#Output : No. of vowels : 5
[END]
|
Concatenated string with uncommon characters in Python
|
https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-python/
|
# Function to concatenated string with uncommon
# characters of two strings
def uncommonConcat(str1, str2):
# convert both strings into set
set1 = set(str1)
set2 = set(str2)
# take intersection of two sets to get list of
# common characters
common = list(set1 & set2)
# separate out characters in each string
# which are not common in both strings
result = [ch for ch in str1 if ch not in common] + [
ch for ch in str2 if ch not in common
]
# join each character without space to get
# final string
print("".join(result))
# Driver program
if __name__ == "__main__":
str1 = "aacdb"
str2 = "gafd"
uncommonConcat(str1, str2)
|
#Output : cbgf
|
Concatenated string with uncommon characters in Python
# Function to concatenated string with uncommon
# characters of two strings
def uncommonConcat(str1, str2):
# convert both strings into set
set1 = set(str1)
set2 = set(str2)
# take intersection of two sets to get list of
# common characters
common = list(set1 & set2)
# separate out characters in each string
# which are not common in both strings
result = [ch for ch in str1 if ch not in common] + [
ch for ch in str2 if ch not in common
]
# join each character without space to get
# final string
print("".join(result))
# Driver program
if __name__ == "__main__":
str1 = "aacdb"
str2 = "gafd"
uncommonConcat(str1, str2)
#Output : cbgf
[END]
|
Concatenated string with uncommon characters in Python
|
https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-python/
|
# Function to concatenated string with uncommon
# characters of two strings
def uncommonConcat(str1, str2):
# convert both strings into set
set1 = set(str1)
set2 = set(str2)
# Performing symmetric difference operation of set
# to pull out uncommon characters
uncommon = list(set1 ^ set2)
# join each character without space to get
# final string
print("".join(uncommon))
# Driver program
if __name__ == "__main__":
str1 = "aacdb"
str2 = "gafd"
uncommonConcat(str1, str2)
|
#Output : cbgf
|
Concatenated string with uncommon characters in Python
# Function to concatenated string with uncommon
# characters of two strings
def uncommonConcat(str1, str2):
# convert both strings into set
set1 = set(str1)
set2 = set(str2)
# Performing symmetric difference operation of set
# to pull out uncommon characters
uncommon = list(set1 ^ set2)
# join each character without space to get
# final string
print("".join(uncommon))
# Driver program
if __name__ == "__main__":
str1 = "aacdb"
str2 = "gafd"
uncommonConcat(str1, str2)
#Output : cbgf
[END]
|
Concatenated string with uncommon characters in Python
|
https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-python/
|
# Function to concatenated string with uncommon
# characters of two strings
from collections import Counter
def uncommonConcat(str1, str2):
result = []
frequency_str1 = Counter(str1)
frequency_str2 = Counter(str2)
for key in frequency_str1:
if key not in frequency_str2:
result.append(key)
for key in frequency_str2:
if key not in frequency_str1:
result.append(key)
# Sorting the result
result.sort()
print("".join(set(result)))
# Driver program
if __name__ == "__main__":
str1 = "aacdb"
str2 = "gafd"
uncommonConcat(str1, str2)
|
#Output : cbgf
|
Concatenated string with uncommon characters in Python
# Function to concatenated string with uncommon
# characters of two strings
from collections import Counter
def uncommonConcat(str1, str2):
result = []
frequency_str1 = Counter(str1)
frequency_str2 = Counter(str2)
for key in frequency_str1:
if key not in frequency_str2:
result.append(key)
for key in frequency_str2:
if key not in frequency_str1:
result.append(key)
# Sorting the result
result.sort()
print("".join(set(result)))
# Driver program
if __name__ == "__main__":
str1 = "aacdb"
str2 = "gafd"
uncommonConcat(str1, str2)
#Output : cbgf
[END]
|
Concatenated string with uncommon characters in Python
|
https://www.geeksforgeeks.org/concatenated-string-uncommon-characters-python/
|
# Function to concatenate uncommon characters
# of two different strings
def concatenate_uncommon(str1, str2):
# variable to store
# the final string
final_str = ""
# iterating over first string
# and checking each character is present
# in the other string or not
# if not then simply store that character
# in the variable
for i in str1:
if i in str2:
pass
else:
final_str += i
# iterating over second string
# and checking each character is present
# in the other string or not
# if not then simply store that character
# in the same variable as earlier
for j in str2:
if j in str1:
pass
else:
final_str += j
# returning the final string as result
return final_str
# Driver Code
# Example - 1
str1 = "abcs"
str2 = "cxzca"
print(concatenate_uncommon(str1, str2))
# Example - 2
str1 = "aacdb"
str2 = "gafd"
print(concatenate_uncommon(str1, str2))
|
#Output : cbgf
|
Concatenated string with uncommon characters in Python
# Function to concatenate uncommon characters
# of two different strings
def concatenate_uncommon(str1, str2):
# variable to store
# the final string
final_str = ""
# iterating over first string
# and checking each character is present
# in the other string or not
# if not then simply store that character
# in the variable
for i in str1:
if i in str2:
pass
else:
final_str += i
# iterating over second string
# and checking each character is present
# in the other string or not
# if not then simply store that character
# in the same variable as earlier
for j in str2:
if j in str1:
pass
else:
final_str += j
# returning the final string as result
return final_str
# Driver Code
# Example - 1
str1 = "abcs"
str2 = "cxzca"
print(concatenate_uncommon(str1, str2))
# Example - 2
str1 = "aacdb"
str2 = "gafd"
print(concatenate_uncommon(str1, str2))
#Output : cbgf
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
def check(string):
string = string.lower()
# set() function convert "aeiou"
# string into set of characters
# i.e.vowels = {'a', 'e', 'i', 'o', 'u'}
vowels = set("aeiou")
# set() function convert empty
# dictionary into empty set
s = set({})
# looping through each
# character of the string
for char in string:
# Check for the character is present inside
# the vowels set or not. If present, then
# add into the set s by using add method
if char in vowels:
s.add(char)
else:
pass
# check the length of set s equal to length
# of vowels set or not. If equal, string is
# accepted otherwise not
if len(s) == len(vowels):
print("Accepted")
else:
print("Not Accepted")
# Driver code
if __name__ == "__main__":
string = "SEEquoiaL"
# calling function
check(string)
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
def check(string):
string = string.lower()
# set() function convert "aeiou"
# string into set of characters
# i.e.vowels = {'a', 'e', 'i', 'o', 'u'}
vowels = set("aeiou")
# set() function convert empty
# dictionary into empty set
s = set({})
# looping through each
# character of the string
for char in string:
# Check for the character is present inside
# the vowels set or not. If present, then
# add into the set s by using add method
if char in vowels:
s.add(char)
else:
pass
# check the length of set s equal to length
# of vowels set or not. If equal, string is
# accepted otherwise not
if len(s) == len(vowels):
print("Accepted")
else:
print("Not Accepted")
# Driver code
if __name__ == "__main__":
string = "SEEquoiaL"
# calling function
check(string)
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
def check(string):
string = string.replace(" ", "")
string = string.lower()
vowel = [
string.count("a"),
string.count("e"),
string.count("i"),
string.count("o"),
string.count("u"),
]
# If 0 is present int vowel count array
if vowel.count(0) > 0:
return "not accepted"
else:
return "accepted"
# Driver code
if __name__ == "__main__":
string = "SEEquoiaL"
print(check(string))
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
def check(string):
string = string.replace(" ", "")
string = string.lower()
vowel = [
string.count("a"),
string.count("e"),
string.count("i"),
string.count("o"),
string.count("u"),
]
# If 0 is present int vowel count array
if vowel.count(0) > 0:
return "not accepted"
else:
return "accepted"
# Driver code
if __name__ == "__main__":
string = "SEEquoiaL"
print(check(string))
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
# Python program for the above approach
def check(string):
if len(set(string.lower()).intersection("aeiou")) >= 5:
return "accepted"
else:
return "not accepted"
# Driver code
if __name__ == "__main__":
string = "geeksforgeeks"
print(check(string))
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
# Python program for the above approach
def check(string):
if len(set(string.lower()).intersection("aeiou")) >= 5:
return "accepted"
else:
return "not accepted"
# Driver code
if __name__ == "__main__":
string = "geeksforgeeks"
print(check(string))
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
# import library
import re
sampleInput = "aeioAEiuioea"
# regular expression to find the strings
# which have characters other than a,e,i,o and u
c = re.compile("[^aeiouAEIOU]")
# use findall() to get the list of strings
# that have characters other than a,e,i,o and u.
if len(c.findall(sampleInput)):
print("Not Accepted") # if length of list > 0 then it is not accepted
else:
print("Accepted") # if length of list = 0 then it is accepted
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
# import library
import re
sampleInput = "aeioAEiuioea"
# regular expression to find the strings
# which have characters other than a,e,i,o and u
c = re.compile("[^aeiouAEIOU]")
# use findall() to get the list of strings
# that have characters other than a,e,i,o and u.
if len(c.findall(sampleInput)):
print("Not Accepted") # if length of list > 0 then it is not accepted
else:
print("Accepted") # if length of list = 0 then it is accepted
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
# Python | Program to accept the strings which contains all vowels
def all_vowels(str_value):
new_list = [char for char in str_value.lower() if char in "aeiou"]
if new_list:
dic, lst = {}, []
for char in new_list:
dic["a"] = new_list.count("a")
dic["e"] = new_list.count("e")
dic["i"] = new_list.count("i")
dic["o"] = new_list.count("o")
dic["u"] = new_list.count("u")
for i, j in dic.items():
if j == 0:
lst.append(i)
if lst:
return f"All vowels except {','.join(lst)} are not present"
else:
return "All vowels are present"
else:
return "No vowels present"
# function-call
str_value = "geeksforgeeks"
print(all_vowels(str_value))
str_value = "ABeeIghiObhkUul"
print(all_vowels(str_value))
# contribute by saikot
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
# Python | Program to accept the strings which contains all vowels
def all_vowels(str_value):
new_list = [char for char in str_value.lower() if char in "aeiou"]
if new_list:
dic, lst = {}, []
for char in new_list:
dic["a"] = new_list.count("a")
dic["e"] = new_list.count("e")
dic["i"] = new_list.count("i")
dic["o"] = new_list.count("o")
dic["u"] = new_list.count("u")
for i, j in dic.items():
if j == 0:
lst.append(i)
if lst:
return f"All vowels except {','.join(lst)} are not present"
else:
return "All vowels are present"
else:
return "No vowels present"
# function-call
str_value = "geeksforgeeks"
print(all_vowels(str_value))
str_value = "ABeeIghiObhkUul"
print(all_vowels(str_value))
# contribute by saikot
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
def check(string):
# Checking if "aeiou" is a subset of the set of all letters in the string
if set("aeiou").issubset(set(string.lower())):
return "Accepted"
return "Not accepted"
# Driver code
if __name__ == "__main__":
string = "SEEquoiaL"
# calling function
print(check(string))
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
def check(string):
# Checking if "aeiou" is a subset of the set of all letters in the string
if set("aeiou").issubset(set(string.lower())):
return "Accepted"
return "Not accepted"
# Driver code
if __name__ == "__main__":
string = "SEEquoiaL"
# calling function
print(check(string))
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
import collections
def check(string):
# create a Counter object to count the occurrences of each character
counter = collections.Counter(string.lower())
# set of vowels
vowels = set("aeiou")
# counter for the number of vowels present
vowel_count = 0
# check if each vowel is present in the string
for vowel in vowels:
if counter[vowel] > 0:
vowel_count += 1
# check if all vowels are present
if vowel_count == len(vowels):
print("Accepted")
else:
print("Not Accepted")
# test the function
string = "SEEquoiaL"
check(string)
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
import collections
def check(string):
# create a Counter object to count the occurrences of each character
counter = collections.Counter(string.lower())
# set of vowels
vowels = set("aeiou")
# counter for the number of vowels present
vowel_count = 0
# check if each vowel is present in the string
for vowel in vowels:
if counter[vowel] > 0:
vowel_count += 1
# check if all vowels are present
if vowel_count == len(vowels):
print("Accepted")
else:
print("Not Accepted")
# test the function
string = "SEEquoiaL"
check(string)
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
# using all() method
def check(string):
vowels = "aeiou" # storing vowels
if all(vowel in string.lower() for vowel in vowels):
return "Accepted"
return "Not accepted"
# initializing string
string = "SEEquoiaL"
# test the function
print(check(string))
# this code contributed by tvsk
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
# Python program to accept the strings
# which contains all the vowels
# Function for check if string
# is accepted or not
# using all() method
def check(string):
vowels = "aeiou" # storing vowels
if all(vowel in string.lower() for vowel in vowels):
return "Accepted"
return "Not accepted"
# initializing string
string = "SEEquoiaL"
# test the function
print(check(string))
# this code contributed by tvsk
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Python - Program to accept the strings which contains all vowels
|
https://www.geeksforgeeks.org/python-program-to-accept-the-strings-which-contains-all-vowels/
|
# function definition
def check(s):
A = {"a", "e", "i", "o", "u"}
# using the set difference
if len(A.difference(set(s.lower()))) == 0:
print("accepted")
else:
print("not accepted")
# input
s = "SEEquoiaL"
# function call
check(s)
|
#Input : geeksforgeeks
#Output : Not Accepted
|
Python - Program to accept the strings which contains all vowels
# function definition
def check(s):
A = {"a", "e", "i", "o", "u"}
# using the set difference
if len(A.difference(set(s.lower()))) == 0:
print("accepted")
else:
print("not accepted")
# input
s = "SEEquoiaL"
# function call
check(s)
#Input : geeksforgeeks
#Output : Not Accepted
[END]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.