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 given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
# set function convert string
# into set of characters .
p = set(string)
# declare set of '0', '1' .
s = {"0", "1"}
# check set p is same as set s
# or set p contains only '0'
# or set p contains only '1'
# or not, if any one condition
# is true then string is accepted
# otherwise not .
if s == p or p == {"0"} or p == {"1"}:
print("Yes")
else:
print("No")
# driver code
if __name__ == "__main__":
string = "101010000111"
# function calling
check(string)
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
# set function convert string
# into set of characters .
p = set(string)
# declare set of '0', '1' .
s = {"0", "1"}
# check set p is same as set s
# or set p contains only '0'
# or set p contains only '1'
# or not, if any one condition
# is true then string is accepted
# otherwise not .
if s == p or p == {"0"} or p == {"1"}:
print("Yes")
else:
print("No")
# driver code
if __name__ == "__main__":
string = "101010000111"
# function calling
check(string)
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check2(string):
# initialize the variable t
# with '01' string
t = "01"
# initialize the variable count
# with 0 value
count = 0
# looping through each character
# of the string .
for char in string:
# check the character is present in
# string t or not.
# if this condition is true
# assign 1 to the count variable
# and break out of the for loop
# otherwise pass
if char not in t:
count = 1
break
else:
pass
# after coming out of the loop
# check value of count is non-zero or not
# if the value is non-zero the en condition is true
# and string is not accepted
# otherwise string is accepted
if count:
print("No")
else:
print("Yes")
# driver code
if __name__ == "__main__":
string = "001021010001010"
# function calling
check2(string)
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check2(string):
# initialize the variable t
# with '01' string
t = "01"
# initialize the variable count
# with 0 value
count = 0
# looping through each character
# of the string .
for char in string:
# check the character is present in
# string t or not.
# if this condition is true
# assign 1 to the count variable
# and break out of the for loop
# otherwise pass
if char not in t:
count = 1
break
else:
pass
# after coming out of the loop
# check value of count is non-zero or not
# if the value is non-zero the en condition is true
# and string is not accepted
# otherwise string is accepted
if count:
print("No")
else:
print("Yes")
# driver code
if __name__ == "__main__":
string = "001021010001010"
# function calling
check2(string)
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
# import library
import re
sampleInput = "1001010"
# regular expression to find the strings
# which have characters other than 0 and 1
c = re.compile("[^01]")
# use findall() to get the list of strings
# that have characters other than 0 and 1.
if len(c.findall(sampleInput)):
print("No") # if length of list > 0 then it is not binary
else:
print("Yes") # if length of list = 0 then it is binary
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
# import library
import re
sampleInput = "1001010"
# regular expression to find the strings
# which have characters other than 0 and 1
c = re.compile("[^01]")
# use findall() to get the list of strings
# that have characters other than 0 and 1.
if len(c.findall(sampleInput)):
print("No") # if length of list > 0 then it is not binary
else:
print("Yes") # if length of list = 0 then it is binary
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
try:
# this will raise value error if
# string is not of base 2
int(string, 2)
except ValueError:
return "No"
return "Yes"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
try:
# this will raise value error if
# string is not of base 2
int(string, 2)
except ValueError:
return "No"
return "Yes"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
string = "01010101010"
if string.count("0") + string.count("1") == len(string):
print("Yes")
else:
print("No")
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
string = "01010101010"
if string.count("0") + string.count("1") == len(string):
print("Yes")
else:
print("No")
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
# Python program to check string is binary or not
string = "01010121010"
binary = "01"
for i in binary:
string = string.replace(i, "")
if len(string) == 0:
print("Yes")
else:
print("No")
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
# Python program to check string is binary or not
string = "01010121010"
binary = "01"
for i in binary:
string = string.replace(i, "")
if len(string) == 0:
print("Yes")
else:
print("No")
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
if all((letter in "01") for letter in string):
return "Yes"
return "No"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
# Python program to check
# if a string is binary or not
# function for checking the
# string is accepted or not
def check(string):
if all((letter in "01") for letter in string):
return "Yes"
return "No"
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(check(string1))
print(check(string2))
# this code is contributed by phasing17
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
def is_binary_string(s):
# use set comprehension to extract all unique characters from the string
unique_chars = {c for c in s}
# check if the unique characters are only 0 and 1
return unique_chars.issubset({"0", "1"})
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(is_binary_string(string1))
print(is_binary_string(string2))
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
def is_binary_string(s):
# use set comprehension to extract all unique characters from the string
unique_chars = {c for c in s}
# check if the unique characters are only 0 and 1
return unique_chars.issubset({"0", "1"})
# driver code
if __name__ == "__main__":
string1 = "101011000111"
string2 = "201000001"
# function calling
print(is_binary_string(string1))
print(is_binary_string(string2))
Input: str = "01010101010"
Output: Yes
[END]
|
Python - Check if a given string is binary string or not
|
https://www.geeksforgeeks.org/python-check-if-a-given-string-is-binary-string-or-not/
|
import re
def is_binary_string(str):
# Define regular expression
regex = r"[^01]"
# Search for regular expression in string
if re.search(regex, str):
return False
else:
return True
# Examples
print(is_binary_string("01010101010")) # Output: Yes
print(is_binary_string("geeks101")) # Output: No
|
Input: str = "01010101010"
Output: Yes
|
Python - Check if a given string is binary string or not
import re
def is_binary_string(str):
# Define regular expression
regex = r"[^01]"
# Search for regular expression in string
if re.search(regex, str):
return False
else:
return True
# Examples
print(is_binary_string("01010101010")) # Output: Yes
print(is_binary_string("geeks101")) # Output: No
Input: str = "01010101010"
Output: Yes
[END]
|
Python set to check if string is panagram
|
https://www.geeksforgeeks.org/python-set-check-string-panagram/
|
# import from string all ascii_lowercase and asc_lower
from string import ascii_lowercase as asc_lower
# function to check if all elements are present or not
def check(s):
return set(asc_lower) - set(s.lower()) == set([])
# driver code
string = "The quick brown fox jumps over the lazy dog"
if check(string) == True:
print("The string is a pangram")
else:
print("The string isn't a pangram")
|
#Input : The quick brown fox jumps over the lazy dog
#Output : The string is a pangram
|
Python set to check if string is panagram
# import from string all ascii_lowercase and asc_lower
from string import ascii_lowercase as asc_lower
# function to check if all elements are present or not
def check(s):
return set(asc_lower) - set(s.lower()) == set([])
# driver code
string = "The quick brown fox jumps over the lazy dog"
if check(string) == True:
print("The string is a pangram")
else:
print("The string isn't a pangram")
#Input : The quick brown fox jumps over the lazy dog
#Output : The string is a pangram
[END]
|
Python set to check if string is panagram
|
https://www.geeksforgeeks.org/python-set-check-string-panagram/
|
# function to check if all elements are present or not
string = "The quick brown fox jumps over the lazy dog"
string = string.replace(" ", "")
string = string.lower()
x = list(set(string))
x.sort()
x = "".join(x)
alphabets = "abcdefghijklmnopqrstuvwxyz"
if x == alphabets:
print("The string is a pangram")
else:
print("The string isn't a pangram")
|
#Input : The quick brown fox jumps over the lazy dog
#Output : The string is a pangram
|
Python set to check if string is panagram
# function to check if all elements are present or not
string = "The quick brown fox jumps over the lazy dog"
string = string.replace(" ", "")
string = string.lower()
x = list(set(string))
x.sort()
x = "".join(x)
alphabets = "abcdefghijklmnopqrstuvwxyz"
if x == alphabets:
print("The string is a pangram")
else:
print("The string isn't a pangram")
#Input : The quick brown fox jumps over the lazy dog
#Output : The string is a pangram
[END]
|
Python set to check if string is panagram
|
https://www.geeksforgeeks.org/python-set-check-string-panagram/
|
# function to check if all elements are present or not
string = "The quick brown fox jumps over the lazy dog"
string = string.replace(" ", "")
string = string.lower()
alphabets = "abcdefghijklmnopqrstuvwxyz"
c = 0
for i in alphabets:
if i in string:
c += 1
if c == len(alphabets):
print("The string is a pangram")
else:
print("The string isn't a pangram")
|
#Input : The quick brown fox jumps over the lazy dog
#Output : The string is a pangram
|
Python set to check if string is panagram
# function to check if all elements are present or not
string = "The quick brown fox jumps over the lazy dog"
string = string.replace(" ", "")
string = string.lower()
alphabets = "abcdefghijklmnopqrstuvwxyz"
c = 0
for i in alphabets:
if i in string:
c += 1
if c == len(alphabets):
print("The string is a pangram")
else:
print("The string isn't a pangram")
#Input : The quick brown fox jumps over the lazy dog
#Output : The string is a pangram
[END]
|
Python Set - Pairs of complete strings in two sets
|
https://www.geeksforgeeks.org/python-set-pairs-complete-strings-two-sets/
|
# Function to find pairs of complete strings
# in two sets of strings
def completePair(set1, set2):
# consider all pairs of string from
# set1 and set2
count = 0
for str1 in set1:
for str2 in set2:
result = str1 + str2
# push all alphabets of concatenated
# string into temporary set
tmpSet = set(
[ch for ch in result if (ord(ch) >= ord("a") and ord(ch) <= ord("z"))]
)
if len(tmpSet) == 26:
count = count + 1
print(count)
# Driver program
if __name__ == "__main__":
set1 = ["abcdefgh", "geeksforgeeks", "lmnopqrst", "abc"]
set2 = [
"ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz",
]
completePair(set1, set2)
|
#Input : set1[] = {"abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc"}
|
Python Set - Pairs of complete strings in two sets
# Function to find pairs of complete strings
# in two sets of strings
def completePair(set1, set2):
# consider all pairs of string from
# set1 and set2
count = 0
for str1 in set1:
for str2 in set2:
result = str1 + str2
# push all alphabets of concatenated
# string into temporary set
tmpSet = set(
[ch for ch in result if (ord(ch) >= ord("a") and ord(ch) <= ord("z"))]
)
if len(tmpSet) == 26:
count = count + 1
print(count)
# Driver program
if __name__ == "__main__":
set1 = ["abcdefgh", "geeksforgeeks", "lmnopqrst", "abc"]
set2 = [
"ijklmnopqrstuvwxyz",
"abcdefghijklmnopqrstuvwxyz",
"defghijklmnopqrstuvwxyz",
]
completePair(set1, set2)
#Input : set1[] = {"abcdefgh", "geeksforgeeks",
"lmnopqrst", "abc"}
[END]
|
Python program to check whether a given string is Heterogram or not
|
https://www.geeksforgeeks.org/python-set-check-whether-given-string-heterogram-not/
|
# Function to Check whether a given string is Heterogram or not
def heterogram(input):
# separate out list of alphabets using list comprehension
# ord function returns ascii value of character
alphabets = [ch for ch in input if (ord(ch) >= ord("a") and ord(ch) <= ord("z"))]
# convert list of alphabets into set and
# compare lengths
if len(set(alphabets)) == len(alphabets):
print("Yes")
else:
print("No")
# Driver program
if __name__ == "__main__":
input = "the big dwarf only jumps"
heterogram(input)
|
#Input : S = "the big dwarf only jumps"
#Output : Yes
|
Python program to check whether a given string is Heterogram or not
# Function to Check whether a given string is Heterogram or not
def heterogram(input):
# separate out list of alphabets using list comprehension
# ord function returns ascii value of character
alphabets = [ch for ch in input if (ord(ch) >= ord("a") and ord(ch) <= ord("z"))]
# convert list of alphabets into set and
# compare lengths
if len(set(alphabets)) == len(alphabets):
print("Yes")
else:
print("No")
# Driver program
if __name__ == "__main__":
input = "the big dwarf only jumps"
heterogram(input)
#Input : S = "the big dwarf only jumps"
#Output : Yes
[END]
|
Python program to check whether a given string is Heterogram or not
|
https://www.geeksforgeeks.org/python-set-check-whether-given-string-heterogram-not/
|
def is_heterogram(string):
sorted_string = sorted(string.lower())
for i in range(1, len(sorted_string)):
if sorted_string[i] == sorted_string[i - 1] and sorted_string[i].isalpha():
return "No"
return "Yes"
string = "the big dwarf only jumps"
print(is_heterogram(string))
|
#Input : S = "the big dwarf only jumps"
#Output : Yes
|
Python program to check whether a given string is Heterogram or not
def is_heterogram(string):
sorted_string = sorted(string.lower())
for i in range(1, len(sorted_string)):
if sorted_string[i] == sorted_string[i - 1] and sorted_string[i].isalpha():
return "No"
return "Yes"
string = "the big dwarf only jumps"
print(is_heterogram(string))
#Input : S = "the big dwarf only jumps"
#Output : Yes
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
# program to convert set to tuple
# create set
s = {"a", "b", "c", "d", "e"}
# print set
print(type(s), " ", s)
# call tuple() method
# this method convert set to tuple
t = tuple(s)
# print tuple
print(type(t), " ", t)
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
# program to convert set to tuple
# create set
s = {"a", "b", "c", "d", "e"}
# print set
print(type(s), " ", s)
# call tuple() method
# this method convert set to tuple
t = tuple(s)
# print tuple
print(type(t), " ", t)
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
s = {"a", "b", "c", "d", "e"}
x = [i for i in s]
print(tuple(x))
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
s = {"a", "b", "c", "d", "e"}
x = [i for i in s]
print(tuple(x))
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
s = {"a", "b", "c", "d", "e"}
x = [i for a, i in enumerate(s)]
print(tuple(x))
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
s = {"a", "b", "c", "d", "e"}
x = [i for a, i in enumerate(s)]
print(tuple(x))
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
# program to convert tuple into set
# create tuple
t = ("x", "y", "z")
# print tuple
print(type(t), " ", t)
# call set() method
s = set(t)
# print set
print(type(s), " ", s)
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
# program to convert tuple into set
# create tuple
t = ("x", "y", "z")
# print tuple
print(type(t), " ", t)
# call set() method
s = set(t)
# print set
print(type(s), " ", s)
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
# initializing a set
test_set = {6, 3, 7, 1, 2, 4}
# converting the set into a tuple
test_tuple = (*test_set,)
# printing the converted tuple
print("The converted tuple : " + str(test_tuple))
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
# initializing a set
test_set = {6, 3, 7, 1, 2, 4}
# converting the set into a tuple
test_tuple = (*test_set,)
# printing the converted tuple
print("The converted tuple : " + str(test_tuple))
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
s = {"a", "b", "c", "d", "e"}
# initialize an empty tuple
t = tuple()
# loop through each element in the set s
for i in s:
# create a one-element tuple with the current element i and concatenate it to t
t += (i,)
# print the resulting tuple
print(t)
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
s = {"a", "b", "c", "d", "e"}
# initialize an empty tuple
t = tuple()
# loop through each element in the set s
for i in s:
# create a one-element tuple with the current element i and concatenate it to t
t += (i,)
# print the resulting tuple
print(t)
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
import itertools
# initializing set
s = {"a", "b", "c", "d", "e"}
t = tuple(itertools.chain(s))
# print the resulting tuple
print(t)
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
import itertools
# initializing set
s = {"a", "b", "c", "d", "e"}
t = tuple(itertools.chain(s))
# print the resulting tuple
print(t)
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert Set into Tuple and Tuple into Set
|
https://www.geeksforgeeks.org/python-program-to-convert-set-into-tuple-and-tuple-into-set/
|
# Python program for the above approach
from functools import redu
s = {"a", "b", "c", "d", "e"}
t = reduce(lambda acc, x: acc + (x,), s, ())
# Print the converted tuple
print("The converted tuple : " + str(t))
|
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
|
Python program to convert Set into Tuple and Tuple into Set
# Python program for the above approach
from functools import redu
s = {"a", "b", "c", "d", "e"}
t = reduce(lambda acc, x: acc + (x,), s, ())
# Print the converted tuple
print("The converted tuple : " + str(t))
Input: {'a', 'b', 'c', 'd', 'e'}
Output: ('a', 'c', 'b', 'e', 'd')
[END]
|
Python program to convert set into a list
|
https://www.geeksforgeeks.org/python-convert-set-into-a-list/
|
# Python3 program to convert a
# set into a list
my_set = {"Geeks", "for", "geeks"}
s = list(my_set)
print(s)
|
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
|
Python program to convert set into a list
# Python3 program to convert a
# set into a list
my_set = {"Geeks", "for", "geeks"}
s = list(my_set)
print(s)
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
[END]
|
Python program to convert set into a list
|
https://www.geeksforgeeks.org/python-convert-set-into-a-list/
|
# Python3 program to convert a
# set into a list
def convert(set):
return list(set)
# Driver function
s = set({1, 2, 3})
print(convert(s))
|
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
|
Python program to convert set into a list
# Python3 program to convert a
# set into a list
def convert(set):
return list(set)
# Driver function
s = set({1, 2, 3})
print(convert(s))
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
[END]
|
Python program to convert set into a list
|
https://www.geeksforgeeks.org/python-convert-set-into-a-list/
|
# Python3 program to convert a
# set into a list
def convert(set):
return sorted(set)
# Driver function
my_set = {1, 2, 3}
s = set(my_set)
print(convert(s))
|
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
|
Python program to convert set into a list
# Python3 program to convert a
# set into a list
def convert(set):
return sorted(set)
# Driver function
my_set = {1, 2, 3}
s = set(my_set)
print(convert(s))
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
[END]
|
Python program to convert set into a list
|
https://www.geeksforgeeks.org/python-convert-set-into-a-list/
|
# Python3 program to convert a
# set into a list
def convert(set):
return [
*set,
]
# Driver function
s = set({1, 2, 3})
print(convert(s))
|
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
|
Python program to convert set into a list
# Python3 program to convert a
# set into a list
def convert(set):
return [
*set,
]
# Driver function
s = set({1, 2, 3})
print(convert(s))
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
[END]
|
Python program to convert set into a list
|
https://www.geeksforgeeks.org/python-convert-set-into-a-list/
|
# Python3 program to convert a
# set into a list
def convert(s):
return list(map(lambda x: x, s))
# Driver function
s = {1, 2, 3}
print(convert(s))
# This code is contributed by Ravipati Deepthi
|
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
|
Python program to convert set into a list
# Python3 program to convert a
# set into a list
def convert(s):
return list(map(lambda x: x, s))
# Driver function
s = {1, 2, 3}
print(convert(s))
# This code is contributed by Ravipati Deepthi
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
[END]
|
Python program to convert set into a list
|
https://www.geeksforgeeks.org/python-convert-set-into-a-list/
|
def convert(s):
# Use a list comprehension to create a new list from the elements in the set
return [elem for elem in s]
s = {1, 2, 3}
print(convert(s))
# This code is contributed by Edula Vinay Kumar Reddy
|
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
|
Python program to convert set into a list
def convert(s):
# Use a list comprehension to create a new list from the elements in the set
return [elem for elem in s]
s = {1, 2, 3}
print(convert(s))
# This code is contributed by Edula Vinay Kumar Reddy
#Input : {1, 2, 3, 4}
#Output : [1, 2, 3, 4]
[END]
|
Python program to convert Set to String List
|
https://www.geeksforgeeks.org/convert-set-to-string-in-python/
|
# create a set
s = {"a", "b", "c", "d"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
|
#Output : Initially
|
Python program to convert Set to String List
# create a set
s = {"a", "b", "c", "d"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
#Output : Initially
[END]
|
Python program to convert Set to String List
|
https://www.geeksforgeeks.org/convert-set-to-string-in-python/
|
# create a set
s = {"g", "e", "e", "k", "s"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
|
#Output : Initially
|
Python program to convert Set to String List
# create a set
s = {"g", "e", "e", "k", "s"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
s = str(s)
print("\nAfter the conversion")
print("The datatype of s : " + str(type(s)))
print("Contents of s : " + s)
#Output : Initially
[END]
|
Python program to convert Set to String List
|
https://www.geeksforgeeks.org/convert-set-to-string-in-python/
|
# create a set
s = {"a", "b", "c", "d"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
S = ", ".join(s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)
|
#Output : Initially
|
Python program to convert Set to String List
# create a set
s = {"a", "b", "c", "d"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
S = ", ".join(s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)
#Output : Initially
[END]
|
Python program to convert Set to String List
|
https://www.geeksforgeeks.org/convert-set-to-string-in-python/
|
from functools import reduce
# create a set
s = {"a", "b", "c", "d"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
S = reduce(lambda a, b: a + ", " + b, s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)
|
#Output : Initially
|
Python program to convert Set to String List
from functools import reduce
# create a set
s = {"a", "b", "c", "d"}
print("Initially")
print("The datatype of s : " + str(type(s)))
print("Contents of s : ", s)
# convert Set to String
S = reduce(lambda a, b: a + ", " + b, s)
print("The datatype of s : " + str(type(S)))
print("Contents of s : ", S)
#Output : Initially
[END]
|
Python program to convert String List to Set
|
https://www.geeksforgeeks.org/convert-string-to-set-in-python/
|
# create a string str
string = "geeks"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)
|
#Output :
|
Python program to convert String List to Set
# create a string str
string = "geeks"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)
#Output :
[END]
|
Python program to convert String List to Set
|
https://www.geeksforgeeks.org/convert-string-to-set-in-python/
|
# create a string str
string = "Hello World!"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)
|
#Output :
|
Python program to convert String List to Set
# create a string str
string = "Hello World!"
print("Initially")
print("The datatype of string : " + str(type(string)))
print("Contents of string : " + string)
# convert String to Set
string = set(string)
print("\nAfter the conversion")
print("The datatype of string : " + str(type(string)))
print("Contents of string : ", string)
#Output :
[END]
|
Python - Convert a set into dict
|
https://www.geeksforgeeks.org/python-convert-a-set-into-dictionary/
|
# Python code to demonstrate
# converting set into dictionary
# using fromkeys()
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print("initial string", ini_set)
print(type(ini_set))
# Converting set to dictionary
res = dict.fromkeys(ini_set, 0)
# printing final result and its type
print("final list", res)
print(type(res))
|
#Output : initial string {1, 2, 3, 4, 5}
|
Python - Convert a set into dict
# Python code to demonstrate
# converting set into dictionary
# using fromkeys()
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print("initial string", ini_set)
print(type(ini_set))
# Converting set to dictionary
res = dict.fromkeys(ini_set, 0)
# printing final result and its type
print("final list", res)
print(type(res))
#Output : initial string {1, 2, 3, 4, 5}
[END]
|
Python - Convert a set into dict
|
https://www.geeksforgeeks.org/python-convert-a-set-into-dictionary/
|
# Python code to demonstrate
# converting set into dictionary
# using dict comprehension
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print("initial string", ini_set)
print(type(ini_set))
str = "fg"
# Converting set to dict
res = {element: "Geek" + str for element in ini_set}
# printing final result and its type
print("final list", res)
print(type(res))
|
#Output : initial string {1, 2, 3, 4, 5}
|
Python - Convert a set into dict
# Python code to demonstrate
# converting set into dictionary
# using dict comprehension
# initializing set
ini_set = {1, 2, 3, 4, 5}
# printing initialized set
print("initial string", ini_set)
print(type(ini_set))
str = "fg"
# Converting set to dict
res = {element: "Geek" + str for element in ini_set}
# printing final result and its type
print("final list", res)
print(type(res))
#Output : initial string {1, 2, 3, 4, 5}
[END]
|
Python - Convert a set into dict
|
https://www.geeksforgeeks.org/python-convert-a-set-into-dictionary/
|
def set_to_dict(s):
keys = list(s)
values = [None] * len(s)
return {k: v for k, v in zip(keys, values)}
s = {1, 2, 3}
print(set_to_dict(s))
|
#Output : initial string {1, 2, 3, 4, 5}
|
Python - Convert a set into dict
def set_to_dict(s):
keys = list(s)
values = [None] * len(s)
return {k: v for k, v in zip(keys, values)}
s = {1, 2, 3}
print(set_to_dict(s))
#Output : initial string {1, 2, 3, 4, 5}
[END]
|
Python program to find union of n arrays
|
https://www.geeksforgeeks.org/set-update-python-union-n-arrays/
|
# Function to combine n arrays
def combineAll(input):
# cast first array as set and assign it
# to variable named as result
result = set(input[0])
# now traverse remaining list of arrays
# and take it's update with result variable
for array in input[1:]:
result.update(array)
return list(result)
# Driver program
if __name__ == "__main__":
input = [[1, 2, 2, 4, 3, 6], [5, 1, 3, 4], [9, 5, 7, 1], [2, 4, 1, 3]]
print(combineAll(input))
|
#Input : arr = [[1, 2, 2, 4, 3, 6],
[5, 1, 3, 4],
|
Python program to find union of n arrays
# Function to combine n arrays
def combineAll(input):
# cast first array as set and assign it
# to variable named as result
result = set(input[0])
# now traverse remaining list of arrays
# and take it's update with result variable
for array in input[1:]:
result.update(array)
return list(result)
# Driver program
if __name__ == "__main__":
input = [[1, 2, 2, 4, 3, 6], [5, 1, 3, 4], [9, 5, 7, 1], [2, 4, 1, 3]]
print(combineAll(input))
#Input : arr = [[1, 2, 2, 4, 3, 6],
[5, 1, 3, 4],
[END]
|
Python - Intersection of two lists
|
https://www.geeksforgeeks.org/python-intersection-two-lists/
|
# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
return lst3
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(lst1, lst2))
|
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
|
Python - Intersection of two lists
# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
lst3 = [value for value in lst1 if value in lst2]
return lst3
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(lst1, lst2))
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
[END]
|
Python - Intersection of two lists
|
https://www.geeksforgeeks.org/python-intersection-two-lists/
|
# Python program to illustrate the intersection
# of two lists using set() method
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
# Driver Code
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
print(intersection(lst1, lst2))
|
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
|
Python - Intersection of two lists
# Python program to illustrate the intersection
# of two lists using set() method
def intersection(lst1, lst2):
return list(set(lst1) & set(lst2))
# Driver Code
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
print(intersection(lst1, lst2))
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
[END]
|
Python - Intersection of two lists
|
https://www.geeksforgeeks.org/python-intersection-two-lists/
|
# Python program to illustrate the intersection
# of two lists using set() and intersection()
def Intersection(lst1, lst2):
return set(lst1).intersection(lst2)
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
lst2 = [9, 9, 74, 21, 45, 11, 63]
print(Intersection(lst1, lst2))
|
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
|
Python - Intersection of two lists
# Python program to illustrate the intersection
# of two lists using set() and intersection()
def Intersection(lst1, lst2):
return set(lst1).intersection(lst2)
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
lst2 = [9, 9, 74, 21, 45, 11, 63]
print(Intersection(lst1, lst2))
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
[END]
|
Python - Intersection of two lists
|
https://www.geeksforgeeks.org/python-intersection-two-lists/
|
# Python program to illustrate the intersection
# of two lists
def intersection(lst1, lst2):
# Use of hybrid method
temp = set(lst2)
lst3 = [value for value in lst1 if value in temp]
return lst3
# Driver Code
lst1 = [9, 9, 74, 21, 45, 11, 63]
lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
print(intersection(lst1, lst2))
|
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
|
Python - Intersection of two lists
# Python program to illustrate the intersection
# of two lists
def intersection(lst1, lst2):
# Use of hybrid method
temp = set(lst2)
lst3 = [value for value in lst1 if value in temp]
return lst3
# Driver Code
lst1 = [9, 9, 74, 21, 45, 11, 63]
lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
print(intersection(lst1, lst2))
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
[END]
|
Python - Intersection of two lists
|
https://www.geeksforgeeks.org/python-intersection-two-lists/
|
# Python program to illustrate the intersection
# of two lists, sublists and use of filter()
def intersection(lst1, lst2):
lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2]
return lst3
# Driver Code
lst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
print(intersection(lst1, lst2))
|
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
|
Python - Intersection of two lists
# Python program to illustrate the intersection
# of two lists, sublists and use of filter()
def intersection(lst1, lst2):
lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2]
return lst3
# Driver Code
lst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
print(intersection(lst1, lst2))
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
[END]
|
Python - Intersection of two lists
|
https://www.geeksforgeeks.org/python-intersection-two-lists/
|
from functools import reduce
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
intersection = reduce(
lambda acc, x: acc + [x] if x in lst2 and x not in acc else acc, lst1, []
)
print(intersection)
# This code is contributed by Rayudu.
|
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
|
Python - Intersection of two lists
from functools import reduce
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
intersection = reduce(
lambda acc, x: acc + [x] if x in lst2 and x not in acc else acc, lst1, []
)
print(intersection)
# This code is contributed by Rayudu.
#Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
[END]
|
Python program to get all subsets of given size of a set
|
https://www.geeksforgeeks.org/python-program-to-get-all-subsets-of-given-size-of-a-set/
|
# Python Program to Print
# all subsets of given size of a set
import itertools
def findsubsets(s, n):
return list(itertools.combinations(s, n))
# Driver Code
s = {1, 2, 3}
n = 2
print(findsubsets(s, n))
|
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
|
Python program to get all subsets of given size of a set
# Python Program to Print
# all subsets of given size of a set
import itertools
def findsubsets(s, n):
return list(itertools.combinations(s, n))
# Driver Code
s = {1, 2, 3}
n = 2
print(findsubsets(s, n))
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
[END]
|
Python program to get all subsets of given size of a set
|
https://www.geeksforgeeks.org/python-program-to-get-all-subsets-of-given-size-of-a-set/
|
# Python Program to Print
# all subsets of given size of a set
import itertools
from itertools import combinations, chain
def findsubsets(s, n):
return list(map(set, itertools.combinations(s, n)))
# Driver Code
s = {1, 2, 3}
n = 2
print(findsubsets(s, n))
|
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
|
Python program to get all subsets of given size of a set
# Python Program to Print
# all subsets of given size of a set
import itertools
from itertools import combinations, chain
def findsubsets(s, n):
return list(map(set, itertools.combinations(s, n)))
# Driver Code
s = {1, 2, 3}
n = 2
print(findsubsets(s, n))
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
[END]
|
Python program to get all subsets of given size of a set
|
https://www.geeksforgeeks.org/python-program-to-get-all-subsets-of-given-size-of-a-set/
|
# Python Program to Print
# all subsets of given size of a set
import itertools
# def findsubsets(s, n):
def findsubsets(s, n):
return [set(i) for i in itertools.combinations(s, n)]
# Driver Code
s = {1, 2, 3, 4}
n = 3
print(findsubsets(s, n))
|
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
|
Python program to get all subsets of given size of a set
# Python Program to Print
# all subsets of given size of a set
import itertools
# def findsubsets(s, n):
def findsubsets(s, n):
return [set(i) for i in itertools.combinations(s, n)]
# Driver Code
s = {1, 2, 3, 4}
n = 3
print(findsubsets(s, n))
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
[END]
|
Python program to get all subsets of given size of a set
|
https://www.geeksforgeeks.org/python-program-to-get-all-subsets-of-given-size-of-a-set/
|
def subsets(numbers):
if numbers == []:
return [[]]
x = subsets(numbers[1:])
return x + [[numbers[0]] + y for y in x]
# wrapper function
def subsets_of_given_size(numbers, n):
return [x for x in subsets(numbers) if len(x) == n]
if __name__ == "__main__":
numbers = [1, 2, 3, 4]
n = 3
print(subsets_of_given_size(numbers, n))
|
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
|
Python program to get all subsets of given size of a set
def subsets(numbers):
if numbers == []:
return [[]]
x = subsets(numbers[1:])
return x + [[numbers[0]] + y for y in x]
# wrapper function
def subsets_of_given_size(numbers, n):
return [x for x in subsets(numbers) if len(x) == n]
if __name__ == "__main__":
numbers = [1, 2, 3, 4]
n = 3
print(subsets_of_given_size(numbers, n))
#Input : {1, 2, 3}, n = 2
#Output : [{1, 2}, {1, 3}, {2, 3}]
[END]
|
Python - Minimum number of subsets with distinct elements using Counter
|
https://www.geeksforgeeks.org/python-minimum-number-subsets-distinct-elements-using-counter/
|
# Python program to find Minimum number of
# subsets with distinct elements using Counter
# function to find Minimum number of subsets
# with distinct elements
from collections import Counter
def minSubsets(input):
# calculate frequency of each element
freqDict = Counter(input)
# get list of all frequency values
# print maximum from it
print(max(freqDict.values()))
# Driver program
if __name__ == "__main__":
input = [1, 2, 3, 3]
minSubsets(input)
|
#Input : arr[] = {1, 2, 3, 4}
#Output : 1
|
Python - Minimum number of subsets with distinct elements using Counter
# Python program to find Minimum number of
# subsets with distinct elements using Counter
# function to find Minimum number of subsets
# with distinct elements
from collections import Counter
def minSubsets(input):
# calculate frequency of each element
freqDict = Counter(input)
# get list of all frequency values
# print maximum from it
print(max(freqDict.values()))
# Driver program
if __name__ == "__main__":
input = [1, 2, 3, 3]
minSubsets(input)
#Input : arr[] = {1, 2, 3, 4}
#Output : 1
[END]
|
Python - Minimum number of subsets with distinct elements using Counter
|
https://www.geeksforgeeks.org/python-minimum-number-subsets-distinct-elements-using-counter/
|
from collections import Counter
from itertools import combinations
def count_min_subsets(arr):
freq = Counter(arr)
num_distinct = len(set(arr))
if num_distinct == len(arr):
return 1
else:
for i in range(1, num_distinct + 1):
for subset in combinations(freq.keys(), i):
if len(set(subset)) == i:
if sum([freq[k] for k in subset]) >= i:
return i + 1
arr = [1, 2, 3, 4]
print(count_min_subsets(arr))
|
#Input : arr[] = {1, 2, 3, 4}
#Output : 1
|
Python - Minimum number of subsets with distinct elements using Counter
from collections import Counter
from itertools import combinations
def count_min_subsets(arr):
freq = Counter(arr)
num_distinct = len(set(arr))
if num_distinct == len(arr):
return 1
else:
for i in range(1, num_distinct + 1):
for subset in combinations(freq.keys(), i):
if len(set(subset)) == i:
if sum([freq[k] for k in subset]) >= i:
return i + 1
arr = [1, 2, 3, 4]
print(count_min_subsets(arr))
#Input : arr[] = {1, 2, 3, 4}
#Output : 1
[END]
|
Python dictionary, set and counter to check if frequencies can become same
|
https://www.geeksforgeeks.org/python-dictionary-set-counter-check-frequencies-can-become/
|
# Function to Check if frequency of all characters
# can become same by one removal
from collections import Counter
def allSame(input):
# calculate frequency of each character
# and convert string into dictionary
dict = Counter(input)
# now get list of all values and push it
# in set
same = list(set(dict.values()))
if len(same) > 2:
print("No")
elif len(same) == 2 and same[1] - same[0] > 1:
print("No")
else:
print("Yes")
# now check if frequency of all characters
# can become same
# Driver program
if __name__ == "__main__":
input = "xxxyyzzt"
allSame(input)
|
Input : str = ?????????xyyz
|
Python dictionary, set and counter to check if frequencies can become same
# Function to Check if frequency of all characters
# can become same by one removal
from collections import Counter
def allSame(input):
# calculate frequency of each character
# and convert string into dictionary
dict = Counter(input)
# now get list of all values and push it
# in set
same = list(set(dict.values()))
if len(same) > 2:
print("No")
elif len(same) == 2 and same[1] - same[0] > 1:
print("No")
else:
print("Yes")
# now check if frequency of all characters
# can become same
# Driver program
if __name__ == "__main__":
input = "xxxyyzzt"
allSame(input)
Input : str = ?????????xyyz
[END]
|
Python splitfields() Method
|
https://www.geeksforgeeks.org/python-splitfields-method/
|
# Example of a TypeError when calling splitfields()
num = 123
fields = num.splitfields(",")
|
#Output : Traceback (most recent call last):
|
Python splitfields() Method
# Example of a TypeError when calling splitfields()
num = 123
fields = num.splitfields(",")
#Output : Traceback (most recent call last):
[END]
|
Python splitfields() Method
|
https://www.geeksforgeeks.org/python-splitfields-method/
|
class MyString(str):
def splitfields(self, sep=None):
if sep is None:
return self.split()
else:
return self.split(sep)
# Splitting a string into fields using whitespace as delimiter
str1 = "The quick brown fox"
fields1 = MyString(str1).splitfields()
print(fields1)
# Splitting a string into fields using a specific delimiter
str2 = "apple,banana,orange"
fields2 = MyString(str2).splitfields(",")
print(fields2)
|
#Output : Traceback (most recent call last):
|
Python splitfields() Method
class MyString(str):
def splitfields(self, sep=None):
if sep is None:
return self.split()
else:
return self.split(sep)
# Splitting a string into fields using whitespace as delimiter
str1 = "The quick brown fox"
fields1 = MyString(str1).splitfields()
print(fields1)
# Splitting a string into fields using a specific delimiter
str2 = "apple,banana,orange"
fields2 = MyString(str2).splitfields(",")
print(fields2)
#Output : Traceback (most recent call last):
[END]
|
Python splitfields() Method
|
https://www.geeksforgeeks.org/python-splitfields-method/
|
class MyString(str):
def splitfields(self, sep=None):
if sep is None:
return self.split()
else:
return self.split(sep)
# Splitting a list into fields using whitespace as delimiter
lst1 = ["The", "quick", "brown", "fox"]
fields3 = MyString(" ".join(lst1)).splitfields()
print(fields3)
# Splitting a list into fields using a specific delimiter
lst2 = ["apple", "banana", "orange"]
fields4 = MyString(",".join(lst2)).splitfields(",")
print(fields4)
|
#Output : Traceback (most recent call last):
|
Python splitfields() Method
class MyString(str):
def splitfields(self, sep=None):
if sep is None:
return self.split()
else:
return self.split(sep)
# Splitting a list into fields using whitespace as delimiter
lst1 = ["The", "quick", "brown", "fox"]
fields3 = MyString(" ".join(lst1)).splitfields()
print(fields3)
# Splitting a list into fields using a specific delimiter
lst2 = ["apple", "banana", "orange"]
fields4 = MyString(",".join(lst2)).splitfields(",")
print(fields4)
#Output : Traceback (most recent call last):
[END]
|
Python splitfields() Method
|
https://www.geeksforgeeks.org/python-splitfields-method/
|
class MyString(str):
def splitfields(self, sep=None):
if sep is None:
return self.split()
else:
return self.split(sep)
class MySet(set):
def splitfields(self, sep=None):
str_set = " ".join(self)
return MyString(str_set).splitfields(sep)
# Splitting a set into fields using whitespace as delimiter
set1 = {"The", "quick", "brown", "fox"}
fields5 = MySet(set1).splitfields()
print(fields5)
# Splitting a set into fields using a specific delimiter
set2 = {"apple", "banana", "orange"}
fields6 = MySet(set2).splitfields(",")
print(fields6)
|
#Output : Traceback (most recent call last):
|
Python splitfields() Method
class MyString(str):
def splitfields(self, sep=None):
if sep is None:
return self.split()
else:
return self.split(sep)
class MySet(set):
def splitfields(self, sep=None):
str_set = " ".join(self)
return MyString(str_set).splitfields(sep)
# Splitting a set into fields using whitespace as delimiter
set1 = {"The", "quick", "brown", "fox"}
fields5 = MySet(set1).splitfields()
print(fields5)
# Splitting a set into fields using a specific delimiter
set2 = {"apple", "banana", "orange"}
fields6 = MySet(set2).splitfields(",")
print(fields6)
#Output : Traceback (most recent call last):
[END]
|
Python - Lambda Function to Check if value is in a List
|
https://www.geeksforgeeks.org/python-lambda-function-to-check-if-value-is-in-a-list/
|
arr = [1, 2, 3, 4]
v = 3
def x(arr, v):
return arr.count(v)
if x(arr, v):
print("Element is Present in the list")
else:
print("Element is Not Present in the list")
|
Input : L = [1, 2, 3, 4, 5]
element = 4
|
Python - Lambda Function to Check if value is in a List
arr = [1, 2, 3, 4]
v = 3
def x(arr, v):
return arr.count(v)
if x(arr, v):
print("Element is Present in the list")
else:
print("Element is Not Present in the list")
Input : L = [1, 2, 3, 4, 5]
element = 4
[END]
|
Python - Lambda Function to Check if value is in a List
|
https://www.geeksforgeeks.org/python-lambda-function-to-check-if-value-is-in-a-list/
|
arr = [1, 2, 3, 4]
v = 8
x = lambda arr, v: True if v in arr else False
if x(arr, v):
print("Element is Present in the list")
else:
print("Element is Not Present in the list")
|
Input : L = [1, 2, 3, 4, 5]
element = 4
|
Python - Lambda Function to Check if value is in a List
arr = [1, 2, 3, 4]
v = 8
x = lambda arr, v: True if v in arr else False
if x(arr, v):
print("Element is Present in the list")
else:
print("Element is Not Present in the list")
Input : L = [1, 2, 3, 4, 5]
element = 4
[END]
|
Simple Diamond Pattern in Python
|
https://www.geeksforgeeks.org/simple-diamond-pattern-in-python/
|
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 8
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size // 2 + 2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print *
if j < i - 1:
print(" ", end=" ")
elif j > spaces:
print(" ", end=" ")
elif (i == 0 and j == 0) | (i == 0 and j == size - 1):
print(" ", end=" ")
else:
print("*", end=" ")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print()
|
#Output : For size = 5
|
Simple Diamond Pattern in Python
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 8
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size // 2 + 2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print *
if j < i - 1:
print(" ", end=" ")
elif j > spaces:
print(" ", end=" ")
elif (i == 0 and j == 0) | (i == 0 and j == size - 1):
print(" ", end=" ")
else:
print("*", end=" ")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print()
#Output : For size = 5
[END]
|
Simple Diamond Pattern in Python
|
https://www.geeksforgeeks.org/simple-diamond-pattern-in-python/
|
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 11
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size // 2 + 2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print ^
if j < i - 1:
print(" ", end=" ")
elif j > spaces:
print(" ", end=" ")
elif (i == 0 and j == 0) | (i == 0 and j == size - 1):
print(" ", end=" ")
else:
print("*", end=" ")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print()
|
#Output : For size = 5
|
Simple Diamond Pattern in Python
# define the size (no. of columns)
# must be odd to draw proper diamond shape
size = 11
# initialize the spaces
spaces = size
# loops for iterations to create worksheet
for i in range(size // 2 + 2):
for j in range(size):
# condition to left space
# condition to right space
# condition for making diamond
# else print ^
if j < i - 1:
print(" ", end=" ")
elif j > spaces:
print(" ", end=" ")
elif (i == 0 and j == 0) | (i == 0 and j == size - 1):
print(" ", end=" ")
else:
print("*", end=" ")
# increase space area by decreasing spaces
spaces -= 1
# for line change
print()
#Output : For size = 5
[END]
|
Python - Iterating through a range of dates
|
https://www.geeksforgeeks.org/python-iterating-through-a-range-of-dates/
|
# import datetime module
import datetime
# consider the start date as 2021-february 1 st
start_date = datetime.date(2021, 2, 1)
# consider the end date as 2021-march 1 st
end_date = datetime.date(2021, 3, 1)
# delta time
delta = datetime.timedelta(days=1)
# iterate over range of dates
while start_date <= end_date:
print(start_date, end="\n")
start_date += delta
|
#Output : 2021-02-01
|
Python - Iterating through a range of dates
# import datetime module
import datetime
# consider the start date as 2021-february 1 st
start_date = datetime.date(2021, 2, 1)
# consider the end date as 2021-march 1 st
end_date = datetime.date(2021, 3, 1)
# delta time
delta = datetime.timedelta(days=1)
# iterate over range of dates
while start_date <= end_date:
print(start_date, end="\n")
start_date += delta
#Output : 2021-02-01
[END]
|
Python - Iterating through a range of dates
|
https://www.geeksforgeeks.org/python-iterating-through-a-range-of-dates/
|
# importing the required lib
from datetime import date
from dateutil.rrule import rrule, DAILY
# initializing the start and end date
start_date = date(2022, 9, 1)
end_date = date(2022, 9, 11)
# iterating over the dates
for d in rrule(DAILY, dtstart=start_date, until=end_date):
print(d.strftime("%Y-%m-%d"))
|
#Output : 2021-02-01
|
Python - Iterating through a range of dates
# importing the required lib
from datetime import date
from dateutil.rrule import rrule, DAILY
# initializing the start and end date
start_date = date(2022, 9, 1)
end_date = date(2022, 9, 11)
# iterating over the dates
for d in rrule(DAILY, dtstart=start_date, until=end_date):
print(d.strftime("%Y-%m-%d"))
#Output : 2021-02-01
[END]
|
Python - Iterating through a range of dates
|
https://www.geeksforgeeks.org/python-iterating-through-a-range-of-dates/
|
# import pandas module
import pandas as pd
# specify the start date is 2021 jan 1 st
# specify the end date is 2021 feb 1 st
a = pd.date_range(start="1/1/2021", end="2/1/2021")
# display only date using date() function
for i in a:
print(i.date())
|
#Output : 2021-02-01
|
Python - Iterating through a range of dates
# import pandas module
import pandas as pd
# specify the start date is 2021 jan 1 st
# specify the end date is 2021 feb 1 st
a = pd.date_range(start="1/1/2021", end="2/1/2021")
# display only date using date() function
for i in a:
print(i.date())
#Output : 2021-02-01
[END]
|
Python - Get index in the list of objects by attribute in Python
|
https://www.geeksforgeeks.org/get-index-in-the-list-of-objects-by-attribute-in-python/
|
# This code gets the index in the
# list of objects by attribute.
class X:
def __init__(self, val):
self.val = val
def getIndex(li, target):
for index, x in enumerate(li):
if x.val == target:
return index
return -1
# Driver code
li = [1, 2, 3, 4, 5, 6]
# Converting all the items in
# list to object of class X
a = list()
for i in li:
a.append(X(i))
print(getIndex(a, 3))
|
#Output : 2
|
Python - Get index in the list of objects by attribute in Python
# This code gets the index in the
# list of objects by attribute.
class X:
def __init__(self, val):
self.val = val
def getIndex(li, target):
for index, x in enumerate(li):
if x.val == target:
return index
return -1
# Driver code
li = [1, 2, 3, 4, 5, 6]
# Converting all the items in
# list to object of class X
a = list()
for i in li:
a.append(X(i))
print(getIndex(a, 3))
#Output : 2
[END]
|
Python - Validate an IP address using Python without using RegEx
|
https://www.geeksforgeeks.org/validate-an-ip-address-using-python-without-using-regex/
|
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# check number of periods
if s.count(".") != 3:
return "Invalid Ip address"
l = list(map(str, s.split(".")))
# check range of each number between periods
for ele in l:
if int(ele) < 0 or int(ele) > 255 or (ele[0] == "0" and len(ele) != 1):
return "Invalid Ip address"
return "Valid Ip address"
# Driver Code
print(isValidIP("666.1.2.2"))
|
#Output : Invalid Ip address
|
Python - Validate an IP address using Python without using RegEx
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# check number of periods
if s.count(".") != 3:
return "Invalid Ip address"
l = list(map(str, s.split(".")))
# check range of each number between periods
for ele in l:
if int(ele) < 0 or int(ele) > 255 or (ele[0] == "0" and len(ele) != 1):
return "Invalid Ip address"
return "Valid Ip address"
# Driver Code
print(isValidIP("666.1.2.2"))
#Output : Invalid Ip address
[END]
|
Python - Validate an IP address using Python without using RegEx
|
https://www.geeksforgeeks.org/validate-an-ip-address-using-python-without-using-regex/
|
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# initialize counter
counter = 0
# check if period is present
for i in range(0, len(s)):
if s[i] == ".":
counter = counter + 1
if counter != 3:
return 0
# check the range of numbers between periods
st = set()
for i in range(0, 256):
st.add(str(i))
counter = 0
temp = ""
for i in range(0, len(s)):
if s[i] != ".":
temp = temp + s[i]
else:
if temp in st:
counter = counter + 1
temp = ""
if temp in st:
counter = counter + 1
# verifying all conditions
if counter == 4:
return "Valid Ip address"
else:
return "Invalid Ip address"
# Driver Code
print(isValidIP("110.234.52.124"))
|
#Output : Invalid Ip address
|
Python - Validate an IP address using Python without using RegEx
# Python program to verify IP without using RegEx
# explicit function to verify IP
def isValidIP(s):
# initialize counter
counter = 0
# check if period is present
for i in range(0, len(s)):
if s[i] == ".":
counter = counter + 1
if counter != 3:
return 0
# check the range of numbers between periods
st = set()
for i in range(0, 256):
st.add(str(i))
counter = 0
temp = ""
for i in range(0, len(s)):
if s[i] != ".":
temp = temp + s[i]
else:
if temp in st:
counter = counter + 1
temp = ""
if temp in st:
counter = counter + 1
# verifying all conditions
if counter == 4:
return "Valid Ip address"
else:
return "Invalid Ip address"
# Driver Code
print(isValidIP("110.234.52.124"))
#Output : Invalid Ip address
[END]
|
Python program to Search an Element in a Circular Linked List
|
https://www.geeksforgeeks.org/python-program-to-search-an-element-in-a-circular-linked-list/
|
# Python program to Search an Element
# in a Circular Linked List
# Class to define node of the linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
# Declaring Circular Linked List
def __init__(self):
self.head = Node(None)
self.tail = Node(None)
self.head.next = self.tail
self.tail.next = self.head
# Adds new nodes to the Circular Linked List
def add(self, data):
# Declares a new node to be added
newNode = Node(data)
# Checks if the Circular
# Linked List is empty
if self.head.data is None:
# If list is empty then new node
# will be the first node
# to be added in the Circular Linked List
self.head = newNode
self.tail = newNode
newNode.next = self.head
else:
# If a node is already present then
# tail of the last node will point to
# new node
self.tail.next = newNode
# New node will become new tail
self.tail = newNode
# New Tail will point to the head
self.tail.next = self.head
# Function to search the element in the
# Circular Linked List
def findNode(self, element):
# Pointing the head to start the search
current = self.head
i = 1
# Declaring f = 0
f = 0
# Check if the list is empty or not
if self.head == None:
print("Empty list")
else:
while True:
# Comparing the elements
# of each node to the
# element to be searched
if current.data == element:
# If the element is present
# then incrementing f
f += 1
break
# Jumping to next node
current = current.next
i = i + 1
# If we reach the head
# again then element is not
# present in the list so
# we will break the loop
if current == self.head:
break
# Checking the value of f
if f > 0:
print("element is present")
else:
print("element is not present")
# Driver Code
if __name__ == "__main__":
# Creating a Circular Linked List
"""
Circular Linked List we will be working on:
1 -> 2 -> 3 -> 4 -> 5 -> 6
"""
circularLinkedList = CircularLinkedList()
# Adding nodes to the list
circularLinkedList.add(1)
circularLinkedList.add(2)
circularLinkedList.add(3)
circularLinkedList.add(4)
circularLinkedList.add(5)
circularLinkedList.add(6)
# Searching for node 2 in the list
circularLinkedList.findNode(2)
# Searching for node in the list
circularLinkedList.findNode(7)
|
Input: CList = 6->5->4->3->2, find = 3
Output: Element is present
|
Python program to Search an Element in a Circular Linked List
# Python program to Search an Element
# in a Circular Linked List
# Class to define node of the linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
class CircularLinkedList:
# Declaring Circular Linked List
def __init__(self):
self.head = Node(None)
self.tail = Node(None)
self.head.next = self.tail
self.tail.next = self.head
# Adds new nodes to the Circular Linked List
def add(self, data):
# Declares a new node to be added
newNode = Node(data)
# Checks if the Circular
# Linked List is empty
if self.head.data is None:
# If list is empty then new node
# will be the first node
# to be added in the Circular Linked List
self.head = newNode
self.tail = newNode
newNode.next = self.head
else:
# If a node is already present then
# tail of the last node will point to
# new node
self.tail.next = newNode
# New node will become new tail
self.tail = newNode
# New Tail will point to the head
self.tail.next = self.head
# Function to search the element in the
# Circular Linked List
def findNode(self, element):
# Pointing the head to start the search
current = self.head
i = 1
# Declaring f = 0
f = 0
# Check if the list is empty or not
if self.head == None:
print("Empty list")
else:
while True:
# Comparing the elements
# of each node to the
# element to be searched
if current.data == element:
# If the element is present
# then incrementing f
f += 1
break
# Jumping to next node
current = current.next
i = i + 1
# If we reach the head
# again then element is not
# present in the list so
# we will break the loop
if current == self.head:
break
# Checking the value of f
if f > 0:
print("element is present")
else:
print("element is not present")
# Driver Code
if __name__ == "__main__":
# Creating a Circular Linked List
"""
Circular Linked List we will be working on:
1 -> 2 -> 3 -> 4 -> 5 -> 6
"""
circularLinkedList = CircularLinkedList()
# Adding nodes to the list
circularLinkedList.add(1)
circularLinkedList.add(2)
circularLinkedList.add(3)
circularLinkedList.add(4)
circularLinkedList.add(5)
circularLinkedList.add(6)
# Searching for node 2 in the list
circularLinkedList.findNode(2)
# Searching for node in the list
circularLinkedList.findNode(7)
Input: CList = 6->5->4->3->2, find = 3
Output: Element is present
[END]
|
Binary Search (bisect) in Python
|
https://www.geeksforgeeks.org/binary-search-bisect-in-python/
|
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
a = [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
print(x, "is absent")
else:
print("First occurrence of", x, "is present at", res)
|
#Output : First occurrence of 4 is present at 2
|
Binary Search (bisect) in Python
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
else:
return -1
a = [1, 2, 4, 4, 8]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
print(x, "is absent")
else:
print("First occurrence of", x, "is present at", res)
#Output : First occurrence of 4 is present at 2
[END]
|
Binary Search (bisect) in Python
|
https://www.geeksforgeeks.org/binary-search-bisect-in-python/
|
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i:
return i - 1
else:
return -1
# Driver code
a = [1, 2, 4, 4, 8]
x = int(7)
res = BinarySearch(a, x)
if res == -1:
print("No value smaller than ", x)
else:
print("Largest value smaller than ", x, " is at index ", res)
|
#Output : First occurrence of 4 is present at 2
|
Binary Search (bisect) in Python
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_left
def BinarySearch(a, x):
i = bisect_left(a, x)
if i:
return i - 1
else:
return -1
# Driver code
a = [1, 2, 4, 4, 8]
x = int(7)
res = BinarySearch(a, x)
if res == -1:
print("No value smaller than ", x)
else:
print("Largest value smaller than ", x, " is at index ", res)
#Output : First occurrence of 4 is present at 2
[END]
|
Binary Search (bisect) in Python
|
https://www.geeksforgeeks.org/binary-search-bisect-in-python/
|
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_right
def BinarySearch(a, x):
i = bisect_right(a, x)
if i != 0 and a[i - 1] == x:
return i - 1
else:
return -1
a = [1, 2, 4, 4]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
print(x, "is absent")
else:
print("Last occurrence of", x, "is present at", res)
|
#Output : First occurrence of 4 is present at 2
|
Binary Search (bisect) in Python
# Python code to demonstrate working
# of binary search in library
from bisect import bisect_right
def BinarySearch(a, x):
i = bisect_right(a, x)
if i != 0 and a[i - 1] == x:
return i - 1
else:
return -1
a = [1, 2, 4, 4]
x = int(4)
res = BinarySearch(a, x)
if res == -1:
print(x, "is absent")
else:
print("Last occurrence of", x, "is present at", res)
#Output : First occurrence of 4 is present at 2
[END]
|
Python Code for time Complexity plot of Heap Sort
|
https://www.geeksforgeeks.org/python-code-for-time-complexity-plot-of-heap-sort/
|
# Python Code for Implementation and running time Algorithm
# Complexity plot of Heap Sort
# by Ashok Kajal
# This python code intends to implement Heap Sort Algorithm
# Plots its time Complexity on list of different sizes
# ---------------------Important Note -------------------
# numpy, time and matplotlib.pyplot are required to run this code
import time
from numpy.random import seed
from numpy.random import randint
import matplotlib.pyplot as plt
# find left child of node i
def left(i):
return 2 * i + 1
# find right child of node i
def right(i):
return 2 * i + 2
# calculate and return array size
def heapSize(A):
return len(A) - 1
# This function takes an array and Heapyfies
# the at node i
def MaxHeapify(A, i):
# print("in heapy", i)
l = left(i)
r = right(i)
# heapSize = len(A)
# print("left", l, "Rightt", r, "Size", heapSize)
if l <= heapSize(A) and A[l] > A[i]:
largest = l
else:
largest = i
if r <= heapSize(A) and A[r] > A[largest]:
largest = r
if largest != i:
# print("Largest", largest)
A[i], A[largest] = A[largest], A[i]
# print("List", A)
MaxHeapify(A, largest)
# this function makes a heapified array
def BuildMaxHeap(A):
for i in range(int(heapSize(A) / 2) - 1, -1, -1):
MaxHeapify(A, i)
# Sorting is done using heap of array
def HeapSort(A):
BuildMaxHeap(A)
B = list()
heapSize1 = heapSize(A)
for i in range(heapSize(A), 0, -1):
A[0], A[i] = A[i], A[0]
B.append(A[heapSize1])
A = A[:-1]
heapSize1 = heapSize1 - 1
MaxHeapify(A, 0)
# randomly generates list of different
# sizes and call HeapSort function
elements = list()
times = list()
for i in range(1, 10):
# generate some integers
a = randint(0, 1000 * i, 1000 * i)
# print(i)
start = time.clock()
HeapSort(a)
end = time.clock()
# print("Sorted list is ", a)
print(len(a), "Elements Sorted by HeapSort in ", end - start)
elements.append(len(a))
times.append(end - start)
plt.xlabel("List Length")
plt.ylabel("Time Complexity")
plt.plot(elements, times, label="Heap Sort")
plt.grid()
plt.legend()
plt.show()
# This code is contributed by Ashok Kajal
|
#Input : Unsorted Lists of Different sizes are Generated Randomly
#Output :
|
Python Code for time Complexity plot of Heap Sort
# Python Code for Implementation and running time Algorithm
# Complexity plot of Heap Sort
# by Ashok Kajal
# This python code intends to implement Heap Sort Algorithm
# Plots its time Complexity on list of different sizes
# ---------------------Important Note -------------------
# numpy, time and matplotlib.pyplot are required to run this code
import time
from numpy.random import seed
from numpy.random import randint
import matplotlib.pyplot as plt
# find left child of node i
def left(i):
return 2 * i + 1
# find right child of node i
def right(i):
return 2 * i + 2
# calculate and return array size
def heapSize(A):
return len(A) - 1
# This function takes an array and Heapyfies
# the at node i
def MaxHeapify(A, i):
# print("in heapy", i)
l = left(i)
r = right(i)
# heapSize = len(A)
# print("left", l, "Rightt", r, "Size", heapSize)
if l <= heapSize(A) and A[l] > A[i]:
largest = l
else:
largest = i
if r <= heapSize(A) and A[r] > A[largest]:
largest = r
if largest != i:
# print("Largest", largest)
A[i], A[largest] = A[largest], A[i]
# print("List", A)
MaxHeapify(A, largest)
# this function makes a heapified array
def BuildMaxHeap(A):
for i in range(int(heapSize(A) / 2) - 1, -1, -1):
MaxHeapify(A, i)
# Sorting is done using heap of array
def HeapSort(A):
BuildMaxHeap(A)
B = list()
heapSize1 = heapSize(A)
for i in range(heapSize(A), 0, -1):
A[0], A[i] = A[i], A[0]
B.append(A[heapSize1])
A = A[:-1]
heapSize1 = heapSize1 - 1
MaxHeapify(A, 0)
# randomly generates list of different
# sizes and call HeapSort function
elements = list()
times = list()
for i in range(1, 10):
# generate some integers
a = randint(0, 1000 * i, 1000 * i)
# print(i)
start = time.clock()
HeapSort(a)
end = time.clock()
# print("Sorted list is ", a)
print(len(a), "Elements Sorted by HeapSort in ", end - start)
elements.append(len(a))
times.append(end - start)
plt.xlabel("List Length")
plt.ylabel("Time Complexity")
plt.plot(elements, times, label="Heap Sort")
plt.grid()
plt.legend()
plt.show()
# This code is contributed by Ashok Kajal
#Input : Unsorted Lists of Different sizes are Generated Randomly
#Output :
[END]
|
Take input from user and store in .txt file in Python
|
https://www.geeksforgeeks.org/take-input-from-user-and-store-in-txt-file-in-python/
|
temp = input("Please enter your information!! ")
try:
with open("gfg.txt", "w") as gfg:
gfg.write(temp)
except Exception as e:
print("There is a Problem", str(e))
|
#Output : # this means the file will open
|
Take input from user and store in .txt file in Python
temp = input("Please enter your information!! ")
try:
with open("gfg.txt", "w") as gfg:
gfg.write(temp)
except Exception as e:
print("There is a Problem", str(e))
#Output : # this means the file will open
[END]
|
Take input from user and store in .txt file in Python
|
https://www.geeksforgeeks.org/take-input-from-user-and-store-in-txt-file-in-python/
|
temp = input("Please enter your information!! ")
try:
with open("gfg.txt", "w") as gfg:
gfg.write(temp)
except Exception as e:
print("There is a Problem", str(e))
|
#Output : # this means the file will open
|
Take input from user and store in .txt file in Python
temp = input("Please enter your information!! ")
try:
with open("gfg.txt", "w") as gfg:
gfg.write(temp)
except Exception as e:
print("There is a Problem", str(e))
#Output : # this means the file will open
[END]
|
Python program to extract a single value from JSON response
|
https://www.geeksforgeeks.org/python-program-to-extract-a-single-value-from-json-response/
|
# importing required module
import urllib.parse
import requests
# setting the base URL value
baseUrl = "https://v6.exchangerate-api.com/v6/0f215802f0c83392e64ee40d/pair/"
First = input("Enter First Currency Value")
Second = input("Enter Second Currency Value")
result = First + "/" + Second
final_url = baseUrl + result
# retrieving data from JSON Data
json_data = requests.get(final_url).json()
Final_result = json_data["conversion_rate"]
print("Conversion rate from " + First + " to " + Second + " = ", Final_result)
|
#Output : # install jsonpath-ng library
|
Python program to extract a single value from JSON response
# importing required module
import urllib.parse
import requests
# setting the base URL value
baseUrl = "https://v6.exchangerate-api.com/v6/0f215802f0c83392e64ee40d/pair/"
First = input("Enter First Currency Value")
Second = input("Enter Second Currency Value")
result = First + "/" + Second
final_url = baseUrl + result
# retrieving data from JSON Data
json_data = requests.get(final_url).json()
Final_result = json_data["conversion_rate"]
print("Conversion rate from " + First + " to " + Second + " = ", Final_result)
#Output : # install jsonpath-ng library
[END]
|
Python program to extract a single value from JSON response
|
https://www.geeksforgeeks.org/python-program-to-extract-a-single-value-from-json-response/
|
# import required libraries
import urllib.parse
import requests
from jsonpath_ng import jsonpath, parse
# setting the base URL value
baseUrl = "https://v6.exchangerate-api.com/v6/0f215802f0c83392e64ee40d/pair/"
# ask user to enter currency values
First = input("Enter First Currency Value: ")
Second = input("Enter Second Currency Value: ")
# combine base URL with final URL including both currencies
result = First + "/" + Second
final_url = baseUrl + result
# send API call and retrieve JSON data
json_data = requests.get(final_url).json()
# set up jsonpath expression to select conversion rate
jsonpath_expr = parse("$.conversion_rate")
# use jsonpath expression to extract conversion rate
result = jsonpath_expr.find(json_data)[0].value
print("Conversion rate from " + First + " to " + Second + " = ", result)
|
#Output : # install jsonpath-ng library
|
Python program to extract a single value from JSON response
# import required libraries
import urllib.parse
import requests
from jsonpath_ng import jsonpath, parse
# setting the base URL value
baseUrl = "https://v6.exchangerate-api.com/v6/0f215802f0c83392e64ee40d/pair/"
# ask user to enter currency values
First = input("Enter First Currency Value: ")
Second = input("Enter Second Currency Value: ")
# combine base URL with final URL including both currencies
result = First + "/" + Second
final_url = baseUrl + result
# send API call and retrieve JSON data
json_data = requests.get(final_url).json()
# set up jsonpath expression to select conversion rate
jsonpath_expr = parse("$.conversion_rate")
# use jsonpath expression to extract conversion rate
result = jsonpath_expr.find(json_data)[0].value
print("Conversion rate from " + First + " to " + Second + " = ", result)
#Output : # install jsonpath-ng library
[END]
|
Python program to extract a single value from JSON response
|
https://www.geeksforgeeks.org/python-program-to-extract-a-single-value-from-json-response/
|
import json
with open("exam.json", "r") as json_File:
sample_load_file = json.load(json_File)
print(sample_load_file)
|
#Output : # install jsonpath-ng library
|
Python program to extract a single value from JSON response
import json
with open("exam.json", "r") as json_File:
sample_load_file = json.load(json_File)
print(sample_load_file)
#Output : # install jsonpath-ng library
[END]
|
Python program to extract a single value from JSON response
|
https://www.geeksforgeeks.org/python-program-to-extract-a-single-value-from-json-response/
|
import json
with open("exam.json", "r") as json_File:
sample_load_file = json.load(json_File)
# getting hold of all values inside
# the dictionary
test = sample_load_file["criteria"]
# getting hold of the values of
# variableParam
test1 = test[1].values()
test2 = list(test1)[0]
test3 = test2[1:-1].split(",")
print(test3[1])
|
#Output : # install jsonpath-ng library
|
Python program to extract a single value from JSON response
import json
with open("exam.json", "r") as json_File:
sample_load_file = json.load(json_File)
# getting hold of all values inside
# the dictionary
test = sample_load_file["criteria"]
# getting hold of the values of
# variableParam
test1 = test[1].values()
test2 = list(test1)[0]
test3 = test2[1:-1].split(",")
print(test3[1])
#Output : # install jsonpath-ng library
[END]
|
Python Program to Get the File Name From the File Path
|
https://www.geeksforgeeks.org/python-program-to-get-the-file-name-from-the-file-path/
|
import os
path = "D:\home\Riot Games\VALORANT\live\VALORANT.exe"
print(os.path.basename(path).split("/")[-1])
|
#Output : VALORANT.exe
|
Python Program to Get the File Name From the File Path
import os
path = "D:\home\Riot Games\VALORANT\live\VALORANT.exe"
print(os.path.basename(path).split("/")[-1])
#Output : VALORANT.exe
[END]
|
Python Program to Get the File Name From the File Path
|
https://www.geeksforgeeks.org/python-program-to-get-the-file-name-from-the-file-path/
|
import os
file_path = "C:/Users/test.txt" # file path
# using basename function from os
# module to print file name
file_name = os.path.basename(file_path)
print(file_name)
|
#Output : VALORANT.exe
|
Python Program to Get the File Name From the File Path
import os
file_path = "C:/Users/test.txt" # file path
# using basename function from os
# module to print file name
file_name = os.path.basename(file_path)
print(file_name)
#Output : VALORANT.exe
[END]
|
Python Program to Get the File Name From the File Path
|
https://www.geeksforgeeks.org/python-program-to-get-the-file-name-from-the-file-path/
|
import os
file_path = "C:/Users/test.txt"
file_name = os.path.basename(file_path)
file = os.path.splitext(file_name)
print(file) # returns tuple of string
print(file[0] + file[1])
|
#Output : VALORANT.exe
|
Python Program to Get the File Name From the File Path
import os
file_path = "C:/Users/test.txt"
file_name = os.path.basename(file_path)
file = os.path.splitext(file_name)
print(file) # returns tuple of string
print(file[0] + file[1])
#Output : VALORANT.exe
[END]
|
Python Program to Get the File Name From the File Path
|
https://www.geeksforgeeks.org/python-program-to-get-the-file-name-from-the-file-path/
|
from pathlib import Path
file_path = "C:/Users/test.txt"
# stem attribute extracts the file
# name
print(Path(file_path).stem)
# name attribute returns full name
# of the file
print(Path(file_path).name)
|
#Output : VALORANT.exe
|
Python Program to Get the File Name From the File Path
from pathlib import Path
file_path = "C:/Users/test.txt"
# stem attribute extracts the file
# name
print(Path(file_path).stem)
# name attribute returns full name
# of the file
print(Path(file_path).name)
#Output : VALORANT.exe
[END]
|
Python Program to Get the File Name From the File Path
|
https://www.geeksforgeeks.org/python-program-to-get-the-file-name-from-the-file-path/
|
import re
file_path = "C:/Users/test.txt"
pattern = "[\w-]+?(?=\.)"
# searching the pattern
a = re.search(pattern, file_path)
# printing the match
print(a.group())
|
#Output : VALORANT.exe
|
Python Program to Get the File Name From the File Path
import re
file_path = "C:/Users/test.txt"
pattern = "[\w-]+?(?=\.)"
# searching the pattern
a = re.search(pattern, file_path)
# printing the match
print(a.group())
#Output : VALORANT.exe
[END]
|
Python Program to Get the File Name From the File Path
|
https://www.geeksforgeeks.org/python-program-to-get-the-file-name-from-the-file-path/
|
def get_file_name(file_path):
file_path_components = file_path.split("/")
file_name_and_extension = file_path_components[-1].rsplit(".", 1)
return file_name_and_extension[0]
# Example usage
file_path = "C:/Users/test.txt"
result = get_file_name(file_path)
print(result) # Output: 'test'
|
#Output : VALORANT.exe
|
Python Program to Get the File Name From the File Path
def get_file_name(file_path):
file_path_components = file_path.split("/")
file_name_and_extension = file_path_components[-1].rsplit(".", 1)
return file_name_and_extension[0]
# Example usage
file_path = "C:/Users/test.txt"
result = get_file_name(file_path)
print(result) # Output: 'test'
#Output : VALORANT.exe
[END]
|
How to get a new API response in a Tkinter textbox?
|
https://www.geeksforgeeks.org/how-to-get-a-new-api-response-in-a-tkinter-textbox/
|
import requests
# Response Object
r = requests.get("https://api.quotable.io/random")
|
#Output : pip install tkinter
|
How to get a new API response in a Tkinter textbox?
import requests
# Response Object
r = requests.get("https://api.quotable.io/random")
#Output : pip install tkinter
[END]
|
How to get a new API response in a Tkinter textbox?
|
https://www.geeksforgeeks.org/how-to-get-a-new-api-response-in-a-tkinter-textbox/
|
import requests
r = requests.get("https://api.quotable.io/random")
data = r.json()
|
#Output : pip install tkinter
|
How to get a new API response in a Tkinter textbox?
import requests
r = requests.get("https://api.quotable.io/random")
data = r.json()
#Output : pip install tkinter
[END]
|
How to get a new API response in a Tkinter textbox?
|
https://www.geeksforgeeks.org/how-to-get-a-new-api-response-in-a-tkinter-textbox/
|
import tkinter as tk
from tkinter import END, Text
from tkinter.ttk import Button
root = tk.Tk()
root.title("Quoter")
text_box = Text(root, height=10, width=50)
get_button = Button(root, text="Get Quote", command=get_quote)
text_box.pack()
get_button.pack()
root.mainloop()
|
#Output : pip install tkinter
|
How to get a new API response in a Tkinter textbox?
import tkinter as tk
from tkinter import END, Text
from tkinter.ttk import Button
root = tk.Tk()
root.title("Quoter")
text_box = Text(root, height=10, width=50)
get_button = Button(root, text="Get Quote", command=get_quote)
text_box.pack()
get_button.pack()
root.mainloop()
#Output : pip install tkinter
[END]
|
How to get a new API response in a Tkinter textbox?
|
https://www.geeksforgeeks.org/how-to-get-a-new-api-response-in-a-tkinter-textbox/
|
def get_quote():
r = requests.get("https://api.quotable.io/random")
data = r.json()
quote = data["content"]
text_box.delete("1.0", END)
text_box.insert(END, quote)
|
#Output : pip install tkinter
|
How to get a new API response in a Tkinter textbox?
def get_quote():
r = requests.get("https://api.quotable.io/random")
data = r.json()
quote = data["content"]
text_box.delete("1.0", END)
text_box.insert(END, quote)
#Output : pip install tkinter
[END]
|
How to get a new API response in a Tkinter textbox?
|
https://www.geeksforgeeks.org/how-to-get-a-new-api-response-in-a-tkinter-textbox/
|
# import library
import requests
import tkinter as tk
from tkinter import END, Text
from tkinter.ttk import Button
# create a main window
root = tk.Tk()
root.title("Quoter")
# function that will get the data
# from the API
def get_quote():
# API request
r = requests.get("https://api.quotable.io/random")
data = r.json()
quote = data["content"]
# deletes all the text that is currently
# in the TextBox
text_box.delete("1.0", END)
# inserts new data into the TextBox
text_box.insert(END, quote)
text_box = Text(root, height=10, width=50)
get_button = Button(root, text="Get Quote", command=get_quote)
text_box.pack()
get_button.pack()
root.mainloop()
|
#Output : pip install tkinter
|
How to get a new API response in a Tkinter textbox?
# import library
import requests
import tkinter as tk
from tkinter import END, Text
from tkinter.ttk import Button
# create a main window
root = tk.Tk()
root.title("Quoter")
# function that will get the data
# from the API
def get_quote():
# API request
r = requests.get("https://api.quotable.io/random")
data = r.json()
quote = data["content"]
# deletes all the text that is currently
# in the TextBox
text_box.delete("1.0", END)
# inserts new data into the TextBox
text_box.insert(END, quote)
text_box = Text(root, height=10, width=50)
get_button = Button(root, text="Get Quote", command=get_quote)
text_box.pack()
get_button.pack()
root.mainloop()
#Output : pip install tkinter
[END]
|
How to create an empty and a full NumPy array?
|
https://www.geeksforgeeks.org/how-to-create-an-empty-and-a-full-numpy-array/
|
# python program to create
# Empty and Full Numpy arrays
import numpy as np
# Create an empty array
empa = np.empty((3, 4), dtype=int)
print("Empty Array")
print(empa)
# Create a full array
flla = np.full([3, 3], 55, dtype=int)
print("\n Full Array")
print(flla)
|
#Output : numpy.full(shape, fill_value, dtype = None, order = ?????????
|
How to create an empty and a full NumPy array?
# python program to create
# Empty and Full Numpy arrays
import numpy as np
# Create an empty array
empa = np.empty((3, 4), dtype=int)
print("Empty Array")
print(empa)
# Create a full array
flla = np.full([3, 3], 55, dtype=int)
print("\n Full Array")
print(flla)
#Output : numpy.full(shape, fill_value, dtype = None, order = ?????????
[END]
|
How to create an empty and a full NumPy array?
|
https://www.geeksforgeeks.org/how-to-create-an-empty-and-a-full-numpy-array/
|
# python program to create
# Empty and Full Numpy arrays
import numpy as np
# Create an empty array
empa = np.empty([4, 2])
print("Empty Array")
print(empa)
# Create a full array
flla = np.full([4, 3], 95)
print("\n Full Array")
print(flla)
|
#Output : numpy.full(shape, fill_value, dtype = None, order = ?????????
|
How to create an empty and a full NumPy array?
# python program to create
# Empty and Full Numpy arrays
import numpy as np
# Create an empty array
empa = np.empty([4, 2])
print("Empty Array")
print(empa)
# Create a full array
flla = np.full([4, 3], 95)
print("\n Full Array")
print(flla)
#Output : numpy.full(shape, fill_value, dtype = None, order = ?????????
[END]
|
How to create an empty and a full NumPy array?
|
https://www.geeksforgeeks.org/how-to-create-an-empty-and-a-full-numpy-array/
|
# python program to create
# Empty and Full Numpy arrays
import numpy as np
# Create an empty array
empa = np.empty([3, 3])
print("Empty Array")
print(empa)
# Create a full array
flla = np.full([5, 3], 9.9)
print("\n Full Array")
print(flla)
|
#Output : numpy.full(shape, fill_value, dtype = None, order = ?????????
|
How to create an empty and a full NumPy array?
# python program to create
# Empty and Full Numpy arrays
import numpy as np
# Create an empty array
empa = np.empty([3, 3])
print("Empty Array")
print(empa)
# Create a full array
flla = np.full([5, 3], 9.9)
print("\n Full Array")
print(flla)
#Output : numpy.full(shape, fill_value, dtype = None, order = ?????????
[END]
|
Create a Numpy array filled with all zeros
|
https://www.geeksforgeeks.org/create-a-numpy-array-filled-with-all-zeros-python/
|
# Python Program to create array with all zeros
import numpy as geek
a = geek.zeros(3, dtype=int)
print("Matrix a : \n", a)
b = geek.zeros([3, 3], dtype=int)
print("\nMatrix b : \n", b)
|
#Output : shape : integer or sequence of integers
|
Create a Numpy array filled with all zeros
# Python Program to create array with all zeros
import numpy as geek
a = geek.zeros(3, dtype=int)
print("Matrix a : \n", a)
b = geek.zeros([3, 3], dtype=int)
print("\nMatrix b : \n", b)
#Output : shape : integer or sequence of integers
[END]
|
Create a Numpy array filled with all zeros
|
https://www.geeksforgeeks.org/create-a-numpy-array-filled-with-all-zeros-python/
|
# Python Program to create array with all zeros
import numpy as geek
c = geek.zeros([5, 3])
print("\nMatrix c : \n", c)
d = geek.zeros([5, 2], dtype=float)
print("\nMatrix d : \n", d)
|
#Output : shape : integer or sequence of integers
|
Create a Numpy array filled with all zeros
# Python Program to create array with all zeros
import numpy as geek
c = geek.zeros([5, 3])
print("\nMatrix c : \n", c)
d = geek.zeros([5, 2], dtype=float)
print("\nMatrix d : \n", d)
#Output : shape : integer or sequence of integers
[END]
|
Create a Numpy array filled with all ones
|
https://www.geeksforgeeks.org/create-a-numpy-array-filled-with-all-ones/
|
# Python Program to create array with all ones
import numpy as geek
a = geek.ones(3, dtype=int)
print("Matrix a : \n", a)
b = geek.ones([3, 3], dtype=int)
print("\nMatrix b : \n", b)
|
#Output : shape : integer or sequence of integers
|
Create a Numpy array filled with all ones
# Python Program to create array with all ones
import numpy as geek
a = geek.ones(3, dtype=int)
print("Matrix a : \n", a)
b = geek.ones([3, 3], dtype=int)
print("\nMatrix b : \n", b)
#Output : shape : integer or sequence of integers
[END]
|
Create a Numpy array filled with all ones
|
https://www.geeksforgeeks.org/create-a-numpy-array-filled-with-all-ones/
|
# Python Program to create array with all ones
import numpy as geek
c = geek.ones([5, 3])
print("\nMatrix c : \n", c)
d = geek.ones([5, 2], dtype=float)
print("\nMatrix d : \n", d)
|
#Output : shape : integer or sequence of integers
|
Create a Numpy array filled with all ones
# Python Program to create array with all ones
import numpy as geek
c = geek.ones([5, 3])
print("\nMatrix c : \n", c)
d = geek.ones([5, 2], dtype=float)
print("\nMatrix d : \n", d)
#Output : shape : integer or sequence of integers
[END]
|
Check whether a Numpy array contains a specified row
|
https://www.geeksforgeeks.org/check-whether-a-numpy-array-contains-a-specified-row/
|
# importing package
import numpy
# create numpy array
arr = numpy.array(
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
)
# view array
print(arr)
# check for some lists
print([1, 2, 3, 4, 5] in arr.tolist())
print([16, 17, 20, 19, 18] in arr.tolist())
print([3, 2, 5, -4, 5] in arr.tolist())
print([11, 12, 13, 14, 15] in arr.tolist())
|
#Output : [[ 1 2 3 4 5]
|
Check whether a Numpy array contains a specified row
# importing package
import numpy
# create numpy array
arr = numpy.array(
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
)
# view array
print(arr)
# check for some lists
print([1, 2, 3, 4, 5] in arr.tolist())
print([16, 17, 20, 19, 18] in arr.tolist())
print([3, 2, 5, -4, 5] in arr.tolist())
print([11, 12, 13, 14, 15] in arr.tolist())
#Output : [[ 1 2 3 4 5]
[END]
|
Remove single-dimensional entries from the shape of an array
|
https://www.geeksforgeeks.org/numpy-squeeze-in-python/
|
# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]])
print("Input array : ", in_arr)
print("Shape of input array : ", in_arr.shape)
out_arr = geek.squeeze(in_arr)
print("output squeezed array : ", out_arr)
print("Shape of output array : ", out_arr.shape)
|
Input array : [[[2 2 2]
[2 2 2]]]
|
Remove single-dimensional entries from the shape of an array
# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.array([[[2, 2, 2], [2, 2, 2]]])
print("Input array : ", in_arr)
print("Shape of input array : ", in_arr.shape)
out_arr = geek.squeeze(in_arr)
print("output squeezed array : ", out_arr)
print("Shape of output array : ", out_arr.shape)
Input array : [[[2 2 2]
[2 2 2]]]
[END]
|
Remove single-dimensional entries from the shape of an array
|
https://www.geeksforgeeks.org/numpy-squeeze-in-python/
|
# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.arange(9).reshape(1, 3, 3)
print("Input array : ", in_arr)
out_arr = geek.squeeze(in_arr, axis=0)
print("output array : ", out_arr)
print("The shapes of Input and Output array : ")
print(in_arr.shape, out_arr.shape)
|
Input array : [[[2 2 2]
[2 2 2]]]
|
Remove single-dimensional entries from the shape of an array
# Python program explaining
# numpy.squeeze function
import numpy as geek
in_arr = geek.arange(9).reshape(1, 3, 3)
print("Input array : ", in_arr)
out_arr = geek.squeeze(in_arr, axis=0)
print("output array : ", out_arr)
print("The shapes of Input and Output array : ")
print(in_arr.shape, out_arr.shape)
Input array : [[[2 2 2]
[2 2 2]]]
[END]
|
Remove single-dimensional entries from the shape of an array
|
https://www.geeksforgeeks.org/numpy-squeeze-in-python/
|
# Python program explaining
# numpy.squeeze function
# when value error occurs
import numpy as geek
in_arr = geek.arange(9).reshape(1, 3, 3)
print("Input array : ", in_arr)
out_arr = geek.squeeze(in_arr, axis=1)
print("output array : ", out_arr)
print("The shapes of Input and Output array : ")
print(in_arr.shape, out_arr.shape)
|
Input array : [[[2 2 2]
[2 2 2]]]
|
Remove single-dimensional entries from the shape of an array
# Python program explaining
# numpy.squeeze function
# when value error occurs
import numpy as geek
in_arr = geek.arange(9).reshape(1, 3, 3)
print("Input array : ", in_arr)
out_arr = geek.squeeze(in_arr, axis=1)
print("output array : ", out_arr)
print("The shapes of Input and Output array : ")
print(in_arr.shape, out_arr.shape)
Input array : [[[2 2 2]
[2 2 2]]]
[END]
|
Find the number of occurrences of a sequence in a NumPy array
|
https://www.geeksforgeeks.org/find-the-number-of-occurrences-of-a-sequence-in-a-numpy-array/
|
# importing package
import numpy
# create numpy array
arr = numpy.array([[2, 8, 9, 4], [9, 4, 9, 4], [4, 5, 9, 7], [2, 9, 4, 3]])
# Counting sequence
output = repr(arr).count("9, 4")
# view output
print(output)
|
#Output : Arr = [[2,8,9,4],
|
Find the number of occurrences of a sequence in a NumPy array
# importing package
import numpy
# create numpy array
arr = numpy.array([[2, 8, 9, 4], [9, 4, 9, 4], [4, 5, 9, 7], [2, 9, 4, 3]])
# Counting sequence
output = repr(arr).count("9, 4")
# view output
print(output)
#Output : Arr = [[2,8,9,4],
[END]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.