Description
stringlengths
9
105
Link
stringlengths
45
135
Code
stringlengths
10
26.8k
Test_Case
stringlengths
9
202
Merge
stringlengths
63
27k
Python | Check if a Substring is Present in a Given String
https://www.geeksforgeeks.org/python-check-substring-present-given-string/
# When you have imported the re module, # you can start using regular expressions. import re # Take input from users MyString1 = "A geek in need is a geek indeed" MyString2 = "geeks" # re.search() returns a Match object # if there is a match anywhere in the string if re.search(MyString2, MyString1): print("YES,string '{0}' is present in string '{1}'".format(MyString2, MyString1)) else: print( "NO,string '{0}' is not present in string '{1}' ".format(MyString2, MyString1) )
#Output : Example 1: #Input : Substring = "geeks"
Python | Check if a Substring is Present in a Given String # When you have imported the re module, # you can start using regular expressions. import re # Take input from users MyString1 = "A geek in need is a geek indeed" MyString2 = "geeks" # re.search() returns a Match object # if there is a match anywhere in the string if re.search(MyString2, MyString1): print("YES,string '{0}' is present in string '{1}'".format(MyString2, MyString1)) else: print( "NO,string '{0}' is not present in string '{1}' ".format(MyString2, MyString1) ) #Output : Example 1: #Input : Substring = "geeks" [END]
Python | Check if a Substring is Present in a Given String
https://www.geeksforgeeks.org/python-check-substring-present-given-string/
s = "geeks for geeks" s2 = "geeks" print(["yes" if s2 in s else "no"])
#Output : Example 1: #Input : Substring = "geeks"
Python | Check if a Substring is Present in a Given String s = "geeks for geeks" s2 = "geeks" print(["yes" if s2 in s else "no"]) #Output : Example 1: #Input : Substring = "geeks" [END]
Python | Check if a Substring is Present in a Given String
https://www.geeksforgeeks.org/python-check-substring-present-given-string/
s = "geeks for geeks" s2 = "geeks" x = list(filter(lambda x: (s2 in s), s.split())) print(["yes" if x else "no"])
#Output : Example 1: #Input : Substring = "geeks"
Python | Check if a Substring is Present in a Given String s = "geeks for geeks" s2 = "geeks" x = list(filter(lambda x: (s2 in s), s.split())) print(["yes" if x else "no"]) #Output : Example 1: #Input : Substring = "geeks" [END]
Python | Check if a Substring is Present in a Given String
https://www.geeksforgeeks.org/python-check-substring-present-given-string/
import operator as op s = "geeks for geeks" s2 = "geeks" print(["yes" if op.countOf(s.split(), s2) > 0 else "no"])
#Output : Example 1: #Input : Substring = "geeks"
Python | Check if a Substring is Present in a Given String import operator as op s = "geeks for geeks" s2 = "geeks" print(["yes" if op.countOf(s.split(), s2) > 0 else "no"]) #Output : Example 1: #Input : Substring = "geeks" [END]
Python | Check if a Substring is Present in a Given String
https://www.geeksforgeeks.org/python-check-substring-present-given-string/
# Python program to check if a substring is present in a given string import operator as op s = "geeks for geeks" s2 = "geeks" if op.contains(s, s2): print("yes") else: print("no")
#Output : Example 1: #Input : Substring = "geeks"
Python | Check if a Substring is Present in a Given String # Python program to check if a substring is present in a given string import operator as op s = "geeks for geeks" s2 = "geeks" if op.contains(s, s2): print("yes") else: print("no") #Output : Example 1: #Input : Substring = "geeks" [END]
Python | Check if a Substring is Present in a Given String
https://www.geeksforgeeks.org/python-check-substring-present-given-string/
def is_substring(string, substring): for i in range(len(string) - len(substring) + 1): if string[i : i + len(substring)] == substring: return True return False string = "A geeks in need is a geek indeed" substring = "geeks" print(is_substring(string, substring))
#Output : Example 1: #Input : Substring = "geeks"
Python | Check if a Substring is Present in a Given String def is_substring(string, substring): for i in range(len(string) - len(substring) + 1): if string[i : i + len(substring)] == substring: return True return False string = "A geeks in need is a geek indeed" substring = "geeks" print(is_substring(string, substring)) #Output : Example 1: #Input : Substring = "geeks" [END]
Python | Check if a Substring is Present in a Given String
https://www.geeksforgeeks.org/python-check-substring-present-given-string/
import re MyString1 = "A geek in need is a geek indeed" if re.search("need", MyString1): print("Yes! it is present in the string") else: print("No! it is not present")
#Output : Example 1: #Input : Substring = "geeks"
Python | Check if a Substring is Present in a Given String import re MyString1 = "A geek in need is a geek indeed" if re.search("need", MyString1): print("Yes! it is present in the string") else: print("No! it is not present") #Output : Example 1: #Input : Substring = "geeks" [END]
Python - Substring presence in String List
https://www.geeksforgeeks.org/python-substring-presence-in-strings-list/
# Python3 code to demonstrate working of # Substring presence in Strings List # Using loop # initializing lists test_list1 = ["Gfg", "is", "Best"] test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] # printing original lists print("The original list 1 : " + str(test_list1)) print("The original list 2 : " + str(test_list2)) # using loop to iterate res = [] for ele in test_list1: temp = False # inner loop to check for # presence of element in any list for sub in test_list2: if ele in sub: temp = True break res.append(temp) # printing result print("The match list : " + str(res))
#Output : The original list 1 : ['Gfg', 'is', 'Best']
Python - Substring presence in String List # Python3 code to demonstrate working of # Substring presence in Strings List # Using loop # initializing lists test_list1 = ["Gfg", "is", "Best"] test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] # printing original lists print("The original list 1 : " + str(test_list1)) print("The original list 2 : " + str(test_list2)) # using loop to iterate res = [] for ele in test_list1: temp = False # inner loop to check for # presence of element in any list for sub in test_list2: if ele in sub: temp = True break res.append(temp) # printing result print("The match list : " + str(res)) #Output : The original list 1 : ['Gfg', 'is', 'Best'] [END]
Python - Substring presence in String List
https://www.geeksforgeeks.org/python-substring-presence-in-strings-list/
# Python3 code to demonstrate working of # Substring presence in Strings List # Using list comprehension + any() # initializing lists test_list1 = ["Gfg", "is", "Best"] test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] # printing original lists print("The original list 1 : " + str(test_list1)) print("The original list 2 : " + str(test_list2)) # any() reduces a nesting # checks for element presence in all Substrings res = [True if any(i in j for j in test_list2) else False for i in test_list1] # printing result print("The match list : " + str(res))
#Output : The original list 1 : ['Gfg', 'is', 'Best']
Python - Substring presence in String List # Python3 code to demonstrate working of # Substring presence in Strings List # Using list comprehension + any() # initializing lists test_list1 = ["Gfg", "is", "Best"] test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] # printing original lists print("The original list 1 : " + str(test_list1)) print("The original list 2 : " + str(test_list2)) # any() reduces a nesting # checks for element presence in all Substrings res = [True if any(i in j for j in test_list2) else False for i in test_list1] # printing result print("The match list : " + str(res)) #Output : The original list 1 : ['Gfg', 'is', 'Best'] [END]
Python - Substring presence in String List
https://www.geeksforgeeks.org/python-substring-presence-in-strings-list/
# Python3 code to demonstrate working of # Substring presence in Strings List # Using set intersection # initializing lists test_list1 = ["Gfg", "is", "Best"] test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] # convert to sets and compute intersection set1 = set(test_list1) set2 = set(" ".join(test_list2).split()) intersection = set1.intersection(set2) # convert intersection back to list intersection_list = list(intersection) # initialize result list result = [] # check if each string in test_list1 is in the intersection list for string in test_list1: if string in intersection_list: result.append(True) else: result.append(False) # print result print("The match list : " + str(result))
#Output : The original list 1 : ['Gfg', 'is', 'Best']
Python - Substring presence in String List # Python3 code to demonstrate working of # Substring presence in Strings List # Using set intersection # initializing lists test_list1 = ["Gfg", "is", "Best"] test_list2 = ["I love Gfg", "Its Best for Geeks", "Gfg means CS"] # convert to sets and compute intersection set1 = set(test_list1) set2 = set(" ".join(test_list2).split()) intersection = set1.intersection(set2) # convert intersection back to list intersection_list = list(intersection) # initialize result list result = [] # check if each string in test_list1 is in the intersection list for string in test_list1: if string in intersection_list: result.append(True) else: result.append(False) # print result print("The match list : " + str(result)) #Output : The original list 1 : ['Gfg', 'is', 'Best'] [END]
Python - Substring presence in String List
https://www.geeksforgeeks.org/python-substring-presence-in-strings-list/
import numpy as np # initializing arrays arr1 = np.array(["Gfg", "is", "Best"]) arr2 = np.array(["I love Gfg", "Its Best for Geeks", "Gfg means CS"]) # printing original lists print("The original list 1 : " + str(arr1)) print("The original list 2 : " + str(arr2)) # find if substring is present res = np.array([any(np.char.find(arr2, i) != -1) for i in arr1]) # printing result print("The match list : ", res) # This code is contributed by Vinay Pinjala
#Output : The original list 1 : ['Gfg', 'is', 'Best']
Python - Substring presence in String List import numpy as np # initializing arrays arr1 = np.array(["Gfg", "is", "Best"]) arr2 = np.array(["I love Gfg", "Its Best for Geeks", "Gfg means CS"]) # printing original lists print("The original list 1 : " + str(arr1)) print("The original list 2 : " + str(arr2)) # find if substring is present res = np.array([any(np.char.find(arr2, i) != -1) for i in arr1]) # printing result print("The match list : ", res) # This code is contributed by Vinay Pinjala #Output : The original list 1 : ['Gfg', 'is', 'Best'] [END]
Python - All substrings Frequency in String
https://www.geeksforgeeks.org/python-all-substrings-frequency-in-string/
# Python3 code to demonstrate working of # All substrings Frequency in String # Using loop + list comprehension # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # list comprehension to extract substrings temp = [ test_str[idx:j] for idx in range(len(test_str)) for j in range(idx + 1, len(test_str) + 1) ] # loop to extract final result of frequencies d = dict() for i in temp: d[i] = test_str.count(i) # printing result print("Extracted frequency dictionary : " + str(d))
#Output : The original string is : abababa
Python - All substrings Frequency in String # Python3 code to demonstrate working of # All substrings Frequency in String # Using loop + list comprehension # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # list comprehension to extract substrings temp = [ test_str[idx:j] for idx in range(len(test_str)) for j in range(idx + 1, len(test_str) + 1) ] # loop to extract final result of frequencies d = dict() for i in temp: d[i] = test_str.count(i) # printing result print("Extracted frequency dictionary : " + str(d)) #Output : The original string is : abababa [END]
Python - All substrings Frequency in String
https://www.geeksforgeeks.org/python-all-substrings-frequency-in-string/
# Python3 code to demonstrate working of # All substrings Frequency in String # Using loop + list comprehension # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # list comprehension to extract substrings temp = [ test_str[idx:j] for idx in range(len(test_str)) for j in range(idx + 1, len(test_str) + 1) ] # loop to extract final result of frequencies res = {} for idx in temp: if idx not in res.keys(): res[idx] = 1 else: res[idx] += 1 # printing result print("Extracted frequency dictionary : " + str(res))
#Output : The original string is : abababa
Python - All substrings Frequency in String # Python3 code to demonstrate working of # All substrings Frequency in String # Using loop + list comprehension # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # list comprehension to extract substrings temp = [ test_str[idx:j] for idx in range(len(test_str)) for j in range(idx + 1, len(test_str) + 1) ] # loop to extract final result of frequencies res = {} for idx in temp: if idx not in res.keys(): res[idx] = 1 else: res[idx] += 1 # printing result print("Extracted frequency dictionary : " + str(res)) #Output : The original string is : abababa [END]
Python - All substrings Frequency in String
https://www.geeksforgeeks.org/python-all-substrings-frequency-in-string/
# Python3 code to demonstrate working of # All substrings Frequency in String # Using list comprehension # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # list comprehension to extract substrings and frequency res = dict() for ele in [ test_str[idx:j] for idx in range(len(test_str)) for j in range(idx + 1, len(test_str) + 1) ]: res[ele] = 1 if ele not in res.keys() else res[ele] + 1 # printing result print("Extracted frequency dictionary : " + str(res))
#Output : The original string is : abababa
Python - All substrings Frequency in String # Python3 code to demonstrate working of # All substrings Frequency in String # Using list comprehension # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # list comprehension to extract substrings and frequency res = dict() for ele in [ test_str[idx:j] for idx in range(len(test_str)) for j in range(idx + 1, len(test_str) + 1) ]: res[ele] = 1 if ele not in res.keys() else res[ele] + 1 # printing result print("Extracted frequency dictionary : " + str(res)) #Output : The original string is : abababa [END]
Python - All substrings Frequency in String
https://www.geeksforgeeks.org/python-all-substrings-frequency-in-string/
import re # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # using regex to count substring frequencies d = {} for i in range(1, len(test_str) + 1): for sub in re.findall("(?=(.{" + str(i) + "}))", test_str): d[sub] = d.get(sub, 0) + 1 # printing result print("Extracted frequency dictionary : " + str(d))
#Output : The original string is : abababa
Python - All substrings Frequency in String import re # initializing string test_str = "abababa" # printing original string print("The original string is : " + str(test_str)) # using regex to count substring frequencies d = {} for i in range(1, len(test_str) + 1): for sub in re.findall("(?=(.{" + str(i) + "}))", test_str): d[sub] = d.get(sub, 0) + 1 # printing result print("Extracted frequency dictionary : " + str(d)) #Output : The original string is : abababa [END]
Python - Maximum Consecutive Substring Occurrence
https://www.geeksforgeeks.org/python-maximum-consecutive-substring-occurrence/
# Python3 code to demonstrate working of # Maximum Consecutive Substring Occurrence # Using max() + re.findall() import re # Initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # Printing original string print("The original string is : " + str(test_str)) # Initializing subs sub_str = "geeks" # Maximum Consecutive Substring Occurrence # using max() + re.findall() res = max(re.findall("((?:" + re.escape(sub_str) + ")*)", test_str), key=len) # Printing result print("The maximum run of Substring : " + res)
#Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks
Python - Maximum Consecutive Substring Occurrence # Python3 code to demonstrate working of # Maximum Consecutive Substring Occurrence # Using max() + re.findall() import re # Initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # Printing original string print("The original string is : " + str(test_str)) # Initializing subs sub_str = "geeks" # Maximum Consecutive Substring Occurrence # using max() + re.findall() res = max(re.findall("((?:" + re.escape(sub_str) + ")*)", test_str), key=len) # Printing result print("The maximum run of Substring : " + res) #Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks [END]
Python - Maximum Consecutive Substring Occurrence
https://www.geeksforgeeks.org/python-maximum-consecutive-substring-occurrence/
# initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # initializing subs sub_str = "geeks" # printing original string print("The original string is : " + str(test_str)) max_sub = max( [ sub_str * n for n in range(len(test_str) // len(sub_str) + 1) if sub_str * n in test_str ], key=len, ) # printing result print("The maximum run of Substring : " + max_sub)
#Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks
Python - Maximum Consecutive Substring Occurrence # initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # initializing subs sub_str = "geeks" # printing original string print("The original string is : " + str(test_str)) max_sub = max( [ sub_str * n for n in range(len(test_str) // len(sub_str) + 1) if sub_str * n in test_str ], key=len, ) # printing result print("The maximum run of Substring : " + max_sub) #Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks [END]
Python - Maximum Consecutive Substring Occurrence
https://www.geeksforgeeks.org/python-maximum-consecutive-substring-occurrence/
# Python3 code to demonstrate working of # Maximum Consecutive Substring Occurrence import re # initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing subs sub_str = "geeks" # using lambda function to find maximum consecutive substring max_substring = lambda s, sub: max( re.findall("((?:" + re.escape(sub) + ")*)", s), key=len ) # Maximum Consecutive Substring Occurrence res = max_substring(test_str, sub_str) # printing result print("The maximum run of Substring : " + res)
#Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks
Python - Maximum Consecutive Substring Occurrence # Python3 code to demonstrate working of # Maximum Consecutive Substring Occurrence import re # initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing subs sub_str = "geeks" # using lambda function to find maximum consecutive substring max_substring = lambda s, sub: max( re.findall("((?:" + re.escape(sub) + ")*)", s), key=len ) # Maximum Consecutive Substring Occurrence res = max_substring(test_str, sub_str) # printing result print("The maximum run of Substring : " + res) #Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks [END]
Python - Maximum Consecutive Substring Occurrence
https://www.geeksforgeeks.org/python-maximum-consecutive-substring-occurrence/
# initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # initializing subs sub_str = "geeks" # printing original string print("The original string is : " + str(test_str)) # initializing variables max_count = 0 max_sub = "" # split the input string into a list of words words = test_str.split() # loop over the words in the list for word in words: # count the number of occurrences of the given substring in the word count = word.count(sub_str) # update max_count and max_sub if necessary if count >= max_count: max_count = count max_sub = sub_str * max_count # printing result print("The maximum run of Substring : " + max_sub)
#Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks
Python - Maximum Consecutive Substring Occurrence # initializing string test_str = "geeksgeeks are geeks for all geeksgeeksgeeks" # initializing subs sub_str = "geeks" # printing original string print("The original string is : " + str(test_str)) # initializing variables max_count = 0 max_sub = "" # split the input string into a list of words words = test_str.split() # loop over the words in the list for word in words: # count the number of occurrences of the given substring in the word count = word.count(sub_str) # update max_count and max_sub if necessary if count >= max_count: max_count = count max_sub = sub_str * max_count # printing result print("The maximum run of Substring : " + max_sub) #Output : The original string is : geeksgeeks are geeks for all geeksgeeksgeeks [END]
Python - Maximum occurring Substring from List
https://www.geeksforgeeks.org/python-maximum-occurring-substring-from-list/
# Python3 code to demonstrate working of # Maximum occurring Substring from list # Using regex() + groupby() + max() + lambda import re import itertools # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using regex() + groupby() + max() + lambda seqs = re.findall(str.join("|", test_list), test_str) grps = [(key, len(list(j))) for key, j in itertools.groupby(seqs)] res = max(grps, key=lambda ele: ele[1]) # printing result print("Maximum frequency substring : " + str(res[0]))
#Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb
Python - Maximum occurring Substring from List # Python3 code to demonstrate working of # Maximum occurring Substring from list # Using regex() + groupby() + max() + lambda import re import itertools # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using regex() + groupby() + max() + lambda seqs = re.findall(str.join("|", test_list), test_str) grps = [(key, len(list(j))) for key, j in itertools.groupby(seqs)] res = max(grps, key=lambda ele: ele[1]) # printing result print("Maximum frequency substring : " + str(res[0])) #Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb [END]
Python - Maximum occurring Substring from List
https://www.geeksforgeeks.org/python-maximum-occurring-substring-from-list/
# Python3 code to demonstrate working of # Maximum occurring Substring from list # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) res = [] for i in test_list: res.append(test_str.count(i)) x = max(res) result = test_list[res.index(x)] # printing result print("Maximum frequency substring : " + str(result))
#Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb
Python - Maximum occurring Substring from List # Python3 code to demonstrate working of # Maximum occurring Substring from list # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) res = [] for i in test_list: res.append(test_str.count(i)) x = max(res) result = test_list[res.index(x)] # printing result print("Maximum frequency substring : " + str(result)) #Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb [END]
Python - Maximum occurring Substring from List
https://www.geeksforgeeks.org/python-maximum-occurring-substring-from-list/
# Python3 code to demonstrate working of # Maximum occurring Substring from list # Using re.findall() + Counter # importing modules import collections import re # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using re.findall() + Counter seqs = re.findall(str.join("|", test_list), test_str) res = collections.Counter(seqs).most_common(1)[0][0] # printing result print("Maximum frequency substring : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy
#Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb
Python - Maximum occurring Substring from List # Python3 code to demonstrate working of # Maximum occurring Substring from list # Using re.findall() + Counter # importing modules import collections import re # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using re.findall() + Counter seqs = re.findall(str.join("|", test_list), test_str) res = collections.Counter(seqs).most_common(1)[0][0] # printing result print("Maximum frequency substring : " + str(res)) # This code is contributed by Edula Vinay Kumar Reddy #Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb [END]
Python - Maximum occurring Substring from List
https://www.geeksforgeeks.org/python-maximum-occurring-substring-from-list/
# Python3 code to demonstrate working of # Maximum occurring Substring from list # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) res = [] for i in test_list: import operator res.append(operator.countOf(test_str, i)) x = max(res) result = test_list[res.index(x)] # printing result print("Maximum frequency substring : " + str(result))
#Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb
Python - Maximum occurring Substring from List # Python3 code to demonstrate working of # Maximum occurring Substring from list # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) res = [] for i in test_list: import operator res.append(operator.countOf(test_str, i)) x = max(res) result = test_list[res.index(x)] # printing result print("Maximum frequency substring : " + str(result)) #Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb [END]
Python - Maximum occurring Substring from List
https://www.geeksforgeeks.org/python-maximum-occurring-substring-from-list/
# Python3 code to demonstrate working of # Maximum occurring Substring from list # Using dictionary # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using dictionary count_dict = {} for sub in test_list: count_dict[sub] = test_str.count(sub) res = max(count_dict, key=count_dict.get) # printing result print("Maximum frequency substring : " + str(res))
#Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb
Python - Maximum occurring Substring from List # Python3 code to demonstrate working of # Maximum occurring Substring from list # Using dictionary # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using dictionary count_dict = {} for sub in test_list: count_dict[sub] = test_str.count(sub) res = max(count_dict, key=count_dict.get) # printing result print("Maximum frequency substring : " + str(res)) #Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb [END]
Python - Maximum occurring Substring from List
https://www.geeksforgeeks.org/python-maximum-occurring-substring-from-list/
# Python3 code to demonstrate working of # Maximum occurring Substring from list # Using itertools.product() and count() import itertools # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using itertools.product() and count() max_count = 0 max_substring = "" for sub in test_list: for substring in itertools.product(*[sub] * len(sub)): count = test_str.count("".join(substring)) if count > max_count: max_count = count max_substring = "".join(substring) # printing result print("Maximum frequency substring : " + str(max_substring))
#Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb
Python - Maximum occurring Substring from List # Python3 code to demonstrate working of # Maximum occurring Substring from list # Using itertools.product() and count() import itertools # initializing string test_str = "gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb" test_list = ["gfg", "is", "best"] # printing original string and list print("The original string is : " + test_str) print("The original list is : " + str(test_list)) # Maximum occurring Substring from list # Using itertools.product() and count() max_count = 0 max_substring = "" for sub in test_list: for substring in itertools.product(*[sub] * len(sub)): count = test_str.count("".join(substring)) if count > max_count: max_count = count max_substring = "".join(substring) # printing result print("Maximum frequency substring : " + str(max_substring)) #Output : The original string is : gfghsisbjknlmkesbestgfgsdcngfgcsdjnisdjnlbestdjsklgfgcdsbestbnjdsgfgdbhisbhsbestdkgfgb [END]
Python - Possible Substring count from String
https://www.geeksforgeeks.org/python-possible-substring-count-from-string/
# Python3 code to demonstrate working of # Possible Substring count from String # Using min() + list comprehension + count() # initializing string test_str = "gekseforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing arg string arg_str = "geeks" # using min and count to get minimum possible # occurrence of character res = min(test_str.count(char) // arg_str.count(char) for char in set(arg_str)) # printing result print("Possible substrings count : " + str(res))
#Output : The original string is : gekseforgeeks
Python - Possible Substring count from String # Python3 code to demonstrate working of # Possible Substring count from String # Using min() + list comprehension + count() # initializing string test_str = "gekseforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing arg string arg_str = "geeks" # using min and count to get minimum possible # occurrence of character res = min(test_str.count(char) // arg_str.count(char) for char in set(arg_str)) # printing result print("Possible substrings count : " + str(res)) #Output : The original string is : gekseforgeeks [END]
Python - Possible Substring count from String
https://www.geeksforgeeks.org/python-possible-substring-count-from-string/
# Python3 code to demonstrate working of # Possible Substring count from String # Using Counter() + list comprehension from collections import Counter # initializing string test_str = "gekseforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing arg string arg_str = "geeks" # using Counter to get character frequencies temp1 = Counter(test_str) temp2 = Counter(arg_str) res = min(temp1[char] // temp2[char] for char in temp2.keys()) # printing result print("Possible substrings count : " + str(res))
#Output : The original string is : gekseforgeeks
Python - Possible Substring count from String # Python3 code to demonstrate working of # Possible Substring count from String # Using Counter() + list comprehension from collections import Counter # initializing string test_str = "gekseforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing arg string arg_str = "geeks" # using Counter to get character frequencies temp1 = Counter(test_str) temp2 = Counter(arg_str) res = min(temp1[char] // temp2[char] for char in temp2.keys()) # printing result print("Possible substrings count : " + str(res)) #Output : The original string is : gekseforgeeks [END]
Python - Possible Substring count from String
https://www.geeksforgeeks.org/python-possible-substring-count-from-string/
# Python3 code to demonstrate working of # Possible Substring count from String import operator as op # initializing string test_str = "gekseforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing arg string arg_str = "geeks" # using min and count to get minimum possible # occurrence of character res = min( op.countOf(test_str, char) // op.countOf(arg_str, char) for char in set(arg_str) ) # printing result print("Possible substrings count : " + str(res))
#Output : The original string is : gekseforgeeks
Python - Possible Substring count from String # Python3 code to demonstrate working of # Possible Substring count from String import operator as op # initializing string test_str = "gekseforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing arg string arg_str = "geeks" # using min and count to get minimum possible # occurrence of character res = min( op.countOf(test_str, char) // op.countOf(arg_str, char) for char in set(arg_str) ) # printing result print("Possible substrings count : " + str(res)) #Output : The original string is : gekseforgeeks [END]
Python - Replace all occurrences of a substring in a string
https://www.geeksforgeeks.org/python-replace-all-occurrences-of-a-substring-in-a-string/?ref=leftbar-rightbar
# Python has inbuilt function replace to replace all occurrences of substring. input_string = "geeksforgeeks" s1 = "geeks" s2 = "abcd" input_string = input_string.replace(s1, s2) print(input_string)
#Output : abcdforabcd
Python - Replace all occurrences of a substring in a string # Python has inbuilt function replace to replace all occurrences of substring. input_string = "geeksforgeeks" s1 = "geeks" s2 = "abcd" input_string = input_string.replace(s1, s2) print(input_string) #Output : abcdforabcd [END]
Python - Replace all occurrences of a substring in a string
https://www.geeksforgeeks.org/python-replace-all-occurrences-of-a-substring-in-a-string/?ref=leftbar-rightbar
# code for replacing all occurrences of substring s1 with new string s2 test_str = "geeksforgeeks" s1 = "geeks" s2 = "abcd" # string split by substring s = test_str.split(s1) new_str = "" for i in s: if i == "": new_str += s2 else: new_str += i # printing the replaced string print(new_str) # contributed by Bhavya Koganti
#Output : abcdforabcd
Python - Replace all occurrences of a substring in a string # code for replacing all occurrences of substring s1 with new string s2 test_str = "geeksforgeeks" s1 = "geeks" s2 = "abcd" # string split by substring s = test_str.split(s1) new_str = "" for i in s: if i == "": new_str += s2 else: new_str += i # printing the replaced string print(new_str) # contributed by Bhavya Koganti #Output : abcdforabcd [END]
Python - Replace all occurrences of a substring in a string
https://www.geeksforgeeks.org/python-replace-all-occurrences-of-a-substring-in-a-string/?ref=leftbar-rightbar
import re def replace_substring(test_str, s1, s2): # Replacing all occurrences of substring s1 with s2 test_str = re.sub(s1, s2, test_str) return test_str # test test_str = "geeksforgeeks" s1 = "geeks" s2 = "abcd" print(replace_substring(test_str, s1, s2))
#Output : abcdforabcd
Python - Replace all occurrences of a substring in a string import re def replace_substring(test_str, s1, s2): # Replacing all occurrences of substring s1 with s2 test_str = re.sub(s1, s2, test_str) return test_str # test test_str = "geeksforgeeks" s1 = "geeks" s2 = "abcd" print(replace_substring(test_str, s1, s2)) #Output : abcdforabcd [END]
Python - Replace all occurrences of a substring in a string
https://www.geeksforgeeks.org/python-replace-all-occurrences-of-a-substring-in-a-string/?ref=leftbar-rightbar
def replace_substring(test_str, s1, s2): # Initialize an empty string to store the result result = "" # Initialize a variable to keep track of our position in the string i = 0 # Loop through the string one character at a time while i < len(test_str): # Check if the current substring matches the substring we want to replace if test_str[i : i + len(s1)] == s1: # If it does, add the replacement substring to the result and move the pointer forward result += s2 i += len(s1) else: # If it doesn't, add the current character to the result and move the pointer forward result += test_str[i] i += 1 # Return the final result return result # test test_str = "geeksforgeeks" s1 = "geeks" s2 = "abcd" print(replace_substring(test_str, s1, s2))
#Output : abcdforabcd
Python - Replace all occurrences of a substring in a string def replace_substring(test_str, s1, s2): # Initialize an empty string to store the result result = "" # Initialize a variable to keep track of our position in the string i = 0 # Loop through the string one character at a time while i < len(test_str): # Check if the current substring matches the substring we want to replace if test_str[i : i + len(s1)] == s1: # If it does, add the replacement substring to the result and move the pointer forward result += s2 i += len(s1) else: # If it doesn't, add the current character to the result and move the pointer forward result += test_str[i] i += 1 # Return the final result return result # test test_str = "geeksforgeeks" s1 = "geeks" s2 = "abcd" print(replace_substring(test_str, s1, s2)) #Output : abcdforabcd [END]
Python - Longest Substring Length of K
https://www.geeksforgeeks.org/python-longest-substring-length-of-k/
# Python3 code to demonstrate working of # Longest Substring of K # Using loop # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" cnt = 0 res = 0 for idx in range(len(test_str)): # increment counter on checking if test_str[idx] == K: cnt += 1 else: cnt = 0 # retaining max res = max(res, cnt) # printing result print("The Longest Substring Length : " + str(res))
#Output : The original string is : abcaaaacbbaa
Python - Longest Substring Length of K # Python3 code to demonstrate working of # Longest Substring of K # Using loop # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" cnt = 0 res = 0 for idx in range(len(test_str)): # increment counter on checking if test_str[idx] == K: cnt += 1 else: cnt = 0 # retaining max res = max(res, cnt) # printing result print("The Longest Substring Length : " + str(res)) #Output : The original string is : abcaaaacbbaa [END]
Python - Longest Substring Length of K
https://www.geeksforgeeks.org/python-longest-substring-length-of-k/
# Python3 code to demonstrate working of # Longest Substring of K # Using findall() + max() import re # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" # getting all substrings res = re.findall(r"" + K + "+", test_str) # getting maximum of substrings Length res = len(max(res, key=len)) # printing result print("The Longest Substring Length : " + str(res))
#Output : The original string is : abcaaaacbbaa
Python - Longest Substring Length of K # Python3 code to demonstrate working of # Longest Substring of K # Using findall() + max() import re # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" # getting all substrings res = re.findall(r"" + K + "+", test_str) # getting maximum of substrings Length res = len(max(res, key=len)) # printing result print("The Longest Substring Length : " + str(res)) #Output : The original string is : abcaaaacbbaa [END]
Python - Longest Substring Length of K
https://www.geeksforgeeks.org/python-longest-substring-length-of-k/
# Importing itertools module import itertools # Initializing input string and the character to be searched test_str = "abcaaaacbbaa" K = "a" # printing the original string print("The original string is : " + str(test_str)) # Using groupby() function to group the characters of the string res = max([len(list(grp)) for char, grp in itertools.groupby(test_str) if char == K]) # Printing the result print("The Longest Substring Length : " + str(res))
#Output : The original string is : abcaaaacbbaa
Python - Longest Substring Length of K # Importing itertools module import itertools # Initializing input string and the character to be searched test_str = "abcaaaacbbaa" K = "a" # printing the original string print("The original string is : " + str(test_str)) # Using groupby() function to group the characters of the string res = max([len(list(grp)) for char, grp in itertools.groupby(test_str) if char == K]) # Printing the result print("The Longest Substring Length : " + str(res)) #Output : The original string is : abcaaaacbbaa [END]
Python - Longest Substring Length of K
https://www.geeksforgeeks.org/python-longest-substring-length-of-k/
import re # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" # Using generator expression, max() and re.split() function res = max(len(sub_str) for sub_str in re.split(f"[^{K}]", test_str)) # printing result print("The Longest Substring Length : " + str(res))
#Output : The original string is : abcaaaacbbaa
Python - Longest Substring Length of K import re # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" # Using generator expression, max() and re.split() function res = max(len(sub_str) for sub_str in re.split(f"[^{K}]", test_str)) # printing result print("The Longest Substring Length : " + str(res)) #Output : The original string is : abcaaaacbbaa [END]
Python - Longest Substring Length of K
https://www.geeksforgeeks.org/python-longest-substring-length-of-k/
# Python3 code to demonstrate working of # Longest Substring of K # Using Regular expression and max() # importing regular expression module import re # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" # find all occurrences of the character matches = re.findall(K + "+", test_str) # find the length of the longest substring res = len(max(matches, key=len)) # printing result print("The Longest Substring Length : " + str(res))
#Output : The original string is : abcaaaacbbaa
Python - Longest Substring Length of K # Python3 code to demonstrate working of # Longest Substring of K # Using Regular expression and max() # importing regular expression module import re # initializing string test_str = "abcaaaacbbaa" # printing original String print("The original string is : " + str(test_str)) # initializing K K = "a" # find all occurrences of the character matches = re.findall(K + "+", test_str) # find the length of the longest substring res = len(max(matches, key=len)) # printing result print("The Longest Substring Length : " + str(res)) #Output : The original string is : abcaaaacbbaa [END]
Python - Longest Substring Length of K
https://www.geeksforgeeks.org/python-longest-substring-length-of-k/
import numpy as np # Initializing input string and the character to be searched test_str = "abcaaaacbbaa" K = "a" # creating a numpy array from the input string arr = np.array(list(test_str)) # finding the indices where the character K appears indices = np.where(arr == K)[0] # finding the consecutive differences between indices differences = np.diff(indices) # finding the maximum consecutive difference res = np.max(differences) # printing the original string and the result print("The original string is : " + str(test_str)) print("The Longest Substring Length : " + str(res)) # This code is contributed by Rayudu.
#Output : The original string is : abcaaaacbbaa
Python - Longest Substring Length of K import numpy as np # Initializing input string and the character to be searched test_str = "abcaaaacbbaa" K = "a" # creating a numpy array from the input string arr = np.array(list(test_str)) # finding the indices where the character K appears indices = np.where(arr == K)[0] # finding the consecutive differences between indices differences = np.diff(indices) # finding the maximum consecutive difference res = np.max(differences) # printing the original string and the result print("The original string is : " + str(test_str)) print("The Longest Substring Length : " + str(res)) # This code is contributed by Rayudu. #Output : The original string is : abcaaaacbbaa [END]
Python - Extract Indices of substring mathches
https://www.geeksforgeeks.org/python-extract-indices-of-substring-matches/
# Python3 code to demonstrate working of # Extract Indices of substring matches # Using loop + enumerate() # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using loop to iterate through list res = [] for idx, ele in enumerate(test_list): if K in ele: res.append(idx) # printing result print("The indices list : " + str(res))
#Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3]
Python - Extract Indices of substring mathches # Python3 code to demonstrate working of # Extract Indices of substring matches # Using loop + enumerate() # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using loop to iterate through list res = [] for idx, ele in enumerate(test_list): if K in ele: res.append(idx) # printing result print("The indices list : " + str(res)) #Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3] [END]
Python - Extract Indices of substring mathches
https://www.geeksforgeeks.org/python-extract-indices-of-substring-matches/
# Python3 code to demonstrate working of # Extract Indices of substring matches # Using list comprehension + enumerate() # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using list comprehension and enumerate to offer compact solution res = [idx for idx, val in enumerate(test_list) if K in val] # printing result print("The indices list : " + str(res))
#Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3]
Python - Extract Indices of substring mathches # Python3 code to demonstrate working of # Extract Indices of substring matches # Using list comprehension + enumerate() # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using list comprehension and enumerate to offer compact solution res = [idx for idx, val in enumerate(test_list) if K in val] # printing result print("The indices list : " + str(res)) #Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3] [END]
Python - Extract Indices of substring mathches
https://www.geeksforgeeks.org/python-extract-indices-of-substring-matches/
# Python3 code to demonstrate working of # Extract Indices of substring matches # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using loop to iterate through list res = [] for i in range(0, len(test_list)): if test_list[i].find(K) != -1: res.append(i) # printing result print("The indices list : " + str(res))
#Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3]
Python - Extract Indices of substring mathches # Python3 code to demonstrate working of # Extract Indices of substring matches # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using loop to iterate through list res = [] for i in range(0, len(test_list)): if test_list[i].find(K) != -1: res.append(i) # printing result print("The indices list : " + str(res)) #Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3] [END]
Python - Extract Indices of substring mathches
https://www.geeksforgeeks.org/python-extract-indices-of-substring-matches/
# Python3 code to demonstrate working of # Extract Indices of substring matches # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using loop to iterate through list res = [] import operator for i in range(0, len(test_list)): if operator.contains(test_list[i], K): res.append(i) # printing result print("The indices list : " + str(res))
#Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3]
Python - Extract Indices of substring mathches # Python3 code to demonstrate working of # Extract Indices of substring matches # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using loop to iterate through list res = [] import operator for i in range(0, len(test_list)): if operator.contains(test_list[i], K): res.append(i) # printing result print("The indices list : " + str(res)) #Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3] [END]
Python - Extract Indices of substring mathches
https://www.geeksforgeeks.org/python-extract-indices-of-substring-matches/
# Python3 code to demonstrate working of # Extract Indices of substring matches # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using map() function with lambda function to get the list of True/False values bool_list = list(map(lambda x: K in x, test_list)) # using map() function with lambda function to convert bool_list into a list of 1's and 0's int_list = list(map(lambda x: 1 if x else 0, bool_list)) # using enumerate() function to get the indices of the int_list enum_list = list(enumerate(int_list)) # extracting the indices of the elements that have 1 in the int_list res = [i for i, j in enum_list if j == 1] # printing result print("The indices list : " + str(res))
#Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3]
Python - Extract Indices of substring mathches # Python3 code to demonstrate working of # Extract Indices of substring matches # initializing list test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Its useful"] # initializing K K = "Gfg" # printing original list print("The original list : " + str(test_list)) # using map() function with lambda function to get the list of True/False values bool_list = list(map(lambda x: K in x, test_list)) # using map() function with lambda function to convert bool_list into a list of 1's and 0's int_list = list(map(lambda x: 1 if x else 0, bool_list)) # using enumerate() function to get the indices of the int_list enum_list = list(enumerate(int_list)) # extracting the indices of the elements that have 1 in the int_list res = [i for i, j in enum_list if j == 1] # printing result print("The indices list : " + str(res)) #Input : test_list = ["Gfg is good", "for Geeks", "I love Gfg", "Gfg is useful"], K = "Gfg" #Output : [0, 2, 3] [END]
Python | Split by repeating substring
https://www.geeksforgeeks.org/python-split-by-repeating-substring/
# Python3 code to demonstrate working of # Split by repeating substring # Using * operator + len() # initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring # Using * operator + len() temp = len(test_str) // len(str(K)) res = [K] * temp # printing result print("The split string is : " + str(res))
#Output : The original string is : gfggfggfggfggfggfggfggfg
Python | Split by repeating substring # Python3 code to demonstrate working of # Split by repeating substring # Using * operator + len() # initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring # Using * operator + len() temp = len(test_str) // len(str(K)) res = [K] * temp # printing result print("The split string is : " + str(res)) #Output : The original string is : gfggfggfggfggfggfggfggfg [END]
Python | Split by repeating substring
https://www.geeksforgeeks.org/python-split-by-repeating-substring/
# Python3 code to demonstrate working of # Split by repeating substring # Using re.findall() import re # initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring # Using re.findall() res = re.findall(K, test_str) # printing result print("The split string is : " + str(res))
#Output : The original string is : gfggfggfggfggfggfggfggfg
Python | Split by repeating substring # Python3 code to demonstrate working of # Split by repeating substring # Using re.findall() import re # initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring # Using re.findall() res = re.findall(K, test_str) # printing result print("The split string is : " + str(res)) #Output : The original string is : gfggfggfggfggfggfggfggfg [END]
Python | Split by repeating substring
https://www.geeksforgeeks.org/python-split-by-repeating-substring/
# Python3 code to demonstrate working of # Split by repeating substring # initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring re = test_str.count(K) res = [K] * re # printing result print("The split string is : " + str(res))
#Output : The original string is : gfggfggfggfggfggfggfggfg
Python | Split by repeating substring # Python3 code to demonstrate working of # Split by repeating substring # initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring re = test_str.count(K) res = [K] * re # printing result print("The split string is : " + str(res)) #Output : The original string is : gfggfggfggfggfggfggfggfg [END]
Python | Split by repeating substring
https://www.geeksforgeeks.org/python-split-by-repeating-substring/
# initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring using loop and slicing res = [] start = 0 while start < len(test_str): end = start + len(K) if test_str[start:end] == K: res.append(K) start = end else: start += 1 # printing result print("The split string is : " + str(res)) # This code is contributed by Vinay Pinjala.
#Output : The original string is : gfggfggfggfggfggfggfggfg
Python | Split by repeating substring # initializing string test_str = "gfggfggfggfggfggfggfggfg" # printing original string print("The original string is : " + test_str) # initializing target K = "gfg" # Split by repeating substring using loop and slicing res = [] start = 0 while start < len(test_str): end = start + len(K) if test_str[start:end] == K: res.append(K) start = end else: start += 1 # printing result print("The split string is : " + str(res)) # This code is contributed by Vinay Pinjala. #Output : The original string is : gfggfggfggfggfggfggfggfg [END]
Python | Split by repeating substring
https://www.geeksforgeeks.org/python-split-by-repeating-substring/
import re # initializing string test_str = "gfggfggfggfggfggfggfggfg" # initializing target K = "gfg" # Split by repeating substring using re.findall() method res = re.findall(K, test_str) # printing result print("The original string is : " + test_str) print("The split string is : " + str(res))
#Output : The original string is : gfggfggfggfggfggfggfggfg
Python | Split by repeating substring import re # initializing string test_str = "gfggfggfggfggfggfggfggfg" # initializing target K = "gfg" # Split by repeating substring using re.findall() method res = re.findall(K, test_str) # printing result print("The original string is : " + test_str) print("The split string is : " + str(res)) #Output : The original string is : gfggfggfggfggfggfggfggfg [END]
Python | Remove substring list from string
https://www.geeksforgeeks.org/python-remove-substring-list-from-string/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove substring list from String # Using loop + replace() # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] # Remove substring list from String # Using loop + replace() for sub in sub_list: test_str = test_str.replace(" " + sub + " ", " ") # printing result print("The string after substring removal : " + test_str)
#Output : The original string is : gfg is best for all geeks
Python | Remove substring list from string # Python3 code to demonstrate working of # Remove substring list from String # Using loop + replace() # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] # Remove substring list from String # Using loop + replace() for sub in sub_list: test_str = test_str.replace(" " + sub + " ", " ") # printing result print("The string after substring removal : " + test_str) #Output : The original string is : gfg is best for all geeks [END]
Python | Remove substring list from string
https://www.geeksforgeeks.org/python-remove-substring-list-from-string/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove substring list from String # Using replace() + join() + split() # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] # Remove substring list from String # Using replace() + join() + split() for sub in sub_list: test_str = test_str.replace(sub, " ") res = " ".join(test_str.split()) # printing result print("The string after substring removal : " + res)
#Output : The original string is : gfg is best for all geeks
Python | Remove substring list from string # Python3 code to demonstrate working of # Remove substring list from String # Using replace() + join() + split() # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] # Remove substring list from String # Using replace() + join() + split() for sub in sub_list: test_str = test_str.replace(sub, " ") res = " ".join(test_str.split()) # printing result print("The string after substring removal : " + res) #Output : The original string is : gfg is best for all geeks [END]
Python | Remove substring list from string
https://www.geeksforgeeks.org/python-remove-substring-list-from-string/?ref=leftbar-rightbar
# Python3 code to demonstrate working of # Remove substring list from String # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] b = test_str.split() x = [] for i in b: if i not in sub_list: x.append(i) res = " ".join(x) # printing result print("The string after substring removal : " + res)
#Output : The original string is : gfg is best for all geeks
Python | Remove substring list from string # Python3 code to demonstrate working of # Remove substring list from String # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] b = test_str.split() x = [] for i in b: if i not in sub_list: x.append(i) res = " ".join(x) # printing result print("The string after substring removal : " + res) #Output : The original string is : gfg is best for all geeks [END]
Python | Remove substring list from string
https://www.geeksforgeeks.org/python-remove-substring-list-from-string/?ref=leftbar-rightbar
import re # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] # Remove substring list from String using regex and join() function pattern = "|".join(map(re.escape, sub_list)) test_str = re.sub(r"\b(?:{})\b".format(pattern), "", test_str) # printing result print("The string after substring removal : " + test_str) # This code is contributed by Vinay Pinjala.
#Output : The original string is : gfg is best for all geeks
Python | Remove substring list from string import re # initializing string test_str = "gfg is best for all geeks" # printing original string print("The original string is : " + test_str) # initializing sub list sub_list = ["best", "all"] # Remove substring list from String using regex and join() function pattern = "|".join(map(re.escape, sub_list)) test_str = re.sub(r"\b(?:{})\b".format(pattern), "", test_str) # printing result print("The string after substring removal : " + test_str) # This code is contributed by Vinay Pinjala. #Output : The original string is : gfg is best for all geeks [END]
Python | Remove substring list from string
https://www.geeksforgeeks.org/python-remove-substring-list-from-string/?ref=leftbar-rightbar
import numpy as np # initializing string test_str = "gfg is best for all geeks" # initializing sub list sub_list = ["best", "all"] # Remove substring list from String using numpy and string functions sub_arr = np.array(sub_list) test_arr = np.array(test_str.split()) mask_arr = np.ones(len(test_arr), dtype=bool) for i in range(len(sub_arr)): mask_arr &= ~(test_arr == sub_arr[i]) # Join the remaining words in the array to form the final string final_str = " ".join(test_arr[mask_arr]) # printing original string print("The original string is : " + test_str) # printing result print("The string after substring removal : " + final_str) # This code is contributed by Rayudu.
#Output : The original string is : gfg is best for all geeks
Python | Remove substring list from string import numpy as np # initializing string test_str = "gfg is best for all geeks" # initializing sub list sub_list = ["best", "all"] # Remove substring list from String using numpy and string functions sub_arr = np.array(sub_list) test_arr = np.array(test_str.split()) mask_arr = np.ones(len(test_arr), dtype=bool) for i in range(len(sub_arr)): mask_arr &= ~(test_arr == sub_arr[i]) # Join the remaining words in the array to form the final string final_str = " ".join(test_arr[mask_arr]) # printing original string print("The original string is : " + test_str) # printing result print("The string after substring removal : " + final_str) # This code is contributed by Rayudu. #Output : The original string is : gfg is best for all geeks [END]
Python - Remove after substring in String
https://www.geeksforgeeks.org/python-remove-after-substring-in-string/
# Python3 code to demonstrate working of # Remove after substring in String # Using index() + len() + slicing # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # slicing off after length computation res = test_str[: test_str.index(sub_str) + len(sub_str)] # printing result print("The string after removal : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
Python - Remove after substring in String # Python3 code to demonstrate working of # Remove after substring in String # Using index() + len() + slicing # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # slicing off after length computation res = test_str[: test_str.index(sub_str) + len(sub_str)] # printing result print("The string after removal : " + str(res)) #Output : The original string is : geeksforgeeks is best for geeks [END]
Python - Remove after substring in String
https://www.geeksforgeeks.org/python-remove-after-substring-in-string/
# Python3 code to demonstrate working of # Remove after substring in String # Using regex() ( for stripping off after numeric occurrence) import re # initializing strings test_str = "geeksforgeeks is best 4 geeks" # printing original string print("The original string is : " + str(test_str)) # slicing after the numeric occurrence res = re.match(r"(.*\d+)", test_str).group() # printing result print("The string after removal : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
Python - Remove after substring in String # Python3 code to demonstrate working of # Remove after substring in String # Using regex() ( for stripping off after numeric occurrence) import re # initializing strings test_str = "geeksforgeeks is best 4 geeks" # printing original string print("The original string is : " + str(test_str)) # slicing after the numeric occurrence res = re.match(r"(.*\d+)", test_str).group() # printing result print("The string after removal : " + str(res)) #Output : The original string is : geeksforgeeks is best for geeks [END]
Python - Remove after substring in String
https://www.geeksforgeeks.org/python-remove-after-substring-in-string/
# Python3 code to demonstrate working of # Remove after substring in String # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" re = test_str.split(sub_str) res = re[0] + sub_str # printing result print("The string after removal : " + str(res))
#Output : The original string is : geeksforgeeks is best for geeks
Python - Remove after substring in String # Python3 code to demonstrate working of # Remove after substring in String # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" re = test_str.split(sub_str) res = re[0] + sub_str # printing result print("The string after removal : " + str(res)) #Output : The original string is : geeksforgeeks is best for geeks [END]
Python - Remove after substring in String
https://www.geeksforgeeks.org/python-remove-after-substring-in-string/
# initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # Remove after substring in String # Using str.find() and str.slice() if sub_str in test_str: res = test_str[: test_str.find(sub_str) + len(sub_str)] # printing result print("The string after removal : " + str(res)) # This code is contributed by Vinay Pinjala.
#Output : The original string is : geeksforgeeks is best for geeks
Python - Remove after substring in String # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # Remove after substring in String # Using str.find() and str.slice() if sub_str in test_str: res = test_str[: test_str.find(sub_str) + len(sub_str)] # printing result print("The string after removal : " + str(res)) # This code is contributed by Vinay Pinjala. #Output : The original string is : geeksforgeeks is best for geeks [END]
Python - Remove after substring in String
https://www.geeksforgeeks.org/python-remove-after-substring-in-string/
# Python3 code to demonstrate working of # Remove after substring in String # Using index() + len() + slicing from functools import reduce # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # define a function to remove the substring and get the result def remove_substring(s, sub): idx = s.find(sub) if idx != -1: return s[: idx + len(sub)] return s # using reduce to apply the function and get the final result res = reduce(lambda s, sub: remove_substring(s, sub), [sub_str], test_str) # printing result print("The string after removal : " + str(res)) # This code is contributed by Rayudu.
#Output : The original string is : geeksforgeeks is best for geeks
Python - Remove after substring in String # Python3 code to demonstrate working of # Remove after substring in String # Using index() + len() + slicing from functools import reduce # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # define a function to remove the substring and get the result def remove_substring(s, sub): idx = s.find(sub) if idx != -1: return s[: idx + len(sub)] return s # using reduce to apply the function and get the final result res = reduce(lambda s, sub: remove_substring(s, sub), [sub_str], test_str) # printing result print("The string after removal : " + str(res)) # This code is contributed by Rayudu. #Output : The original string is : geeksforgeeks is best for geeks [END]
Python - Remove after substring in String
https://www.geeksforgeeks.org/python-remove-after-substring-in-string/
# initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # remove string after sub string res = test_str.replace(test_str[test_str.find(sub_str) + len(sub_str) :], "") # printing result print("The string after removal : " + str(res)) # This code is contributed by Jyothi pinjala.
#Output : The original string is : geeksforgeeks is best for geeks
Python - Remove after substring in String # initializing strings test_str = "geeksforgeeks is best for geeks" # printing original string print("The original string is : " + str(test_str)) # initializing sub string sub_str = "best" # remove string after sub string res = test_str.replace(test_str[test_str.find(sub_str) + len(sub_str) :], "") # printing result print("The string after removal : " + str(res)) # This code is contributed by Jyothi pinjala. #Output : The original string is : geeksforgeeks is best for geeks [END]
Python | Remove Reduntant Substrings from String List
https://www.geeksforgeeks.org/python-remove-reduntant-substrings-from-strings-list/
# Python3 code to demonstrate working of # Remove Redundant Substrings from Strings List # Using enumerate() + join() + sort() # initializing list test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"] # printing original list print("The original list : " + str(test_list)) # using loop to iterate for each string test_list.sort(key=len) res = [] for idx, val in enumerate(test_list): # concatenating all next values and checking for existence if val not in ", ".join(test_list[idx + 1 :]): res.append(val) # printing result print("The filtered list : " + str(res))
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
Python | Remove Reduntant Substrings from String List # Python3 code to demonstrate working of # Remove Redundant Substrings from Strings List # Using enumerate() + join() + sort() # initializing list test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"] # printing original list print("The original list : " + str(test_list)) # using loop to iterate for each string test_list.sort(key=len) res = [] for idx, val in enumerate(test_list): # concatenating all next values and checking for existence if val not in ", ".join(test_list[idx + 1 :]): res.append(val) # printing result print("The filtered list : " + str(res)) #Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] [END]
Python | Remove Reduntant Substrings from String List
https://www.geeksforgeeks.org/python-remove-reduntant-substrings-from-strings-list/
# Python3 code to demonstrate working of # Remove Redundant Substrings from Strings List # Using list comprehension + join() + enumerate() # initializing list test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"] # printing original list print("The original list : " + str(test_list)) # using list comprehension to iterate for each string # and perform join in one liner test_list.sort(key=len) res = [ val for idx, val in enumerate(test_list) if val not in ", ".join(test_list[idx + 1 :]) ] # printing result print("The filtered list : " + str(res))
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
Python | Remove Reduntant Substrings from String List # Python3 code to demonstrate working of # Remove Redundant Substrings from Strings List # Using list comprehension + join() + enumerate() # initializing list test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"] # printing original list print("The original list : " + str(test_list)) # using list comprehension to iterate for each string # and perform join in one liner test_list.sort(key=len) res = [ val for idx, val in enumerate(test_list) if val not in ", ".join(test_list[idx + 1 :]) ] # printing result print("The filtered list : " + str(res)) #Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] [END]
Python | Remove Reduntant Substrings from String List
https://www.geeksforgeeks.org/python-remove-reduntant-substrings-from-strings-list/
def remove_redundant_substrings(strings): # Base case: if the list is empty or has only one element, return it if len(strings) <= 1: return strings # Sort the list by length to simplify the recursion strings.sort(key=len) # Take the first string and remove it from the list current_string = strings.pop(0) # Recursively remove redundant substrings from the rest of the list remaining_strings = remove_redundant_substrings(strings) # Check if the current string is a redundant substring of any of the remaining strings for string in remaining_strings: if current_string in string: return remaining_strings # If the current string is not redundant, add it back to the list and return it remaining_strings.append(current_string) return remaining_strings test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"] print("The original list : " + str(test_list)) res = remove_redundant_substrings(test_list) print("The filtered list : " + str(res))
#Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks']
Python | Remove Reduntant Substrings from String List def remove_redundant_substrings(strings): # Base case: if the list is empty or has only one element, return it if len(strings) <= 1: return strings # Sort the list by length to simplify the recursion strings.sort(key=len) # Take the first string and remove it from the list current_string = strings.pop(0) # Recursively remove redundant substrings from the rest of the list remaining_strings = remove_redundant_substrings(strings) # Check if the current string is a redundant substring of any of the remaining strings for string in remaining_strings: if current_string in string: return remaining_strings # If the current string is not redundant, add it back to the list and return it remaining_strings.append(current_string) return remaining_strings test_list = ["Gfg", "Gfg is best", "Geeks", "Gfg is for Geeks"] print("The original list : " + str(test_list)) res = remove_redundant_substrings(test_list) print("The filtered list : " + str(res)) #Output : The original list : ['Gfg', 'Gfg is best', 'Geeks', 'Gfg is for Geeks'] [END]
Python - Test substring order
https://www.geeksforgeeks.org/python-test-substring-order/
# Python3 code to demonstrate working of # Test substring order # Using join() + in operator + generator expression # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" # concatenating required characters def temp(sub): return "".join(chr for chr in sub if chr in set(K)) # checking in order res = K in temp(test_str) # printing result print("Is substring in order : " + str(res))
#Output : The original string is : geeksforgeeks
Python - Test substring order # Python3 code to demonstrate working of # Test substring order # Using join() + in operator + generator expression # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" # concatenating required characters def temp(sub): return "".join(chr for chr in sub if chr in set(K)) # checking in order res = K in temp(test_str) # printing result print("Is substring in order : " + str(res)) #Output : The original string is : geeksforgeeks [END]
Python - Test substring order
https://www.geeksforgeeks.org/python-test-substring-order/
# Python3 code to demonstrate working of # Test substring order # Using all() + next() + generator expression # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" # concatenating required characters using next() # all() used to test order test_str = iter(test_str) res = all(next((ele for ele in test_str if ele == chr), None) is not None for chr in K) # printing result print("Is substring in order : " + str(res))
#Output : The original string is : geeksforgeeks
Python - Test substring order # Python3 code to demonstrate working of # Test substring order # Using all() + next() + generator expression # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" # concatenating required characters using next() # all() used to test order test_str = iter(test_str) res = all(next((ele for ele in test_str if ele == chr), None) is not None for chr in K) # printing result print("Is substring in order : " + str(res)) #Output : The original string is : geeksforgeeks [END]
Python - Test substring order
https://www.geeksforgeeks.org/python-test-substring-order/
# Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" ns = "" for i in test_str: if i in K: ns += i res = False if ns.find(K) != -1: res = True # printing result print("Is substring in order : " + str(res))
#Output : The original string is : geeksforgeeks
Python - Test substring order # Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" ns = "" for i in test_str: if i in K: ns += i res = False if ns.find(K) != -1: res = True # printing result print("Is substring in order : " + str(res)) #Output : The original string is : geeksforgeeks [END]
Python - Test substring order
https://www.geeksforgeeks.org/python-test-substring-order/
# Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" for i in test_str: if i not in K: test_str = test_str.replace(i, "") res = False if test_str.find(K) != -1: res = True # printing result print("Is substring in order : " + str(res))
#Output : The original string is : geeksforgeeks
Python - Test substring order # Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" for i in test_str: if i not in K: test_str = test_str.replace(i, "") res = False if test_str.find(K) != -1: res = True # printing result print("Is substring in order : " + str(res)) #Output : The original string is : geeksforgeeks [END]
Python - Test substring order
https://www.geeksforgeeks.org/python-test-substring-order/
# Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" for i in test_str: if i not in K: test_str = test_str.replace(i, "") import operator res = operator.contains(test_str, K) # printing result print("Is substring in order : " + str(res))
#Output : The original string is : geeksforgeeks
Python - Test substring order # Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" for i in test_str: if i not in K: test_str = test_str.replace(i, "") import operator res = operator.contains(test_str, K) # printing result print("Is substring in order : " + str(res)) #Output : The original string is : geeksforgeeks [END]
Python - Test substring order
https://www.geeksforgeeks.org/python-test-substring-order/
# Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" # using list comprehension and all() res = all(K[i] in test_str[test_str.find(K[i - 1]) + 1 :] for i in range(1, len(K))) # printing result print("Is substring in order : " + str(res))
#Output : The original string is : geeksforgeeks
Python - Test substring order # Python3 code to demonstrate working of # Test substring order # initializing string test_str = "geeksforgeeks" # printing original string print("The original string is : " + str(test_str)) # initializing substring K = "seek" # using list comprehension and all() res = all(K[i] in test_str[test_str.find(K[i - 1]) + 1 :] for i in range(1, len(K))) # printing result print("Is substring in order : " + str(res)) #Output : The original string is : geeksforgeeks [END]
Python - String till Substring
https://www.geeksforgeeks.org/python-string-till-substring/
# Python3 code to demonstrate # String till Substring # using partition() # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing split word spl_word = "best" # printing original string print("The original string : " + str(test_string)) # printing split string print("The split string : " + str(spl_word)) # using partition() # String till Substring res = test_string.partition(spl_word)[0] # print result print("String before the substring occurrence : " + res)
#Output : The original string : GeeksforGeeks is best for geeks
Python - String till Substring # Python3 code to demonstrate # String till Substring # using partition() # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing split word spl_word = "best" # printing original string print("The original string : " + str(test_string)) # printing split string print("The split string : " + str(spl_word)) # using partition() # String till Substring res = test_string.partition(spl_word)[0] # print result print("String before the substring occurrence : " + res) #Output : The original string : GeeksforGeeks is best for geeks [END]
Python - String till Substring
https://www.geeksforgeeks.org/python-string-till-substring/
# Python3 code to demonstrate # String till Substring # using split() # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing split word spl_word = "best" # printing original string print("The original string : " + str(test_string)) # printing split string print("The split string : " + str(spl_word)) # using split() # String till Substring res = test_string.split(spl_word)[0] # print result print("String before the substring occurrence : " + res)
#Output : The original string : GeeksforGeeks is best for geeks
Python - String till Substring # Python3 code to demonstrate # String till Substring # using split() # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing split word spl_word = "best" # printing original string print("The original string : " + str(test_string)) # printing split string print("The split string : " + str(spl_word)) # using split() # String till Substring res = test_string.split(spl_word)[0] # print result print("String before the substring occurrence : " + res) #Output : The original string : GeeksforGeeks is best for geeks [END]
Python - String till Substring
https://www.geeksforgeeks.org/python-string-till-substring/
# Python3 code to demonstrate # String till Substring # using find() # you can also use index() instead of find() # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing substring spl_word = "best" # printing original string print("The original string : " + str(test_string)) # String till Substring x = test_string.find(spl_word) res = test_string[0:x] # print result print("String before the substring occurrence : " + res)
#Output : The original string : GeeksforGeeks is best for geeks
Python - String till Substring # Python3 code to demonstrate # String till Substring # using find() # you can also use index() instead of find() # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing substring spl_word = "best" # printing original string print("The original string : " + str(test_string)) # String till Substring x = test_string.find(spl_word) res = test_string[0:x] # print result print("String before the substring occurrence : " + res) #Output : The original string : GeeksforGeeks is best for geeks [END]
Python - String till Substring
https://www.geeksforgeeks.org/python-string-till-substring/
import re # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing substring spl_word = "best" # using regular expression result = re.split(spl_word, test_string, maxsplit=1)[0] # printing result print("String before the substring occurrence:", result)
#Output : The original string : GeeksforGeeks is best for geeks
Python - String till Substring import re # initializing string test_string = "GeeksforGeeks is best for geeks" # initializing substring spl_word = "best" # using regular expression result = re.split(spl_word, test_string, maxsplit=1)[0] # printing result print("String before the substring occurrence:", result) #Output : The original string : GeeksforGeeks is best for geeks [END]
Python - String till Substring
https://www.geeksforgeeks.org/python-string-till-substring/
# Initializing string test_string = "GeeksforGeeks is best for geeks" # Initializing substring spl_word = "best" # Initializing an empty string to store the characters before the substring occurrence res = "" # Looping over the characters of the string for char in test_string: # Checking if the current character is the first character of the substring if char == spl_word[0]: # Checking if the substring is found if ( test_string[ test_string.index(char) : test_string.index(char) + len(spl_word) ] == spl_word ): break res += char # Printing the result print("String before the substring occurrence: " + res)
#Output : The original string : GeeksforGeeks is best for geeks
Python - String till Substring # Initializing string test_string = "GeeksforGeeks is best for geeks" # Initializing substring spl_word = "best" # Initializing an empty string to store the characters before the substring occurrence res = "" # Looping over the characters of the string for char in test_string: # Checking if the current character is the first character of the substring if char == spl_word[0]: # Checking if the substring is found if ( test_string[ test_string.index(char) : test_string.index(char) + len(spl_word) ] == spl_word ): break res += char # Printing the result print("String before the substring occurrence: " + res) #Output : The original string : GeeksforGeeks is best for geeks [END]
Python - Filter string combination of K substring
https://www.geeksforgeeks.org/python-filter-strings-combination-of-k-substrings/
# Python3 code to demonstrate working of # Filter Strings combination of K substrings # Using permutations() + map() + join() + set() + loop from itertools import permutations # initializing list test_list = ["geeks4u", "allbest", "abcdef"] # printing string print("The original list : " + str(test_list)) # initializing substring list substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"] # initializing K K = 3 # getting all permutations perms = list(set(map("".join, permutations(substr_list, r=K)))) # using loop to check permutations with list res = [] for ele in perms: if ele in test_list: res.append(ele) # printing results print("Strings after joins : " + str(res))
#Output : The original list : ['geeks4u', 'allbest', 'abcdef']
Python - Filter string combination of K substring # Python3 code to demonstrate working of # Filter Strings combination of K substrings # Using permutations() + map() + join() + set() + loop from itertools import permutations # initializing list test_list = ["geeks4u", "allbest", "abcdef"] # printing string print("The original list : " + str(test_list)) # initializing substring list substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"] # initializing K K = 3 # getting all permutations perms = list(set(map("".join, permutations(substr_list, r=K)))) # using loop to check permutations with list res = [] for ele in perms: if ele in test_list: res.append(ele) # printing results print("Strings after joins : " + str(res)) #Output : The original list : ['geeks4u', 'allbest', 'abcdef'] [END]
Python - Filter string combination of K substring
https://www.geeksforgeeks.org/python-filter-strings-combination-of-k-substrings/
# Python3 code to demonstrate working of # Filter Strings combination of K substrings # Using permutations() + map() + join() + set() + intersection() from itertools import permutations # initializing list test_list = ["geeks4u", "allbest", "abcdef"] # printing string print("The original list : " + str(test_list)) # initializing substring list substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"] # initializing K K = 3 # getting all permutations perms = set(map("".join, permutations(substr_list, r=K))) # using intersection() to solve this problem res = list(set(test_list).intersection(perms)) # printing results print("Strings after joins : " + str(res))
#Output : The original list : ['geeks4u', 'allbest', 'abcdef']
Python - Filter string combination of K substring # Python3 code to demonstrate working of # Filter Strings combination of K substrings # Using permutations() + map() + join() + set() + intersection() from itertools import permutations # initializing list test_list = ["geeks4u", "allbest", "abcdef"] # printing string print("The original list : " + str(test_list)) # initializing substring list substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"] # initializing K K = 3 # getting all permutations perms = set(map("".join, permutations(substr_list, r=K))) # using intersection() to solve this problem res = list(set(test_list).intersection(perms)) # printing results print("Strings after joins : " + str(res)) #Output : The original list : ['geeks4u', 'allbest', 'abcdef'] [END]
Python - Filter string combination of K substring
https://www.geeksforgeeks.org/python-filter-strings-combination-of-k-substrings/
from itertools import permutations test_list = ["geeks4u", "allbest", "abcdef"] substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"] K = 3 print("The original list : " + str(test_list)) res = [] for s in test_list: for p in permutations(substr_list, K): if "".join(p) in s: res.append(s) break print("Strings after joins : " + str(res))
#Output : The original list : ['geeks4u', 'allbest', 'abcdef']
Python - Filter string combination of K substring from itertools import permutations test_list = ["geeks4u", "allbest", "abcdef"] substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"] K = 3 print("The original list : " + str(test_list)) res = [] for s in test_list: for p in permutations(substr_list, K): if "".join(p) in s: res.append(s) break print("Strings after joins : " + str(res)) #Output : The original list : ['geeks4u', 'allbest', 'abcdef'] [END]
Python program to Find the size of a Tuple
https://www.geeksforgeeks.org/find-the-size-of-a-tuple-in-python/
import sys # sample Tuples Tuple1 = ("A", 1, "B", 2, "C", 3) Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu") Tuple3 = ((1, "Lion"), (2, "Tiger"), (3, "Fox"), (4, "Wolf")) # print the sizes of sample Tuples print("Size of Tuple1: " + str(sys.getsizeof(Tuple1)) + "bytes") print("Size of Tuple2: " + str(sys.getsizeof(Tuple2)) + "bytes") print("Size of Tuple3: " + str(sys.getsizeof(Tuple3)) + "bytes")
#Output : Size of Tuple1: 96bytes
Python program to Find the size of a Tuple import sys # sample Tuples Tuple1 = ("A", 1, "B", 2, "C", 3) Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu") Tuple3 = ((1, "Lion"), (2, "Tiger"), (3, "Fox"), (4, "Wolf")) # print the sizes of sample Tuples print("Size of Tuple1: " + str(sys.getsizeof(Tuple1)) + "bytes") print("Size of Tuple2: " + str(sys.getsizeof(Tuple2)) + "bytes") print("Size of Tuple3: " + str(sys.getsizeof(Tuple3)) + "bytes") #Output : Size of Tuple1: 96bytes [END]
Python program to Find the size of a Tuple
https://www.geeksforgeeks.org/find-the-size-of-a-tuple-in-python/
# sample Tuples Tuple1 = ("A", 1, "B", 2, "C", 3) Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu") Tuple3 = ((1, "Lion"), (2, "Tiger"), (3, "Fox"), (4, "Wolf")) # print the sizes of sample Tuples print("Size of Tuple1: " + str(Tuple1.__sizeof__()) + "bytes") print("Size of Tuple2: " + str(Tuple2.__sizeof__()) + "bytes") print("Size of Tuple3: " + str(Tuple3.__sizeof__()) + "bytes")
#Output : Size of Tuple1: 96bytes
Python program to Find the size of a Tuple # sample Tuples Tuple1 = ("A", 1, "B", 2, "C", 3) Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu") Tuple3 = ((1, "Lion"), (2, "Tiger"), (3, "Fox"), (4, "Wolf")) # print the sizes of sample Tuples print("Size of Tuple1: " + str(Tuple1.__sizeof__()) + "bytes") print("Size of Tuple2: " + str(Tuple2.__sizeof__()) + "bytes") print("Size of Tuple3: " + str(Tuple3.__sizeof__()) + "bytes") #Output : Size of Tuple1: 96bytes [END]
Python - Maximum and Minimum K elements in Tuple
https://www.geeksforgeeks.org/python-maximum-and-minimum-k-elements-in-tuple/
# Python3 code to demonstrate working of # Maximum and Minimum K elements in Tuple # Using sorted() + loop # initializing tuple test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) # initializing K K = 2 # Maximum and Minimum K elements in Tuple # Using sorted() + loop res = [] test_tup = list(sorted(test_tup)) for idx, val in enumerate(test_tup): if idx < K or idx >= len(test_tup) - K: res.append(val) res = tuple(res) # printing result print("The extracted values : " + str(res))
#Output : The original tuple is : (5, 20, 3, 7, 6, 8)
Python - Maximum and Minimum K elements in Tuple # Python3 code to demonstrate working of # Maximum and Minimum K elements in Tuple # Using sorted() + loop # initializing tuple test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) # initializing K K = 2 # Maximum and Minimum K elements in Tuple # Using sorted() + loop res = [] test_tup = list(sorted(test_tup)) for idx, val in enumerate(test_tup): if idx < K or idx >= len(test_tup) - K: res.append(val) res = tuple(res) # printing result print("The extracted values : " + str(res)) #Output : The original tuple is : (5, 20, 3, 7, 6, 8) [END]
Python - Maximum and Minimum K elements in Tuple
https://www.geeksforgeeks.org/python-maximum-and-minimum-k-elements-in-tuple/
# Python3 code to demonstrate working of # Maximum and Minimum K elements in Tuple # Using slicing + sorted() # initializing tuple test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) # initializing K K = 2 # Maximum and Minimum K elements in Tuple # Using slicing + sorted() test_tup = list(test_tup) temp = sorted(test_tup) res = tuple(temp[:K] + temp[-K:]) # printing result print("The extracted values : " + str(res))
#Output : The original tuple is : (5, 20, 3, 7, 6, 8)
Python - Maximum and Minimum K elements in Tuple # Python3 code to demonstrate working of # Maximum and Minimum K elements in Tuple # Using slicing + sorted() # initializing tuple test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) # initializing K K = 2 # Maximum and Minimum K elements in Tuple # Using slicing + sorted() test_tup = list(test_tup) temp = sorted(test_tup) res = tuple(temp[:K] + temp[-K:]) # printing result print("The extracted values : " + str(res)) #Output : The original tuple is : (5, 20, 3, 7, 6, 8) [END]
Python - Maximum and Minimum K elements in Tuple
https://www.geeksforgeeks.org/python-maximum-and-minimum-k-elements-in-tuple/
import heapq test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) K = 2 smallest = heapq.nsmallest(K, test_tup) largest = heapq.nlargest(K, test_tup) result = tuple(sorted(smallest + largest)) print("The extracted values : " + str(result)) # This code is contributed by Jyothi pinjala
#Output : The original tuple is : (5, 20, 3, 7, 6, 8)
Python - Maximum and Minimum K elements in Tuple import heapq test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) K = 2 smallest = heapq.nsmallest(K, test_tup) largest = heapq.nlargest(K, test_tup) result = tuple(sorted(smallest + largest)) print("The extracted values : " + str(result)) # This code is contributed by Jyothi pinjala #Output : The original tuple is : (5, 20, 3, 7, 6, 8) [END]
Python - Maximum and Minimum K elements in Tuple
https://www.geeksforgeeks.org/python-maximum-and-minimum-k-elements-in-tuple/
# Python3 code to demonstrate working of # Maximum and Minimum K elements in Tuple # Using built-in functions and loop # initializing tuple test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) # initializing K K = 2 # Find the minimum and maximum elements in the tuple min_val = min(test_tup) max_val = max(test_tup) # Create two lists to store the K minimum and maximum elements min_list = [] max_list = [] # Loop through the tuple and add elements to the appropriate list for elem in test_tup: if elem <= max_val: if len(max_list) < K: max_list.append(elem) else: max_list.remove(min(max_list)) max_list.append(elem) max_val = max(max_list) if elem >= min_val: if len(min_list) < K: min_list.append(elem) else: min_list.remove(max(min_list)) min_list.append(elem) min_val = min(min_list) # Combine the two lists and convert the result back to a tuple result = tuple(min_list + max_list) # Print the original tuple and the extracted values print("The extracted values : " + str(result))
#Output : The original tuple is : (5, 20, 3, 7, 6, 8)
Python - Maximum and Minimum K elements in Tuple # Python3 code to demonstrate working of # Maximum and Minimum K elements in Tuple # Using built-in functions and loop # initializing tuple test_tup = (5, 20, 3, 7, 6, 8) # printing original tuple print("The original tuple is : " + str(test_tup)) # initializing K K = 2 # Find the minimum and maximum elements in the tuple min_val = min(test_tup) max_val = max(test_tup) # Create two lists to store the K minimum and maximum elements min_list = [] max_list = [] # Loop through the tuple and add elements to the appropriate list for elem in test_tup: if elem <= max_val: if len(max_list) < K: max_list.append(elem) else: max_list.remove(min(max_list)) max_list.append(elem) max_val = max(max_list) if elem >= min_val: if len(min_list) < K: min_list.append(elem) else: min_list.remove(max(min_list)) min_list.append(elem) min_val = min(min_list) # Combine the two lists and convert the result back to a tuple result = tuple(min_list + max_list) # Print the original tuple and the extracted values print("The extracted values : " + str(result)) #Output : The original tuple is : (5, 20, 3, 7, 6, 8) [END]
Create a list of tuples from given list having number and its cube in each tuple
https://www.geeksforgeeks.org/python-program-to-create-a-list-of-tuples-from-given-list-having-number-and-its-cube-in-each-tuple/
# Python program to create a list of tuples # from given list having number and # its cube in each tuple # creating a list list1 = [1, 2, 5, 6] # using list comprehension to iterate each # values in list and create a tuple as specified res = [(val, pow(val, 3)) for val in list1] # print the result print(res)
Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)]
Create a list of tuples from given list having number and its cube in each tuple # Python program to create a list of tuples # from given list having number and # its cube in each tuple # creating a list list1 = [1, 2, 5, 6] # using list comprehension to iterate each # values in list and create a tuple as specified res = [(val, pow(val, 3)) for val in list1] # print the result print(res) Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] [END]
Create a list of tuples from given list having number and its cube in each tuple
https://www.geeksforgeeks.org/python-program-to-create-a-list-of-tuples-from-given-list-having-number-and-its-cube-in-each-tuple/
# Python program to create a list of tuples # from given list having number and # its cube in each tuple # creating a list list1 = [1, 2, 5, 6] # using list comprehension to iterate each # values in list and create a tuple as specified res = [(val, val**3) for val in list1] # print the result print(res)
Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)]
Create a list of tuples from given list having number and its cube in each tuple # Python program to create a list of tuples # from given list having number and # its cube in each tuple # creating a list list1 = [1, 2, 5, 6] # using list comprehension to iterate each # values in list and create a tuple as specified res = [(val, val**3) for val in list1] # print the result print(res) Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] [END]
Create a list of tuples from given list having number and its cube in each tuple
https://www.geeksforgeeks.org/python-program-to-create-a-list-of-tuples-from-given-list-having-number-and-its-cube-in-each-tuple/
list1 = [1, 2, 5, 6] res = list(map(lambda x: (x, x**3), list1)) print(res) # This code is contributed by Edula Vinay Kumar Reddy
Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)]
Create a list of tuples from given list having number and its cube in each tuple list1 = [1, 2, 5, 6] res = list(map(lambda x: (x, x**3), list1)) print(res) # This code is contributed by Edula Vinay Kumar Reddy Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] [END]
Create a list of tuples from given list having number and its cube in each tuple
https://www.geeksforgeeks.org/python-program-to-create-a-list-of-tuples-from-given-list-having-number-and-its-cube-in-each-tuple/
# creating a list list1 = [1, 2, 5, 6] # creating an empty list to store the result res = [] # iterating through each value in the list for val in list1: # creating a tuple of the value and its cube tup = (val, val**3) # adding the tuple to the result list res.append(tup) # print the result print(res)
Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)]
Create a list of tuples from given list having number and its cube in each tuple # creating a list list1 = [1, 2, 5, 6] # creating an empty list to store the result res = [] # iterating through each value in the list for val in list1: # creating a tuple of the value and its cube tup = (val, val**3) # adding the tuple to the result list res.append(tup) # print the result print(res) Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] [END]
Create a list of tuples from given list having number and its cube in each tuple
https://www.geeksforgeeks.org/python-program-to-create-a-list-of-tuples-from-given-list-having-number-and-its-cube-in-each-tuple/
import re lst_str = "1, 2, 5, 6" lst = [int(num) for num in re.findall(r"\d+", lst_str)] result = [(num, num**3) for num in lst] print(result)
Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)]
Create a list of tuples from given list having number and its cube in each tuple import re lst_str = "1, 2, 5, 6" lst = [int(num) for num in re.findall(r"\d+", lst_str)] result = [(num, num**3) for num in lst] print(result) Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] [END]
Python - Adding Tuple to List and vice versa
https://www.geeksforgeeks.org/python-adding-tuple-to-list-and-vice-versa/
# Python3 code to demonstrate working of # Adding Tuple to List and vice - versa # Using += operator (list + tuple) # initializing list test_list = [5, 6, 7] # printing original list print("The original list is : " + str(test_list)) # initializing tuple test_tup = (9, 10) # Adding Tuple to List and vice - versa # Using += operator (list + tuple) test_list += test_tup # printing result print("The container after addition : " + str(test_list))
#Output : The original list is : [5, 6, 7]
Python - Adding Tuple to List and vice versa # Python3 code to demonstrate working of # Adding Tuple to List and vice - versa # Using += operator (list + tuple) # initializing list test_list = [5, 6, 7] # printing original list print("The original list is : " + str(test_list)) # initializing tuple test_tup = (9, 10) # Adding Tuple to List and vice - versa # Using += operator (list + tuple) test_list += test_tup # printing result print("The container after addition : " + str(test_list)) #Output : The original list is : [5, 6, 7] [END]
Python - Adding Tuple to List and vice versa
https://www.geeksforgeeks.org/python-adding-tuple-to-list-and-vice-versa/
# Python3 code to demonstrate working of # Adding Tuple to List and vice - versa # Using tuple(), data type conversion [tuple + list] # initializing list test_list = [5, 6, 7] # printing original list print("The original list is : " + str(test_list)) # initializing tuple test_tup = (9, 10) # Adding Tuple to List and vice - versa # Using tuple(), data type conversion [tuple + list] res = tuple(list(test_tup) + test_list) # printing result print("The container after addition : " + str(res))
#Output : The original list is : [5, 6, 7]
Python - Adding Tuple to List and vice versa # Python3 code to demonstrate working of # Adding Tuple to List and vice - versa # Using tuple(), data type conversion [tuple + list] # initializing list test_list = [5, 6, 7] # printing original list print("The original list is : " + str(test_list)) # initializing tuple test_tup = (9, 10) # Adding Tuple to List and vice - versa # Using tuple(), data type conversion [tuple + list] res = tuple(list(test_tup) + test_list) # printing result print("The container after addition : " + str(res)) #Output : The original list is : [5, 6, 7] [END]
Python - Adding Tuple to List and vice versa
https://www.geeksforgeeks.org/python-adding-tuple-to-list-and-vice-versa/
# Python3 code to demonstrate working of # Adding Tuple to List and vice - versa # initializing list and tuple test_list = [5, 6, 7] test_tup = (9, 10) # printing original list print("The original list is : " + str(test_list)) # Adding Tuple to List test_list.extend(list(test_tup)) # printing result print("The container after addition : " + str(test_list)) # ********************************************************* # initializing list and tuple test_list = [1, 2, 3, 4] test_tup = (5, 6) # printing original tuple print("The original tuple is : " + str(test_tup)) # Adding list to tuple test_tup = list(test_tup) test_tup.extend(test_list) test_tup = tuple(test_tup) # printing result print("The container after addition : " + str(test_tup))
#Output : The original list is : [5, 6, 7]
Python - Adding Tuple to List and vice versa # Python3 code to demonstrate working of # Adding Tuple to List and vice - versa # initializing list and tuple test_list = [5, 6, 7] test_tup = (9, 10) # printing original list print("The original list is : " + str(test_list)) # Adding Tuple to List test_list.extend(list(test_tup)) # printing result print("The container after addition : " + str(test_list)) # ********************************************************* # initializing list and tuple test_list = [1, 2, 3, 4] test_tup = (5, 6) # printing original tuple print("The original tuple is : " + str(test_tup)) # Adding list to tuple test_tup = list(test_tup) test_tup.extend(test_list) test_tup = tuple(test_tup) # printing result print("The container after addition : " + str(test_tup)) #Output : The original list is : [5, 6, 7] [END]
Python - Adding Tuple to List and vice versa
https://www.geeksforgeeks.org/python-adding-tuple-to-list-and-vice-versa/
my_list = [5, 6, 7] my_tuple = (9, 10) index = 3 my_list.insert(index, my_tuple) print("List after addition: ", my_list)
#Output : The original list is : [5, 6, 7]
Python - Adding Tuple to List and vice versa my_list = [5, 6, 7] my_tuple = (9, 10) index = 3 my_list.insert(index, my_tuple) print("List after addition: ", my_list) #Output : The original list is : [5, 6, 7] [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
def summation(test_tup): # Converting into list test = list(test_tup) # Initializing count count = 0 # for loop for i in test: count += i return count # Initializing test_tup test_tup = (5, 20, 3, 7, 6, 8) print(summation(test_tup))
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements def summation(test_tup): # Converting into list test = list(test_tup) # Initializing count count = 0 # for loop for i in test: count += i return count # Initializing test_tup test_tup = (5, 20, 3, 7, 6, 8) print(summation(test_tup)) #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
# Python 3 code to demonstrate working of # Tuple elements inversions # Using map() + list() + sum() # initializing tup test_tup = ([7, 8], [9, 1], [10, 7]) # printing original tuple print("The original tuple is : " + str(test_tup)) # Tuple elements inversions # Using map() + list() + sum() res = sum(list(map(sum, list(test_tup)))) # printing result print("The summation of tuple elements are : " + str(res))
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements # Python 3 code to demonstrate working of # Tuple elements inversions # Using map() + list() + sum() # initializing tup test_tup = ([7, 8], [9, 1], [10, 7]) # printing original tuple print("The original tuple is : " + str(test_tup)) # Tuple elements inversions # Using map() + list() + sum() res = sum(list(map(sum, list(test_tup)))) # printing result print("The summation of tuple elements are : " + str(res)) #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
# Python3 code to demonstrate working of # Tuple summation # Initializing tuple test_tup = (7, 8, 9, 1, 10, 7) # Printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 for i in test_tup: res += i # Printing result print("The summation of tuple elements are : " + str(res))
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements # Python3 code to demonstrate working of # Tuple summation # Initializing tuple test_tup = (7, 8, 9, 1, 10, 7) # Printing original tuple print("The original tuple is : " + str(test_tup)) res = 0 for i in test_tup: res += i # Printing result print("The summation of tuple elements are : " + str(res)) #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
import operator from functools import reduce def summation(test_tup): # Using reduce() + operator.add() return reduce(operator.add, test_tup) # initializing test_tup test_tup = (5, 20, 3, 7, 6, 8) print(summation(test_tup)) # This code is contributed by Edula Vinay Kumar Reddy
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements import operator from functools import reduce def summation(test_tup): # Using reduce() + operator.add() return reduce(operator.add, test_tup) # initializing test_tup test_tup = (5, 20, 3, 7, 6, 8) print(summation(test_tup)) # This code is contributed by Edula Vinay Kumar Reddy #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
# Python3 code to demonstrate working of # Tuple summation using numpy import numpy as np # Initializing tuple test_tup = (7, 8, 9, 1, 10, 7) # Converting tuple to numpy array test_array = np.array(test_tup) # Printing original tuple print("The original tuple is : " + str(test_tup)) # Finding sum of array elements res = np.sum(test_array) # Printing result print("The summation of tuple elements are : " + str(res))
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements # Python3 code to demonstrate working of # Tuple summation using numpy import numpy as np # Initializing tuple test_tup = (7, 8, 9, 1, 10, 7) # Converting tuple to numpy array test_array = np.array(test_tup) # Printing original tuple print("The original tuple is : " + str(test_tup)) # Finding sum of array elements res = np.sum(test_array) # Printing result print("The summation of tuple elements are : " + str(res)) #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
def summation(test_tup): # Convert the tuple to a list using a list comprehension test = [x for x in test_tup] # Find the sum of the elements in the list using the built-in sum() function return sum(test) # Test the function with a tuple of integers test_tup = (5, 20, 3, 7, 6, 8) print(summation(test_tup))
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements def summation(test_tup): # Convert the tuple to a list using a list comprehension test = [x for x in test_tup] # Find the sum of the elements in the list using the built-in sum() function return sum(test) # Test the function with a tuple of integers test_tup = (5, 20, 3, 7, 6, 8) print(summation(test_tup)) #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
def summation2(test_tup): # Check if the input is empty or contains non-integer elements if len(test_tup) == 0: raise ValueError("Input tuple is empty") if not all(isinstance(x, int) for x in test_tup): raise TypeError("Input tuple must contain only integers") # Use a generator expression to convert the tuple to an iterable iterable = (x for x in test_tup) # Find the sum of the elements in the iterable using the built-in sum() function total_sum = sum(iterable) return total_sum test_tup = (5, 20, 3, 7, 6, 8) print(summation2(test_tup))
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements def summation2(test_tup): # Check if the input is empty or contains non-integer elements if len(test_tup) == 0: raise ValueError("Input tuple is empty") if not all(isinstance(x, int) for x in test_tup): raise TypeError("Input tuple must contain only integers") # Use a generator expression to convert the tuple to an iterable iterable = (x for x in test_tup) # Find the sum of the elements in the iterable using the built-in sum() function total_sum = sum(iterable) return total_sum test_tup = (5, 20, 3, 7, 6, 8) print(summation2(test_tup)) #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Sum of tuple elements
https://www.geeksforgeeks.org/python-sum-of-tuple-elements/
import math # initializing tuple test_tup = (7, 8, 9, 1, 10, 7) # calculating sum of tuple elements using math.fsum() res = math.fsum(test_tup) # printing result print("The summation of tuple elements are : " + str(res))
#Output : The original tuple is : (7, 8, 9, 1, 10, 7)
Python - Sum of tuple elements import math # initializing tuple test_tup = (7, 8, 9, 1, 10, 7) # calculating sum of tuple elements using math.fsum() res = math.fsum(test_tup) # printing result print("The summation of tuple elements are : " + str(res)) #Output : The original tuple is : (7, 8, 9, 1, 10, 7) [END]
Python - Modulo of tuple elements
https://www.geeksforgeeks.org/python-modulo-of-tuple-elements/
# Python3 code to demonstrate working of # Tuple modulo # using zip() + generator expression # Initialize tuples test_tup1 = (10, 4, 5, 6) test_tup2 = (5, 6, 7, 5) # Printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple modulo # using zip() + generator expression res = tuple(ele1 % ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # Printing result print("The modulus tuple : " + str(res))
#Output : The original tuple 1 : (10, 4, 5, 6)
Python - Modulo of tuple elements # Python3 code to demonstrate working of # Tuple modulo # using zip() + generator expression # Initialize tuples test_tup1 = (10, 4, 5, 6) test_tup2 = (5, 6, 7, 5) # Printing original tuples print("The original tuple 1 : " + str(test_tup1)) print("The original tuple 2 : " + str(test_tup2)) # Tuple modulo # using zip() + generator expression res = tuple(ele1 % ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) # Printing result print("The modulus tuple : " + str(res)) #Output : The original tuple 1 : (10, 4, 5, 6) [END]