title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Garbage Collector with Pandas DataFrame | Apratim Biswas | Dec 2020 | Towards Data Science
|
It’s almost 2021. Memory is inexpensive and it’s easy to access cloud platforms like Amazon Web Services (AWS) or Google Cloud Platform (GCP) and throw vast amount of resources at a data problem. And so, we usually don’t worry about memory (RAM) these days. But there are at least two problems with this line of thinking:
i) if we can use our resource efficiently, we can do more with the same amount of resources (i.e. save money!); and, ii) “data has mass” in the sense that the rate at which large volume of data moves is slower than smaller volumes of data. In other words, smaller volume of data moves around faster, and hence, processed faster (i.e. save time and money!!).
There are several aspects of managing memory usage. To list a few, we have: garbage collection, the option to use certain data types over others, the option to use tries and directed acyclic word graphs, and option to use probabilistic data structures. Each of these deserves an article (or perhaps several articles!) on their own. So in this article, I’ll stick with just one of them: garbage collection. Often overlooked, it is one of the primary ways Python manages memory. It happens in the background without us doing anything special. But it is possible to control some aspects of it, and knowing them can be really useful when handling large amounts of data.
Before we can dive into the details, it may be useful to provide a little bit of background in variable names in python. In python, variable names are simply symbolic names that are pointers to objects. The schematic below illustrates this.
Let’s define a and b separately:
a = "banana"b = "banana"
Now let’s take a look at the location of these two variables are referring to:
for name in [a,b]: print(object.__repr__(name))<str object at 0x7f0f901548b0><str object at 0x7f0f901548b0>
Notice that internally both a and b are pointing to the same object. When we assign a = "banana", we create a string object with value "banana". And when we assign b = "banana", we are simply creating a new symbolic name b for the same object. Put in the language of computer science, we create a second reference to the object.
Now that we have some background on variable names in python, we’re ready to get started! We’ll load and process a medium sized dataset using the python library, pandas. At every step, we’ll carefully monitor memory usage and try to implement garbage collection strategies to make it more efficient. Please note this is not meant as an analysis of the dataset. Any analytical step in this exercise is merely to demonstrate its effect on memory usage.
#Import necessary librariesimport pandas as pdimport sys #system specific parameters and namesimport gc #garbage collector interface
Let’s define the relative path to the dataset. The data is in a csv file that occupies 205.2 MB on my system. I’ll use the usual read_csv function to load it to memory.
file_path='./data/Housing_Maintenance_Code_Complaints.csv'df=pd.read_csv(file_path, low_memory=False)df.head(3)
Let’s check the objects occupying space in the memory at this stage. We should see the newly created DataFrame, df, in the list.
memory_usage_by_variable=pd.DataFrame({k:sys.getsizeof(v) for (k,v) in locals().items()},index=['Size'])memory_usage_by_variable=memory_usage_by_variable.Tmemory_usage_by_variable=memory_usage_by_variable.sort_values(by='Size',ascending=False).head(10)memory_usage_by_variable.head()
df is at the top of the list, occupying a little over 1.2 GB. There is a large variation in the order of magnitudes. Let’s define a function that makes it easier to check memory usage and generate more human-readable result.
def obj_size_fmt(num): if num<10**3: return "{:.2f}{}".format(num,"B") elif ((num>=10**3)&(num<10**6)): return "{:.2f}{}".format(num/(1.024*10**3),"KB") elif ((num>=10**6)&(num<10**9)): return "{:.2f}{}".format(num/(1.024*10**6),"MB") else: return "{:.2f}{}".format(num/(1.024*10**9),"GB")def memory_usage(): memory_usage_by_variable=pd.DataFrame({k:sys.getsizeof(v)\ for (k,v) in globals().items()},index=['Size']) memory_usage_by_variable=memory_usage_by_variable.T memory_usage_by_variable=memory_usage_by_variable\ .sort_values(by='Size',ascending=False).head(10) memory_usage_by_variable['Size']=memory_usage_by_variable['Size'] \.apply(lambda x: obj_size_fmt(x)) return memory_usage_by_variablememory_usage()
Looking at the sizes, there are two things that stand out:
df accounts for almost all of the memory usage; and,the DataFrame is markedly larger than the csv file. The original csv file I uploaded is only 205.2 MB. df was created simply by converting the data in the csv file to pandas dataframe. But the DataFrame occupies over 1.22 GB, about 6 times the size of the csv file.
df accounts for almost all of the memory usage; and,
the DataFrame is markedly larger than the csv file. The original csv file I uploaded is only 205.2 MB. df was created simply by converting the data in the csv file to pandas dataframe. But the DataFrame occupies over 1.22 GB, about 6 times the size of the csv file.
It is important to keep these observations in mind while processing large datasets. Working with DataFrames involves treacherously large amounts of memory, a lot more than one’s intuition would suggest. We have to be judicious about creating slices and intermediate DataFrames, and ensure that we don’t make unnecessary copies. Otherwise, space occupied by copies of slices can add up quickly. Let’s see an example. Say, we want to take the first 6 columns and name it df2.
df2=df.iloc[:,0:6]df2.head(3)
#Let's check the memory usagememory_usage()
As before, we check the location that the variable names df and df2 are referring to.
print(object.__repr__(df))print(object.__repr__(df2))<pandas.core.frame.DataFrame object at 0x7f0f90136ca0><pandas.core.frame.DataFrame object at 0x7f0f58980490>
Clearly, df2 is now pointing to a new object that occupies 468.49 MB in the memory. One way to deal with this problem is by using the garbage collection module. And that’s what we are going to look into in the next section.
The primary garbage collection algorithm used by python is reference counting. Python keeps track of all the different places that have reference to an object. A “place” can be a variable or another object. When the number of such places becomes zero, the object is deallocated. In turn, reference count of all other objects that the deallocated object had reference to, is decreased by 1. For reasons outside the scope of this article, reference counting alone cannot clean data structure with reference cycles (see official python documentation for further details). This is where the Garbage Collector (GC) comes in. The GC focuses exclusively on cleaning objects with reference cycles and supplements reference counting.
The gc module provides an interface to the garbage collector. We can perform a wide variety of functions through it, including enabling and disabling the collector. I'll touch upon just a few of them.
Garbage collection is a scheduled activity. Python keeps track of all objects in the memory and classifies them into three generations: 0 being the newest and 2 is the oldest. Each generation has its own counter and threshold. Python initiates garbage collection when the magnitude of (the number of allocation minus the number of deallocation) exceeds the threshold value for that generation. The default threshold values for generations 0 to 2, in order, are 700, 10 and 10. We can check the threshold values for all three generations using the function get_threshold as shown below:
gc.get_threshold() #Tuple showing thresholds for the 3 generations at which automatic garbage collection is triggered.(700, 10, 10)
We can also trigger garbage collection at any point using the collect function. But before we do that, let's take a look at the current memory usage and collection counts for the three generations. This will be our baseline.
gc.get_count()(534, 4, 9)memory_usage()
It appears that there are close to 600 objects, two of them accounting for almost 100% of memory usage.
gc.collect()gc.get_count()(34, 0, 0)memory_usage()
The object count decreased from 598 to 21. That’s >96% drop in count! But notice we still have df and df2. This is because we still have references to df and df2. So let’s call the collect function again, but this time we first delete reference to df and df2:
#deleting referencesdel dfdel df2#triggering collectiongc.collect()#finally check memory usagememory_usage()
And they’re gone!!
When working with large datasets, chances are, many of the objects in the memory are also going to be large. Their size can quickly add up to a level where performance becomes a problem. I find the set_threshold function particularly effective at addressing this challenge. Setting thresholds to lower values for each of the generations makes garbage collection sweeps more frequent and makes more memory accessible.
There is a big caveat to this, however. Garbage collection is computationally expensive. It’s something that must be considered before changing the default thresholds. The appropriate threshold values are application-specific and depends on resource constraints. In fact, the standard conservative recommendation in python is to stick with default values. That said, if you are memory constrained, and/or you are working on a single machine, it can be a useful tool. As the python source code describes, the python object allocator is designed as “a fast, special-purpose memory allocator for small blocks, to be used on top of a general-purpose malloc”, referring to malloc function in the C language.[2][3] If you find yourself deallocating large objects, or a lot of smaller objects for that matter, using the garbage collection module may give your process a big boost.
Once an object is collected by the garbage collector, the “freed” memory can be occupied by a new python object. But it does not guarantee that it’ll return the “freed” memory to the system. Instead, the object allocator keeps a portion of it, just in case, for future usage.
https://runestone.academy/runestone/books/published/thinkcspy/Lists/ObjectsandReferences.htmlhttps://github.com/python/cpython/blob/7d6ddb96b34b94c1cbdf95baa94492c48426404e/Objects/obmalloc.c (lines 559–560 as of 12/10/2020).https://realpython.com/python-memory-management/
https://runestone.academy/runestone/books/published/thinkcspy/Lists/ObjectsandReferences.html
https://github.com/python/cpython/blob/7d6ddb96b34b94c1cbdf95baa94492c48426404e/Objects/obmalloc.c (lines 559–560 as of 12/10/2020).
|
[
{
"code": null,
"e": 494,
"s": 172,
"text": "It’s almost 2021. Memory is inexpensive and it’s easy to access cloud platforms like Amazon Web Services (AWS) or Google Cloud Platform (GCP) and throw vast amount of resources at a data problem. And so, we usually don’t worry about memory (RAM) these days. But there are at least two problems with this line of thinking:"
},
{
"code": null,
"e": 852,
"s": 494,
"text": "i) if we can use our resource efficiently, we can do more with the same amount of resources (i.e. save money!); and, ii) “data has mass” in the sense that the rate at which large volume of data moves is slower than smaller volumes of data. In other words, smaller volume of data moves around faster, and hence, processed faster (i.e. save time and money!!)."
},
{
"code": null,
"e": 1518,
"s": 852,
"text": "There are several aspects of managing memory usage. To list a few, we have: garbage collection, the option to use certain data types over others, the option to use tries and directed acyclic word graphs, and option to use probabilistic data structures. Each of these deserves an article (or perhaps several articles!) on their own. So in this article, I’ll stick with just one of them: garbage collection. Often overlooked, it is one of the primary ways Python manages memory. It happens in the background without us doing anything special. But it is possible to control some aspects of it, and knowing them can be really useful when handling large amounts of data."
},
{
"code": null,
"e": 1759,
"s": 1518,
"text": "Before we can dive into the details, it may be useful to provide a little bit of background in variable names in python. In python, variable names are simply symbolic names that are pointers to objects. The schematic below illustrates this."
},
{
"code": null,
"e": 1792,
"s": 1759,
"text": "Let’s define a and b separately:"
},
{
"code": null,
"e": 1818,
"s": 1792,
"text": "a = \"banana\"b = \"banana\" "
},
{
"code": null,
"e": 1897,
"s": 1818,
"text": "Now let’s take a look at the location of these two variables are referring to:"
},
{
"code": null,
"e": 2008,
"s": 1897,
"text": "for name in [a,b]: print(object.__repr__(name))<str object at 0x7f0f901548b0><str object at 0x7f0f901548b0>"
},
{
"code": null,
"e": 2337,
"s": 2008,
"text": "Notice that internally both a and b are pointing to the same object. When we assign a = \"banana\", we create a string object with value \"banana\". And when we assign b = \"banana\", we are simply creating a new symbolic name b for the same object. Put in the language of computer science, we create a second reference to the object."
},
{
"code": null,
"e": 2788,
"s": 2337,
"text": "Now that we have some background on variable names in python, we’re ready to get started! We’ll load and process a medium sized dataset using the python library, pandas. At every step, we’ll carefully monitor memory usage and try to implement garbage collection strategies to make it more efficient. Please note this is not meant as an analysis of the dataset. Any analytical step in this exercise is merely to demonstrate its effect on memory usage."
},
{
"code": null,
"e": 2924,
"s": 2788,
"text": "#Import necessary librariesimport pandas as pdimport sys #system specific parameters and namesimport gc #garbage collector interface"
},
{
"code": null,
"e": 3093,
"s": 2924,
"text": "Let’s define the relative path to the dataset. The data is in a csv file that occupies 205.2 MB on my system. I’ll use the usual read_csv function to load it to memory."
},
{
"code": null,
"e": 3205,
"s": 3093,
"text": "file_path='./data/Housing_Maintenance_Code_Complaints.csv'df=pd.read_csv(file_path, low_memory=False)df.head(3)"
},
{
"code": null,
"e": 3334,
"s": 3205,
"text": "Let’s check the objects occupying space in the memory at this stage. We should see the newly created DataFrame, df, in the list."
},
{
"code": null,
"e": 3618,
"s": 3334,
"text": "memory_usage_by_variable=pd.DataFrame({k:sys.getsizeof(v) for (k,v) in locals().items()},index=['Size'])memory_usage_by_variable=memory_usage_by_variable.Tmemory_usage_by_variable=memory_usage_by_variable.sort_values(by='Size',ascending=False).head(10)memory_usage_by_variable.head()"
},
{
"code": null,
"e": 3843,
"s": 3618,
"text": "df is at the top of the list, occupying a little over 1.2 GB. There is a large variation in the order of magnitudes. Let’s define a function that makes it easier to check memory usage and generate more human-readable result."
},
{
"code": null,
"e": 4619,
"s": 3843,
"text": "def obj_size_fmt(num): if num<10**3: return \"{:.2f}{}\".format(num,\"B\") elif ((num>=10**3)&(num<10**6)): return \"{:.2f}{}\".format(num/(1.024*10**3),\"KB\") elif ((num>=10**6)&(num<10**9)): return \"{:.2f}{}\".format(num/(1.024*10**6),\"MB\") else: return \"{:.2f}{}\".format(num/(1.024*10**9),\"GB\")def memory_usage(): memory_usage_by_variable=pd.DataFrame({k:sys.getsizeof(v)\\ for (k,v) in globals().items()},index=['Size']) memory_usage_by_variable=memory_usage_by_variable.T memory_usage_by_variable=memory_usage_by_variable\\ .sort_values(by='Size',ascending=False).head(10) memory_usage_by_variable['Size']=memory_usage_by_variable['Size'] \\.apply(lambda x: obj_size_fmt(x)) return memory_usage_by_variablememory_usage()"
},
{
"code": null,
"e": 4678,
"s": 4619,
"text": "Looking at the sizes, there are two things that stand out:"
},
{
"code": null,
"e": 4996,
"s": 4678,
"text": "df accounts for almost all of the memory usage; and,the DataFrame is markedly larger than the csv file. The original csv file I uploaded is only 205.2 MB. df was created simply by converting the data in the csv file to pandas dataframe. But the DataFrame occupies over 1.22 GB, about 6 times the size of the csv file."
},
{
"code": null,
"e": 5049,
"s": 4996,
"text": "df accounts for almost all of the memory usage; and,"
},
{
"code": null,
"e": 5315,
"s": 5049,
"text": "the DataFrame is markedly larger than the csv file. The original csv file I uploaded is only 205.2 MB. df was created simply by converting the data in the csv file to pandas dataframe. But the DataFrame occupies over 1.22 GB, about 6 times the size of the csv file."
},
{
"code": null,
"e": 5789,
"s": 5315,
"text": "It is important to keep these observations in mind while processing large datasets. Working with DataFrames involves treacherously large amounts of memory, a lot more than one’s intuition would suggest. We have to be judicious about creating slices and intermediate DataFrames, and ensure that we don’t make unnecessary copies. Otherwise, space occupied by copies of slices can add up quickly. Let’s see an example. Say, we want to take the first 6 columns and name it df2."
},
{
"code": null,
"e": 5819,
"s": 5789,
"text": "df2=df.iloc[:,0:6]df2.head(3)"
},
{
"code": null,
"e": 5863,
"s": 5819,
"text": "#Let's check the memory usagememory_usage()"
},
{
"code": null,
"e": 5949,
"s": 5863,
"text": "As before, we check the location that the variable names df and df2 are referring to."
},
{
"code": null,
"e": 6111,
"s": 5949,
"text": "print(object.__repr__(df))print(object.__repr__(df2))<pandas.core.frame.DataFrame object at 0x7f0f90136ca0><pandas.core.frame.DataFrame object at 0x7f0f58980490>"
},
{
"code": null,
"e": 6335,
"s": 6111,
"text": "Clearly, df2 is now pointing to a new object that occupies 468.49 MB in the memory. One way to deal with this problem is by using the garbage collection module. And that’s what we are going to look into in the next section."
},
{
"code": null,
"e": 7060,
"s": 6335,
"text": "The primary garbage collection algorithm used by python is reference counting. Python keeps track of all the different places that have reference to an object. A “place” can be a variable or another object. When the number of such places becomes zero, the object is deallocated. In turn, reference count of all other objects that the deallocated object had reference to, is decreased by 1. For reasons outside the scope of this article, reference counting alone cannot clean data structure with reference cycles (see official python documentation for further details). This is where the Garbage Collector (GC) comes in. The GC focuses exclusively on cleaning objects with reference cycles and supplements reference counting."
},
{
"code": null,
"e": 7261,
"s": 7060,
"text": "The gc module provides an interface to the garbage collector. We can perform a wide variety of functions through it, including enabling and disabling the collector. I'll touch upon just a few of them."
},
{
"code": null,
"e": 7847,
"s": 7261,
"text": "Garbage collection is a scheduled activity. Python keeps track of all objects in the memory and classifies them into three generations: 0 being the newest and 2 is the oldest. Each generation has its own counter and threshold. Python initiates garbage collection when the magnitude of (the number of allocation minus the number of deallocation) exceeds the threshold value for that generation. The default threshold values for generations 0 to 2, in order, are 700, 10 and 10. We can check the threshold values for all three generations using the function get_threshold as shown below:"
},
{
"code": null,
"e": 7979,
"s": 7847,
"text": "gc.get_threshold() #Tuple showing thresholds for the 3 generations at which automatic garbage collection is triggered.(700, 10, 10)"
},
{
"code": null,
"e": 8204,
"s": 7979,
"text": "We can also trigger garbage collection at any point using the collect function. But before we do that, let's take a look at the current memory usage and collection counts for the three generations. This will be our baseline."
},
{
"code": null,
"e": 8244,
"s": 8204,
"text": "gc.get_count()(534, 4, 9)memory_usage()"
},
{
"code": null,
"e": 8348,
"s": 8244,
"text": "It appears that there are close to 600 objects, two of them accounting for almost 100% of memory usage."
},
{
"code": null,
"e": 8399,
"s": 8348,
"text": "gc.collect()gc.get_count()(34, 0, 0)memory_usage()"
},
{
"code": null,
"e": 8659,
"s": 8399,
"text": "The object count decreased from 598 to 21. That’s >96% drop in count! But notice we still have df and df2. This is because we still have references to df and df2. So let’s call the collect function again, but this time we first delete reference to df and df2:"
},
{
"code": null,
"e": 8768,
"s": 8659,
"text": "#deleting referencesdel dfdel df2#triggering collectiongc.collect()#finally check memory usagememory_usage()"
},
{
"code": null,
"e": 8787,
"s": 8768,
"text": "And they’re gone!!"
},
{
"code": null,
"e": 9204,
"s": 8787,
"text": "When working with large datasets, chances are, many of the objects in the memory are also going to be large. Their size can quickly add up to a level where performance becomes a problem. I find the set_threshold function particularly effective at addressing this challenge. Setting thresholds to lower values for each of the generations makes garbage collection sweeps more frequent and makes more memory accessible."
},
{
"code": null,
"e": 10078,
"s": 9204,
"text": "There is a big caveat to this, however. Garbage collection is computationally expensive. It’s something that must be considered before changing the default thresholds. The appropriate threshold values are application-specific and depends on resource constraints. In fact, the standard conservative recommendation in python is to stick with default values. That said, if you are memory constrained, and/or you are working on a single machine, it can be a useful tool. As the python source code describes, the python object allocator is designed as “a fast, special-purpose memory allocator for small blocks, to be used on top of a general-purpose malloc”, referring to malloc function in the C language.[2][3] If you find yourself deallocating large objects, or a lot of smaller objects for that matter, using the garbage collection module may give your process a big boost."
},
{
"code": null,
"e": 10354,
"s": 10078,
"text": "Once an object is collected by the garbage collector, the “freed” memory can be occupied by a new python object. But it does not guarantee that it’ll return the “freed” memory to the system. Instead, the object allocator keeps a portion of it, just in case, for future usage."
},
{
"code": null,
"e": 10628,
"s": 10354,
"text": "https://runestone.academy/runestone/books/published/thinkcspy/Lists/ObjectsandReferences.htmlhttps://github.com/python/cpython/blob/7d6ddb96b34b94c1cbdf95baa94492c48426404e/Objects/obmalloc.c (lines 559–560 as of 12/10/2020).https://realpython.com/python-memory-management/"
},
{
"code": null,
"e": 10722,
"s": 10628,
"text": "https://runestone.academy/runestone/books/published/thinkcspy/Lists/ObjectsandReferences.html"
}
] |
Python | Find elements within range in numpy - GeeksforGeeks
|
12 Mar, 2019
Given numpy array, the task is to find elements within some specific range. Let’s discuss some ways to do the task. Method #1: Using np.where()
# python code to demonstrate# finding elements in range# in numpy arrayimport numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 810, 9, 6]) # printing initial arrayprint("initial_array : ", str(ini_array)); # find elements in range 6 to 10result = np.where(np.logical_and(ini_array>= 6, ini_array<= 10)) # printing resultprint("resultant_array : ", result)
initial_array : [ 1 2 3 45 4 7 810 9 6]
resultant_array : (array([5, 7, 8]),)
Method #2: Using numpy.searchsorted()
# Python code to demonstrate# finding elements in range# in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6]) # printing initial arrayprint("initial_array : ", str(ini_array)); # find elements in range 6 to 10start = np.searchsorted(ini_array, 6, 'left')end = np.searchsorted(ini_array, 10, 'right')result = np.arange(start, end) # printing resultprint("resultant_array : ", result)
initial_array : [ 1 2 3 45 4 7 9 6]
resultant_array : [5 6 7]
Method #3: Using *
# Python code to demonstrate# finding elements in range# in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6]) # printing initial arrayprint("initial_array : ", str(ini_array)); # find elements in range 6 to 10result = ini_array[(ini_array>6)*(ini_array<10)] # printing resultprint("resultant_array : ", result)
initial_array : [ 1 2 3 45 4 7 9 6]
resultant_array : [7 9]
Python numpy-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n12 Mar, 2019"
},
{
"code": null,
"e": 24045,
"s": 23901,
"text": "Given numpy array, the task is to find elements within some specific range. Let’s discuss some ways to do the task. Method #1: Using np.where()"
},
{
"code": "# python code to demonstrate# finding elements in range# in numpy arrayimport numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 810, 9, 6]) # printing initial arrayprint(\"initial_array : \", str(ini_array)); # find elements in range 6 to 10result = np.where(np.logical_and(ini_array>= 6, ini_array<= 10)) # printing resultprint(\"resultant_array : \", result)",
"e": 24409,
"s": 24045,
"text": null
},
{
"code": null,
"e": 24504,
"s": 24409,
"text": "initial_array : [ 1 2 3 45 4 7 810 9 6]\nresultant_array : (array([5, 7, 8]),)\n"
},
{
"code": null,
"e": 24543,
"s": 24504,
"text": " Method #2: Using numpy.searchsorted()"
},
{
"code": "# Python code to demonstrate# finding elements in range# in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6]) # printing initial arrayprint(\"initial_array : \", str(ini_array)); # find elements in range 6 to 10start = np.searchsorted(ini_array, 6, 'left')end = np.searchsorted(ini_array, 10, 'right')result = np.arange(start, end) # printing resultprint(\"resultant_array : \", result)",
"e": 24962,
"s": 24543,
"text": null
},
{
"code": null,
"e": 25033,
"s": 24962,
"text": "initial_array : [ 1 2 3 45 4 7 9 6]\nresultant_array : [5 6 7]\n"
},
{
"code": null,
"e": 25053,
"s": 25033,
"text": " Method #3: Using *"
},
{
"code": "# Python code to demonstrate# finding elements in range# in numpy array import numpy as np ini_array = np.array([1, 2, 3, 45, 4, 7, 9, 6]) # printing initial arrayprint(\"initial_array : \", str(ini_array)); # find elements in range 6 to 10result = ini_array[(ini_array>6)*(ini_array<10)] # printing resultprint(\"resultant_array : \", result)",
"e": 25400,
"s": 25053,
"text": null
},
{
"code": null,
"e": 25469,
"s": 25400,
"text": "initial_array : [ 1 2 3 45 4 7 9 6]\nresultant_array : [7 9]\n"
},
{
"code": null,
"e": 25490,
"s": 25469,
"text": "Python numpy-program"
},
{
"code": null,
"e": 25497,
"s": 25490,
"text": "Python"
},
{
"code": null,
"e": 25595,
"s": 25497,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25604,
"s": 25595,
"text": "Comments"
},
{
"code": null,
"e": 25617,
"s": 25604,
"text": "Old Comments"
},
{
"code": null,
"e": 25649,
"s": 25617,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25705,
"s": 25649,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25747,
"s": 25705,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25789,
"s": 25747,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25825,
"s": 25789,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25864,
"s": 25825,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25886,
"s": 25864,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25917,
"s": 25886,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25944,
"s": 25917,
"text": "Python Classes and Objects"
}
] |
Firebase - Event Types
|
Firebase offers several different event types for reading data. Some of the most commonly used ones are described below.
The first event type is value. We showed you how to use value in our last chapter. This event type will be triggered every time the data changes and it will retrieve all the data including children.
This event type will be triggered once for every player and every time a new player is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");
playersRef.on("child_added", function(data, prevChildKey) {
var newPlayer = data.val();
console.log("name: " + newPlayer.name);
console.log("age: " + newPlayer.age);
console.log("number: " + newPlayer.number);
console.log("Previous Player: " + prevChildKey);
});
We will get the following result.
If we add a new player named Bob, we will get the updated data.
This event type is triggered when the data has changed.
Let us consider the following example.
var playersRef = firebase.database().ref("players/");
playersRef.on("child_changed", function(data) {
var player = data.val();
console.log("The updated player name is " + player.name);
});
We can change Bob to Maria in Firebase to get the update.
If we want to get access of deleted data, we can use child_removed event type.
var playersRef = firebase.database().ref("players/");
playersRef.on("child_removed", function(data) {
var deletedPlayer = data.val();
console.log(deletedPlayer.name + " has been deleted");
});
Now, we can delete Maria from Firebase to get notifications.
60 Lectures
5 hours
University Code
28 Lectures
2.5 hours
Appeteria
85 Lectures
14.5 hours
Appeteria
46 Lectures
2.5 hours
Gautham Vijayan
13 Lectures
1.5 hours
Nishant Kumar
85 Lectures
16.5 hours
Rahul Agarwal
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2287,
"s": 2166,
"text": "Firebase offers several different event types for reading data. Some of the most commonly used ones are described below."
},
{
"code": null,
"e": 2486,
"s": 2287,
"text": "The first event type is value. We showed you how to use value in our last chapter. This event type will be triggered every time the data changes and it will retrieve all the data including children."
},
{
"code": null,
"e": 2704,
"s": 2486,
"text": "This event type will be triggered once for every player and every time a new player is added to our data. It is useful for reading list data because we get access of the added player and previous player from the list."
},
{
"code": null,
"e": 2743,
"s": 2704,
"text": "Let us consider the following example."
},
{
"code": null,
"e": 3076,
"s": 2743,
"text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.on(\"child_added\", function(data, prevChildKey) {\n var newPlayer = data.val();\n console.log(\"name: \" + newPlayer.name);\n console.log(\"age: \" + newPlayer.age);\n console.log(\"number: \" + newPlayer.number);\n console.log(\"Previous Player: \" + prevChildKey);\n});"
},
{
"code": null,
"e": 3110,
"s": 3076,
"text": "We will get the following result."
},
{
"code": null,
"e": 3174,
"s": 3110,
"text": "If we add a new player named Bob, we will get the updated data."
},
{
"code": null,
"e": 3230,
"s": 3174,
"text": "This event type is triggered when the data has changed."
},
{
"code": null,
"e": 3269,
"s": 3230,
"text": "Let us consider the following example."
},
{
"code": null,
"e": 3465,
"s": 3269,
"text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.on(\"child_changed\", function(data) {\n var player = data.val();\n console.log(\"The updated player name is \" + player.name);\n});"
},
{
"code": null,
"e": 3523,
"s": 3465,
"text": "We can change Bob to Maria in Firebase to get the update."
},
{
"code": null,
"e": 3602,
"s": 3523,
"text": "If we want to get access of deleted data, we can use child_removed event type."
},
{
"code": null,
"e": 3802,
"s": 3602,
"text": "var playersRef = firebase.database().ref(\"players/\");\n\nplayersRef.on(\"child_removed\", function(data) {\n var deletedPlayer = data.val();\n console.log(deletedPlayer.name + \" has been deleted\");\n});"
},
{
"code": null,
"e": 3863,
"s": 3802,
"text": "Now, we can delete Maria from Firebase to get notifications."
},
{
"code": null,
"e": 3896,
"s": 3863,
"text": "\n 60 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3913,
"s": 3896,
"text": " University Code"
},
{
"code": null,
"e": 3948,
"s": 3913,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3959,
"s": 3948,
"text": " Appeteria"
},
{
"code": null,
"e": 3995,
"s": 3959,
"text": "\n 85 Lectures \n 14.5 hours \n"
},
{
"code": null,
"e": 4006,
"s": 3995,
"text": " Appeteria"
},
{
"code": null,
"e": 4041,
"s": 4006,
"text": "\n 46 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4058,
"s": 4041,
"text": " Gautham Vijayan"
},
{
"code": null,
"e": 4093,
"s": 4058,
"text": "\n 13 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4108,
"s": 4093,
"text": " Nishant Kumar"
},
{
"code": null,
"e": 4144,
"s": 4108,
"text": "\n 85 Lectures \n 16.5 hours \n"
},
{
"code": null,
"e": 4159,
"s": 4144,
"text": " Rahul Agarwal"
},
{
"code": null,
"e": 4166,
"s": 4159,
"text": " Print"
},
{
"code": null,
"e": 4177,
"s": 4166,
"text": " Add Notes"
}
] |
Difference Between Identifier and Variable
|
In this post, we will understand the difference between an identifier and a variable.
All of them are not variables.
All of them are not variables.
They are used to name a variable, a function, a class, a structure, a union.
They are used to name a variable, a function, a class, a structure, a union.
It is created to give a unique name to an entity.
It is created to give a unique name to an entity.
They can consist of alphabets, digits, and underscores.
They can consist of alphabets, digits, and underscores.
There is no punctuation or special symbol, except the underscore.
There is no punctuation or special symbol, except the underscore.
It can be upper case or lower case.
It can be upper case or lower case.
It can start with lower case letter, upper case letter or an underscore.
It can start with lower case letter, upper case letter or an underscore.
It helps locate the name of the entity which is defined along with a keyword.
It helps locate the name of the entity which is defined along with a keyword.
enum geeks_artiles_in {Jan=1, Feb, Mar, Apr, May, June, July}
It is used to give a name to a memory location.
It is used to give a name to a memory location.
It holds a value.
It holds a value.
The names of variables are different.
The names of variables are different.
They help allot a unique name to a specific memory location.
They help allot a unique name to a specific memory location.
int a = 6;
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "In this post, we will understand the difference between an identifier and a variable."
},
{
"code": null,
"e": 1179,
"s": 1148,
"text": "All of them are not variables."
},
{
"code": null,
"e": 1210,
"s": 1179,
"text": "All of them are not variables."
},
{
"code": null,
"e": 1287,
"s": 1210,
"text": "They are used to name a variable, a function, a class, a structure, a union."
},
{
"code": null,
"e": 1364,
"s": 1287,
"text": "They are used to name a variable, a function, a class, a structure, a union."
},
{
"code": null,
"e": 1414,
"s": 1364,
"text": "It is created to give a unique name to an entity."
},
{
"code": null,
"e": 1464,
"s": 1414,
"text": "It is created to give a unique name to an entity."
},
{
"code": null,
"e": 1520,
"s": 1464,
"text": "They can consist of alphabets, digits, and underscores."
},
{
"code": null,
"e": 1576,
"s": 1520,
"text": "They can consist of alphabets, digits, and underscores."
},
{
"code": null,
"e": 1642,
"s": 1576,
"text": "There is no punctuation or special symbol, except the underscore."
},
{
"code": null,
"e": 1708,
"s": 1642,
"text": "There is no punctuation or special symbol, except the underscore."
},
{
"code": null,
"e": 1744,
"s": 1708,
"text": "It can be upper case or lower case."
},
{
"code": null,
"e": 1780,
"s": 1744,
"text": "It can be upper case or lower case."
},
{
"code": null,
"e": 1853,
"s": 1780,
"text": "It can start with lower case letter, upper case letter or an underscore."
},
{
"code": null,
"e": 1926,
"s": 1853,
"text": "It can start with lower case letter, upper case letter or an underscore."
},
{
"code": null,
"e": 2004,
"s": 1926,
"text": "It helps locate the name of the entity which is defined along with a keyword."
},
{
"code": null,
"e": 2082,
"s": 2004,
"text": "It helps locate the name of the entity which is defined along with a keyword."
},
{
"code": null,
"e": 2144,
"s": 2082,
"text": "enum geeks_artiles_in {Jan=1, Feb, Mar, Apr, May, June, July}"
},
{
"code": null,
"e": 2192,
"s": 2144,
"text": "It is used to give a name to a memory location."
},
{
"code": null,
"e": 2240,
"s": 2192,
"text": "It is used to give a name to a memory location."
},
{
"code": null,
"e": 2258,
"s": 2240,
"text": "It holds a value."
},
{
"code": null,
"e": 2276,
"s": 2258,
"text": "It holds a value."
},
{
"code": null,
"e": 2314,
"s": 2276,
"text": "The names of variables are different."
},
{
"code": null,
"e": 2352,
"s": 2314,
"text": "The names of variables are different."
},
{
"code": null,
"e": 2413,
"s": 2352,
"text": "They help allot a unique name to a specific memory location."
},
{
"code": null,
"e": 2474,
"s": 2413,
"text": "They help allot a unique name to a specific memory location."
},
{
"code": null,
"e": 2485,
"s": 2474,
"text": "int a = 6;"
}
] |
JavaScript String - match() Method
|
This method is used to retrieve the matches when matching a string against a regular expression.
Use the following syntax to use the match() method.
string.match( param )
param − A regular expression object.
If the regular expression does not include the g flag, it returns the same result as regexp.exec(string).
If the regular expression does not include the g flag, it returns the same result as regexp.exec(string).
If the regular expression includes the g flag, the method returns an Array containing all the matches.
If the regular expression includes the g flag, the method returns an Array containing all the matches.
Try the following example.
<html>
<head>
<title>JavaScript String match() Method</title>
</head>
<body>
<script type = "text/javascript">
var str = "For more information, see Chapter 3.4.5.1";
var re = /(chapter \d+(\.\d)*)/i;
var found = str.match( re );
document.write(found );
</script>
</body>
</html>
Chapter 3.4.5.1,Chapter 3.4.5.1,.1
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2563,
"s": 2466,
"text": "This method is used to retrieve the matches when matching a string against a regular expression."
},
{
"code": null,
"e": 2615,
"s": 2563,
"text": "Use the following syntax to use the match() method."
},
{
"code": null,
"e": 2638,
"s": 2615,
"text": "string.match( param )\n"
},
{
"code": null,
"e": 2675,
"s": 2638,
"text": "param − A regular expression object."
},
{
"code": null,
"e": 2781,
"s": 2675,
"text": "If the regular expression does not include the g flag, it returns the same result as regexp.exec(string)."
},
{
"code": null,
"e": 2887,
"s": 2781,
"text": "If the regular expression does not include the g flag, it returns the same result as regexp.exec(string)."
},
{
"code": null,
"e": 2990,
"s": 2887,
"text": "If the regular expression includes the g flag, the method returns an Array containing all the matches."
},
{
"code": null,
"e": 3093,
"s": 2990,
"text": "If the regular expression includes the g flag, the method returns an Array containing all the matches."
},
{
"code": null,
"e": 3120,
"s": 3093,
"text": "Try the following example."
},
{
"code": null,
"e": 3486,
"s": 3120,
"text": "<html>\n <head>\n <title>JavaScript String match() Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var str = \"For more information, see Chapter 3.4.5.1\";\n var re = /(chapter \\d+(\\.\\d)*)/i;\n var found = str.match( re ); \n document.write(found ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3522,
"s": 3486,
"text": "Chapter 3.4.5.1,Chapter 3.4.5.1,.1\n"
},
{
"code": null,
"e": 3557,
"s": 3522,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3571,
"s": 3557,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3605,
"s": 3571,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3619,
"s": 3605,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3654,
"s": 3619,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3671,
"s": 3654,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3706,
"s": 3671,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3723,
"s": 3706,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3756,
"s": 3723,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3784,
"s": 3756,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3818,
"s": 3784,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3846,
"s": 3818,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3853,
"s": 3846,
"text": " Print"
},
{
"code": null,
"e": 3864,
"s": 3853,
"text": " Add Notes"
}
] |
What is the difference between Func delegate and Action delegate in C#?
|
A delegate is a type that represents references to methods with a particular parameter list and return type. When we instantiate a delegate, we can associate its instance with any method with a compatible signature and return type. We can invoke (or call) the method through the delegate instance.
Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value.
Below is the Func delegate with two input and an output parameter.
Func<string, string, string > Append;
Live Demo
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
Func<string, string, string> func = Append;
string fullName = func("Michael", "Jackson");
Console.WriteLine(fullName);
Console.ReadLine();
}
static string Append(string firstName, string lastName) {
return firstName + lastName;
}
}
}
MichaelJackson
Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter.
Below is the Func delegate with two input and an output parameter.
Func<string, string,> Print;
using System;
namespace DemoApplication {
class Program {
static void Main(string[] args) {
Action func = AppendPrint;
func("Michael", "Jackson");
Console.ReadLine();
}
static void AppendPrint(string firstName, string lastName) {
string fullName = firstName + lastName;
Console.WriteLine($"{fullName}");
}
}
}
The output of the above code is
MichaelJackson
|
[
{
"code": null,
"e": 1360,
"s": 1062,
"text": "A delegate is a type that represents references to methods with a particular parameter list and return type. When we instantiate a delegate, we can associate its instance with any method with a compatible signature and return type. We can invoke (or call) the method through the delegate instance."
},
{
"code": null,
"e": 1623,
"s": 1360,
"text": "Func is a generic delegate included in the System namespace. It has zero or more input parameters and one out parameter. The last parameter is considered as an out parameter. This delegate can point to a method that takes up to 16 Parameters and returns a value."
},
{
"code": null,
"e": 1690,
"s": 1623,
"text": "Below is the Func delegate with two input and an output parameter."
},
{
"code": null,
"e": 1728,
"s": 1690,
"text": "Func<string, string, string > Append;"
},
{
"code": null,
"e": 1739,
"s": 1728,
"text": " Live Demo"
},
{
"code": null,
"e": 2140,
"s": 1739,
"text": "using System;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n Func<string, string, string> func = Append;\n string fullName = func(\"Michael\", \"Jackson\");\n Console.WriteLine(fullName);\n Console.ReadLine();\n }\n static string Append(string firstName, string lastName) {\n return firstName + lastName;\n }\n }\n}"
},
{
"code": null,
"e": 2155,
"s": 2140,
"text": "MichaelJackson"
},
{
"code": null,
"e": 2516,
"s": 2155,
"text": "Action is a delegate type defined in the System namespace. An Action type delegate is the same as Func delegate except that the Action delegate doesn't return a value. In other words, an Action delegate can be used with a method that has a void return type. It can contain minimum 1 and maximum of 16 input parameters and does not contain any output parameter."
},
{
"code": null,
"e": 2583,
"s": 2516,
"text": "Below is the Func delegate with two input and an output parameter."
},
{
"code": null,
"e": 2612,
"s": 2583,
"text": "Func<string, string,> Print;"
},
{
"code": null,
"e": 2997,
"s": 2612,
"text": "using System;\nnamespace DemoApplication {\n class Program {\n static void Main(string[] args) {\n Action func = AppendPrint;\n func(\"Michael\", \"Jackson\");\n Console.ReadLine();\n }\n static void AppendPrint(string firstName, string lastName) {\n string fullName = firstName + lastName;\n Console.WriteLine($\"{fullName}\");\n }\n }\n}"
},
{
"code": null,
"e": 3029,
"s": 2997,
"text": "The output of the above code is"
},
{
"code": null,
"e": 3044,
"s": 3029,
"text": "MichaelJackson"
}
] |
PHP | imagecreatefrombmp() Function - GeeksforGeeks
|
29 Jan, 2020
The imagecreatefrombmp() function is an inbuilt function in PHP which is used to create a new image from file or URL.
Syntax:
resource imagecreatefrombmp( string $filename )
Parameters: This function accepts a single parameter $filename which holds the name or URL of a file.
Return Value: This function returns an image resource identifier on success, FALSE on errors.
Below given programs illustrate the imagecreatefrombmp() function in PHP:
Program 1: Viewing a bmp file in browser.
<?php // Load the BMP image$im = imagecreatefrombmp('https://media.geeksforgeeks.org/wp-content/uploads/20200122193540/g4gbmp.bmp'); // Output the image to browserheader('Content-type: image/bmp'); imagebmp($im);imagedestroy($im);?>
Output:
Program 2: This program converting the bitmap into png.
<?php // Load the BMP image$im = imagecreatefrombmp('https://media.geeksforgeeks.org/wp-content/uploads/20200122193540/g4gbmp.bmp'); // Convert it to a PNG file, press Ctrl + S to save the new png imageheader('Content-type: image/png'); imagepng($im);imagedestroy($im);?>
Output:
Reference: https://www.php.net/manual/en/function.imagecreatefrombmp.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to fetch data from localserver database and display on HTML table using PHP ?
How to pass form variables from one page to other page in PHP ?
Create a drop-down list that options fetched from a MySQL database in PHP
How to create admin login page using PHP?
Different ways for passing data to view in Laravel
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24581,
"s": 24553,
"text": "\n29 Jan, 2020"
},
{
"code": null,
"e": 24699,
"s": 24581,
"text": "The imagecreatefrombmp() function is an inbuilt function in PHP which is used to create a new image from file or URL."
},
{
"code": null,
"e": 24707,
"s": 24699,
"text": "Syntax:"
},
{
"code": null,
"e": 24755,
"s": 24707,
"text": "resource imagecreatefrombmp( string $filename )"
},
{
"code": null,
"e": 24857,
"s": 24755,
"text": "Parameters: This function accepts a single parameter $filename which holds the name or URL of a file."
},
{
"code": null,
"e": 24951,
"s": 24857,
"text": "Return Value: This function returns an image resource identifier on success, FALSE on errors."
},
{
"code": null,
"e": 25025,
"s": 24951,
"text": "Below given programs illustrate the imagecreatefrombmp() function in PHP:"
},
{
"code": null,
"e": 25067,
"s": 25025,
"text": "Program 1: Viewing a bmp file in browser."
},
{
"code": "<?php // Load the BMP image$im = imagecreatefrombmp('https://media.geeksforgeeks.org/wp-content/uploads/20200122193540/g4gbmp.bmp'); // Output the image to browserheader('Content-type: image/bmp'); imagebmp($im);imagedestroy($im);?>",
"e": 25303,
"s": 25067,
"text": null
},
{
"code": null,
"e": 25311,
"s": 25303,
"text": "Output:"
},
{
"code": null,
"e": 25367,
"s": 25311,
"text": "Program 2: This program converting the bitmap into png."
},
{
"code": "<?php // Load the BMP image$im = imagecreatefrombmp('https://media.geeksforgeeks.org/wp-content/uploads/20200122193540/g4gbmp.bmp'); // Convert it to a PNG file, press Ctrl + S to save the new png imageheader('Content-type: image/png'); imagepng($im);imagedestroy($im);?>",
"e": 25642,
"s": 25367,
"text": null
},
{
"code": null,
"e": 25650,
"s": 25642,
"text": "Output:"
},
{
"code": null,
"e": 25723,
"s": 25650,
"text": "Reference: https://www.php.net/manual/en/function.imagecreatefrombmp.php"
},
{
"code": null,
"e": 25736,
"s": 25723,
"text": "PHP-function"
},
{
"code": null,
"e": 25740,
"s": 25736,
"text": "PHP"
},
{
"code": null,
"e": 25757,
"s": 25740,
"text": "Web Technologies"
},
{
"code": null,
"e": 25761,
"s": 25757,
"text": "PHP"
},
{
"code": null,
"e": 25859,
"s": 25761,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25868,
"s": 25859,
"text": "Comments"
},
{
"code": null,
"e": 25881,
"s": 25868,
"text": "Old Comments"
},
{
"code": null,
"e": 25963,
"s": 25881,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 26027,
"s": 25963,
"text": "How to pass form variables from one page to other page in PHP ?"
},
{
"code": null,
"e": 26101,
"s": 26027,
"text": "Create a drop-down list that options fetched from a MySQL database in PHP"
},
{
"code": null,
"e": 26143,
"s": 26101,
"text": "How to create admin login page using PHP?"
},
{
"code": null,
"e": 26194,
"s": 26143,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 26250,
"s": 26194,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26283,
"s": 26250,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26345,
"s": 26283,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26388,
"s": 26345,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Find Weekday using Zeller's Algorithm
|
Zeller’s Algorithm is used to find the weekday from a given date. The formula to find weekday using Zeller’s Algorithm is here:
The formula is containing some variables; They are −
d − The day of the date.
m: It is the month code. From March to December it is 3 to 12, for January it is 13, and for February it is 14. When we consider January or February, then given year will be decreased by 1.
y − Last two digits of the year
c − first two digits of the year
w − The weekday. When it is 0, it is Saturday, when it is 6, it means Friday
Input:
The day, month and the year: 4, 1, 1997
Output:
It was: Saturday
zellersAlgorithm(day, month, year)
Input: The date of the day.
Output: Which day it was, (Sunday to Saturday).
Begin
if month > 2, then
mon := month
else
mon := 12 + month
decrease year by 1
y := last two digit of the year
c := first two digit of the year
w := day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + 5*c
w := w mod 7
return weekday[w] //weekday will hold days from Saturday to Friday
End
#include<iostream>
#include<cmath>
using namespace std;
string weekday[7] = {"Saturday","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday"};
string zellersAlgorithm(int day, int month, int year) {
int mon;
if(month > 2)
mon = month; //for march to december month code is same as month
else {
mon = (12+month); //for Jan and Feb, month code will be 13 and 14
year--; //decrease year for month Jan and Feb
}
int y = year % 100; //last two digit
int c = year / 100; //first two digit
int w = (day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + (5*c));
w = w % 7;
return weekday[w];
}
int main() {
int day, month, year;
cout << "Enter Day: "; cin >>day;
cout << "Enter Month: "; cin >>month;
cout << "Enter Year: "; cin >>year;
cout << "It was: " <<zellersAlgorithm(day, month, year);
}
Enter Day: 04
Enter Month: 01
Enter Year: 1997
It was: Saturday
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "Zeller’s Algorithm is used to find the weekday from a given date. The formula to find weekday using Zeller’s Algorithm is here:"
},
{
"code": null,
"e": 1243,
"s": 1190,
"text": "The formula is containing some variables; They are −"
},
{
"code": null,
"e": 1268,
"s": 1243,
"text": "d − The day of the date."
},
{
"code": null,
"e": 1458,
"s": 1268,
"text": "m: It is the month code. From March to December it is 3 to 12, for January it is 13, and for February it is 14. When we consider January or February, then given year will be decreased by 1."
},
{
"code": null,
"e": 1490,
"s": 1458,
"text": "y − Last two digits of the year"
},
{
"code": null,
"e": 1523,
"s": 1490,
"text": "c − first two digits of the year"
},
{
"code": null,
"e": 1600,
"s": 1523,
"text": "w − The weekday. When it is 0, it is Saturday, when it is 6, it means Friday"
},
{
"code": null,
"e": 1672,
"s": 1600,
"text": "Input:\nThe day, month and the year: 4, 1, 1997\nOutput:\nIt was: Saturday"
},
{
"code": null,
"e": 1707,
"s": 1672,
"text": "zellersAlgorithm(day, month, year)"
},
{
"code": null,
"e": 1735,
"s": 1707,
"text": "Input: The date of the day."
},
{
"code": null,
"e": 1783,
"s": 1735,
"text": "Output: Which day it was, (Sunday to Saturday)."
},
{
"code": null,
"e": 2120,
"s": 1783,
"text": "Begin\n if month > 2, then\n mon := month\n else\n mon := 12 + month\n decrease year by 1\n y := last two digit of the year\n c := first two digit of the year\n w := day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + 5*c\n w := w mod 7\n return weekday[w] //weekday will hold days from Saturday to Friday\nEnd"
},
{
"code": null,
"e": 3037,
"s": 2120,
"text": "#include<iostream>\n#include<cmath>\nusing namespace std;\n\nstring weekday[7] = {\"Saturday\",\"Sunday\",\"Monday\",\"Tuesday\",\"Wednesday\",\"Thursday\",\"Friday\"};\n \nstring zellersAlgorithm(int day, int month, int year) {\n int mon;\n if(month > 2)\n mon = month; //for march to december month code is same as month\n else {\n mon = (12+month); //for Jan and Feb, month code will be 13 and 14\n year--; //decrease year for month Jan and Feb\n }\n \n int y = year % 100; //last two digit\n int c = year / 100; //first two digit\n int w = (day + floor((13*(mon+1))/5) + y + floor(y/4) + floor(c/4) + (5*c));\n w = w % 7;\n return weekday[w];\n}\n\nint main() {\n int day, month, year;\n cout << \"Enter Day: \"; cin >>day;\n cout << \"Enter Month: \"; cin >>month;\n cout << \"Enter Year: \"; cin >>year;\n cout << \"It was: \" <<zellersAlgorithm(day, month, year);\n}"
},
{
"code": null,
"e": 3101,
"s": 3037,
"text": "Enter Day: 04\nEnter Month: 01\nEnter Year: 1997\nIt was: Saturday"
}
] |
Feature Selection Techniques in Machine Learning with Python | by Rahil Shaikh | Towards Data Science
|
With the new day comes new strength and new thoughts — Eleanor Roosevelt
We all may have faced this problem of identifying the related features from a set of data and removing the irrelevant or less important features with do not contribute much to our target variable in order to achieve better accuracy for our model.
Feature Selection is one of the core concepts in machine learning which hugely impacts the performance of your model. The data features that you use to train your machine learning models have a huge influence on the performance you can achieve.
Irrelevant or partially relevant features can negatively impact model performance.
Feature selection and Data cleaning should be the first and most important step of your model designing.
In this post, you will discover feature selection techniques that you can use in Machine Learning.
Feature Selection is the process where you automatically or manually select those features which contribute most to your prediction variable or output in which you are interested in.
Having irrelevant features in your data can decrease the accuracy of the models and make your model learn based on irrelevant features.
How to select features and what are Benefits of performing feature selection before modeling your data?
· Reduces Overfitting: Less redundant data means less opportunity to make decisions based on noise.
· Improves Accuracy: Less misleading data means modeling accuracy improves.
· Reduces Training Time: fewer data points reduce algorithm complexity and algorithms train faster.
I want to share my personal experience with this.
I prepared a model by selecting all the features and I got an accuracy of around 65% which is not pretty good for a predictive model and after doing some feature selection and feature engineering without doing any logical changes in my model code my accuracy jumped to 81% which is quite impressive
Now you know why I say feature selection should be the first and most important step of your model design.
Feature Selection Methods:
I will share 3 Feature selection techniques that are easy to use and also gives good results.
1. Univariate Selection
2. Feature Importance
3.Correlation Matrix with Heatmap
Let’s have a look at these techniques one by one with an example
You can download the dataset from here https://www.kaggle.com/iabhishekofficial/mobile-price-classification#train.csv
Description of variables in the above file
battery_power: Total energy a battery can store in one time measured in mAh
blue: Has Bluetooth or not
clock_speed: the speed at which microprocessor executes instructions
dual_sim: Has dual sim support or not
fc: Front Camera megapixels
four_g: Has 4G or not
int_memory: Internal Memory in Gigabytes
m_dep: Mobile Depth in cm
mobile_wt: Weight of mobile phone
n_cores: Number of cores of the processor
pc: Primary Camera megapixels
px_height
Pixel Resolution Height
px_width: Pixel Resolution Width
ram: Random Access Memory in MegaBytes
sc_h: Screen Height of mobile in cm
sc_w: Screen Width of mobile in cm
talk_time: the longest time that a single battery charge will last when you are
three_g: Has 3G or not
touch_screen: Has touch screen or not
wifi: Has wifi or not
price_range: This is the target variable with a value of 0(low cost), 1(medium cost), 2(high cost) and 3(very high cost).
1. Univariate Selection
Statistical tests can be used to select those features that have the strongest relationship with the output variable.
The scikit-learn library provides the SelectKBest class that can be used with a suite of different statistical tests to select a specific number of features.
The example below uses the chi-squared (chi2) statistical test for non-negative features to select 10 of the best features from the Mobile Price Range Prediction Dataset.
import pandas as pdimport numpy as npfrom sklearn.feature_selection import SelectKBestfrom sklearn.feature_selection import chi2data = pd.read_csv("D://Blogs//train.csv")X = data.iloc[:,0:20] #independent columnsy = data.iloc[:,-1] #target column i.e price range#apply SelectKBest class to extract top 10 best featuresbestfeatures = SelectKBest(score_func=chi2, k=10)fit = bestfeatures.fit(X,y)dfscores = pd.DataFrame(fit.scores_)dfcolumns = pd.DataFrame(X.columns)#concat two dataframes for better visualization featureScores = pd.concat([dfcolumns,dfscores],axis=1)featureScores.columns = ['Specs','Score'] #naming the dataframe columnsprint(featureScores.nlargest(10,'Score')) #print 10 best features
You can get the feature importance of each feature of your dataset by using the feature importance property of the model.
Feature importance gives you a score for each feature of your data, the higher the score more important or relevant is the feature towards your output variable.
Feature importance is an inbuilt class that comes with Tree Based Classifiers, we will be using Extra Tree Classifier for extracting the top 10 features for the dataset.
import pandas as pdimport numpy as npdata = pd.read_csv("D://Blogs//train.csv")X = data.iloc[:,0:20] #independent columnsy = data.iloc[:,-1] #target column i.e price rangefrom sklearn.ensemble import ExtraTreesClassifierimport matplotlib.pyplot as pltmodel = ExtraTreesClassifier()model.fit(X,y)print(model.feature_importances_) #use inbuilt class feature_importances of tree based classifiers#plot graph of feature importances for better visualizationfeat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(10).plot(kind='barh')plt.show()
Correlation states how the features are related to each other or the target variable.
Correlation can be positive (increase in one value of feature increases the value of the target variable) or negative (increase in one value of feature decreases the value of the target variable)
Heatmap makes it easy to identify which features are most related to the target variable, we will plot heatmap of correlated features using the seaborn library.
import pandas as pdimport numpy as npimport seaborn as snsdata = pd.read_csv("D://Blogs//train.csv")X = data.iloc[:,0:20] #independent columnsy = data.iloc[:,-1] #target column i.e price range#get correlations of each features in datasetcorrmat = data.corr()top_corr_features = corrmat.indexplt.figure(figsize=(20,20))#plot heat mapg=sns.heatmap(data[top_corr_features].corr(),annot=True,cmap="RdYlGn")
Have a look at the last row i.e price range, see how the price range is correlated with other features, ram is the highly correlated with price range followed by battery power, pixel height and width while m_dep, clock_speed and n_cores seems to be least correlated with price_range.
In this article we have discovered how to select relevant features from data using Univariate Selection technique, feature importance and correlation matrix.
If you found this article useful give it a clap and share it with others.
— Thank You
|
[
{
"code": null,
"e": 245,
"s": 172,
"text": "With the new day comes new strength and new thoughts — Eleanor Roosevelt"
},
{
"code": null,
"e": 492,
"s": 245,
"text": "We all may have faced this problem of identifying the related features from a set of data and removing the irrelevant or less important features with do not contribute much to our target variable in order to achieve better accuracy for our model."
},
{
"code": null,
"e": 737,
"s": 492,
"text": "Feature Selection is one of the core concepts in machine learning which hugely impacts the performance of your model. The data features that you use to train your machine learning models have a huge influence on the performance you can achieve."
},
{
"code": null,
"e": 820,
"s": 737,
"text": "Irrelevant or partially relevant features can negatively impact model performance."
},
{
"code": null,
"e": 925,
"s": 820,
"text": "Feature selection and Data cleaning should be the first and most important step of your model designing."
},
{
"code": null,
"e": 1024,
"s": 925,
"text": "In this post, you will discover feature selection techniques that you can use in Machine Learning."
},
{
"code": null,
"e": 1207,
"s": 1024,
"text": "Feature Selection is the process where you automatically or manually select those features which contribute most to your prediction variable or output in which you are interested in."
},
{
"code": null,
"e": 1343,
"s": 1207,
"text": "Having irrelevant features in your data can decrease the accuracy of the models and make your model learn based on irrelevant features."
},
{
"code": null,
"e": 1447,
"s": 1343,
"text": "How to select features and what are Benefits of performing feature selection before modeling your data?"
},
{
"code": null,
"e": 1547,
"s": 1447,
"text": "· Reduces Overfitting: Less redundant data means less opportunity to make decisions based on noise."
},
{
"code": null,
"e": 1623,
"s": 1547,
"text": "· Improves Accuracy: Less misleading data means modeling accuracy improves."
},
{
"code": null,
"e": 1723,
"s": 1623,
"text": "· Reduces Training Time: fewer data points reduce algorithm complexity and algorithms train faster."
},
{
"code": null,
"e": 1773,
"s": 1723,
"text": "I want to share my personal experience with this."
},
{
"code": null,
"e": 2072,
"s": 1773,
"text": "I prepared a model by selecting all the features and I got an accuracy of around 65% which is not pretty good for a predictive model and after doing some feature selection and feature engineering without doing any logical changes in my model code my accuracy jumped to 81% which is quite impressive"
},
{
"code": null,
"e": 2179,
"s": 2072,
"text": "Now you know why I say feature selection should be the first and most important step of your model design."
},
{
"code": null,
"e": 2206,
"s": 2179,
"text": "Feature Selection Methods:"
},
{
"code": null,
"e": 2300,
"s": 2206,
"text": "I will share 3 Feature selection techniques that are easy to use and also gives good results."
},
{
"code": null,
"e": 2324,
"s": 2300,
"text": "1. Univariate Selection"
},
{
"code": null,
"e": 2346,
"s": 2324,
"text": "2. Feature Importance"
},
{
"code": null,
"e": 2380,
"s": 2346,
"text": "3.Correlation Matrix with Heatmap"
},
{
"code": null,
"e": 2445,
"s": 2380,
"text": "Let’s have a look at these techniques one by one with an example"
},
{
"code": null,
"e": 2563,
"s": 2445,
"text": "You can download the dataset from here https://www.kaggle.com/iabhishekofficial/mobile-price-classification#train.csv"
},
{
"code": null,
"e": 2606,
"s": 2563,
"text": "Description of variables in the above file"
},
{
"code": null,
"e": 2682,
"s": 2606,
"text": "battery_power: Total energy a battery can store in one time measured in mAh"
},
{
"code": null,
"e": 2709,
"s": 2682,
"text": "blue: Has Bluetooth or not"
},
{
"code": null,
"e": 2778,
"s": 2709,
"text": "clock_speed: the speed at which microprocessor executes instructions"
},
{
"code": null,
"e": 2816,
"s": 2778,
"text": "dual_sim: Has dual sim support or not"
},
{
"code": null,
"e": 2844,
"s": 2816,
"text": "fc: Front Camera megapixels"
},
{
"code": null,
"e": 2866,
"s": 2844,
"text": "four_g: Has 4G or not"
},
{
"code": null,
"e": 2907,
"s": 2866,
"text": "int_memory: Internal Memory in Gigabytes"
},
{
"code": null,
"e": 2933,
"s": 2907,
"text": "m_dep: Mobile Depth in cm"
},
{
"code": null,
"e": 2967,
"s": 2933,
"text": "mobile_wt: Weight of mobile phone"
},
{
"code": null,
"e": 3009,
"s": 2967,
"text": "n_cores: Number of cores of the processor"
},
{
"code": null,
"e": 3039,
"s": 3009,
"text": "pc: Primary Camera megapixels"
},
{
"code": null,
"e": 3049,
"s": 3039,
"text": "px_height"
},
{
"code": null,
"e": 3073,
"s": 3049,
"text": "Pixel Resolution Height"
},
{
"code": null,
"e": 3106,
"s": 3073,
"text": "px_width: Pixel Resolution Width"
},
{
"code": null,
"e": 3145,
"s": 3106,
"text": "ram: Random Access Memory in MegaBytes"
},
{
"code": null,
"e": 3181,
"s": 3145,
"text": "sc_h: Screen Height of mobile in cm"
},
{
"code": null,
"e": 3216,
"s": 3181,
"text": "sc_w: Screen Width of mobile in cm"
},
{
"code": null,
"e": 3296,
"s": 3216,
"text": "talk_time: the longest time that a single battery charge will last when you are"
},
{
"code": null,
"e": 3319,
"s": 3296,
"text": "three_g: Has 3G or not"
},
{
"code": null,
"e": 3357,
"s": 3319,
"text": "touch_screen: Has touch screen or not"
},
{
"code": null,
"e": 3379,
"s": 3357,
"text": "wifi: Has wifi or not"
},
{
"code": null,
"e": 3501,
"s": 3379,
"text": "price_range: This is the target variable with a value of 0(low cost), 1(medium cost), 2(high cost) and 3(very high cost)."
},
{
"code": null,
"e": 3525,
"s": 3501,
"text": "1. Univariate Selection"
},
{
"code": null,
"e": 3643,
"s": 3525,
"text": "Statistical tests can be used to select those features that have the strongest relationship with the output variable."
},
{
"code": null,
"e": 3801,
"s": 3643,
"text": "The scikit-learn library provides the SelectKBest class that can be used with a suite of different statistical tests to select a specific number of features."
},
{
"code": null,
"e": 3972,
"s": 3801,
"text": "The example below uses the chi-squared (chi2) statistical test for non-negative features to select 10 of the best features from the Mobile Price Range Prediction Dataset."
},
{
"code": null,
"e": 4682,
"s": 3972,
"text": "import pandas as pdimport numpy as npfrom sklearn.feature_selection import SelectKBestfrom sklearn.feature_selection import chi2data = pd.read_csv(\"D://Blogs//train.csv\")X = data.iloc[:,0:20] #independent columnsy = data.iloc[:,-1] #target column i.e price range#apply SelectKBest class to extract top 10 best featuresbestfeatures = SelectKBest(score_func=chi2, k=10)fit = bestfeatures.fit(X,y)dfscores = pd.DataFrame(fit.scores_)dfcolumns = pd.DataFrame(X.columns)#concat two dataframes for better visualization featureScores = pd.concat([dfcolumns,dfscores],axis=1)featureScores.columns = ['Specs','Score'] #naming the dataframe columnsprint(featureScores.nlargest(10,'Score')) #print 10 best features"
},
{
"code": null,
"e": 4804,
"s": 4682,
"text": "You can get the feature importance of each feature of your dataset by using the feature importance property of the model."
},
{
"code": null,
"e": 4965,
"s": 4804,
"text": "Feature importance gives you a score for each feature of your data, the higher the score more important or relevant is the feature towards your output variable."
},
{
"code": null,
"e": 5135,
"s": 4965,
"text": "Feature importance is an inbuilt class that comes with Tree Based Classifiers, we will be using Extra Tree Classifier for extracting the top 10 features for the dataset."
},
{
"code": null,
"e": 5722,
"s": 5135,
"text": "import pandas as pdimport numpy as npdata = pd.read_csv(\"D://Blogs//train.csv\")X = data.iloc[:,0:20] #independent columnsy = data.iloc[:,-1] #target column i.e price rangefrom sklearn.ensemble import ExtraTreesClassifierimport matplotlib.pyplot as pltmodel = ExtraTreesClassifier()model.fit(X,y)print(model.feature_importances_) #use inbuilt class feature_importances of tree based classifiers#plot graph of feature importances for better visualizationfeat_importances = pd.Series(model.feature_importances_, index=X.columns)feat_importances.nlargest(10).plot(kind='barh')plt.show()"
},
{
"code": null,
"e": 5808,
"s": 5722,
"text": "Correlation states how the features are related to each other or the target variable."
},
{
"code": null,
"e": 6004,
"s": 5808,
"text": "Correlation can be positive (increase in one value of feature increases the value of the target variable) or negative (increase in one value of feature decreases the value of the target variable)"
},
{
"code": null,
"e": 6165,
"s": 6004,
"text": "Heatmap makes it easy to identify which features are most related to the target variable, we will plot heatmap of correlated features using the seaborn library."
},
{
"code": null,
"e": 6572,
"s": 6165,
"text": "import pandas as pdimport numpy as npimport seaborn as snsdata = pd.read_csv(\"D://Blogs//train.csv\")X = data.iloc[:,0:20] #independent columnsy = data.iloc[:,-1] #target column i.e price range#get correlations of each features in datasetcorrmat = data.corr()top_corr_features = corrmat.indexplt.figure(figsize=(20,20))#plot heat mapg=sns.heatmap(data[top_corr_features].corr(),annot=True,cmap=\"RdYlGn\")"
},
{
"code": null,
"e": 6856,
"s": 6572,
"text": "Have a look at the last row i.e price range, see how the price range is correlated with other features, ram is the highly correlated with price range followed by battery power, pixel height and width while m_dep, clock_speed and n_cores seems to be least correlated with price_range."
},
{
"code": null,
"e": 7014,
"s": 6856,
"text": "In this article we have discovered how to select relevant features from data using Univariate Selection technique, feature importance and correlation matrix."
},
{
"code": null,
"e": 7088,
"s": 7014,
"text": "If you found this article useful give it a clap and share it with others."
}
] |
Python Grouping similar substrings in list
|
In this tutorial, we are going to write a program that groups similar substrings from a list. Let's see an example to understand it more clearly.
strings = ['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript', 'python-1', 'python-2',
'javascript-1']
[['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript'], ['python-1', 'python-2'],
['javascript-1']]
We are going to use the groupby method from itertools module to solve the problem. The groupby method will group all the similar string into an iter object. For the given list we have split the string with - and pass the first part of the string to the groupby method.
Let's see the steps involved in solving this problem.
Initialize the list of strings.
Import the itertools module.
Initialize an empty list.
Now, pass the strings and a lambda function to the itertools.groupby method.
The lambda function should return first part of the string after splitting it with −
The groupby method will return a list of the tuples with the element and its group.
In every iteration, convert the group of similar elements into a list.
Append the list to the empty list.
Print the result.
Live Demo
# importing the itertools module
import itertools
# initializing the strings
strings = ['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript', 'python-1', 'python-2', 'javascript-1']
# empty list
result = []
# iterator
# lambda function will return first part from the string
iterator = itertools.groupby(strings, lambda string: string.split('-')[0])
# iterating over the result
# element and its group
for element, group in iterator:
# appending the group by converting it into a list
result.append(list(group))
# printing the result
print(result)
If you run the above code, then you will get the following result.
[['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript'],
ython-1', 'python-2'], ['javascript-1']]
If you have any doubts in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1208,
"s": 1062,
"text": "In this tutorial, we are going to write a program that groups similar substrings from a list. Let's see an example to understand it more clearly."
},
{
"code": null,
"e": 1336,
"s": 1208,
"text": "strings = ['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript', 'python-1', 'python-2',\n'javascript-1']"
},
{
"code": null,
"e": 1460,
"s": 1336,
"text": "[['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript'], ['python-1', 'python-2'],\n['javascript-1']]"
},
{
"code": null,
"e": 1729,
"s": 1460,
"text": "We are going to use the groupby method from itertools module to solve the problem. The groupby method will group all the similar string into an iter object. For the given list we have split the string with - and pass the first part of the string to the groupby method."
},
{
"code": null,
"e": 1783,
"s": 1729,
"text": "Let's see the steps involved in solving this problem."
},
{
"code": null,
"e": 1815,
"s": 1783,
"text": "Initialize the list of strings."
},
{
"code": null,
"e": 1844,
"s": 1815,
"text": "Import the itertools module."
},
{
"code": null,
"e": 1870,
"s": 1844,
"text": "Initialize an empty list."
},
{
"code": null,
"e": 1947,
"s": 1870,
"text": "Now, pass the strings and a lambda function to the itertools.groupby method."
},
{
"code": null,
"e": 2032,
"s": 1947,
"text": "The lambda function should return first part of the string after splitting it with −"
},
{
"code": null,
"e": 2116,
"s": 2032,
"text": "The groupby method will return a list of the tuples with the element and its group."
},
{
"code": null,
"e": 2187,
"s": 2116,
"text": "In every iteration, convert the group of similar elements into a list."
},
{
"code": null,
"e": 2222,
"s": 2187,
"text": "Append the list to the empty list."
},
{
"code": null,
"e": 2240,
"s": 2222,
"text": "Print the result."
},
{
"code": null,
"e": 2251,
"s": 2240,
"text": " Live Demo"
},
{
"code": null,
"e": 2828,
"s": 2251,
"text": "# importing the itertools module\nimport itertools\n# initializing the strings\nstrings = ['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript', 'python-1', 'python-2', 'javascript-1']\n# empty list\nresult = []\n# iterator\n# lambda function will return first part from the string\niterator = itertools.groupby(strings, lambda string: string.split('-')[0])\n# iterating over the result\n# element and its group\nfor element, group in iterator:\n # appending the group by converting it into a list\n result.append(list(group))\n# printing the result\nprint(result)"
},
{
"code": null,
"e": 2895,
"s": 2828,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 3016,
"s": 2895,
"text": "[['tutorials-python', 'tutorials-c', 'tutorials-java', 'tutorials-javascript'],\nython-1', 'python-2'], ['javascript-1']]"
},
{
"code": null,
"e": 3093,
"s": 3016,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
] |
BetaBoosting. XGBoost with a Funky Learning Rate | by Tyler Blume | Towards Data Science
|
TLDR: Traditionally, Gradient Boosting implementations such as XGBoost have used a static learning rate. We propose using a function whose parameters can be passed to a standard hyperparameter tuning process to learn the ‘optimal’ learning rate shape.
All code lives here: BetaBoost Github
At this point, we all know of XGBoost due to the massive success it has had in numerous Data Science competitions held on platforms like Kaggle. Along with its success, we have seen several variations such as CatBoost and LightGBM. All of these implementations are based on the Gradient Boosting algorithm developed by Friedman1, which involves iteratively building an ensemble of weak learners (usually decision trees) where each subsequent learner is trained on the previous learner’s errors. Let’s take a look at some general pseudo-code for the algorithm from Elements of Statistical Learning2:
However, this is not complete! A core mechanism which allows boosting to work is a shrinkage parameter that penalizes each learner at each boosting round that is commonly called the ‘learning rate’. It’s main function is to prevent overfitting and it is a nice callback to the Gradient Descent algorithm which inspired many aspects of Gradient Boosting. To utilize a learning rate, Friedman altered 2.d to:
Now we are multiplying each new round’s learner by a constant. But what constant should we use? This is a common question that is typically handled with hyperparameter tuning and usually results in a constant such as .1 or .01. Some number well below 1 or, in other words, a number that heavily penalizes each round. With that small number we will not be utilizing each learner to it’s fullest extent.
When looking specifically at the learning rate parameter, a natural next question (although one that is typically inconsequential) is why use a constant? Gradient Descent has momentum strategies that allow the learning rate to change. Why can’t Gradient Boosting use a similar idea?
Well, we can...
...it just doesn’t work.
A quick Google search reveals that there has been some work done utilizing a decaying learning rate, one that starts out large and shrinks at each round. But we typically see no accuracy gains in Cross Validation and when looking at test error graphs there are minimal differences between its performance and using a regular old constant. The reasoning behind why a method like this doesn’t work appears to be a mystery. This leads us to a core theme that inspired BetaBoost:
More research should be done in this area.
In keeping with our theme, research was done and a function that appears to be promising has been found: the beta function (with some guardrails of course!). Or, more specifically, the beta probability distribution function. This function was initially found via brute force methods and once it provided encouraging results some semi-coherent rationale was dredged.
So, what is the beta PDF? As the name suggests it is a probability distribution described primarily by 2 parameters: α and β. In addition to these parameters, several more were added along with some further ‘guardrails’ which seem to help. For our purposes, we largely don’t care about any of the properties of the function as a probability density function, only it’s results with boosting.
A clear advantage that the Beta PDF has over many other functions is the sheer amount of shapes you can achieve with it3:
If we wanted to do something similar to exponential decay, or create a large spike in the middle, it is only one parameter change away. Which means if we hand the whole process over to a hyperparameter tuning package, such as Hyperopt, we can discover the learning rate shape which ‘best’ fits (or overfits!) our data. Although, we predominantly see one shape coming out on top.
Ultimately, I have no idea why any of this would provide any benefits, so:
More research should be done in this area.
This all brings us to BetaBoosting. This is not a new method of building a tree or proposing splits. It simply is assigning a different learning rate at each boosting round using callbacks in XGBoost’s Learning API. Our specific implementation assigns the learning rate based on the Beta PDf — thus we get the name ‘BetaBoosting’.
The code is pip installable for ease of use and requires xgboost==1.5:
pip install BetaBoost==0.0.5
As mentioned previously, a specific shape seemed to do better than others. A shape that had a large spike early on and, due to our guardrails, quickly went to a ‘floor’ parameter. Let’s take a look at BetaBoost using the class default parameters. This function passes the default parameters to the scipy Beta PDF function, along with some additional guardrails. Here is a simple standalone function along with the actual BetaBoost implementation:
def beta_pdf(scalar=1.5, a=26, b=1, scale=80, loc=-68, floor=0.01, n_boosting_rounds=100): """ Get the learning rate from the beta PDF Returns ------- lrs : list the resulting learning rates to use. """ lrs = [scalar*beta.pdf(i, a=a, b=b, scale=scale, loc=loc) + floor for i in range(n_boosting_rounds)] return lrs
For ease of use here is the same learning rates using the BetaBoost class:
from BetaBoost import BetaBoost as bbimport matplotlib.pyplot as pltbooster = bb.BetaBoost(n_boosting_rounds=100)plt.plot(booster.beta_kernel())plt.show()
Given that this shape does well, this suggests that taking the larger steps, not in the beginning or in the end, but in the ‘teenage years’ of the boosted tree’s development provides the most bang for our buck.
To further investigate, we can run this with simulated data and compare against other learning rates.
(The following example comes from a post years ago about using a decaying learning rate that I can not find, if anyone finds it let me know so I can cite the article!)
First we will do the imports and simulate some data:
import numpy as npimport xgboost as xgbimport matplotlib.pyplot as pltdef generate_data(): y = np.random.gamma(2, 4, OBS) X = np.random.normal(5, 2, [OBS, FEATURES]) return X, ymax_iter = 300eta_base = 0.2eta_min = 0.1eta_decay = np.linspace(eta_base, eta_min, max_iter).tolist()OBS = 10 ** 4FEATURES = 20PARAMS = { 'eta': eta_base, "booster": "gbtree",}X_train, y_train = generate_data()X_test, y_test = generate_data()dtrain = xgb.DMatrix(X_train, label=y_train)dtest = xgb.DMatrix(X_test, label=y_test)evals_result = {'train': dtrain}
Next, let’s use the decaying learning rate and save our results in a dictionary which we will eventually graph:
progress1 = dict()model1 = xgb.train( maximize=True, params=PARAMS, dtrain=dtrain, num_boost_round=max_iter, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=progress1, verbose_eval=False, callbacks=[xgb.callback.LearningRateScheduler(eta_decay)])
Now, a standard constant of 0.01:
progress2 = dict()model2 = xgb.train( maximize=True, params=PARAMS, dtrain=dtrain, num_boost_round=max_iter, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=progress2, verbose_eval=False, callbacks=[xgb.callback.LearningRateScheduler(list(np.ones(max_iter)*0.01))])
A constant of 0.1
progress3 = dict()model3 = xgb.train( maximize=True, params=PARAMS, dtrain=dtrain, num_boost_round=max_iter, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=progress3, verbose_eval=False, callbacks=[xgb.callback.LearningRateScheduler(list(np.ones(max_iter)*0.1))])
And finally, our BetaBoost where the fit method simply returns the same output as the train method in the XGBoost Learning API
#Here we call the BetaBoost, the wrapper parameters are passed in the class initbb_evals = dict()from BetaBoost import BetaBoost as bbbetabooster = bb.BetaBoost(n_boosting_rounds=max_iter)betabooster.fit(dtrain=dtrain, maximize=True, params=PARAMS, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=bb_evals, verbose_eval=False)
Let’s review the results on each round’s test accuracy:
plt.plot(progress1['test']['rmse'], linestyle = 'dashed', color = 'b', label = 'eta test decay')plt.plot(progress2['test']['rmse'], linestyle = 'dashed', color = 'r', label = '0.01 test')plt.plot(progress3['test']['rmse'], linestyle = 'dashed', color = 'black', label = '0.1 test')plt.plot(bb_evals['test']['rmse'], linestyle = 'dashed', color = 'y', label = 'bb test')plt.legend()plt.show()
Looking at the minimal test-set error, we see that the decaying learning rates actually hit the minimum the fastest, but it also is an unstable result as it quickly begins overfitting the test set. Next to hit its ‘kink’ is the betaboosted test set. Unlike the decay test set however, we can see that it continues to decrease in error slowly as it converges. Eventually around iteration 300 it meets up with the error rate corresponding to the constant 0.01 learning rate. So it appears that we are getting the best of both worlds here: we converge to a near-optimal test accuracy quite quickly and then we are resistant to overfitting. But, does it actually perform the best?
No.
The static 0.01 outperforms it slightly over the next 100 iterations. However, this isn’t always the case and we will see some 5 fold CV results where the optimized BetaBooster actually outperforms optimized vanilla XGBoost on real world data in the next article!
Gradient Boosting using a Beta density function as it’s learning rate appears to give us a quicker convergence and a robustness to overfitting. The cost of this is a few more parameters to tune. Additionally, the idea of tuning some function as the learning rate can be added to major boosting packages such as XGBoost and LightGBM quite quickly using their callback functionality. This seems like a low-hanging fruit in a field where we are currently squeezing water from rock.
Ultimately, BetaBoosting begs the question:
Is there a better function out there?
Our answer is...
More research should be done in this area.
References
Friedman, J. H. “Stochastic Gradient Boosting.” (March 1999)Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer.https://en.wikipedia.org/wiki/Beta_distribution
Friedman, J. H. “Stochastic Gradient Boosting.” (March 1999)
Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer.
|
[
{
"code": null,
"e": 424,
"s": 172,
"text": "TLDR: Traditionally, Gradient Boosting implementations such as XGBoost have used a static learning rate. We propose using a function whose parameters can be passed to a standard hyperparameter tuning process to learn the ‘optimal’ learning rate shape."
},
{
"code": null,
"e": 462,
"s": 424,
"text": "All code lives here: BetaBoost Github"
},
{
"code": null,
"e": 1061,
"s": 462,
"text": "At this point, we all know of XGBoost due to the massive success it has had in numerous Data Science competitions held on platforms like Kaggle. Along with its success, we have seen several variations such as CatBoost and LightGBM. All of these implementations are based on the Gradient Boosting algorithm developed by Friedman1, which involves iteratively building an ensemble of weak learners (usually decision trees) where each subsequent learner is trained on the previous learner’s errors. Let’s take a look at some general pseudo-code for the algorithm from Elements of Statistical Learning2:"
},
{
"code": null,
"e": 1468,
"s": 1061,
"text": "However, this is not complete! A core mechanism which allows boosting to work is a shrinkage parameter that penalizes each learner at each boosting round that is commonly called the ‘learning rate’. It’s main function is to prevent overfitting and it is a nice callback to the Gradient Descent algorithm which inspired many aspects of Gradient Boosting. To utilize a learning rate, Friedman altered 2.d to:"
},
{
"code": null,
"e": 1870,
"s": 1468,
"text": "Now we are multiplying each new round’s learner by a constant. But what constant should we use? This is a common question that is typically handled with hyperparameter tuning and usually results in a constant such as .1 or .01. Some number well below 1 or, in other words, a number that heavily penalizes each round. With that small number we will not be utilizing each learner to it’s fullest extent."
},
{
"code": null,
"e": 2153,
"s": 1870,
"text": "When looking specifically at the learning rate parameter, a natural next question (although one that is typically inconsequential) is why use a constant? Gradient Descent has momentum strategies that allow the learning rate to change. Why can’t Gradient Boosting use a similar idea?"
},
{
"code": null,
"e": 2169,
"s": 2153,
"text": "Well, we can..."
},
{
"code": null,
"e": 2194,
"s": 2169,
"text": "...it just doesn’t work."
},
{
"code": null,
"e": 2670,
"s": 2194,
"text": "A quick Google search reveals that there has been some work done utilizing a decaying learning rate, one that starts out large and shrinks at each round. But we typically see no accuracy gains in Cross Validation and when looking at test error graphs there are minimal differences between its performance and using a regular old constant. The reasoning behind why a method like this doesn’t work appears to be a mystery. This leads us to a core theme that inspired BetaBoost:"
},
{
"code": null,
"e": 2713,
"s": 2670,
"text": "More research should be done in this area."
},
{
"code": null,
"e": 3079,
"s": 2713,
"text": "In keeping with our theme, research was done and a function that appears to be promising has been found: the beta function (with some guardrails of course!). Or, more specifically, the beta probability distribution function. This function was initially found via brute force methods and once it provided encouraging results some semi-coherent rationale was dredged."
},
{
"code": null,
"e": 3471,
"s": 3079,
"text": "So, what is the beta PDF? As the name suggests it is a probability distribution described primarily by 2 parameters: α and β. In addition to these parameters, several more were added along with some further ‘guardrails’ which seem to help. For our purposes, we largely don’t care about any of the properties of the function as a probability density function, only it’s results with boosting."
},
{
"code": null,
"e": 3593,
"s": 3471,
"text": "A clear advantage that the Beta PDF has over many other functions is the sheer amount of shapes you can achieve with it3:"
},
{
"code": null,
"e": 3972,
"s": 3593,
"text": "If we wanted to do something similar to exponential decay, or create a large spike in the middle, it is only one parameter change away. Which means if we hand the whole process over to a hyperparameter tuning package, such as Hyperopt, we can discover the learning rate shape which ‘best’ fits (or overfits!) our data. Although, we predominantly see one shape coming out on top."
},
{
"code": null,
"e": 4047,
"s": 3972,
"text": "Ultimately, I have no idea why any of this would provide any benefits, so:"
},
{
"code": null,
"e": 4090,
"s": 4047,
"text": "More research should be done in this area."
},
{
"code": null,
"e": 4421,
"s": 4090,
"text": "This all brings us to BetaBoosting. This is not a new method of building a tree or proposing splits. It simply is assigning a different learning rate at each boosting round using callbacks in XGBoost’s Learning API. Our specific implementation assigns the learning rate based on the Beta PDf — thus we get the name ‘BetaBoosting’."
},
{
"code": null,
"e": 4492,
"s": 4421,
"text": "The code is pip installable for ease of use and requires xgboost==1.5:"
},
{
"code": null,
"e": 4521,
"s": 4492,
"text": "pip install BetaBoost==0.0.5"
},
{
"code": null,
"e": 4968,
"s": 4521,
"text": "As mentioned previously, a specific shape seemed to do better than others. A shape that had a large spike early on and, due to our guardrails, quickly went to a ‘floor’ parameter. Let’s take a look at BetaBoost using the class default parameters. This function passes the default parameters to the scipy Beta PDF function, along with some additional guardrails. Here is a simple standalone function along with the actual BetaBoost implementation:"
},
{
"code": null,
"e": 5504,
"s": 4968,
"text": "def beta_pdf(scalar=1.5, a=26, b=1, scale=80, loc=-68, floor=0.01, n_boosting_rounds=100): \"\"\" Get the learning rate from the beta PDF Returns ------- lrs : list the resulting learning rates to use. \"\"\" lrs = [scalar*beta.pdf(i, a=a, b=b, scale=scale, loc=loc) + floor for i in range(n_boosting_rounds)] return lrs"
},
{
"code": null,
"e": 5579,
"s": 5504,
"text": "For ease of use here is the same learning rates using the BetaBoost class:"
},
{
"code": null,
"e": 5734,
"s": 5579,
"text": "from BetaBoost import BetaBoost as bbimport matplotlib.pyplot as pltbooster = bb.BetaBoost(n_boosting_rounds=100)plt.plot(booster.beta_kernel())plt.show()"
},
{
"code": null,
"e": 5945,
"s": 5734,
"text": "Given that this shape does well, this suggests that taking the larger steps, not in the beginning or in the end, but in the ‘teenage years’ of the boosted tree’s development provides the most bang for our buck."
},
{
"code": null,
"e": 6047,
"s": 5945,
"text": "To further investigate, we can run this with simulated data and compare against other learning rates."
},
{
"code": null,
"e": 6215,
"s": 6047,
"text": "(The following example comes from a post years ago about using a decaying learning rate that I can not find, if anyone finds it let me know so I can cite the article!)"
},
{
"code": null,
"e": 6268,
"s": 6215,
"text": "First we will do the imports and simulate some data:"
},
{
"code": null,
"e": 6821,
"s": 6268,
"text": "import numpy as npimport xgboost as xgbimport matplotlib.pyplot as pltdef generate_data(): y = np.random.gamma(2, 4, OBS) X = np.random.normal(5, 2, [OBS, FEATURES]) return X, ymax_iter = 300eta_base = 0.2eta_min = 0.1eta_decay = np.linspace(eta_base, eta_min, max_iter).tolist()OBS = 10 ** 4FEATURES = 20PARAMS = { 'eta': eta_base, \"booster\": \"gbtree\",}X_train, y_train = generate_data()X_test, y_test = generate_data()dtrain = xgb.DMatrix(X_train, label=y_train)dtest = xgb.DMatrix(X_test, label=y_test)evals_result = {'train': dtrain}"
},
{
"code": null,
"e": 6933,
"s": 6821,
"text": "Next, let’s use the decaying learning rate and save our results in a dictionary which we will eventually graph:"
},
{
"code": null,
"e": 7247,
"s": 6933,
"text": "progress1 = dict()model1 = xgb.train( maximize=True, params=PARAMS, dtrain=dtrain, num_boost_round=max_iter, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=progress1, verbose_eval=False, callbacks=[xgb.callback.LearningRateScheduler(eta_decay)])"
},
{
"code": null,
"e": 7281,
"s": 7247,
"text": "Now, a standard constant of 0.01:"
},
{
"code": null,
"e": 7614,
"s": 7281,
"text": "progress2 = dict()model2 = xgb.train( maximize=True, params=PARAMS, dtrain=dtrain, num_boost_round=max_iter, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=progress2, verbose_eval=False, callbacks=[xgb.callback.LearningRateScheduler(list(np.ones(max_iter)*0.01))])"
},
{
"code": null,
"e": 7632,
"s": 7614,
"text": "A constant of 0.1"
},
{
"code": null,
"e": 7964,
"s": 7632,
"text": "progress3 = dict()model3 = xgb.train( maximize=True, params=PARAMS, dtrain=dtrain, num_boost_round=max_iter, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=progress3, verbose_eval=False, callbacks=[xgb.callback.LearningRateScheduler(list(np.ones(max_iter)*0.1))])"
},
{
"code": null,
"e": 8091,
"s": 7964,
"text": "And finally, our BetaBoost where the fit method simply returns the same output as the train method in the XGBoost Learning API"
},
{
"code": null,
"e": 8548,
"s": 8091,
"text": "#Here we call the BetaBoost, the wrapper parameters are passed in the class initbb_evals = dict()from BetaBoost import BetaBoost as bbbetabooster = bb.BetaBoost(n_boosting_rounds=max_iter)betabooster.fit(dtrain=dtrain, maximize=True, params=PARAMS, early_stopping_rounds=max_iter, evals=[(dtrain, 'train'),(dtest, 'test')], evals_result=bb_evals, verbose_eval=False)"
},
{
"code": null,
"e": 8604,
"s": 8548,
"text": "Let’s review the results on each round’s test accuracy:"
},
{
"code": null,
"e": 8996,
"s": 8604,
"text": "plt.plot(progress1['test']['rmse'], linestyle = 'dashed', color = 'b', label = 'eta test decay')plt.plot(progress2['test']['rmse'], linestyle = 'dashed', color = 'r', label = '0.01 test')plt.plot(progress3['test']['rmse'], linestyle = 'dashed', color = 'black', label = '0.1 test')plt.plot(bb_evals['test']['rmse'], linestyle = 'dashed', color = 'y', label = 'bb test')plt.legend()plt.show()"
},
{
"code": null,
"e": 9673,
"s": 8996,
"text": "Looking at the minimal test-set error, we see that the decaying learning rates actually hit the minimum the fastest, but it also is an unstable result as it quickly begins overfitting the test set. Next to hit its ‘kink’ is the betaboosted test set. Unlike the decay test set however, we can see that it continues to decrease in error slowly as it converges. Eventually around iteration 300 it meets up with the error rate corresponding to the constant 0.01 learning rate. So it appears that we are getting the best of both worlds here: we converge to a near-optimal test accuracy quite quickly and then we are resistant to overfitting. But, does it actually perform the best?"
},
{
"code": null,
"e": 9677,
"s": 9673,
"text": "No."
},
{
"code": null,
"e": 9941,
"s": 9677,
"text": "The static 0.01 outperforms it slightly over the next 100 iterations. However, this isn’t always the case and we will see some 5 fold CV results where the optimized BetaBooster actually outperforms optimized vanilla XGBoost on real world data in the next article!"
},
{
"code": null,
"e": 10420,
"s": 9941,
"text": "Gradient Boosting using a Beta density function as it’s learning rate appears to give us a quicker convergence and a robustness to overfitting. The cost of this is a few more parameters to tune. Additionally, the idea of tuning some function as the learning rate can be added to major boosting packages such as XGBoost and LightGBM quite quickly using their callback functionality. This seems like a low-hanging fruit in a field where we are currently squeezing water from rock."
},
{
"code": null,
"e": 10464,
"s": 10420,
"text": "Ultimately, BetaBoosting begs the question:"
},
{
"code": null,
"e": 10502,
"s": 10464,
"text": "Is there a better function out there?"
},
{
"code": null,
"e": 10519,
"s": 10502,
"text": "Our answer is..."
},
{
"code": null,
"e": 10562,
"s": 10519,
"text": "More research should be done in this area."
},
{
"code": null,
"e": 10573,
"s": 10562,
"text": "References"
},
{
"code": null,
"e": 10840,
"s": 10573,
"text": "Friedman, J. H. “Stochastic Gradient Boosting.” (March 1999)Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer.https://en.wikipedia.org/wiki/Beta_distribution"
},
{
"code": null,
"e": 10901,
"s": 10840,
"text": "Friedman, J. H. “Stochastic Gradient Boosting.” (March 1999)"
}
] |
Design Patterns | Set 2 (Factory Method) - GeeksforGeeks
|
07 Oct, 2021
Factory method is a creational design pattern, i.e., related to object creation. In Factory pattern, we create objects without exposing the creation logic to the client and the client uses the same common interface to create a new type of object.
The idea is to use a static member-function (static factory method) that creates & returns instances, hiding the details of class modules from the user.A factory pattern is one of the core design principles to create an object, allowing clients to create objects of a library(explained below) in a way such that it doesn’t have tight coupling with the class hierarchy of the library.
What is meant when we talk about libraries and clients? A library is something that is provided by some third party that exposes some public APIs and clients make calls to those public APIs to complete their tasks. A very simple example can be different kinds of Views provided by Android OS. Why factory pattern? Let us understand it with an example:
C
// A design without factory pattern#include <iostream>using namespace std; // Library classesclass Vehicle {public: virtual void printVehicle() = 0;};class TwoWheeler : public Vehicle {public: void printVehicle() { cout << "I am two wheeler" << endl; }};class FourWheeler : public Vehicle { public: void printVehicle() { cout << "I am four wheeler" << endl; }}; // Client (or user) classclass Client {public: Client(int type) { // Client explicitly creates classes according to type if (type == 1) pVehicle = new TwoWheeler(); else if (type == 2) pVehicle = new FourWheeler(); else pVehicle = NULL; } ~Client() { if (pVehicle) { delete[] pVehicle; pVehicle = NULL; } } Vehicle* getVehicle() { return pVehicle; }private: Vehicle *pVehicle;}; // Driver programint main() { Client *pClient = new Client(1); Vehicle * pVehicle = pClient->getVehicle(); pVehicle->printVehicle(); return 0;}
Output:
I am two wheeler
What are the problems with the above design? As you must have observed in the above example, the Client creates objects of either TwoWheeler or FourWheeler based on some input during constructing its object. Say, the library introduces a new class ThreeWheeler to incorporate three-wheeler vehicles also. What would happen? The client will end up chaining a new else if in the conditional ladder to create objects of ThreeWheeler. Which in turn will need the Client to be recompiled. So, each time a new change is made at the library side, the Client would need to make some corresponding changes at its end and recompile the code. Sounds bad? This is a very bad practice of design.
How to avoid the problem? The answer is, create a static (or factory) method. Let us see the below code.
C
// C++ program to demonstrate factory method design pattern#include <iostream>using namespace std; enum VehicleType { VT_TwoWheeler, VT_ThreeWheeler, VT_FourWheeler}; // Library classesclass Vehicle {public: virtual void printVehicle() = 0; static Vehicle* Create(VehicleType type);};class TwoWheeler : public Vehicle {public: void printVehicle() { cout << "I am two wheeler" << endl; }};class ThreeWheeler : public Vehicle {public: void printVehicle() { cout << "I am three wheeler" << endl; }};class FourWheeler : public Vehicle { public: void printVehicle() { cout << "I am four wheeler" << endl; }}; // Factory method to create objects of different types.// Change is required only in this function to create a new object typeVehicle* Vehicle::Create(VehicleType type) { if (type == VT_TwoWheeler) return new TwoWheeler(); else if (type == VT_ThreeWheeler) return new ThreeWheeler(); else if (type == VT_FourWheeler) return new FourWheeler(); else return NULL;} // Client classclass Client {public: // Client doesn't explicitly create objects // but passes type to factory method "Create()" Client() { VehicleType type = VT_ThreeWheeler; pVehicle = Vehicle::Create(type); } ~Client() { if (pVehicle) { delete[] pVehicle; pVehicle = NULL; } } Vehicle* getVehicle() { return pVehicle; } private: Vehicle *pVehicle;}; // Driver programint main() { Client *pClient = new Client(); Vehicle * pVehicle = pClient->getVehicle(); pVehicle->printVehicle(); return 0;}
Output:
I am three wheeler
In the above example, we have totally decoupled the selection of types for object creation from the Client. The library is now responsible to decide which object type to create based on an input. Client just needs to make calls to the library’s factory Create method and pass the type it wants without worrying about the actual implementation of the creation of objects.
Other examples of Factory Method:
Say, in a ‘Drawing’ system, depending on the user’s input, different pictures like square, rectangle, the circle can be drawn. Here we can use the factory method to create instances depending on the user’s input. For adding a new type of shape, no need to change the client’s code.Another example: On the travel site, we can book train tickets as well bus tickets and flight tickets. In this case, the user can give his travel type as ‘bus’, ‘train’, or ‘flight’. Here we have an abstract class ‘AnyTravel’ with a static member function ‘GetObject’ which depending on the user’s travel type, will create & return an object of ‘BusTravel’ or ‘ TrainTravel’. ‘BusTravel’ or ‘ TrainTravel’ have common functions like passenger name, Origin, destination parameters.
Say, in a ‘Drawing’ system, depending on the user’s input, different pictures like square, rectangle, the circle can be drawn. Here we can use the factory method to create instances depending on the user’s input. For adding a new type of shape, no need to change the client’s code.
Another example: On the travel site, we can book train tickets as well bus tickets and flight tickets. In this case, the user can give his travel type as ‘bus’, ‘train’, or ‘flight’. Here we have an abstract class ‘AnyTravel’ with a static member function ‘GetObject’ which depending on the user’s travel type, will create & return an object of ‘BusTravel’ or ‘ TrainTravel’. ‘BusTravel’ or ‘ TrainTravel’ have common functions like passenger name, Origin, destination parameters.
Further Read: Factory Method in PythonPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Pushpender007
dsudhakar07
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
SDE SHEET - A Complete Guide for SDE Preparation
Factory method design pattern in Java
Unified Modeling Language (UML) | An Introduction
MVC Design Pattern
Builder Design Pattern
Composite Design Pattern
Unified Modeling Language (UML) | State Diagrams
Unified Modeling Language (UML) | Activity Diagrams
Abstract Factory Pattern
How to design a parking lot using object-oriented principles?
|
[
{
"code": null,
"e": 24047,
"s": 24019,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 24295,
"s": 24047,
"text": "Factory method is a creational design pattern, i.e., related to object creation. In Factory pattern, we create objects without exposing the creation logic to the client and the client uses the same common interface to create a new type of object. "
},
{
"code": null,
"e": 24679,
"s": 24295,
"text": "The idea is to use a static member-function (static factory method) that creates & returns instances, hiding the details of class modules from the user.A factory pattern is one of the core design principles to create an object, allowing clients to create objects of a library(explained below) in a way such that it doesn’t have tight coupling with the class hierarchy of the library."
},
{
"code": null,
"e": 25034,
"s": 24679,
"text": "What is meant when we talk about libraries and clients? A library is something that is provided by some third party that exposes some public APIs and clients make calls to those public APIs to complete their tasks. A very simple example can be different kinds of Views provided by Android OS. Why factory pattern? Let us understand it with an example: "
},
{
"code": null,
"e": 25036,
"s": 25034,
"text": "C"
},
{
"code": "// A design without factory pattern#include <iostream>using namespace std; // Library classesclass Vehicle {public: virtual void printVehicle() = 0;};class TwoWheeler : public Vehicle {public: void printVehicle() { cout << \"I am two wheeler\" << endl; }};class FourWheeler : public Vehicle { public: void printVehicle() { cout << \"I am four wheeler\" << endl; }}; // Client (or user) classclass Client {public: Client(int type) { // Client explicitly creates classes according to type if (type == 1) pVehicle = new TwoWheeler(); else if (type == 2) pVehicle = new FourWheeler(); else pVehicle = NULL; } ~Client() { if (pVehicle) { delete[] pVehicle; pVehicle = NULL; } } Vehicle* getVehicle() { return pVehicle; }private: Vehicle *pVehicle;}; // Driver programint main() { Client *pClient = new Client(1); Vehicle * pVehicle = pClient->getVehicle(); pVehicle->printVehicle(); return 0;}",
"e": 26105,
"s": 25036,
"text": null
},
{
"code": null,
"e": 26114,
"s": 26105,
"text": "Output: "
},
{
"code": null,
"e": 26131,
"s": 26114,
"text": "I am two wheeler"
},
{
"code": null,
"e": 26814,
"s": 26131,
"text": "What are the problems with the above design? As you must have observed in the above example, the Client creates objects of either TwoWheeler or FourWheeler based on some input during constructing its object. Say, the library introduces a new class ThreeWheeler to incorporate three-wheeler vehicles also. What would happen? The client will end up chaining a new else if in the conditional ladder to create objects of ThreeWheeler. Which in turn will need the Client to be recompiled. So, each time a new change is made at the library side, the Client would need to make some corresponding changes at its end and recompile the code. Sounds bad? This is a very bad practice of design."
},
{
"code": null,
"e": 26920,
"s": 26814,
"text": "How to avoid the problem? The answer is, create a static (or factory) method. Let us see the below code. "
},
{
"code": null,
"e": 26922,
"s": 26920,
"text": "C"
},
{
"code": "// C++ program to demonstrate factory method design pattern#include <iostream>using namespace std; enum VehicleType { VT_TwoWheeler, VT_ThreeWheeler, VT_FourWheeler}; // Library classesclass Vehicle {public: virtual void printVehicle() = 0; static Vehicle* Create(VehicleType type);};class TwoWheeler : public Vehicle {public: void printVehicle() { cout << \"I am two wheeler\" << endl; }};class ThreeWheeler : public Vehicle {public: void printVehicle() { cout << \"I am three wheeler\" << endl; }};class FourWheeler : public Vehicle { public: void printVehicle() { cout << \"I am four wheeler\" << endl; }}; // Factory method to create objects of different types.// Change is required only in this function to create a new object typeVehicle* Vehicle::Create(VehicleType type) { if (type == VT_TwoWheeler) return new TwoWheeler(); else if (type == VT_ThreeWheeler) return new ThreeWheeler(); else if (type == VT_FourWheeler) return new FourWheeler(); else return NULL;} // Client classclass Client {public: // Client doesn't explicitly create objects // but passes type to factory method \"Create()\" Client() { VehicleType type = VT_ThreeWheeler; pVehicle = Vehicle::Create(type); } ~Client() { if (pVehicle) { delete[] pVehicle; pVehicle = NULL; } } Vehicle* getVehicle() { return pVehicle; } private: Vehicle *pVehicle;}; // Driver programint main() { Client *pClient = new Client(); Vehicle * pVehicle = pClient->getVehicle(); pVehicle->printVehicle(); return 0;}",
"e": 28575,
"s": 26922,
"text": null
},
{
"code": null,
"e": 28584,
"s": 28575,
"text": "Output: "
},
{
"code": null,
"e": 28603,
"s": 28584,
"text": "I am three wheeler"
},
{
"code": null,
"e": 28974,
"s": 28603,
"text": "In the above example, we have totally decoupled the selection of types for object creation from the Client. The library is now responsible to decide which object type to create based on an input. Client just needs to make calls to the library’s factory Create method and pass the type it wants without worrying about the actual implementation of the creation of objects."
},
{
"code": null,
"e": 29009,
"s": 28974,
"text": "Other examples of Factory Method: "
},
{
"code": null,
"e": 29771,
"s": 29009,
"text": "Say, in a ‘Drawing’ system, depending on the user’s input, different pictures like square, rectangle, the circle can be drawn. Here we can use the factory method to create instances depending on the user’s input. For adding a new type of shape, no need to change the client’s code.Another example: On the travel site, we can book train tickets as well bus tickets and flight tickets. In this case, the user can give his travel type as ‘bus’, ‘train’, or ‘flight’. Here we have an abstract class ‘AnyTravel’ with a static member function ‘GetObject’ which depending on the user’s travel type, will create & return an object of ‘BusTravel’ or ‘ TrainTravel’. ‘BusTravel’ or ‘ TrainTravel’ have common functions like passenger name, Origin, destination parameters."
},
{
"code": null,
"e": 30053,
"s": 29771,
"text": "Say, in a ‘Drawing’ system, depending on the user’s input, different pictures like square, rectangle, the circle can be drawn. Here we can use the factory method to create instances depending on the user’s input. For adding a new type of shape, no need to change the client’s code."
},
{
"code": null,
"e": 30534,
"s": 30053,
"text": "Another example: On the travel site, we can book train tickets as well bus tickets and flight tickets. In this case, the user can give his travel type as ‘bus’, ‘train’, or ‘flight’. Here we have an abstract class ‘AnyTravel’ with a static member function ‘GetObject’ which depending on the user’s travel type, will create & return an object of ‘BusTravel’ or ‘ TrainTravel’. ‘BusTravel’ or ‘ TrainTravel’ have common functions like passenger name, Origin, destination parameters."
},
{
"code": null,
"e": 30697,
"s": 30534,
"text": "Further Read: Factory Method in PythonPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30711,
"s": 30697,
"text": "Pushpender007"
},
{
"code": null,
"e": 30723,
"s": 30711,
"text": "dsudhakar07"
},
{
"code": null,
"e": 30738,
"s": 30723,
"text": "Design Pattern"
},
{
"code": null,
"e": 30836,
"s": 30738,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30845,
"s": 30836,
"text": "Comments"
},
{
"code": null,
"e": 30858,
"s": 30845,
"text": "Old Comments"
},
{
"code": null,
"e": 30907,
"s": 30858,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 30945,
"s": 30907,
"text": "Factory method design pattern in Java"
},
{
"code": null,
"e": 30995,
"s": 30945,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 31014,
"s": 30995,
"text": "MVC Design Pattern"
},
{
"code": null,
"e": 31037,
"s": 31014,
"text": "Builder Design Pattern"
},
{
"code": null,
"e": 31062,
"s": 31037,
"text": "Composite Design Pattern"
},
{
"code": null,
"e": 31111,
"s": 31062,
"text": "Unified Modeling Language (UML) | State Diagrams"
},
{
"code": null,
"e": 31163,
"s": 31111,
"text": "Unified Modeling Language (UML) | Activity Diagrams"
},
{
"code": null,
"e": 31188,
"s": 31163,
"text": "Abstract Factory Pattern"
}
] |
Calculate the Mean of each Row of an Object in R Programming – rowMeans() Function - GeeksforGeeks
|
05 Jun, 2020
rowMeans() function in R Language is used to find out the mean of each row of a data frame, matrix, or array.
Syntax: rowMeans(data)
Parameter:data: data frame, array, or matrix
Example 1
# R program to illustrate # rowMean function # Create example values # Set seedset.seed(1234) # Create example data data <- data.frame(matrix(round(runif(12, 2, 20)), nrow = 4, ncol = 3)) # Print dataprint(rowMeans(data))
Output:
[1] 11.666667 12.666667 9.666667 10.333333
Example 2:
# R program to illustrate # rowMean function # Create example data with NAdata_na <- data.frame(matrix(round(runif(12, 2, 20)), nrow = 4, ncol = 3)) data_na[rbinom(length(data_na), 1, 0.3) == 1] <- NAdata_na <- as.data.frame(data_na) print(rowMeans(data_na, na.rm = TRUE))
Output:
[1] 3 16 9 3
R DataFrame-Function
R Math-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Loops in R (for, while, repeat)
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
How to change Row Names of DataFrame in R ?
Change Color of Bars in Barchart using ggplot2 in R
Data Visualization in R
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
Logistic Regression in R Programming
|
[
{
"code": null,
"e": 24992,
"s": 24964,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 25102,
"s": 24992,
"text": "rowMeans() function in R Language is used to find out the mean of each row of a data frame, matrix, or array."
},
{
"code": null,
"e": 25125,
"s": 25102,
"text": "Syntax: rowMeans(data)"
},
{
"code": null,
"e": 25170,
"s": 25125,
"text": "Parameter:data: data frame, array, or matrix"
},
{
"code": null,
"e": 25180,
"s": 25170,
"text": "Example 1"
},
{
"code": "# R program to illustrate # rowMean function # Create example values # Set seedset.seed(1234) # Create example data data <- data.frame(matrix(round(runif(12, 2, 20)), nrow = 4, ncol = 3)) # Print dataprint(rowMeans(data)) ",
"e": 25518,
"s": 25180,
"text": null
},
{
"code": null,
"e": 25526,
"s": 25518,
"text": "Output:"
},
{
"code": null,
"e": 25570,
"s": 25526,
"text": "[1] 11.666667 12.666667 9.666667 10.333333"
},
{
"code": null,
"e": 25581,
"s": 25570,
"text": "Example 2:"
},
{
"code": "# R program to illustrate # rowMean function # Create example data with NAdata_na <- data.frame(matrix(round(runif(12, 2, 20)), nrow = 4, ncol = 3)) data_na[rbinom(length(data_na), 1, 0.3) == 1] <- NAdata_na <- as.data.frame(data_na) print(rowMeans(data_na, na.rm = TRUE)) ",
"e": 25925,
"s": 25581,
"text": null
},
{
"code": null,
"e": 25933,
"s": 25925,
"text": "Output:"
},
{
"code": null,
"e": 25949,
"s": 25933,
"text": "[1] 3 16 9 3"
},
{
"code": null,
"e": 25970,
"s": 25949,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 25986,
"s": 25970,
"text": "R Math-Function"
},
{
"code": null,
"e": 26004,
"s": 25986,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 26022,
"s": 26004,
"text": "R Object-Function"
},
{
"code": null,
"e": 26040,
"s": 26022,
"text": "R Vector-Function"
},
{
"code": null,
"e": 26051,
"s": 26040,
"text": "R Language"
},
{
"code": null,
"e": 26149,
"s": 26051,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26158,
"s": 26149,
"text": "Comments"
},
{
"code": null,
"e": 26171,
"s": 26158,
"text": "Old Comments"
},
{
"code": null,
"e": 26203,
"s": 26171,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26261,
"s": 26203,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26313,
"s": 26261,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26357,
"s": 26313,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26409,
"s": 26357,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26433,
"s": 26409,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 26465,
"s": 26433,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 26503,
"s": 26465,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26538,
"s": 26503,
"text": "Group by function in R using Dplyr"
}
] |
Bayesian A/B Testing in PyMC3 | by Dr. Robert Kübler | Towards Data Science
|
From time to time, you have to choose between two options. This might be in completely uninformed situations where you can pick the better option with a mere probability of 50%. In some of these uninformed cases, you can even boost this probability with a simple trick, as demonstrated in my other article.
However, usually, you are able to gather some information that helps you pick the better option with high probability. One easy, yet smart method to do this is A/B testing that you have probably heard of or even used already.
In this article, I will briefly explain the motivation behind A/B testing and outline the logic behind it. The problem with this approach is that it uses p-values that are easy to misinterpret.
Thus, we will take our time to refine this approach with a pinch of Bayesian magic, yielding Bayesian A/B testing. To top it off, we will implement a simple Bayesian A/B test using the wonderful PyMC3 library in Python.
If you are not entirely sure what Bayesian statistics are or you have never used PyMC3 before, check out my entry-level articles about this topic:
A gentle Introduction to Bayesian Inference (introduction)
Beginner-friendly Bayesian Inference (a simple problem solved via Bayes without programming)
Conducting Bayesian Inference in Python using PyMC3 (the aforementioned simple problem solved via Bayes in PyMC3)
Imagine that you operate a moderately successful online store with around 10,000 visitors every day. Around 100 of these 10,000 people actually buy something from your shop — your so-called conversion rate is about 100/10,000 = 1%, which is rather small.
Most online shops achieve conversion rates of around 1–3%, Amazon more than 10% even.
Since many people reach your shop anyway, yet only an underwhelming percentage of them become customers, you conclude to increase your shop’s conversion rate as this is the biggest lever for higher revenues. You think:
What keeps people from buying my awesome products?
You can’t come up with a good explanation, so you ask some friends for inspiration. They tell you that they no fans of the color blue of your buy button. Perhaps a red would be more inviting? This is something you can test!
The method is the following:
Randomly assign new visitors to your shop to either team blue or team red with a 50% probability. People in team blue will see the blue button, team red the red one. After running this process for some time, you check which team achieved a higher conversion rate.
Terminology: You call the blue team control group and the red team treatment group or test group. The control group gives you an indication of what happens if you leave everything as is, the treatment group tells you what happens if you do some kind of intervention, such as changing the button color.
Note that this kind of randomization is important if you want to evaluate the experiment easily. Things that you should not do include:
Assigning all men to team red, all women to team blue, because even if one team’s conversion rate is much higher, you cannot know if this is due to the button color or merely the gender.
Assign everyone to team red this week and to team blue the next week, because even if one team’s conversion rate is much higher, you cannot know if this is due to the button color or if people just bought more stuff in one week, regardless of the color. Maybe one of the weeks included holidays like Black Friday or Christmas, or other, more subtle seasonal patterns.
...
You get the idea. In order to distill the button color effect, there should be no other confounding effects that could explain the different conversion rates in both teams as well.
Let’s assume that you conducted a proper data collection for your A/B test for one day and ended up with some data. You had exactly 10,000 visitors which you randomly grouped into team blue (control group) and red (treatment group). You took notes about if this visitor bought something (encoded as 1) or not (encoded as 0).
We simulate the outcome using this code:
import numpy as npnp.random.seed(0)blue_conversions = np.random.binomial(1, 0.01, size=4800)red_conversions = np.random.binomial(1, 0.012, size=5200)
You can see that I put 1% as the control group conversion rate and 1.2% as the treatment group conversion rate. So you already know that the red button should perform better if the sampling did nothing too weird! But let us pretend from now that we do not know how the data was generated because that is what we always face in reality.
Also, note that the groups have different sizes, which usually happens with random assignments. They are around 10,000/2=5,000, but it’s unlikely to get such a perfect 50:50 split. This is fine, however.
Both NumPy arrays consist of ones and zeroes, with most of the entries being zero.
print(blue_conversions)# output: [0 0 0 ... 0 0 0]print(red_conversions)# output: [0 0 0 ... 0 0 0]
The next thing we can check is the share of ones (i.e. the visitors who bought something) is.
print(f'Blue: {blue_conversions.mean():.3%}')print(f'Red: {red_conversions.mean():.3%}')# output: Blue: 0.854%, Red: 1.135%
This indicates that the red button might perform better, but we can’t really know at this point. Even if the conversion rates across the different groups were exactly the same, one group would end up with more conversions than the other one with a high probability.
We still have to rule out that this happened only due to mere chance and this is exactly what an A/B test is for.
Let us now see how we can come up with a better explanation of what is going on. Is the blue or the red button better? At first, we will reproduce the traditional way, and afterward, we will do it Bayesian style.
I will not go into depth here because there are plenty of resources that perfectly explain how to conduct a normal A/B test. You want to know which of the two following hypotheses are true:
Basically, you compute some kind of test statistics such as in Fisher’s exact test or Welch’s t-test. Then you compute a p-value and check if this is under some arbitrary bound such as 5%. Let’s go for Welch’s t-test.
from scipy.stats import ttest_indprint(f'p-value: {ttest_ind(blue_conversions, red_conversions, equal_var=False, alternative="less").pvalue:.1%}')# output: p-value: 7.8%
Because some people struggle with p-values, here is how you can read it:
Given that H0 is true, the chance that we get our observed or an even more extreme outcome is at most 7.8%.
Since 7.8% > 5%, we keep the null hypothesis. It’s not evident that the red button is significantly better, so we just leave the blue button.
I think that the definition of a p-value is rather unintuitive — and everyone who ever misinterpreted p-values proves this. The most common misinterpretation is the following:
The probability that blue is better is 7.8%. (WRONG!!!)
While this is not what a p-value tells you, being able to formulate such a clear and short statement is desirable, isn’t it? Well then, Bayes to the rescue.
Bayesian A/B testing has the following advantages:
It enables you to make statements about one version being better than the other one with a certain probability. Just what we want.You don’t have to know all the statistical tests. You can just make up a proper generative model and press the Bayesian Inference ButtonTM.
It enables you to make statements about one version being better than the other one with a certain probability. Just what we want.
You don’t have to know all the statistical tests. You can just make up a proper generative model and press the Bayesian Inference ButtonTM.
I assume that you have some prior knowledge about using PyMC3 now, otherwise, check my linked article above.
To make these advantages more clear, let’s analyze our problem the Bayesian way with the help of PyMC3. First, we need to think about which parameters we want to infer. This is easy, there are two unknown parameters:
the conversion rate of the blue button and
the conversion rate of the red button.
We now need to decide for a prior distribution for both parameters. As conversion rates can be between 0 and 1, a Beta distribution makes sense. Beta distributions have two parameters a and b, and you can create diverse distributions by varying them.
Because we know that the conversion rates are rather small, good priors for both of them are Beta(1, 99), for example.
Now, we have to model how the outcomes that we observed (arrays containing zeroes and ones) are connected to these parameters. The straightforward way is to use Bernoulli variables, as they can take only the values 0 and 1 and use a single probability parameter.
Long story short, we can write the following short program:
import pymc3 as pmwith pm.Model(): blue_rate = pm.Beta('blue_rate', 1, 99) red_rate = pm.Beta('red_rate', 1, 99) blue_obs = pm.Bernoulli('blue_obs', blue_rate, observed=blue_conversions) red_obs = pm.Bernoulli('red_obs', red_rate, observed=red_conversions) trace = pm.sample(return_inferencedata=True)
Together with the explanations, the program should make sense to you. In the top first two lines of the model, we define the priors. Afterwards we design the output of the model (Bernoulli variables) and additionally give it the observations from our A/B test preparation using the observed parameter. The last line is the PyMC3 version of the famous Bayesian Inference ButtonTM.
With the help of thetrace object you can reconstruct the posterior distributions of the conversion rates.
import arviz as azaz.plot_posterior(trace)
We find something close to our maximum likelihood estimated conversion rates of around 0.854% for blue and around 1.135% for red, and even a credible interval for these estimates. For example, the blue rate is between 0.62% and 1.1% with a 94% probability.
Neat, right? But this does not answer our question. What is the probability that the conversion rate of the red button is higher than the one of the blue button? To answer this, we can just sample both posterior distributions and see, how often the red rate is higher than the blue rate. Luckily, the samples are stored within the trace object already. We just have to see how often the red rate samples are larger than the blue rate samples.
blue_rate_samples = trace.posterior['blue_rate'].valuesred_rate_samples = trace.posterior['red_rate'].valuesprint(f'Probability that red is better: {(red_rate_samples > blue_rate_samples).mean():.1%}.')# output (for me): Probability that red is better: 91.7%.
This is something we can work with! It’s easy for us, but also everyone else — I’m especially looking to the business department — to understand. The red button is better with a probability of around 92%?
“Perfect!”, you think and the red version in your shop, hoping that it will increase your conversion rate.
And now imagine: This is only a tiny change that has the potential to increase your sales. There are probably various other smaller and larger things you can tinker with that leave your shop better off. The game has just begun.
There are many circumstances in which we have to choose between two options. This can simply be the color of a button, but also the position of an object on the website, the text on a button or image, anything that could potentially be changed.
One way to choose between two versions is by running an A/B test. The idea is simple: You group your customers into two groups that only differ in this very thing you want to change, i.e. a button color. This way you can be sure that only the thing you changed caused a change in the outcome, and nothing else. Not the age or gender of people, not the weekday when you collected the data.
Usually, people use a classical A/B test using p-values. While this is a familiar concept for statisticians, normal people often get confused statements involving p-values. That’s why we turned to Bayesian A/B testing, which allows for results that everyone can easily grasp. In the end, we could even formulate such a result using PyMC3 without much code.
I hope that you learned something new, interesting, and useful today. Thanks for reading!
As the last point, if you
want to support me in writing more about machine learning andplan to get a Medium subscription anyway,
want to support me in writing more about machine learning and
plan to get a Medium subscription anyway,
why not do it via this link? This would help me a lot! 😊
To be transparent, the price for you does not change, but about half of the subscription fees go directly to me.
Thanks a lot, if you consider supporting me!
If you have any questions, write me on LinkedIn!
|
[
{
"code": null,
"e": 479,
"s": 172,
"text": "From time to time, you have to choose between two options. This might be in completely uninformed situations where you can pick the better option with a mere probability of 50%. In some of these uninformed cases, you can even boost this probability with a simple trick, as demonstrated in my other article."
},
{
"code": null,
"e": 705,
"s": 479,
"text": "However, usually, you are able to gather some information that helps you pick the better option with high probability. One easy, yet smart method to do this is A/B testing that you have probably heard of or even used already."
},
{
"code": null,
"e": 899,
"s": 705,
"text": "In this article, I will briefly explain the motivation behind A/B testing and outline the logic behind it. The problem with this approach is that it uses p-values that are easy to misinterpret."
},
{
"code": null,
"e": 1119,
"s": 899,
"text": "Thus, we will take our time to refine this approach with a pinch of Bayesian magic, yielding Bayesian A/B testing. To top it off, we will implement a simple Bayesian A/B test using the wonderful PyMC3 library in Python."
},
{
"code": null,
"e": 1266,
"s": 1119,
"text": "If you are not entirely sure what Bayesian statistics are or you have never used PyMC3 before, check out my entry-level articles about this topic:"
},
{
"code": null,
"e": 1325,
"s": 1266,
"text": "A gentle Introduction to Bayesian Inference (introduction)"
},
{
"code": null,
"e": 1418,
"s": 1325,
"text": "Beginner-friendly Bayesian Inference (a simple problem solved via Bayes without programming)"
},
{
"code": null,
"e": 1532,
"s": 1418,
"text": "Conducting Bayesian Inference in Python using PyMC3 (the aforementioned simple problem solved via Bayes in PyMC3)"
},
{
"code": null,
"e": 1787,
"s": 1532,
"text": "Imagine that you operate a moderately successful online store with around 10,000 visitors every day. Around 100 of these 10,000 people actually buy something from your shop — your so-called conversion rate is about 100/10,000 = 1%, which is rather small."
},
{
"code": null,
"e": 1873,
"s": 1787,
"text": "Most online shops achieve conversion rates of around 1–3%, Amazon more than 10% even."
},
{
"code": null,
"e": 2092,
"s": 1873,
"text": "Since many people reach your shop anyway, yet only an underwhelming percentage of them become customers, you conclude to increase your shop’s conversion rate as this is the biggest lever for higher revenues. You think:"
},
{
"code": null,
"e": 2143,
"s": 2092,
"text": "What keeps people from buying my awesome products?"
},
{
"code": null,
"e": 2367,
"s": 2143,
"text": "You can’t come up with a good explanation, so you ask some friends for inspiration. They tell you that they no fans of the color blue of your buy button. Perhaps a red would be more inviting? This is something you can test!"
},
{
"code": null,
"e": 2396,
"s": 2367,
"text": "The method is the following:"
},
{
"code": null,
"e": 2660,
"s": 2396,
"text": "Randomly assign new visitors to your shop to either team blue or team red with a 50% probability. People in team blue will see the blue button, team red the red one. After running this process for some time, you check which team achieved a higher conversion rate."
},
{
"code": null,
"e": 2962,
"s": 2660,
"text": "Terminology: You call the blue team control group and the red team treatment group or test group. The control group gives you an indication of what happens if you leave everything as is, the treatment group tells you what happens if you do some kind of intervention, such as changing the button color."
},
{
"code": null,
"e": 3098,
"s": 2962,
"text": "Note that this kind of randomization is important if you want to evaluate the experiment easily. Things that you should not do include:"
},
{
"code": null,
"e": 3285,
"s": 3098,
"text": "Assigning all men to team red, all women to team blue, because even if one team’s conversion rate is much higher, you cannot know if this is due to the button color or merely the gender."
},
{
"code": null,
"e": 3653,
"s": 3285,
"text": "Assign everyone to team red this week and to team blue the next week, because even if one team’s conversion rate is much higher, you cannot know if this is due to the button color or if people just bought more stuff in one week, regardless of the color. Maybe one of the weeks included holidays like Black Friday or Christmas, or other, more subtle seasonal patterns."
},
{
"code": null,
"e": 3657,
"s": 3653,
"text": "..."
},
{
"code": null,
"e": 3838,
"s": 3657,
"text": "You get the idea. In order to distill the button color effect, there should be no other confounding effects that could explain the different conversion rates in both teams as well."
},
{
"code": null,
"e": 4163,
"s": 3838,
"text": "Let’s assume that you conducted a proper data collection for your A/B test for one day and ended up with some data. You had exactly 10,000 visitors which you randomly grouped into team blue (control group) and red (treatment group). You took notes about if this visitor bought something (encoded as 1) or not (encoded as 0)."
},
{
"code": null,
"e": 4204,
"s": 4163,
"text": "We simulate the outcome using this code:"
},
{
"code": null,
"e": 4354,
"s": 4204,
"text": "import numpy as npnp.random.seed(0)blue_conversions = np.random.binomial(1, 0.01, size=4800)red_conversions = np.random.binomial(1, 0.012, size=5200)"
},
{
"code": null,
"e": 4690,
"s": 4354,
"text": "You can see that I put 1% as the control group conversion rate and 1.2% as the treatment group conversion rate. So you already know that the red button should perform better if the sampling did nothing too weird! But let us pretend from now that we do not know how the data was generated because that is what we always face in reality."
},
{
"code": null,
"e": 4894,
"s": 4690,
"text": "Also, note that the groups have different sizes, which usually happens with random assignments. They are around 10,000/2=5,000, but it’s unlikely to get such a perfect 50:50 split. This is fine, however."
},
{
"code": null,
"e": 4977,
"s": 4894,
"text": "Both NumPy arrays consist of ones and zeroes, with most of the entries being zero."
},
{
"code": null,
"e": 5077,
"s": 4977,
"text": "print(blue_conversions)# output: [0 0 0 ... 0 0 0]print(red_conversions)# output: [0 0 0 ... 0 0 0]"
},
{
"code": null,
"e": 5171,
"s": 5077,
"text": "The next thing we can check is the share of ones (i.e. the visitors who bought something) is."
},
{
"code": null,
"e": 5295,
"s": 5171,
"text": "print(f'Blue: {blue_conversions.mean():.3%}')print(f'Red: {red_conversions.mean():.3%}')# output: Blue: 0.854%, Red: 1.135%"
},
{
"code": null,
"e": 5561,
"s": 5295,
"text": "This indicates that the red button might perform better, but we can’t really know at this point. Even if the conversion rates across the different groups were exactly the same, one group would end up with more conversions than the other one with a high probability."
},
{
"code": null,
"e": 5675,
"s": 5561,
"text": "We still have to rule out that this happened only due to mere chance and this is exactly what an A/B test is for."
},
{
"code": null,
"e": 5888,
"s": 5675,
"text": "Let us now see how we can come up with a better explanation of what is going on. Is the blue or the red button better? At first, we will reproduce the traditional way, and afterward, we will do it Bayesian style."
},
{
"code": null,
"e": 6078,
"s": 5888,
"text": "I will not go into depth here because there are plenty of resources that perfectly explain how to conduct a normal A/B test. You want to know which of the two following hypotheses are true:"
},
{
"code": null,
"e": 6296,
"s": 6078,
"text": "Basically, you compute some kind of test statistics such as in Fisher’s exact test or Welch’s t-test. Then you compute a p-value and check if this is under some arbitrary bound such as 5%. Let’s go for Welch’s t-test."
},
{
"code": null,
"e": 6466,
"s": 6296,
"text": "from scipy.stats import ttest_indprint(f'p-value: {ttest_ind(blue_conversions, red_conversions, equal_var=False, alternative=\"less\").pvalue:.1%}')# output: p-value: 7.8%"
},
{
"code": null,
"e": 6539,
"s": 6466,
"text": "Because some people struggle with p-values, here is how you can read it:"
},
{
"code": null,
"e": 6647,
"s": 6539,
"text": "Given that H0 is true, the chance that we get our observed or an even more extreme outcome is at most 7.8%."
},
{
"code": null,
"e": 6789,
"s": 6647,
"text": "Since 7.8% > 5%, we keep the null hypothesis. It’s not evident that the red button is significantly better, so we just leave the blue button."
},
{
"code": null,
"e": 6965,
"s": 6789,
"text": "I think that the definition of a p-value is rather unintuitive — and everyone who ever misinterpreted p-values proves this. The most common misinterpretation is the following:"
},
{
"code": null,
"e": 7021,
"s": 6965,
"text": "The probability that blue is better is 7.8%. (WRONG!!!)"
},
{
"code": null,
"e": 7178,
"s": 7021,
"text": "While this is not what a p-value tells you, being able to formulate such a clear and short statement is desirable, isn’t it? Well then, Bayes to the rescue."
},
{
"code": null,
"e": 7229,
"s": 7178,
"text": "Bayesian A/B testing has the following advantages:"
},
{
"code": null,
"e": 7499,
"s": 7229,
"text": "It enables you to make statements about one version being better than the other one with a certain probability. Just what we want.You don’t have to know all the statistical tests. You can just make up a proper generative model and press the Bayesian Inference ButtonTM."
},
{
"code": null,
"e": 7630,
"s": 7499,
"text": "It enables you to make statements about one version being better than the other one with a certain probability. Just what we want."
},
{
"code": null,
"e": 7770,
"s": 7630,
"text": "You don’t have to know all the statistical tests. You can just make up a proper generative model and press the Bayesian Inference ButtonTM."
},
{
"code": null,
"e": 7879,
"s": 7770,
"text": "I assume that you have some prior knowledge about using PyMC3 now, otherwise, check my linked article above."
},
{
"code": null,
"e": 8096,
"s": 7879,
"text": "To make these advantages more clear, let’s analyze our problem the Bayesian way with the help of PyMC3. First, we need to think about which parameters we want to infer. This is easy, there are two unknown parameters:"
},
{
"code": null,
"e": 8139,
"s": 8096,
"text": "the conversion rate of the blue button and"
},
{
"code": null,
"e": 8178,
"s": 8139,
"text": "the conversion rate of the red button."
},
{
"code": null,
"e": 8429,
"s": 8178,
"text": "We now need to decide for a prior distribution for both parameters. As conversion rates can be between 0 and 1, a Beta distribution makes sense. Beta distributions have two parameters a and b, and you can create diverse distributions by varying them."
},
{
"code": null,
"e": 8548,
"s": 8429,
"text": "Because we know that the conversion rates are rather small, good priors for both of them are Beta(1, 99), for example."
},
{
"code": null,
"e": 8811,
"s": 8548,
"text": "Now, we have to model how the outcomes that we observed (arrays containing zeroes and ones) are connected to these parameters. The straightforward way is to use Bernoulli variables, as they can take only the values 0 and 1 and use a single probability parameter."
},
{
"code": null,
"e": 8871,
"s": 8811,
"text": "Long story short, we can write the following short program:"
},
{
"code": null,
"e": 9196,
"s": 8871,
"text": "import pymc3 as pmwith pm.Model(): blue_rate = pm.Beta('blue_rate', 1, 99) red_rate = pm.Beta('red_rate', 1, 99) blue_obs = pm.Bernoulli('blue_obs', blue_rate, observed=blue_conversions) red_obs = pm.Bernoulli('red_obs', red_rate, observed=red_conversions) trace = pm.sample(return_inferencedata=True)"
},
{
"code": null,
"e": 9576,
"s": 9196,
"text": "Together with the explanations, the program should make sense to you. In the top first two lines of the model, we define the priors. Afterwards we design the output of the model (Bernoulli variables) and additionally give it the observations from our A/B test preparation using the observed parameter. The last line is the PyMC3 version of the famous Bayesian Inference ButtonTM."
},
{
"code": null,
"e": 9682,
"s": 9576,
"text": "With the help of thetrace object you can reconstruct the posterior distributions of the conversion rates."
},
{
"code": null,
"e": 9725,
"s": 9682,
"text": "import arviz as azaz.plot_posterior(trace)"
},
{
"code": null,
"e": 9982,
"s": 9725,
"text": "We find something close to our maximum likelihood estimated conversion rates of around 0.854% for blue and around 1.135% for red, and even a credible interval for these estimates. For example, the blue rate is between 0.62% and 1.1% with a 94% probability."
},
{
"code": null,
"e": 10425,
"s": 9982,
"text": "Neat, right? But this does not answer our question. What is the probability that the conversion rate of the red button is higher than the one of the blue button? To answer this, we can just sample both posterior distributions and see, how often the red rate is higher than the blue rate. Luckily, the samples are stored within the trace object already. We just have to see how often the red rate samples are larger than the blue rate samples."
},
{
"code": null,
"e": 10685,
"s": 10425,
"text": "blue_rate_samples = trace.posterior['blue_rate'].valuesred_rate_samples = trace.posterior['red_rate'].valuesprint(f'Probability that red is better: {(red_rate_samples > blue_rate_samples).mean():.1%}.')# output (for me): Probability that red is better: 91.7%."
},
{
"code": null,
"e": 10890,
"s": 10685,
"text": "This is something we can work with! It’s easy for us, but also everyone else — I’m especially looking to the business department — to understand. The red button is better with a probability of around 92%?"
},
{
"code": null,
"e": 10997,
"s": 10890,
"text": "“Perfect!”, you think and the red version in your shop, hoping that it will increase your conversion rate."
},
{
"code": null,
"e": 11225,
"s": 10997,
"text": "And now imagine: This is only a tiny change that has the potential to increase your sales. There are probably various other smaller and larger things you can tinker with that leave your shop better off. The game has just begun."
},
{
"code": null,
"e": 11470,
"s": 11225,
"text": "There are many circumstances in which we have to choose between two options. This can simply be the color of a button, but also the position of an object on the website, the text on a button or image, anything that could potentially be changed."
},
{
"code": null,
"e": 11859,
"s": 11470,
"text": "One way to choose between two versions is by running an A/B test. The idea is simple: You group your customers into two groups that only differ in this very thing you want to change, i.e. a button color. This way you can be sure that only the thing you changed caused a change in the outcome, and nothing else. Not the age or gender of people, not the weekday when you collected the data."
},
{
"code": null,
"e": 12216,
"s": 11859,
"text": "Usually, people use a classical A/B test using p-values. While this is a familiar concept for statisticians, normal people often get confused statements involving p-values. That’s why we turned to Bayesian A/B testing, which allows for results that everyone can easily grasp. In the end, we could even formulate such a result using PyMC3 without much code."
},
{
"code": null,
"e": 12306,
"s": 12216,
"text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!"
},
{
"code": null,
"e": 12332,
"s": 12306,
"text": "As the last point, if you"
},
{
"code": null,
"e": 12435,
"s": 12332,
"text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway,"
},
{
"code": null,
"e": 12497,
"s": 12435,
"text": "want to support me in writing more about machine learning and"
},
{
"code": null,
"e": 12539,
"s": 12497,
"text": "plan to get a Medium subscription anyway,"
},
{
"code": null,
"e": 12596,
"s": 12539,
"text": "why not do it via this link? This would help me a lot! 😊"
},
{
"code": null,
"e": 12709,
"s": 12596,
"text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me."
},
{
"code": null,
"e": 12754,
"s": 12709,
"text": "Thanks a lot, if you consider supporting me!"
}
] |
Byte Code in Java - GeeksforGeeks
|
19 Oct, 2021
Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source code(JAVA Program). This intermediate code makes Java a platform-independent language.
Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual Machine). The byte code is the common piece between the compiler(which creates it) and the Interpreter (which runs it).
Let us look at this phenomenon, step by step
Suppose you are writing your first JAVA program.
Java
/*package whatever //do not write package name here */import java.io.*; class GFG { public static void main (String[] args) { System.out.println("GFG!"); }}
GFG!
The above-written code is called JAVA source code.
The compiler compiles the source code.
Finally, Interpreter executes the compiled source code.
Whenever we write any program, it is not written in machine code. We write it in a high-level language like JAVA, C++, Python, etc. But the computer understands only the machine code. So when we execute our program, it is first converted into machine code or Byte code by the compiler and then executed by the Interpreter.
This intermediate code or the byte can run on any platform making, JAVA a platform-independent language.
Picked
TrueGeek-2021
Java
TrueGeek
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Exceptions in Java
Constructors in Java
Different ways of Reading a text file in Java
Functional Interfaces in Java
How to redirect to another page in ReactJS ?
How to remove duplicate elements from JavaScript Array ?
Basics of API Testing Using Postman
SQL Statement to Remove Part of a String
Types of Internet Protocols
|
[
{
"code": null,
"e": 24090,
"s": 24062,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 24284,
"s": 24090,
"text": "Byte Code can be defined as an intermediate code generated by the compiler after the compilation of source code(JAVA Program). This intermediate code makes Java a platform-independent language."
},
{
"code": null,
"e": 24615,
"s": 24284,
"text": "Compiler converts the source code or the Java program into the Byte Code(or machine code), and secondly, the Interpreter executes the byte code on the system. The Interpreter can also be called JVM(Java Virtual Machine). The byte code is the common piece between the compiler(which creates it) and the Interpreter (which runs it)."
},
{
"code": null,
"e": 24660,
"s": 24615,
"text": "Let us look at this phenomenon, step by step"
},
{
"code": null,
"e": 24709,
"s": 24660,
"text": "Suppose you are writing your first JAVA program."
},
{
"code": null,
"e": 24714,
"s": 24709,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */import java.io.*; class GFG { public static void main (String[] args) { System.out.println(\"GFG!\"); }}",
"e": 24885,
"s": 24714,
"text": null
},
{
"code": null,
"e": 24891,
"s": 24885,
"text": "GFG!\n"
},
{
"code": null,
"e": 24942,
"s": 24891,
"text": "The above-written code is called JAVA source code."
},
{
"code": null,
"e": 24981,
"s": 24942,
"text": "The compiler compiles the source code."
},
{
"code": null,
"e": 25037,
"s": 24981,
"text": "Finally, Interpreter executes the compiled source code."
},
{
"code": null,
"e": 25361,
"s": 25037,
"text": "Whenever we write any program, it is not written in machine code. We write it in a high-level language like JAVA, C++, Python, etc. But the computer understands only the machine code. So when we execute our program, it is first converted into machine code or Byte code by the compiler and then executed by the Interpreter. "
},
{
"code": null,
"e": 25466,
"s": 25361,
"text": "This intermediate code or the byte can run on any platform making, JAVA a platform-independent language."
},
{
"code": null,
"e": 25473,
"s": 25466,
"text": "Picked"
},
{
"code": null,
"e": 25487,
"s": 25473,
"text": "TrueGeek-2021"
},
{
"code": null,
"e": 25492,
"s": 25487,
"text": "Java"
},
{
"code": null,
"e": 25501,
"s": 25492,
"text": "TrueGeek"
},
{
"code": null,
"e": 25506,
"s": 25501,
"text": "Java"
},
{
"code": null,
"e": 25604,
"s": 25506,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25619,
"s": 25604,
"text": "Stream In Java"
},
{
"code": null,
"e": 25638,
"s": 25619,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 25659,
"s": 25638,
"text": "Constructors in Java"
},
{
"code": null,
"e": 25705,
"s": 25659,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 25735,
"s": 25705,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 25780,
"s": 25735,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 25837,
"s": 25780,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 25873,
"s": 25837,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 25914,
"s": 25873,
"text": "SQL Statement to Remove Part of a String"
}
] |
D3.js - Dragging API
|
Drag and drop is one of the most familiar concept in d3.js. This chapter explains dragging and its methods in detail.
We can directly include dragging API using the following script.
<script src = "https://d3js.org/d3-dispatch.v1.min.js"></script>
<script src = "https://d3js.org/d3-selection.v1.min.js"></script>
<script src = "https://d3js.org/d3-drag.v1.min.js"></script>
Following are some of the most important dragging API methods in D3.js.
d3.drag()
drag(selection)
drag.container([container])
drag.filter([filter])
drag.subject([subject])
drag.clickDistance([distance])
drag.on(typenames, [listener])
d3.dragDisable(window)
d3.dragEnable(window[, noclick])
Let us now understand each of these in detail.
This method is used to create a new dragging. You can call this method using the following script.
<script>
var drag = d3.drag();
</script>
This method is used to apply the dragging to the specified selection. You can invoke this function using selection.call. A simple example is defined below.
d3.select(".node").call(d3.drag().on("drag", mousemove));
Here, the drag behavior applied to the selected elements is via selection.call.
drag.container([container])
It is used to set the container to the specified function for dragging. If a container is not specified, it returns the current accessor. To drag any graphical elements with a Canvas, you can redefine the container as itself. It is defined below.
function container() {
return this;
}
It is used to set the filter for the specified function. If the filter is not specified, it returns the current filter as defined below.
function filter() {
return !d3.event.button;
}
It is used to set the subject to the specified function for dragging and is defined below.
function subject(d) {
return d = = null ? {x: d3.event.x, y: d3.event.y} : d;
}
Here, the subject represents the thing being dragged. For example, if you want to drag rectangle elements in SVG, the default subject is datum of the rectangle being dragged.
This method is used to set the maximum distance for clicking a mousedown and mouseup event. If distance is not specified, it points to zero.
This method is used to set the event listener for the specified typenames for dragging. The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, optionally followed by a period (.) and a name, such as drag.one and drag.two. This type should be from one of the following −
start − starts a new pointer.
start − starts a new pointer.
drag − drags an active pointer.
drag − drags an active pointer.
end − Inactive an active pointer.
end − Inactive an active pointer.
This method is used to disable the drag and drop selection. It prevents mousedown event action. Most of the selected browsers supports this action by default. If not supported, you can set the CSS property to none.
This method is used to enable the drag and drop selection on the specified window location. It is used to call mouseup event action. If you assign the noclick value is true then click event expires a zero millisecond timeout.
The D3.event method is used to set the drag event. It consists of the following fields −
Target − It represents the drag behavior.
Target − It represents the drag behavior.
Type − It is a string and can be any one of the following– “start”, “drag” or “end”.
Type − It is a string and can be any one of the following– “start”, “drag” or “end”.
Subject − The drag subject, defined by drag.subject.
Subject − The drag subject, defined by drag.subject.
The event object exposes the event.on method to perform dragging. It is defined as follows.
d3.event.on("drag", dragged).on("end", ended);
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2248,
"s": 2130,
"text": "Drag and drop is one of the most familiar concept in d3.js. This chapter explains dragging and its methods in detail."
},
{
"code": null,
"e": 2313,
"s": 2248,
"text": "We can directly include dragging API using the following script."
},
{
"code": null,
"e": 2505,
"s": 2313,
"text": "<script src = \"https://d3js.org/d3-dispatch.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-selection.v1.min.js\"></script>\n<script src = \"https://d3js.org/d3-drag.v1.min.js\"></script>"
},
{
"code": null,
"e": 2577,
"s": 2505,
"text": "Following are some of the most important dragging API methods in D3.js."
},
{
"code": null,
"e": 2587,
"s": 2577,
"text": "d3.drag()"
},
{
"code": null,
"e": 2603,
"s": 2587,
"text": "drag(selection)"
},
{
"code": null,
"e": 2631,
"s": 2603,
"text": "drag.container([container])"
},
{
"code": null,
"e": 2653,
"s": 2631,
"text": "drag.filter([filter])"
},
{
"code": null,
"e": 2677,
"s": 2653,
"text": "drag.subject([subject])"
},
{
"code": null,
"e": 2708,
"s": 2677,
"text": "drag.clickDistance([distance])"
},
{
"code": null,
"e": 2739,
"s": 2708,
"text": "drag.on(typenames, [listener])"
},
{
"code": null,
"e": 2762,
"s": 2739,
"text": "d3.dragDisable(window)"
},
{
"code": null,
"e": 2795,
"s": 2762,
"text": "d3.dragEnable(window[, noclick])"
},
{
"code": null,
"e": 2842,
"s": 2795,
"text": "Let us now understand each of these in detail."
},
{
"code": null,
"e": 2941,
"s": 2842,
"text": "This method is used to create a new dragging. You can call this method using the following script."
},
{
"code": null,
"e": 2985,
"s": 2941,
"text": "<script>\n var drag = d3.drag();\n</script>"
},
{
"code": null,
"e": 3141,
"s": 2985,
"text": "This method is used to apply the dragging to the specified selection. You can invoke this function using selection.call. A simple example is defined below."
},
{
"code": null,
"e": 3199,
"s": 3141,
"text": "d3.select(\".node\").call(d3.drag().on(\"drag\", mousemove));"
},
{
"code": null,
"e": 3279,
"s": 3199,
"text": "Here, the drag behavior applied to the selected elements is via selection.call."
},
{
"code": null,
"e": 3307,
"s": 3279,
"text": "drag.container([container])"
},
{
"code": null,
"e": 3554,
"s": 3307,
"text": "It is used to set the container to the specified function for dragging. If a container is not specified, it returns the current accessor. To drag any graphical elements with a Canvas, you can redefine the container as itself. It is defined below."
},
{
"code": null,
"e": 3595,
"s": 3554,
"text": "function container() {\n return this;\n}"
},
{
"code": null,
"e": 3732,
"s": 3595,
"text": "It is used to set the filter for the specified function. If the filter is not specified, it returns the current filter as defined below."
},
{
"code": null,
"e": 3782,
"s": 3732,
"text": "function filter() {\n return !d3.event.button;\n}"
},
{
"code": null,
"e": 3873,
"s": 3782,
"text": "It is used to set the subject to the specified function for dragging and is defined below."
},
{
"code": null,
"e": 3957,
"s": 3873,
"text": "function subject(d) {\n return d = = null ? {x: d3.event.x, y: d3.event.y} : d;\n}"
},
{
"code": null,
"e": 4132,
"s": 3957,
"text": "Here, the subject represents the thing being dragged. For example, if you want to drag rectangle elements in SVG, the default subject is datum of the rectangle being dragged."
},
{
"code": null,
"e": 4273,
"s": 4132,
"text": "This method is used to set the maximum distance for clicking a mousedown and mouseup event. If distance is not specified, it points to zero."
},
{
"code": null,
"e": 4596,
"s": 4273,
"text": "This method is used to set the event listener for the specified typenames for dragging. The typenames is a string containing one or more typename separated by whitespace. Each typename is a type, optionally followed by a period (.) and a name, such as drag.one and drag.two. This type should be from one of the following −"
},
{
"code": null,
"e": 4626,
"s": 4596,
"text": "start − starts a new pointer."
},
{
"code": null,
"e": 4656,
"s": 4626,
"text": "start − starts a new pointer."
},
{
"code": null,
"e": 4688,
"s": 4656,
"text": "drag − drags an active pointer."
},
{
"code": null,
"e": 4720,
"s": 4688,
"text": "drag − drags an active pointer."
},
{
"code": null,
"e": 4754,
"s": 4720,
"text": "end − Inactive an active pointer."
},
{
"code": null,
"e": 4788,
"s": 4754,
"text": "end − Inactive an active pointer."
},
{
"code": null,
"e": 5003,
"s": 4788,
"text": "This method is used to disable the drag and drop selection. It prevents mousedown event action. Most of the selected browsers supports this action by default. If not supported, you can set the CSS property to none."
},
{
"code": null,
"e": 5229,
"s": 5003,
"text": "This method is used to enable the drag and drop selection on the specified window location. It is used to call mouseup event action. If you assign the noclick value is true then click event expires a zero millisecond timeout."
},
{
"code": null,
"e": 5318,
"s": 5229,
"text": "The D3.event method is used to set the drag event. It consists of the following fields −"
},
{
"code": null,
"e": 5360,
"s": 5318,
"text": "Target − It represents the drag behavior."
},
{
"code": null,
"e": 5402,
"s": 5360,
"text": "Target − It represents the drag behavior."
},
{
"code": null,
"e": 5487,
"s": 5402,
"text": "Type − It is a string and can be any one of the following– “start”, “drag” or “end”."
},
{
"code": null,
"e": 5572,
"s": 5487,
"text": "Type − It is a string and can be any one of the following– “start”, “drag” or “end”."
},
{
"code": null,
"e": 5625,
"s": 5572,
"text": "Subject − The drag subject, defined by drag.subject."
},
{
"code": null,
"e": 5678,
"s": 5625,
"text": "Subject − The drag subject, defined by drag.subject."
},
{
"code": null,
"e": 5770,
"s": 5678,
"text": "The event object exposes the event.on method to perform dragging. It is defined as follows."
},
{
"code": null,
"e": 5817,
"s": 5770,
"text": "d3.event.on(\"drag\", dragged).on(\"end\", ended);"
},
{
"code": null,
"e": 5824,
"s": 5817,
"text": " Print"
},
{
"code": null,
"e": 5835,
"s": 5824,
"text": " Add Notes"
}
] |
How to Convert Decimal to Octal?
|
Decimal system is most familiar number system to the general public. It is base 10 which has only 10 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Whereas octal system is one of the number systems to represent numbers. It is base 8 which has only 8 symbols − 0, 1, 2, 3, 4, 5, 6, and 7.
There are various direct or indirect methods to convert a decimal number into octal number. In an indirect method, you need to convert a decimal number into other number system (e.g., binary or hexadecimal), then you can convert into binary number by converting each digit into binary number from hexadecimal and using grouping from octal number system.
Example − Convert decimal number 98 into octal number.
First convert it into binary or hexadecimal number,
= (98)10
= (1x26+1x25+0x24+0x23+0x22+1x21+0x20)10 or (6x161+2x160)10
Because base of binary and hexadecimal are 2 and 16 respectively.
= (1100010)2
or (62)16
Then convert each digit of hexadecimal number into 4 bit of binary number whereas convert each group of 3 bits from least significant in binary number.
= (001 100 010)2
or (0110 0010)2
= (001 100 010)2
= (1 4 2)8
= (142)8
However, there are two direct methods are available for converting a decimal number into octal number − Converting with Remainders and Converting with Division. These are explained as following below.
This is a straightforward method which involve dividing the number to be converted. Let decimal number is N then divide this number from 8 because base of octal number system is 8. Note down the value of remainder, which will be − 0, 1, 2, 3, 4, 5, 6, or 7. Again divide remaining decimal number till it became 0 and note every remainder of every step. Then write remainders from bottom to up (or in reverse order), which will be equivalent octal number of given decimal number. This is procedure for converting an integer decimal number, algorithm is given below.
Take decimal number as dividend.
Take decimal number as dividend.
Divide this number by 8 (8 is base of octal so divisor here).
Divide this number by 8 (8 is base of octal so divisor here).
Store the remainder in an array (it will be: 0, 1, 2, 3, 4, 5, 6 or 7 because of divisor 8).
Store the remainder in an array (it will be: 0, 1, 2, 3, 4, 5, 6 or 7 because of divisor 8).
Repeat the above two steps until the number is greater than zero.
Repeat the above two steps until the number is greater than zero.
Print the array in reverse order (which will be equivalent octal number of given decimal number).
Print the array in reverse order (which will be equivalent octal number of given decimal number).
Note that dividend (here given decimal number) is the number being divided, the divisor (here base of octal, i.e., 8) in the number by which the dividend is divided, and quotient (remaining divided decimal number) is the result of the division.
Example − Convert decimal number 210 into octal number.
Since given number is decimal integer number, so by using above algorithm performing short division by 8 with remainder.
Now, write remainder from bottom to up (in reverse order), this will be 322 which is equivalent octal number of decimal integer 210.
But above method can not convert fraction part of a mixed (a number with integer and fraction part) octal number. For decimal fractional part, the method is explained as following below.
Let decimal fractional part is M then multiply this number from 8 because base of octal number system is 8. Note down the value of integer part, which will be − 0, 1, 2, 3, 4, 5, 6, and 7. Again multiply remaining decimal fractional number till it became 0 and note every integer part of result of every step. Then write noted results of integer part, which will be equivalent fraction octal number of given decimal number. This is procedure for converting an fractional decimal number, algorithm is given below.
Take decimal number as multiplicand.
Take decimal number as multiplicand.
Multiple this number by 8 (8 is base of octal so multiplier here).
Multiple this number by 8 (8 is base of octal so multiplier here).
Store the value of integer part of result in an array (it will be: 0, 1, 2, 3, 4, 5, 6, and 7 because of multiplier 8).
Store the value of integer part of result in an array (it will be: 0, 1, 2, 3, 4, 5, 6, and 7 because of multiplier 8).
Repeat the above two steps until the number became zero.
Repeat the above two steps until the number became zero.
Print the array (which will be equivalent fractional octal number of given decimal fractional number).
Print the array (which will be equivalent fractional octal number of given decimal fractional number).
Note that a multiplicand (here decimal fractional number) is that to be multiplied by multiplier (here base of octal, i.e., 8)
Example − Convert decimal fractional number 0.140869140625 into octal number.
Since given number is decimal fractional number, so by using above algorithm performing short multiplication by 8 with integer part.
Now, write these resultant integer part, this will be approximate 0.11010 which is equivalent octal fractional number of decimal fractional 0.140869140625.
This method is guessing octal number of a decimal number. You need to draw a table of power of 8, For integer part, The algorithm is explained as following below.
Start with any decimal number.
Start with any decimal number.
List the powers of 8.
List the powers of 8.
Divide the decimal number by the largest power of eight.
Divide the decimal number by the largest power of eight.
Find the remainder.
Find the remainder.
Divide the remainder by the next power of 8.
Divide the remainder by the next power of 8.
Repeat until you've found the full answer.
Repeat until you've found the full answer.
Example − Convert decimal number 136 into octal number.
According to above algorithm, table of power of 8,
Divide the decimal number by the largest power of eight.
= 136 / 64 = 2.125
So 2 will be first digit or most significant bit (MSB) of octal number.
Now, remainder will be,
= 136 - 642 = 8
Now, divide this remainder by the next power of 8.
= 8 / 8 =1.0
So 1 will be next digit or second most significant bit (MSB) of octal number.
Now, remainder will be,
= 8 - 81 = 0
Now, divide this remainder by the next power of 8.
= 0 / 8 = 0
So, 0 will be last (least significant) bit of required octal number.
Therefore, 210 will be equivalent octal number of given decimal number 136.
|
[
{
"code": null,
"e": 1471,
"s": 1187,
"text": "Decimal system is most familiar number system to the general public. It is base 10 which has only 10 symbols − 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. Whereas octal system is one of the number systems to represent numbers. It is base 8 which has only 8 symbols − 0, 1, 2, 3, 4, 5, 6, and 7."
},
{
"code": null,
"e": 1825,
"s": 1471,
"text": "There are various direct or indirect methods to convert a decimal number into octal number. In an indirect method, you need to convert a decimal number into other number system (e.g., binary or hexadecimal), then you can convert into binary number by converting each digit into binary number from hexadecimal and using grouping from octal number system."
},
{
"code": null,
"e": 1880,
"s": 1825,
"text": "Example − Convert decimal number 98 into octal number."
},
{
"code": null,
"e": 2313,
"s": 1880,
"text": "First convert it into binary or hexadecimal number,\n= (98)10\n\n= (1x26+1x25+0x24+0x23+0x22+1x21+0x20)10 or (6x161+2x160)10\nBecause base of binary and hexadecimal are 2 and 16 respectively.\n= (1100010)2\nor (62)16\nThen convert each digit of hexadecimal number into 4 bit of binary number whereas convert each group of 3 bits from least significant in binary number.\n= (001 100 010)2\nor (0110 0010)2\n= (001 100 010)2\n= (1 4 2)8\n= (142)8"
},
{
"code": null,
"e": 2516,
"s": 2315,
"text": "However, there are two direct methods are available for converting a decimal number into octal number − Converting with Remainders and Converting with Division. These are explained as following below."
},
{
"code": null,
"e": 3081,
"s": 2516,
"text": "This is a straightforward method which involve dividing the number to be converted. Let decimal number is N then divide this number from 8 because base of octal number system is 8. Note down the value of remainder, which will be − 0, 1, 2, 3, 4, 5, 6, or 7. Again divide remaining decimal number till it became 0 and note every remainder of every step. Then write remainders from bottom to up (or in reverse order), which will be equivalent octal number of given decimal number. This is procedure for converting an integer decimal number, algorithm is given below."
},
{
"code": null,
"e": 3114,
"s": 3081,
"text": "Take decimal number as dividend."
},
{
"code": null,
"e": 3147,
"s": 3114,
"text": "Take decimal number as dividend."
},
{
"code": null,
"e": 3209,
"s": 3147,
"text": "Divide this number by 8 (8 is base of octal so divisor here)."
},
{
"code": null,
"e": 3271,
"s": 3209,
"text": "Divide this number by 8 (8 is base of octal so divisor here)."
},
{
"code": null,
"e": 3364,
"s": 3271,
"text": "Store the remainder in an array (it will be: 0, 1, 2, 3, 4, 5, 6 or 7 because of divisor 8)."
},
{
"code": null,
"e": 3457,
"s": 3364,
"text": "Store the remainder in an array (it will be: 0, 1, 2, 3, 4, 5, 6 or 7 because of divisor 8)."
},
{
"code": null,
"e": 3523,
"s": 3457,
"text": "Repeat the above two steps until the number is greater than zero."
},
{
"code": null,
"e": 3589,
"s": 3523,
"text": "Repeat the above two steps until the number is greater than zero."
},
{
"code": null,
"e": 3687,
"s": 3589,
"text": "Print the array in reverse order (which will be equivalent octal number of given decimal number)."
},
{
"code": null,
"e": 3785,
"s": 3687,
"text": "Print the array in reverse order (which will be equivalent octal number of given decimal number)."
},
{
"code": null,
"e": 4030,
"s": 3785,
"text": "Note that dividend (here given decimal number) is the number being divided, the divisor (here base of octal, i.e., 8) in the number by which the dividend is divided, and quotient (remaining divided decimal number) is the result of the division."
},
{
"code": null,
"e": 4086,
"s": 4030,
"text": "Example − Convert decimal number 210 into octal number."
},
{
"code": null,
"e": 4207,
"s": 4086,
"text": "Since given number is decimal integer number, so by using above algorithm performing short division by 8 with remainder."
},
{
"code": null,
"e": 4340,
"s": 4207,
"text": "Now, write remainder from bottom to up (in reverse order), this will be 322 which is equivalent octal number of decimal integer 210."
},
{
"code": null,
"e": 4527,
"s": 4340,
"text": "But above method can not convert fraction part of a mixed (a number with integer and fraction part) octal number. For decimal fractional part, the method is explained as following below."
},
{
"code": null,
"e": 5040,
"s": 4527,
"text": "Let decimal fractional part is M then multiply this number from 8 because base of octal number system is 8. Note down the value of integer part, which will be − 0, 1, 2, 3, 4, 5, 6, and 7. Again multiply remaining decimal fractional number till it became 0 and note every integer part of result of every step. Then write noted results of integer part, which will be equivalent fraction octal number of given decimal number. This is procedure for converting an fractional decimal number, algorithm is given below."
},
{
"code": null,
"e": 5077,
"s": 5040,
"text": "Take decimal number as multiplicand."
},
{
"code": null,
"e": 5114,
"s": 5077,
"text": "Take decimal number as multiplicand."
},
{
"code": null,
"e": 5181,
"s": 5114,
"text": "Multiple this number by 8 (8 is base of octal so multiplier here)."
},
{
"code": null,
"e": 5248,
"s": 5181,
"text": "Multiple this number by 8 (8 is base of octal so multiplier here)."
},
{
"code": null,
"e": 5368,
"s": 5248,
"text": "Store the value of integer part of result in an array (it will be: 0, 1, 2, 3, 4, 5, 6, and 7 because of multiplier 8)."
},
{
"code": null,
"e": 5488,
"s": 5368,
"text": "Store the value of integer part of result in an array (it will be: 0, 1, 2, 3, 4, 5, 6, and 7 because of multiplier 8)."
},
{
"code": null,
"e": 5545,
"s": 5488,
"text": "Repeat the above two steps until the number became zero."
},
{
"code": null,
"e": 5602,
"s": 5545,
"text": "Repeat the above two steps until the number became zero."
},
{
"code": null,
"e": 5705,
"s": 5602,
"text": "Print the array (which will be equivalent fractional octal number of given decimal fractional number)."
},
{
"code": null,
"e": 5808,
"s": 5705,
"text": "Print the array (which will be equivalent fractional octal number of given decimal fractional number)."
},
{
"code": null,
"e": 5935,
"s": 5808,
"text": "Note that a multiplicand (here decimal fractional number) is that to be multiplied by multiplier (here base of octal, i.e., 8)"
},
{
"code": null,
"e": 6013,
"s": 5935,
"text": "Example − Convert decimal fractional number 0.140869140625 into octal number."
},
{
"code": null,
"e": 6146,
"s": 6013,
"text": "Since given number is decimal fractional number, so by using above algorithm performing short multiplication by 8 with integer part."
},
{
"code": null,
"e": 6302,
"s": 6146,
"text": "Now, write these resultant integer part, this will be approximate 0.11010 which is equivalent octal fractional number of decimal fractional 0.140869140625."
},
{
"code": null,
"e": 6465,
"s": 6302,
"text": "This method is guessing octal number of a decimal number. You need to draw a table of power of 8, For integer part, The algorithm is explained as following below."
},
{
"code": null,
"e": 6496,
"s": 6465,
"text": "Start with any decimal number."
},
{
"code": null,
"e": 6527,
"s": 6496,
"text": "Start with any decimal number."
},
{
"code": null,
"e": 6549,
"s": 6527,
"text": "List the powers of 8."
},
{
"code": null,
"e": 6571,
"s": 6549,
"text": "List the powers of 8."
},
{
"code": null,
"e": 6628,
"s": 6571,
"text": "Divide the decimal number by the largest power of eight."
},
{
"code": null,
"e": 6685,
"s": 6628,
"text": "Divide the decimal number by the largest power of eight."
},
{
"code": null,
"e": 6705,
"s": 6685,
"text": "Find the remainder."
},
{
"code": null,
"e": 6725,
"s": 6705,
"text": "Find the remainder."
},
{
"code": null,
"e": 6770,
"s": 6725,
"text": "Divide the remainder by the next power of 8."
},
{
"code": null,
"e": 6815,
"s": 6770,
"text": "Divide the remainder by the next power of 8."
},
{
"code": null,
"e": 6858,
"s": 6815,
"text": "Repeat until you've found the full answer."
},
{
"code": null,
"e": 6901,
"s": 6858,
"text": "Repeat until you've found the full answer."
},
{
"code": null,
"e": 6957,
"s": 6901,
"text": "Example − Convert decimal number 136 into octal number."
},
{
"code": null,
"e": 7008,
"s": 6957,
"text": "According to above algorithm, table of power of 8,"
},
{
"code": null,
"e": 7583,
"s": 7008,
"text": "Divide the decimal number by the largest power of eight.\n= 136 / 64 = 2.125\nSo 2 will be first digit or most significant bit (MSB) of octal number.\nNow, remainder will be,\n= 136 - 642 = 8\nNow, divide this remainder by the next power of 8.\n= 8 / 8 =1.0\nSo 1 will be next digit or second most significant bit (MSB) of octal number.\nNow, remainder will be,\n= 8 - 81 = 0\nNow, divide this remainder by the next power of 8.\n= 0 / 8 = 0\nSo, 0 will be last (least significant) bit of required octal number.\nTherefore, 210 will be equivalent octal number of given decimal number 136."
}
] |
Class getResource() method in Java with Examples
|
27 Dec, 2019
The getResource() method of java.lang.Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of URL object.
Syntax:
public URL getResource(String resourceName)
Parameter: This method accepts a parameter resourceName which is the resource to get.
Return Value: This method returns the specified resource of this class in the form of URL objects.
Exception This method throws:
NullPointerException if name is null
Below programs demonstrate the getResource() method.
Example 1:
// Java program to demonstrate// getResource() method import java.util.*; public class Test { public int obj = 10; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName("Test"); System.out.println("Class represented by myClass: " + myClass.toString()); String resourceName = "obj"; // Get the resource of myClass // using getResource() method System.out.println( resourceName + " resource of myClass: " + myClass.getResource(resourceName)); }}
Class represented by myClass: class Test
obj resource of myClass: null
Example 2:
// Java program to demonstrate// getResource() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName("Main"); System.out.println("Class represented by myClass: " + myClass.toString()); String resourceName = "obj"; try { // Get the resource of myClass // using getResource() method System.out.println( resourceName + " resource of myClass: " + myClass.getResource(resourceName)); } catch (Exception e) { System.out.println(e); } }}
Class represented by myClass: class Main
obj resource of myClass: null
Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getResource-java.lang.String-
Java-Functions
Java-lang package
Java.lang.Class
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "The getResource() method of java.lang.Class class is used to get the resource with the specified resource of this class. The method returns the specified resource of this class in the form of URL object."
},
{
"code": null,
"e": 240,
"s": 232,
"text": "Syntax:"
},
{
"code": null,
"e": 285,
"s": 240,
"text": "public URL getResource(String resourceName)\n"
},
{
"code": null,
"e": 371,
"s": 285,
"text": "Parameter: This method accepts a parameter resourceName which is the resource to get."
},
{
"code": null,
"e": 470,
"s": 371,
"text": "Return Value: This method returns the specified resource of this class in the form of URL objects."
},
{
"code": null,
"e": 500,
"s": 470,
"text": "Exception This method throws:"
},
{
"code": null,
"e": 537,
"s": 500,
"text": "NullPointerException if name is null"
},
{
"code": null,
"e": 590,
"s": 537,
"text": "Below programs demonstrate the getResource() method."
},
{
"code": null,
"e": 601,
"s": 590,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getResource() method import java.util.*; public class Test { public int obj = 10; public static void main(String[] args) throws ClassNotFoundException { // returns the Class object for this class Class myClass = Class.forName(\"Test\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String resourceName = \"obj\"; // Get the resource of myClass // using getResource() method System.out.println( resourceName + \" resource of myClass: \" + myClass.getResource(resourceName)); }}",
"e": 1265,
"s": 601,
"text": null
},
{
"code": null,
"e": 1337,
"s": 1265,
"text": "Class represented by myClass: class Test\nobj resource of myClass: null\n"
},
{
"code": null,
"e": 1348,
"s": 1337,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// getResource() method import java.util.*; class Main { private Object obj; public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException { // returns the Class object for this class Class myClass = Class.forName(\"Main\"); System.out.println(\"Class represented by myClass: \" + myClass.toString()); String resourceName = \"obj\"; try { // Get the resource of myClass // using getResource() method System.out.println( resourceName + \" resource of myClass: \" + myClass.getResource(resourceName)); } catch (Exception e) { System.out.println(e); } }}",
"e": 2140,
"s": 1348,
"text": null
},
{
"code": null,
"e": 2212,
"s": 2140,
"text": "Class represented by myClass: class Main\nobj resource of myClass: null\n"
},
{
"code": null,
"e": 2316,
"s": 2212,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/lang/Class.html#getResource-java.lang.String-"
},
{
"code": null,
"e": 2331,
"s": 2316,
"text": "Java-Functions"
},
{
"code": null,
"e": 2349,
"s": 2331,
"text": "Java-lang package"
},
{
"code": null,
"e": 2365,
"s": 2349,
"text": "Java.lang.Class"
},
{
"code": null,
"e": 2370,
"s": 2365,
"text": "Java"
},
{
"code": null,
"e": 2375,
"s": 2370,
"text": "Java"
},
{
"code": null,
"e": 2473,
"s": 2375,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2488,
"s": 2473,
"text": "Stream In Java"
},
{
"code": null,
"e": 2509,
"s": 2488,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2530,
"s": 2509,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2549,
"s": 2530,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2566,
"s": 2549,
"text": "Generics in Java"
},
{
"code": null,
"e": 2596,
"s": 2566,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 2622,
"s": 2596,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2638,
"s": 2622,
"text": "Strings in Java"
},
{
"code": null,
"e": 2675,
"s": 2638,
"text": "Differences between JDK, JRE and JVM"
}
] |
Python – Group keys to values list
|
10 May, 2020
Sometimes, while working with Python dictionaries, we can have problem in which we need to find all possible values of all keys in a dictionary. This utility is quite common and can occur in many domains including day-day programming and school programming. Lets discuss certain way in which this task can be performed.
Method #1 : Using loop + defaultdict()The combination of above functionalities can be used to perform this task. In this, we capture all the elements in a list by initializing defaultdict with list datatype and keep on appending all the values to associated key.
# Python3 code to demonstrate working of # Group keys to values list# Using loop + defaultdict()from collections import defaultdict # initializing listtest_list = [{'gfg' : 1, 'is' : 4, 'best' : 7}, {'gfg' : 9, 'is' : 8, 'best' : 3}, {'gfg' : 4, 'is' : 4, 'best' : 7}, {'gfg' : 7, 'is' : 2, 'best' : 8}, {'gfg' : 1, 'is' : 4, 'best' : 7}, {'gfg' : 10, 'is' : 9, 'best' : 2}, {'gfg' : 0, 'is' : 5, 'best' : 6}] # printing original listprint("The original list is : " + str(test_list)) # Group keys to values list# Using loop + defaultdict()res = defaultdict(set)for sub in test_list: for key, val in sub.items(): res[key].add(val) # printing result print("The grouped key values : " + str(dict(res)))
The original list is : [{‘best’: 7, ‘gfg’: 1, ‘is’: 4}, {‘best’: 3, ‘gfg’: 9, ‘is’: 8}, {‘best’: 7, ‘gfg’: 4, ‘is’: 4}, {‘best’: 8, ‘gfg’: 7, ‘is’: 2}, {‘best’: 7, ‘gfg’: 1, ‘is’: 4}, {‘best’: 2, ‘gfg’: 10, ‘is’: 9}, {‘best’: 6, ‘gfg’: 0, ‘is’: 5}]The grouped key values : {‘best’: {8, 2, 3, 6, 7}, ‘gfg’: {0, 1, 4, 7, 9, 10}, ‘is’: {8, 9, 2, 4, 5}}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 348,
"s": 28,
"text": "Sometimes, while working with Python dictionaries, we can have problem in which we need to find all possible values of all keys in a dictionary. This utility is quite common and can occur in many domains including day-day programming and school programming. Lets discuss certain way in which this task can be performed."
},
{
"code": null,
"e": 611,
"s": 348,
"text": "Method #1 : Using loop + defaultdict()The combination of above functionalities can be used to perform this task. In this, we capture all the elements in a list by initializing defaultdict with list datatype and keep on appending all the values to associated key."
},
{
"code": "# Python3 code to demonstrate working of # Group keys to values list# Using loop + defaultdict()from collections import defaultdict # initializing listtest_list = [{'gfg' : 1, 'is' : 4, 'best' : 7}, {'gfg' : 9, 'is' : 8, 'best' : 3}, {'gfg' : 4, 'is' : 4, 'best' : 7}, {'gfg' : 7, 'is' : 2, 'best' : 8}, {'gfg' : 1, 'is' : 4, 'best' : 7}, {'gfg' : 10, 'is' : 9, 'best' : 2}, {'gfg' : 0, 'is' : 5, 'best' : 6}] # printing original listprint(\"The original list is : \" + str(test_list)) # Group keys to values list# Using loop + defaultdict()res = defaultdict(set)for sub in test_list: for key, val in sub.items(): res[key].add(val) # printing result print(\"The grouped key values : \" + str(dict(res))) ",
"e": 1399,
"s": 611,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1399,
"text": "The original list is : [{‘best’: 7, ‘gfg’: 1, ‘is’: 4}, {‘best’: 3, ‘gfg’: 9, ‘is’: 8}, {‘best’: 7, ‘gfg’: 4, ‘is’: 4}, {‘best’: 8, ‘gfg’: 7, ‘is’: 2}, {‘best’: 7, ‘gfg’: 1, ‘is’: 4}, {‘best’: 2, ‘gfg’: 10, ‘is’: 9}, {‘best’: 6, ‘gfg’: 0, ‘is’: 5}]The grouped key values : {‘best’: {8, 2, 3, 6, 7}, ‘gfg’: {0, 1, 4, 7, 9, 10}, ‘is’: {8, 9, 2, 4, 5}}"
},
{
"code": null,
"e": 1776,
"s": 1749,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 1783,
"s": 1776,
"text": "Python"
},
{
"code": null,
"e": 1799,
"s": 1783,
"text": "Python Programs"
}
] |
Python | Numpy np.disp() method
|
02 Dec, 2019
With the help of np.disp() method, we can get the string into a display buffer and by using stringIO class we can get the values from buffer by using np.disp() method.
Syntax : np.disp(message, device)Return : Will not return anything without StringIO class.
Example #1 :In this example by using np.disp() method, we are able to collect message from parameter and put that message into display buffer by using this method.
# import numpy and stringIOimport numpy as npfrom io import StringIO buf = StringIO()# using np.disp() methodnp.disp(u'Geeks For Geeks', device = buf)buf.getvalue()
Output :
‘Geeks For Geeks\n’
Example #2 :
# import numpy and stringIOimport numpy as npfrom io import StringIO buf = StringIO()# using np.disp() methodnp.disp(u'Author "Jitender Kumar"', device = buf)buf.getvalue()
Output :
‘Author “Jitender Kumar”\n’
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Dec, 2019"
},
{
"code": null,
"e": 196,
"s": 28,
"text": "With the help of np.disp() method, we can get the string into a display buffer and by using stringIO class we can get the values from buffer by using np.disp() method."
},
{
"code": null,
"e": 287,
"s": 196,
"text": "Syntax : np.disp(message, device)Return : Will not return anything without StringIO class."
},
{
"code": null,
"e": 451,
"s": 287,
"text": "Example #1 :In this example by using np.disp() method, we are able to collect message from parameter and put that message into display buffer by using this method."
},
{
"code": "# import numpy and stringIOimport numpy as npfrom io import StringIO buf = StringIO()# using np.disp() methodnp.disp(u'Geeks For Geeks', device = buf)buf.getvalue()",
"e": 617,
"s": 451,
"text": null
},
{
"code": null,
"e": 626,
"s": 617,
"text": "Output :"
},
{
"code": null,
"e": 646,
"s": 626,
"text": "‘Geeks For Geeks\\n’"
},
{
"code": null,
"e": 659,
"s": 646,
"text": "Example #2 :"
},
{
"code": "# import numpy and stringIOimport numpy as npfrom io import StringIO buf = StringIO()# using np.disp() methodnp.disp(u'Author \"Jitender Kumar\"', device = buf)buf.getvalue()",
"e": 833,
"s": 659,
"text": null
},
{
"code": null,
"e": 842,
"s": 833,
"text": "Output :"
},
{
"code": null,
"e": 870,
"s": 842,
"text": "‘Author “Jitender Kumar”\\n’"
},
{
"code": null,
"e": 883,
"s": 870,
"text": "Python-numpy"
},
{
"code": null,
"e": 890,
"s": 883,
"text": "Python"
},
{
"code": null,
"e": 988,
"s": 890,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1020,
"s": 988,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1047,
"s": 1020,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1068,
"s": 1047,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1091,
"s": 1068,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1147,
"s": 1091,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1178,
"s": 1147,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1220,
"s": 1178,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1262,
"s": 1220,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1301,
"s": 1262,
"text": "Python | Get unique values from a list"
}
] |
Minimum flips required to form given binary string where every flip changes all bits to its right as well
|
13 Feb, 2022
Given a string S, the task is to find minimum flips required to convert an initial binary string consisting of only zeroes to S where every flip of a character flips all succeeding characters as well. Examples:
Input: S = “01011” Output: 3 Explanation: Initial String – “00000” Flip the 2nd bit – “01111” Flip the 3rd bit – “01000” Flip the 4th bit – “01011” Total Flips = 3Input: S = “01001” Output: 3 Explanation: Initial String – “00000” Flip the 2nd bit – “01111” Flip the 3rd bit – “01000” Flip the 5th bit – “01001” Total Flips = 3
Approach: In order to solve the problem, follow the steps below:
Store ‘1’ in curr initially.
Traverse S and find the first occurrence of curr. Increase count when curr is encountered. Store ‘0’ if curr is ‘1’ or vice versa.
Repeat the above step for entire traversal of S.
Final value of count gives the required answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to return the count// of minimum flips requiredint minFlips(string target){ char curr = '1'; int count = 0; for(int i = 0; i < target.length(); i++) { // If curr occurs in the final string if (target[i] == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = (char)(48 + (curr + 1) % 2); } } return count;} // Driver Codeint main(){ string S = "011000"; cout << (minFlips(S));} // This code is contributed by rock_cool
// Java program for the above approachimport java.util.Arrays; public class GFG { // Function to return the count of // minimum flips required public static int minFlips(String target) { char curr = '1'; int count = 0; for (int i = 0; i < target.length(); i++) { // If curr occurs in the final string if (target.charAt(i) == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = (char)(48 + (curr + 1) % 2); } } return count; } // Driver Code public static void main(String args[]) { String S = "011000"; System.out.println(minFlips(S)); }}
# Python3 program for the above approach # Function to return the count# of minimum flips requireddef minFlips(target): curr = '1' count = 0 for i in range(len(target)): # If curr occurs in the final string if (target[i] == curr): count += 1 # Switch curr to '0' if '1' # or vice-versa curr = chr(48 + (ord(curr) + 1) % 2) return count # Driver Codeif __name__ == "__main__": S = "011000" print(minFlips(S)) # This code is contributed by chitranayal
// C# program for the above approachusing System; class GFG{ // Function to return the count of// minimum flips requiredpublic static int minFlips(String target){ char curr = '1'; int count = 0; for(int i = 0; i < target.Length; i++) { // If curr occurs in the readonly string if (target[i] == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = (char)(48 + (curr + 1) % 2); } } return count;} // Driver codepublic static void Main(String []args){ String S = "011000"; Console.WriteLine(minFlips(S));}} // This code is contributed by 29AjayKumar
<script> // Javascript program for the above approach // Function to return the count // of minimum flips required function minFlips(target) { let curr = '1'; let count = 0; for(let i = 0; i < target.length; i++) { // If curr occurs in the final string if (target[i] == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = String.fromCharCode(48 + (curr.charCodeAt() + 1) % 2); } } return count; } let S = "011000"; document.write(minFlips(S)); </script>
2
Time Complexity: O(N) Auxiliary Space: O(1)
29AjayKumar
rock_cool
ukasp
mukesh07
rohitsingh07052
binary-string
Bit Magic
Strings
Strings
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Little and Big Endian Mystery
Binary representation of a given number
Bits manipulation (Important tactics)
Add two numbers without using arithmetic operators
Rotate bits of a number
Reverse a string in Java
Write a program to reverse an array or string
C++ Data Types
KMP Algorithm for Pattern Searching
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Feb, 2022"
},
{
"code": null,
"e": 267,
"s": 54,
"text": "Given a string S, the task is to find minimum flips required to convert an initial binary string consisting of only zeroes to S where every flip of a character flips all succeeding characters as well. Examples: "
},
{
"code": null,
"e": 596,
"s": 267,
"text": "Input: S = “01011” Output: 3 Explanation: Initial String – “00000” Flip the 2nd bit – “01111” Flip the 3rd bit – “01000” Flip the 4th bit – “01011” Total Flips = 3Input: S = “01001” Output: 3 Explanation: Initial String – “00000” Flip the 2nd bit – “01111” Flip the 3rd bit – “01000” Flip the 5th bit – “01001” Total Flips = 3 "
},
{
"code": null,
"e": 665,
"s": 598,
"text": "Approach: In order to solve the problem, follow the steps below: "
},
{
"code": null,
"e": 694,
"s": 665,
"text": "Store ‘1’ in curr initially."
},
{
"code": null,
"e": 825,
"s": 694,
"text": "Traverse S and find the first occurrence of curr. Increase count when curr is encountered. Store ‘0’ if curr is ‘1’ or vice versa."
},
{
"code": null,
"e": 874,
"s": 825,
"text": "Repeat the above step for entire traversal of S."
},
{
"code": null,
"e": 922,
"s": 874,
"text": "Final value of count gives the required answer."
},
{
"code": null,
"e": 973,
"s": 922,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 977,
"s": 973,
"text": "C++"
},
{
"code": null,
"e": 982,
"s": 977,
"text": "Java"
},
{
"code": null,
"e": 990,
"s": 982,
"text": "Python3"
},
{
"code": null,
"e": 993,
"s": 990,
"text": "C#"
},
{
"code": null,
"e": 1004,
"s": 993,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to return the count// of minimum flips requiredint minFlips(string target){ char curr = '1'; int count = 0; for(int i = 0; i < target.length(); i++) { // If curr occurs in the final string if (target[i] == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = (char)(48 + (curr + 1) % 2); } } return count;} // Driver Codeint main(){ string S = \"011000\"; cout << (minFlips(S));} // This code is contributed by rock_cool",
"e": 1647,
"s": 1004,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.Arrays; public class GFG { // Function to return the count of // minimum flips required public static int minFlips(String target) { char curr = '1'; int count = 0; for (int i = 0; i < target.length(); i++) { // If curr occurs in the final string if (target.charAt(i) == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = (char)(48 + (curr + 1) % 2); } } return count; } // Driver Code public static void main(String args[]) { String S = \"011000\"; System.out.println(minFlips(S)); }}",
"e": 2380,
"s": 1647,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to return the count# of minimum flips requireddef minFlips(target): curr = '1' count = 0 for i in range(len(target)): # If curr occurs in the final string if (target[i] == curr): count += 1 # Switch curr to '0' if '1' # or vice-versa curr = chr(48 + (ord(curr) + 1) % 2) return count # Driver Codeif __name__ == \"__main__\": S = \"011000\" print(minFlips(S)) # This code is contributed by chitranayal",
"e": 2949,
"s": 2380,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to return the count of// minimum flips requiredpublic static int minFlips(String target){ char curr = '1'; int count = 0; for(int i = 0; i < target.Length; i++) { // If curr occurs in the readonly string if (target[i] == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = (char)(48 + (curr + 1) % 2); } } return count;} // Driver codepublic static void Main(String []args){ String S = \"011000\"; Console.WriteLine(minFlips(S));}} // This code is contributed by 29AjayKumar",
"e": 3626,
"s": 2949,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to return the count // of minimum flips required function minFlips(target) { let curr = '1'; let count = 0; for(let i = 0; i < target.length; i++) { // If curr occurs in the final string if (target[i] == curr) { count++; // Switch curr to '0' if '1' // or vice-versa curr = String.fromCharCode(48 + (curr.charCodeAt() + 1) % 2); } } return count; } let S = \"011000\"; document.write(minFlips(S)); </script>",
"e": 4284,
"s": 3626,
"text": null
},
{
"code": null,
"e": 4286,
"s": 4284,
"text": "2"
},
{
"code": null,
"e": 4330,
"s": 4286,
"text": "Time Complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4342,
"s": 4330,
"text": "29AjayKumar"
},
{
"code": null,
"e": 4352,
"s": 4342,
"text": "rock_cool"
},
{
"code": null,
"e": 4358,
"s": 4352,
"text": "ukasp"
},
{
"code": null,
"e": 4367,
"s": 4358,
"text": "mukesh07"
},
{
"code": null,
"e": 4383,
"s": 4367,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 4397,
"s": 4383,
"text": "binary-string"
},
{
"code": null,
"e": 4407,
"s": 4397,
"text": "Bit Magic"
},
{
"code": null,
"e": 4415,
"s": 4407,
"text": "Strings"
},
{
"code": null,
"e": 4423,
"s": 4415,
"text": "Strings"
},
{
"code": null,
"e": 4433,
"s": 4423,
"text": "Bit Magic"
},
{
"code": null,
"e": 4531,
"s": 4433,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4561,
"s": 4531,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 4601,
"s": 4561,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 4639,
"s": 4601,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 4690,
"s": 4639,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 4714,
"s": 4690,
"text": "Rotate bits of a number"
},
{
"code": null,
"e": 4739,
"s": 4714,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4785,
"s": 4739,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 4800,
"s": 4785,
"text": "C++ Data Types"
},
{
"code": null,
"e": 4836,
"s": 4800,
"text": "KMP Algorithm for Pattern Searching"
}
] |
Pancake sorting
|
14 Jun, 2022
Given an unsorted array, the task is to sort the given array. You are allowed to do only following operation on array.
flip(arr, i): Reverse array from 0 to i
Examples:
Input: arr[] = { 23, 10, 20, 11, 12, 6, 7 }Output: { 6, 7, 10, 11, 12, 20, 23}
Input: arr[] = { 0, 1, 1, 0, 0 }Output: { 0, 0, 0, 1, 1 }
Approach: Unlike a traditional sorting algorithm, which attempts to sort with the fewest comparisons possible, the goal is to sort the sequence in as few reversals as possible.
The idea is to do something similar to Selection Sort. We one by one place maximum element at the end and reduce the size of current array by one.
Following are the detailed steps. Let given array be arr[] and size of array be n.
Start from current size equal to n and reduce current size by one while it’s greater than 1. Let the current size be curr_size.
Do following for every curr_sizeFind index of the maximum element in arr[0 to curr_szie-1]. Let the index be ‘mi’Call flip(arr, mi)Call flip(arr, curr_size – 1)
Find index of the maximum element in arr[0 to curr_szie-1]. Let the index be ‘mi’
Call flip(arr, mi)
Call flip(arr, curr_size – 1)
See following video for visualization of the above algorithm.http://www.youtube.com/embed/kk-_DDgoXfk
Below is the implementation:
C
CPP
Java
Python3
C#
PHP
Javascript
// C program to// sort array using// pancake sort#include <stdio.h>#include <stdlib.h> /* Reverses arr[0..i] */void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} // Returns index of the// maximum element in// arr[0..n-1]int findMax(int arr[], int n){ int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi;} // The main function that// sorts given array using// flip operationsvoid pancakeSort(int* arr, int n){ // Start from the complete // array and one by one // reduce current size // by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum // element to end of // current array if // it's not already // at the end if (mi != curr_size - 1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size - 1); } }} // A utility function to print// n array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; ++i) printf("%d ", arr[i]);} // Driver program to test above functionint main(){ int arr[] = { 23, 10, 20, 11, 12, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); pancakeSort(arr, n); puts("Sorted Array "); printArray(arr, n); return 0;}
// C++ program to // sort array using // pancake sort #include<bits/stdc++.h> using namespace std; /* Reverses arr[0..i] */void flip(int arr[], int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] int findMax(int arr[], int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations void pancakeSort(int *arr, int n) { // Start from the complete // array and one by one // reduce current size // by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum // element to end of // current array if // it's not already // at the end if (mi != curr_size-1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size-1); } } } // A utility function to print // n array of size n void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) cout<< arr[i]<<" "; } // Driver program to test above function int main() { int arr[] = {23, 10, 20, 11, 12, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); pancakeSort(arr, n); cout<<"Sorted Array "<<endl; printArray(arr, n); return 0; } //This code is contributed by rathbhupendra
// Java program to// sort array using// pancake sortimport java.io.*; class PancakeSort { /* Reverses arr[0..i] */ static void flip(int arr[], int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] static int findMax(int arr[], int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations static int pancakeSort(int arr[], int n) { // Start from the complete // array and one by one // reduce current size by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum element // to end of current array // if it's not already at // the end if (mi != curr_size-1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size-1); } } return 0; } /* Utility function to print array arr[] */ static void printArray(int arr[], int arr_size) { for (int i = 0; i < arr_size; i++) System.out.print(arr[i] + " "); System.out.println(""); } /* Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {23, 10, 20, 11, 12, 6, 7}; int n = arr.length; pancakeSort(arr, n); System.out.println("Sorted Array: "); printArray(arr, n); }}/* This code is contributed by Devesh Agrawal*/
# Python3 program to# sort array using# pancake sort # Reverses arr[0..i] */def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 # Returns index of the maximum# element in arr[0..n-1] */def findMax(arr, n): mi = 0 for i in range(0,n): if arr[i] > arr[mi]: mi = i return mi # The main function that # sorts given array # using flip operationsdef pancakeSort(arr, n): # Start from the complete # array and one by one # reduce current size # by one curr_size = n while curr_size > 1: # Find index of the maximum # element in # arr[0..curr_size-1] mi = findMax(arr, curr_size) # Move the maximum element # to end of current array # if it's not already at # the end if mi != curr_size-1: # To move at the end, # first move maximum # number to beginning flip(arr, mi) # Now move the maximum # number to end by # reversing current array flip(arr, curr_size-1) curr_size -= 1 # A utility function to # print an array of size n def printArray(arr, n): for i in range(0,n): print ("%d"%( arr[i]),end=" ") # Driver program arr = [23, 10, 20, 11, 12, 6, 7]n = len(arr)pancakeSort(arr, n);print ("Sorted Array ")printArray(arr,n) # This code is contributed by shreyanshi_arun.
// C# program to sort array using// pancake sortusing System; class GFG { // Reverses arr[0..i] static void flip(int []arr, int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] static int findMax(int []arr, int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations static int pancakeSort(int []arr, int n) { // Start from the complete // array and one by one // reduce current size by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum element // to end of current array // if it's not already at // the end if (mi != curr_size - 1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size - 1); } } return 0; } // Utility function to print // array arr[] static void printArray(int []arr, int arr_size) { for (int i = 0; i < arr_size; i++) Console.Write(arr[i] + " "); Console.Write(""); } // Driver function to check for // above functions public static void Main () { int []arr = {23, 10, 20, 11, 12, 6, 7}; int n = arr.Length; pancakeSort(arr, n); Console.Write("Sorted Array: "); printArray(arr, n); }} // This code is contributed by nitin mittal.
<?php// PHP program to// sort array using// pancake sort /* Reverses arr[0..i] */function flip(&$arr, $i){ $start = 0; while ($start < $i) { $temp = $arr[$start]; $arr[$start] = $arr[$i]; $arr[$i] = $temp; $start++; $i--; }} // Returns index of the // maximum element in // arr[0..n-1] function findMax($arr, $n){ $mi = 0; for ($i = 0; $i < $n; ++$i) if ($arr[$i] > $arr[$mi]) $mi = $i; return $mi;} // The main function that // sorts given array using // flip operationsfunction pancakeSort(&$arr, $n){ // Start from the complete // array and one by one // reduce current size // by one for ($curr_size = $n; $curr_size > 1; --$curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] $mi = findMax($arr, $curr_size); // Move the maximum // element to end of // current array if // it's not already // at the end if ($mi != $curr_size-1) { // To move at the end, // first move maximum // number to beginning flip($arr, $mi); // Now move the maximum // number to end by // reversing current array flip($arr, $curr_size-1); } }} // A utility function to print // n array of size n function printArray($arr, $n){ for ($i = 0; $i < $n; ++$i) print($arr[$i]." ");} // Driver code$arr = array(23, 10, 20, 11, 12, 6, 7);$n = count($arr); pancakeSort($arr, $n); echo("Sorted Array \n");printArray($arr, $n); return 0; // This code is contributed by chandan_jnu?>
<script> // JavaScript program to sort array using pancake sort // Reverses arr[0..i] function flip(arr, i) { let temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] function findMax(arr, n) { let mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations function pancakeSort(arr, n) { // Start from the complete // array and one by one // reduce current size by one for (let curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] let mi = findMax(arr, curr_size); // Move the maximum element // to end of current array // if it's not already at // the end if (mi != curr_size - 1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size - 1); } } return 0; } // Utility function to print // array arr[] function printArray(arr, arr_size) { for (let i = 0; i < arr_size; i++) document.write(arr[i] + " "); document.write(""); } let arr = [23, 10, 20, 11, 12, 6, 7]; let n = arr.length; pancakeSort(arr, n); document.write("Sorted Array: " + "</br>"); printArray(arr, n); </script>
Sorted Array
6 7 10 11 12 20 23
Time Complexity: O(n2), Total O(n) flip operations are performed in above codeAuxiliary Space: O(1)
References: http://en.wikipedia.org/wiki/Pancake_sortingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
rathbhupendra
Chandan_Kumar
Akanksha_Rai
toshniwalyash05
divyeshrabadiya07
kashishkumar2
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 174,
"s": 54,
"text": "Given an unsorted array, the task is to sort the given array. You are allowed to do only following operation on array. "
},
{
"code": null,
"e": 215,
"s": 174,
"text": "flip(arr, i): Reverse array from 0 to i "
},
{
"code": null,
"e": 225,
"s": 215,
"text": "Examples:"
},
{
"code": null,
"e": 304,
"s": 225,
"text": "Input: arr[] = { 23, 10, 20, 11, 12, 6, 7 }Output: { 6, 7, 10, 11, 12, 20, 23}"
},
{
"code": null,
"e": 362,
"s": 304,
"text": "Input: arr[] = { 0, 1, 1, 0, 0 }Output: { 0, 0, 0, 1, 1 }"
},
{
"code": null,
"e": 540,
"s": 362,
"text": "Approach: Unlike a traditional sorting algorithm, which attempts to sort with the fewest comparisons possible, the goal is to sort the sequence in as few reversals as possible. "
},
{
"code": null,
"e": 688,
"s": 540,
"text": "The idea is to do something similar to Selection Sort. We one by one place maximum element at the end and reduce the size of current array by one. "
},
{
"code": null,
"e": 772,
"s": 688,
"text": "Following are the detailed steps. Let given array be arr[] and size of array be n. "
},
{
"code": null,
"e": 901,
"s": 772,
"text": "Start from current size equal to n and reduce current size by one while it’s greater than 1. Let the current size be curr_size. "
},
{
"code": null,
"e": 1062,
"s": 901,
"text": "Do following for every curr_sizeFind index of the maximum element in arr[0 to curr_szie-1]. Let the index be ‘mi’Call flip(arr, mi)Call flip(arr, curr_size – 1)"
},
{
"code": null,
"e": 1144,
"s": 1062,
"text": "Find index of the maximum element in arr[0 to curr_szie-1]. Let the index be ‘mi’"
},
{
"code": null,
"e": 1163,
"s": 1144,
"text": "Call flip(arr, mi)"
},
{
"code": null,
"e": 1193,
"s": 1163,
"text": "Call flip(arr, curr_size – 1)"
},
{
"code": null,
"e": 1295,
"s": 1193,
"text": "See following video for visualization of the above algorithm.http://www.youtube.com/embed/kk-_DDgoXfk"
},
{
"code": null,
"e": 1324,
"s": 1295,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1326,
"s": 1324,
"text": "C"
},
{
"code": null,
"e": 1330,
"s": 1326,
"text": "CPP"
},
{
"code": null,
"e": 1335,
"s": 1330,
"text": "Java"
},
{
"code": null,
"e": 1343,
"s": 1335,
"text": "Python3"
},
{
"code": null,
"e": 1346,
"s": 1343,
"text": "C#"
},
{
"code": null,
"e": 1350,
"s": 1346,
"text": "PHP"
},
{
"code": null,
"e": 1361,
"s": 1350,
"text": "Javascript"
},
{
"code": "// C program to// sort array using// pancake sort#include <stdio.h>#include <stdlib.h> /* Reverses arr[0..i] */void flip(int arr[], int i){ int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; }} // Returns index of the// maximum element in// arr[0..n-1]int findMax(int arr[], int n){ int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi;} // The main function that// sorts given array using// flip operationsvoid pancakeSort(int* arr, int n){ // Start from the complete // array and one by one // reduce current size // by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum // element to end of // current array if // it's not already // at the end if (mi != curr_size - 1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size - 1); } }} // A utility function to print// n array of size nvoid printArray(int arr[], int n){ for (int i = 0; i < n; ++i) printf(\"%d \", arr[i]);} // Driver program to test above functionint main(){ int arr[] = { 23, 10, 20, 11, 12, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); pancakeSort(arr, n); puts(\"Sorted Array \"); printArray(arr, n); return 0;}",
"e": 3115,
"s": 1361,
"text": null
},
{
"code": "// C++ program to // sort array using // pancake sort #include<bits/stdc++.h> using namespace std; /* Reverses arr[0..i] */void flip(int arr[], int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] int findMax(int arr[], int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations void pancakeSort(int *arr, int n) { // Start from the complete // array and one by one // reduce current size // by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum // element to end of // current array if // it's not already // at the end if (mi != curr_size-1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size-1); } } } // A utility function to print // n array of size n void printArray(int arr[], int n) { for (int i = 0; i < n; ++i) cout<< arr[i]<<\" \"; } // Driver program to test above function int main() { int arr[] = {23, 10, 20, 11, 12, 6, 7}; int n = sizeof(arr)/sizeof(arr[0]); pancakeSort(arr, n); cout<<\"Sorted Array \"<<endl; printArray(arr, n); return 0; } //This code is contributed by rathbhupendra",
"e": 4986,
"s": 3115,
"text": null
},
{
"code": "// Java program to// sort array using// pancake sortimport java.io.*; class PancakeSort { /* Reverses arr[0..i] */ static void flip(int arr[], int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] static int findMax(int arr[], int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations static int pancakeSort(int arr[], int n) { // Start from the complete // array and one by one // reduce current size by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum element // to end of current array // if it's not already at // the end if (mi != curr_size-1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size-1); } } return 0; } /* Utility function to print array arr[] */ static void printArray(int arr[], int arr_size) { for (int i = 0; i < arr_size; i++) System.out.print(arr[i] + \" \"); System.out.println(\"\"); } /* Driver function to check for above functions*/ public static void main (String[] args) { int arr[] = {23, 10, 20, 11, 12, 6, 7}; int n = arr.length; pancakeSort(arr, n); System.out.println(\"Sorted Array: \"); printArray(arr, n); }}/* This code is contributed by Devesh Agrawal*/",
"e": 7193,
"s": 4986,
"text": null
},
{
"code": "# Python3 program to# sort array using# pancake sort # Reverses arr[0..i] */def flip(arr, i): start = 0 while start < i: temp = arr[start] arr[start] = arr[i] arr[i] = temp start += 1 i -= 1 # Returns index of the maximum# element in arr[0..n-1] */def findMax(arr, n): mi = 0 for i in range(0,n): if arr[i] > arr[mi]: mi = i return mi # The main function that # sorts given array # using flip operationsdef pancakeSort(arr, n): # Start from the complete # array and one by one # reduce current size # by one curr_size = n while curr_size > 1: # Find index of the maximum # element in # arr[0..curr_size-1] mi = findMax(arr, curr_size) # Move the maximum element # to end of current array # if it's not already at # the end if mi != curr_size-1: # To move at the end, # first move maximum # number to beginning flip(arr, mi) # Now move the maximum # number to end by # reversing current array flip(arr, curr_size-1) curr_size -= 1 # A utility function to # print an array of size n def printArray(arr, n): for i in range(0,n): print (\"%d\"%( arr[i]),end=\" \") # Driver program arr = [23, 10, 20, 11, 12, 6, 7]n = len(arr)pancakeSort(arr, n);print (\"Sorted Array \")printArray(arr,n) # This code is contributed by shreyanshi_arun.",
"e": 8695,
"s": 7193,
"text": null
},
{
"code": "// C# program to sort array using// pancake sortusing System; class GFG { // Reverses arr[0..i] static void flip(int []arr, int i) { int temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] static int findMax(int []arr, int n) { int mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations static int pancakeSort(int []arr, int n) { // Start from the complete // array and one by one // reduce current size by one for (int curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] int mi = findMax(arr, curr_size); // Move the maximum element // to end of current array // if it's not already at // the end if (mi != curr_size - 1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size - 1); } } return 0; } // Utility function to print // array arr[] static void printArray(int []arr, int arr_size) { for (int i = 0; i < arr_size; i++) Console.Write(arr[i] + \" \"); Console.Write(\"\"); } // Driver function to check for // above functions public static void Main () { int []arr = {23, 10, 20, 11, 12, 6, 7}; int n = arr.Length; pancakeSort(arr, n); Console.Write(\"Sorted Array: \"); printArray(arr, n); }} // This code is contributed by nitin mittal.",
"e": 10960,
"s": 8695,
"text": null
},
{
"code": "<?php// PHP program to// sort array using// pancake sort /* Reverses arr[0..i] */function flip(&$arr, $i){ $start = 0; while ($start < $i) { $temp = $arr[$start]; $arr[$start] = $arr[$i]; $arr[$i] = $temp; $start++; $i--; }} // Returns index of the // maximum element in // arr[0..n-1] function findMax($arr, $n){ $mi = 0; for ($i = 0; $i < $n; ++$i) if ($arr[$i] > $arr[$mi]) $mi = $i; return $mi;} // The main function that // sorts given array using // flip operationsfunction pancakeSort(&$arr, $n){ // Start from the complete // array and one by one // reduce current size // by one for ($curr_size = $n; $curr_size > 1; --$curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] $mi = findMax($arr, $curr_size); // Move the maximum // element to end of // current array if // it's not already // at the end if ($mi != $curr_size-1) { // To move at the end, // first move maximum // number to beginning flip($arr, $mi); // Now move the maximum // number to end by // reversing current array flip($arr, $curr_size-1); } }} // A utility function to print // n array of size n function printArray($arr, $n){ for ($i = 0; $i < $n; ++$i) print($arr[$i].\" \");} // Driver code$arr = array(23, 10, 20, 11, 12, 6, 7);$n = count($arr); pancakeSort($arr, $n); echo(\"Sorted Array \\n\");printArray($arr, $n); return 0; // This code is contributed by chandan_jnu?>",
"e": 12675,
"s": 10960,
"text": null
},
{
"code": "<script> // JavaScript program to sort array using pancake sort // Reverses arr[0..i] function flip(arr, i) { let temp, start = 0; while (start < i) { temp = arr[start]; arr[start] = arr[i]; arr[i] = temp; start++; i--; } } // Returns index of the // maximum element in // arr[0..n-1] function findMax(arr, n) { let mi, i; for (mi = 0, i = 0; i < n; ++i) if (arr[i] > arr[mi]) mi = i; return mi; } // The main function that // sorts given array using // flip operations function pancakeSort(arr, n) { // Start from the complete // array and one by one // reduce current size by one for (let curr_size = n; curr_size > 1; --curr_size) { // Find index of the // maximum element in // arr[0..curr_size-1] let mi = findMax(arr, curr_size); // Move the maximum element // to end of current array // if it's not already at // the end if (mi != curr_size - 1) { // To move at the end, // first move maximum // number to beginning flip(arr, mi); // Now move the maximum // number to end by // reversing current array flip(arr, curr_size - 1); } } return 0; } // Utility function to print // array arr[] function printArray(arr, arr_size) { for (let i = 0; i < arr_size; i++) document.write(arr[i] + \" \"); document.write(\"\"); } let arr = [23, 10, 20, 11, 12, 6, 7]; let n = arr.length; pancakeSort(arr, n); document.write(\"Sorted Array: \" + \"</br>\"); printArray(arr, n); </script>",
"e": 14680,
"s": 12675,
"text": null
},
{
"code": null,
"e": 14714,
"s": 14680,
"text": "Sorted Array \n6 7 10 11 12 20 23 "
},
{
"code": null,
"e": 14814,
"s": 14714,
"text": "Time Complexity: O(n2), Total O(n) flip operations are performed in above codeAuxiliary Space: O(1)"
},
{
"code": null,
"e": 14995,
"s": 14814,
"text": "References: http://en.wikipedia.org/wiki/Pancake_sortingPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 15008,
"s": 14995,
"text": "nitin mittal"
},
{
"code": null,
"e": 15022,
"s": 15008,
"text": "rathbhupendra"
},
{
"code": null,
"e": 15036,
"s": 15022,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 15049,
"s": 15036,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 15065,
"s": 15049,
"text": "toshniwalyash05"
},
{
"code": null,
"e": 15083,
"s": 15065,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 15097,
"s": 15083,
"text": "kashishkumar2"
},
{
"code": null,
"e": 15105,
"s": 15097,
"text": "Sorting"
},
{
"code": null,
"e": 15113,
"s": 15105,
"text": "Sorting"
}
] |
Longest subarray with difference exactly K between any two distinct values
|
30 Sep, 2021
Given an array arr[] of length N and an integer K, the task is to find the longest subarray with difference between any two distinct values equal to K. Print the length of the longest subarray obtained. Otherwise, if no such subarray is obtained, print -1.
Examples:
Input: arr[] = {0, 0, 1, 1, 3, 3, 3}, K = 1 Output: 4 Explanation: The subarray {0, 0, 1, 1} is the only subarray having difference between any two distinct values equal to K( = 1). Hence, length is equal to 4.
Input: arr[] = {5, 7, 1, 1, 2, 4, 4, 4, 5, 5, 4, 5, 8, 9}, K = 1 Output: 7 Explanation: Subarrays {1, 1, 2}, {4, 4, 4, 5, 5, 4, 5} and {8, 9} are the only subarray having difference between any two distinct values equal to K( = 1). The longest subarray among them is {4, 4, 4, 5, 5, 4, 5}. Hence, the length is 7.
Naive Approach:
A simple solution is to consider all subarrays one by one, and find subarrays which contains only two distinct values and the difference between those two values is K. Keep updating the maximum length of subarray obtained.
Finally print the maximum length obtained.
Time Complexity: O(N3) Auxiliary Space: O(N)
Efficient Approach: It can be observed that for any subarray to consist of elements with the difference between any two elements to be exactly K, the subarray must consist of only two distinct values. Hence, the above approach can be further optimized by using set to find longest sub-array having only two distinct values with a difference K. Follow the steps below to solve the problem:
Start the first subarray from starting index of the array.
Insert that element into the set. Proceed to the next element and check if this element is the same as the previous or has an absolute difference of K.
If so, insert that element into the set and continue increasing the length of the subarray. Once, a third distinct element is found, compare the length of the current subarray with the maximum length of the subarray and update accordingly.
Update the new element obtained into the set and proceed to repeat the above steps.
Once, the entire array is traversed, print the maximum length obtained.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to find the// longest subarray consisting of// only two values with difference K#include <bits/stdc++.h>using namespace std; // Function to return the length// of the longest sub-arrayint longestSubarray(int arr[], int n, int k){ int i, j, Max = 1; // Initialize set set<int> s; for (i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.insert(arr[i]); for (j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (abs(arr[i] - arr[j]) == 0 || abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.count(arr[j])) { // If the set contains // two elements if (s.size() == 2) break; // Otherwise else s.insert(arr[j]); } } else break; } if (s.size() == 2) { // Update the maximum // length Max = max(Max, j - i); // Remove the set // elements s.clear(); } else s.clear(); } return Max;} // Driver Codeint main(){ int arr[] = { 1, 0, 2, 2, 5, 5, 5 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 1; int length = longestSubarray( arr, N, K); if (length == 1) cout << -1; else cout << length; return 0;}
// Java implementation to find the// longest subarray consisting of// only two values with difference Kimport java.util.*; class GFG{ // Function to return the length// of the longest sub-arraystatic int longestSubarray(int arr[], int n, int k){ int i, j, Max = 1; // Initialize set HashSet<Integer> s = new HashSet<Integer>(); for(i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.add(arr[i]); for(j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (Math.abs(arr[i] - arr[j]) == 0 || Math.abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.contains(arr[j])) { // If the set contains // two elements if (s.size() == 2) break; // Otherwise else s.add(arr[j]); } } else break; } if (s.size() == 2) { // Update the maximum // length Max = Math.max(Max, j - i); // Remove the set // elements s.clear(); } else s.clear(); } return Max;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 0, 2, 2, 5, 5, 5 }; int N = arr.length; int K = 1; int length = longestSubarray(arr, N, K); if (length == 1) System.out.print(-1); else System.out.print(length);}} // This code is contributed by Princi Singh
# Python3 implementation to find the # longest subarray consisting of # only two values with difference K # Function to return the length # of the longest sub-arraydef longestSubarray (arr, n, k): Max = 1 # Initialize set s = set() for i in range(n - 1): # Store 1st element of # sub-array into set s.add(arr[i]) for j in range(i + 1, n): # Check absolute difference # between two elements if (abs(arr[i] - arr[j]) == 0 or abs(arr[i] - arr[j]) == k): # If the new element is not # present in the set if (not arr[j] in s): # If the set contains # two elements if (len(s) == 2): break # Otherwise else: s.add(arr[j]) else: break if (len(s) == 2): # Update the maximum length Max = max(Max, j - i) # Remove the set elements s.clear() else: s.clear() return Max # Driver Codeif __name__ == '__main__': arr = [ 1, 0, 2, 2, 5, 5, 5 ] N = len(arr) K = 1 length = longestSubarray(arr, N, K) if (length == 1): print("-1") else: print(length) # This code is contributed by himanshu77
// C# implementation to find the// longest subarray consisting of// only two values with difference Kusing System;using System.Collections.Generic; class GFG{ // Function to return the length// of the longest sub-arraystatic int longestSubarray(int []arr, int n, int k){ int i, j, Max = 1; // Initialize set HashSet<int> s = new HashSet<int>(); for(i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.Add(arr[i]); for(j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (Math.Abs(arr[i] - arr[j]) == 0 || Math.Abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.Contains(arr[j])) { // If the set contains // two elements if (s.Count == 2) break; // Otherwise else s.Add(arr[j]); } } else break; } if (s.Count == 2) { // Update the maximum // length Max = Math.Max(Max, j - i); // Remove the set // elements s.Clear(); } else s.Clear(); } return Max;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 0, 2, 2, 5, 5, 5 }; int N = arr.Length; int K = 1; int length = longestSubarray(arr, N, K); if (length == 1) Console.Write(-1); else Console.Write(length);}} // This code is contributed by Princi Singh
<script> // Javascript implementation to find the // longest subarray consisting of // only two values with difference K // Function to return the length // of the longest sub-array function longestSubarray(arr, n, k) { let i, j, Max = 1; // Initialize set let s = new Set(); for (i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.add(arr[i]); for (j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (Math.abs(arr[i] - arr[j]) == 0 || Math.abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.has(arr[j])) { // If the set contains // two elements if (s.size == 2) break; // Otherwise else s.add(arr[j]); } } else break; } if (s.size == 2) { // Update the maximum // length Max = Math.max(Max, j - i); // Remove the set // elements s.clear; } else s.clear; } return Max; } let arr = [ 1, 0, 2, 2, 5, 5, 5 ]; let N = arr.length; let K = 1; let length = longestSubarray(arr, N, K); if (length == 1) document.write(-1); else document.write(length); // This code is contributed by decode2207.</script>
2
Time Complexity: O(N2 * logN) Auxiliary Space: O(N)
princi singh
himanshu77
anikaseth98
decode2207
cpp-set
subarray
two-pointer-algorithm
Arrays
Competitive Programming
Searching
two-pointer-algorithm
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 309,
"s": 52,
"text": "Given an array arr[] of length N and an integer K, the task is to find the longest subarray with difference between any two distinct values equal to K. Print the length of the longest subarray obtained. Otherwise, if no such subarray is obtained, print -1."
},
{
"code": null,
"e": 320,
"s": 309,
"text": "Examples: "
},
{
"code": null,
"e": 531,
"s": 320,
"text": "Input: arr[] = {0, 0, 1, 1, 3, 3, 3}, K = 1 Output: 4 Explanation: The subarray {0, 0, 1, 1} is the only subarray having difference between any two distinct values equal to K( = 1). Hence, length is equal to 4."
},
{
"code": null,
"e": 846,
"s": 531,
"text": "Input: arr[] = {5, 7, 1, 1, 2, 4, 4, 4, 5, 5, 4, 5, 8, 9}, K = 1 Output: 7 Explanation: Subarrays {1, 1, 2}, {4, 4, 4, 5, 5, 4, 5} and {8, 9} are the only subarray having difference between any two distinct values equal to K( = 1). The longest subarray among them is {4, 4, 4, 5, 5, 4, 5}. Hence, the length is 7. "
},
{
"code": null,
"e": 862,
"s": 846,
"text": "Naive Approach:"
},
{
"code": null,
"e": 1085,
"s": 862,
"text": "A simple solution is to consider all subarrays one by one, and find subarrays which contains only two distinct values and the difference between those two values is K. Keep updating the maximum length of subarray obtained."
},
{
"code": null,
"e": 1128,
"s": 1085,
"text": "Finally print the maximum length obtained."
},
{
"code": null,
"e": 1173,
"s": 1128,
"text": "Time Complexity: O(N3) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 1563,
"s": 1173,
"text": "Efficient Approach: It can be observed that for any subarray to consist of elements with the difference between any two elements to be exactly K, the subarray must consist of only two distinct values. Hence, the above approach can be further optimized by using set to find longest sub-array having only two distinct values with a difference K. Follow the steps below to solve the problem: "
},
{
"code": null,
"e": 1622,
"s": 1563,
"text": "Start the first subarray from starting index of the array."
},
{
"code": null,
"e": 1774,
"s": 1622,
"text": "Insert that element into the set. Proceed to the next element and check if this element is the same as the previous or has an absolute difference of K."
},
{
"code": null,
"e": 2014,
"s": 1774,
"text": "If so, insert that element into the set and continue increasing the length of the subarray. Once, a third distinct element is found, compare the length of the current subarray with the maximum length of the subarray and update accordingly."
},
{
"code": null,
"e": 2098,
"s": 2014,
"text": "Update the new element obtained into the set and proceed to repeat the above steps."
},
{
"code": null,
"e": 2170,
"s": 2098,
"text": "Once, the entire array is traversed, print the maximum length obtained."
},
{
"code": null,
"e": 2221,
"s": 2170,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2225,
"s": 2221,
"text": "C++"
},
{
"code": null,
"e": 2230,
"s": 2225,
"text": "Java"
},
{
"code": null,
"e": 2238,
"s": 2230,
"text": "Python3"
},
{
"code": null,
"e": 2241,
"s": 2238,
"text": "C#"
},
{
"code": null,
"e": 2252,
"s": 2241,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the// longest subarray consisting of// only two values with difference K#include <bits/stdc++.h>using namespace std; // Function to return the length// of the longest sub-arrayint longestSubarray(int arr[], int n, int k){ int i, j, Max = 1; // Initialize set set<int> s; for (i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.insert(arr[i]); for (j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (abs(arr[i] - arr[j]) == 0 || abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.count(arr[j])) { // If the set contains // two elements if (s.size() == 2) break; // Otherwise else s.insert(arr[j]); } } else break; } if (s.size() == 2) { // Update the maximum // length Max = max(Max, j - i); // Remove the set // elements s.clear(); } else s.clear(); } return Max;} // Driver Codeint main(){ int arr[] = { 1, 0, 2, 2, 5, 5, 5 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 1; int length = longestSubarray( arr, N, K); if (length == 1) cout << -1; else cout << length; return 0;}",
"e": 3875,
"s": 2252,
"text": null
},
{
"code": "// Java implementation to find the// longest subarray consisting of// only two values with difference Kimport java.util.*; class GFG{ // Function to return the length// of the longest sub-arraystatic int longestSubarray(int arr[], int n, int k){ int i, j, Max = 1; // Initialize set HashSet<Integer> s = new HashSet<Integer>(); for(i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.add(arr[i]); for(j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (Math.abs(arr[i] - arr[j]) == 0 || Math.abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.contains(arr[j])) { // If the set contains // two elements if (s.size() == 2) break; // Otherwise else s.add(arr[j]); } } else break; } if (s.size() == 2) { // Update the maximum // length Max = Math.max(Max, j - i); // Remove the set // elements s.clear(); } else s.clear(); } return Max;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 0, 2, 2, 5, 5, 5 }; int N = arr.length; int K = 1; int length = longestSubarray(arr, N, K); if (length == 1) System.out.print(-1); else System.out.print(length);}} // This code is contributed by Princi Singh",
"e": 5690,
"s": 3875,
"text": null
},
{
"code": "# Python3 implementation to find the # longest subarray consisting of # only two values with difference K # Function to return the length # of the longest sub-arraydef longestSubarray (arr, n, k): Max = 1 # Initialize set s = set() for i in range(n - 1): # Store 1st element of # sub-array into set s.add(arr[i]) for j in range(i + 1, n): # Check absolute difference # between two elements if (abs(arr[i] - arr[j]) == 0 or abs(arr[i] - arr[j]) == k): # If the new element is not # present in the set if (not arr[j] in s): # If the set contains # two elements if (len(s) == 2): break # Otherwise else: s.add(arr[j]) else: break if (len(s) == 2): # Update the maximum length Max = max(Max, j - i) # Remove the set elements s.clear() else: s.clear() return Max # Driver Codeif __name__ == '__main__': arr = [ 1, 0, 2, 2, 5, 5, 5 ] N = len(arr) K = 1 length = longestSubarray(arr, N, K) if (length == 1): print(\"-1\") else: print(length) # This code is contributed by himanshu77",
"e": 7128,
"s": 5690,
"text": null
},
{
"code": "// C# implementation to find the// longest subarray consisting of// only two values with difference Kusing System;using System.Collections.Generic; class GFG{ // Function to return the length// of the longest sub-arraystatic int longestSubarray(int []arr, int n, int k){ int i, j, Max = 1; // Initialize set HashSet<int> s = new HashSet<int>(); for(i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.Add(arr[i]); for(j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (Math.Abs(arr[i] - arr[j]) == 0 || Math.Abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.Contains(arr[j])) { // If the set contains // two elements if (s.Count == 2) break; // Otherwise else s.Add(arr[j]); } } else break; } if (s.Count == 2) { // Update the maximum // length Max = Math.Max(Max, j - i); // Remove the set // elements s.Clear(); } else s.Clear(); } return Max;} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 0, 2, 2, 5, 5, 5 }; int N = arr.Length; int K = 1; int length = longestSubarray(arr, N, K); if (length == 1) Console.Write(-1); else Console.Write(length);}} // This code is contributed by Princi Singh",
"e": 8966,
"s": 7128,
"text": null
},
{
"code": "<script> // Javascript implementation to find the // longest subarray consisting of // only two values with difference K // Function to return the length // of the longest sub-array function longestSubarray(arr, n, k) { let i, j, Max = 1; // Initialize set let s = new Set(); for (i = 0; i < n - 1; i++) { // Store 1st element of // sub-array into set s.add(arr[i]); for (j = i + 1; j < n; j++) { // Check absolute difference // between two elements if (Math.abs(arr[i] - arr[j]) == 0 || Math.abs(arr[i] - arr[j]) == k) { // If the new element is not // present in the set if (!s.has(arr[j])) { // If the set contains // two elements if (s.size == 2) break; // Otherwise else s.add(arr[j]); } } else break; } if (s.size == 2) { // Update the maximum // length Max = Math.max(Max, j - i); // Remove the set // elements s.clear; } else s.clear; } return Max; } let arr = [ 1, 0, 2, 2, 5, 5, 5 ]; let N = arr.length; let K = 1; let length = longestSubarray(arr, N, K); if (length == 1) document.write(-1); else document.write(length); // This code is contributed by decode2207.</script>",
"e": 10726,
"s": 8966,
"text": null
},
{
"code": null,
"e": 10728,
"s": 10726,
"text": "2"
},
{
"code": null,
"e": 10784,
"s": 10730,
"text": "Time Complexity: O(N2 * logN) Auxiliary Space: O(N) "
},
{
"code": null,
"e": 10797,
"s": 10784,
"text": "princi singh"
},
{
"code": null,
"e": 10808,
"s": 10797,
"text": "himanshu77"
},
{
"code": null,
"e": 10820,
"s": 10808,
"text": "anikaseth98"
},
{
"code": null,
"e": 10831,
"s": 10820,
"text": "decode2207"
},
{
"code": null,
"e": 10839,
"s": 10831,
"text": "cpp-set"
},
{
"code": null,
"e": 10848,
"s": 10839,
"text": "subarray"
},
{
"code": null,
"e": 10870,
"s": 10848,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 10877,
"s": 10870,
"text": "Arrays"
},
{
"code": null,
"e": 10901,
"s": 10877,
"text": "Competitive Programming"
},
{
"code": null,
"e": 10911,
"s": 10901,
"text": "Searching"
},
{
"code": null,
"e": 10933,
"s": 10911,
"text": "two-pointer-algorithm"
},
{
"code": null,
"e": 10940,
"s": 10933,
"text": "Arrays"
},
{
"code": null,
"e": 10950,
"s": 10940,
"text": "Searching"
}
] |
Difference between big O notations and tilde
|
09 Jun, 2021
In asymptotic analysis of algorithms we often encounter terms like Big-Oh, Omega, Theta and Tilde, which describe the performance of an algorithm. You can refer to the following links to get more insights about asymptotic analysis :
Analysis of Algorithms Different NotationsDifference between Big Oh, Big Omega and Big Theta
Analysis of Algorithms
Different Notations
Difference between Big Oh, Big Omega and Big Theta
In this article we are going to see the difference between the two notations: Big Oh and Tilde.
1. Big Oh notation (O) :This notation is basically used to describe the asymptotic upper bound. Mathematically, we can describe it as :
f(n) = O(g(n))
if there exist positive constants c and
n0 such that
0 <= f(n) <= c*g(n)
for all n >= n0
The above notation depicts that at the point n=n0, the growth of the function g(n) increases gradually. In algorithms we always deal with larger values of n i.e. n→∞. So, we can also define the Big-Oh notation as :
Therefore, f(n) = O(g(n)) if the above limit value lies in the range [ 0 , ∞ )
Example –
2. Tilde Notation (~) :Tilde notation is used when we want to make a simple approximation of a complex function. It simply drops the lower order terms. It is denoted by ~g(n).If f(n)~g(n) indicates that the value of f(n)/g(n) tends towards 1 for a larger value of n. Mathematically, we can express it as :
Example 1. can be written as ~because when we divide both the functions and find the limit for larger value of n, it will become 1.
2 – In an AVL tree before we insert or delete a key, we first compare and find the location of the key. The number of comparisons required in the worst case is :
h+1, where h is the height of the tree.
The height will be , since AVL tree is a height balanced tree.
Therefore, we can replace the value of h in the expression and it becomes :
We can ignore the lower order term and it becomes ~. So, the number of comparisons in an AVL tree is approximated to ~.
Some important points about ~ notation in asymptotic analysis –
It follows equivalence relation property.
It is identical to big theta notation. There is a minute difference in the arbitrary constant as in big theta notation there can be different values for the constants in the lower bound as well as upper bound but in the case of Tilde, we always get f/g value as 1 or tending towards 1.
The differences between Big Oh and Tilde notations are :
The arbitrary constant incase of Big Oh notation is c which is greater than zero.
0 <= f(n) <= c*g(n) ; c>0, n>=n0
If the time complexity of any algorithm is
,it is given by O() and the constant is ignored.
Algorithms-Analysis of Algorithms
Picked
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Three address code in Compiler
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Phases of a Compiler
Difference between DELETE, DROP and TRUNCATE
Code Optimization in Compiler Design
Segmentation in Operating System
User Datagram Protocol (UDP)
Peephole Optimization in Compiler Design
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 286,
"s": 53,
"text": "In asymptotic analysis of algorithms we often encounter terms like Big-Oh, Omega, Theta and Tilde, which describe the performance of an algorithm. You can refer to the following links to get more insights about asymptotic analysis :"
},
{
"code": null,
"e": 379,
"s": 286,
"text": "Analysis of Algorithms Different NotationsDifference between Big Oh, Big Omega and Big Theta"
},
{
"code": null,
"e": 403,
"s": 379,
"text": "Analysis of Algorithms "
},
{
"code": null,
"e": 423,
"s": 403,
"text": "Different Notations"
},
{
"code": null,
"e": 474,
"s": 423,
"text": "Difference between Big Oh, Big Omega and Big Theta"
},
{
"code": null,
"e": 570,
"s": 474,
"text": "In this article we are going to see the difference between the two notations: Big Oh and Tilde."
},
{
"code": null,
"e": 706,
"s": 570,
"text": "1. Big Oh notation (O) :This notation is basically used to describe the asymptotic upper bound. Mathematically, we can describe it as :"
},
{
"code": null,
"e": 814,
"s": 706,
"text": "f(n) = O(g(n)) \nif there exist positive constants c and \nn0 such that \n0 <= f(n) <= c*g(n) \nfor all n >= n0"
},
{
"code": null,
"e": 1029,
"s": 814,
"text": "The above notation depicts that at the point n=n0, the growth of the function g(n) increases gradually. In algorithms we always deal with larger values of n i.e. n→∞. So, we can also define the Big-Oh notation as :"
},
{
"code": null,
"e": 1108,
"s": 1029,
"text": "Therefore, f(n) = O(g(n)) if the above limit value lies in the range [ 0 , ∞ )"
},
{
"code": null,
"e": 1119,
"s": 1108,
"text": "Example – "
},
{
"code": null,
"e": 1425,
"s": 1119,
"text": "2. Tilde Notation (~) :Tilde notation is used when we want to make a simple approximation of a complex function. It simply drops the lower order terms. It is denoted by ~g(n).If f(n)~g(n) indicates that the value of f(n)/g(n) tends towards 1 for a larger value of n. Mathematically, we can express it as :"
},
{
"code": null,
"e": 1558,
"s": 1425,
"text": "Example 1. can be written as ~because when we divide both the functions and find the limit for larger value of n, it will become 1."
},
{
"code": null,
"e": 1720,
"s": 1558,
"text": "2 – In an AVL tree before we insert or delete a key, we first compare and find the location of the key. The number of comparisons required in the worst case is :"
},
{
"code": null,
"e": 1825,
"s": 1720,
"text": "h+1, where h is the height of the tree. \nThe height will be , since AVL tree is a height balanced tree. "
},
{
"code": null,
"e": 1901,
"s": 1825,
"text": "Therefore, we can replace the value of h in the expression and it becomes :"
},
{
"code": null,
"e": 2021,
"s": 1901,
"text": "We can ignore the lower order term and it becomes ~. So, the number of comparisons in an AVL tree is approximated to ~."
},
{
"code": null,
"e": 2085,
"s": 2021,
"text": "Some important points about ~ notation in asymptotic analysis –"
},
{
"code": null,
"e": 2127,
"s": 2085,
"text": "It follows equivalence relation property."
},
{
"code": null,
"e": 2413,
"s": 2127,
"text": "It is identical to big theta notation. There is a minute difference in the arbitrary constant as in big theta notation there can be different values for the constants in the lower bound as well as upper bound but in the case of Tilde, we always get f/g value as 1 or tending towards 1."
},
{
"code": null,
"e": 2470,
"s": 2413,
"text": "The differences between Big Oh and Tilde notations are :"
},
{
"code": null,
"e": 2552,
"s": 2470,
"text": "The arbitrary constant incase of Big Oh notation is c which is greater than zero."
},
{
"code": null,
"e": 2585,
"s": 2552,
"text": "0 <= f(n) <= c*g(n) ; c>0, n>=n0"
},
{
"code": null,
"e": 2629,
"s": 2585,
"text": "If the time complexity of any algorithm is "
},
{
"code": null,
"e": 2679,
"s": 2629,
"text": ",it is given by O() and the constant is ignored."
},
{
"code": null,
"e": 2713,
"s": 2679,
"text": "Algorithms-Analysis of Algorithms"
},
{
"code": null,
"e": 2720,
"s": 2713,
"text": "Picked"
},
{
"code": null,
"e": 2728,
"s": 2720,
"text": "GATE CS"
},
{
"code": null,
"e": 2826,
"s": 2728,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2879,
"s": 2826,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2910,
"s": 2879,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 2944,
"s": 2910,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 2984,
"s": 2944,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 3005,
"s": 2984,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 3050,
"s": 3005,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 3087,
"s": 3050,
"text": "Code Optimization in Compiler Design"
},
{
"code": null,
"e": 3120,
"s": 3087,
"text": "Segmentation in Operating System"
},
{
"code": null,
"e": 3149,
"s": 3120,
"text": "User Datagram Protocol (UDP)"
}
] |
What is Is-A-Relationship in Java?
|
01 Dec, 2021
A relationship in Java means different relations between two or more classes. For example, if a class Bulb inherits another class Device, then we can say that Bulb is having is-a relationship with Device, which implies Bulb is a device.
In Java, we have two types of relationship:
Is-A relationship: Whenever one class inherits another class, it is called an IS-A relationship.Has-A relationship: Whenever an instance of one class is used in another class, it is called HAS-A relationship.
Is-A relationship: Whenever one class inherits another class, it is called an IS-A relationship.
Has-A relationship: Whenever an instance of one class is used in another class, it is called HAS-A relationship.
IS-A Relationship is wholly related to Inheritance. For example – a kiwi is a fruit; a bulb is a device.
IS-A relationship can simply be achieved by using extends Keyword.
IS-A relationship is additionally used for code reusability in Java and to avoid code redundancy.
IS-A relationship is unidirectional, which means we can say that a bulb is a device, but vice versa; a device is a bulb is not possible since all the devices are not bulbs.
IS-A relationship is tightly coupled, which means changing one entity will affect another entity.
Code Reusability.
Reduce redundancy.
IS-A relationship can simply be achieved by extending an interface or class by using extend keyword.
Let’s understand the IS-A relationship with the help of a flowchart –
In the above flowchart, the class Bulb extends class Device, which implies that Device is the parent class of Bulb, and Class Bulb is said to have an Is-A relationship. Therefore we can say Bulb Is-A device.
1. Class Device has a field named as deviceName.
2. Class Bulb extends Device that means Bulb is a type of Device.
3. Since Device is the parent class which implies that class Device can store the reference of an instance of class Bulb.
Example: Here is the implementation of the same, which is as follows:
Java
// Java program to demonstrate the // working of the Is-A relationship import java.io.*; // parent classclass Device { private String deviceName; public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getDeviceName() { return this.deviceName + " is a Device"; }} // child classclass Bulb extends Device { public static void main(String gg[]) { // parent class can store the reference // of instance of child classes Device device = new Bulb(); // set the device name to bulb System.out.println("Device name is Bulb"); device.setDeviceName("Bulb"); // print the device name System.out.println(device.getDeviceName()); }}
Device name is Bulb
Bulb is a Device
In the above java program Bulb class inherits the Device class. Therefore, we can say that Bulb is having an IS-A relationship with the class Device. Hence Bulb is a Device.
java-inheritance
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Stream In Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
Introduction to Java
Initializing a List in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 293,
"s": 54,
"text": "A relationship in Java means different relations between two or more classes. For example, if a class Bulb inherits another class Device, then we can say that Bulb is having is-a relationship with Device, which implies Bulb is a device. "
},
{
"code": null,
"e": 337,
"s": 293,
"text": "In Java, we have two types of relationship:"
},
{
"code": null,
"e": 546,
"s": 337,
"text": "Is-A relationship: Whenever one class inherits another class, it is called an IS-A relationship.Has-A relationship: Whenever an instance of one class is used in another class, it is called HAS-A relationship."
},
{
"code": null,
"e": 643,
"s": 546,
"text": "Is-A relationship: Whenever one class inherits another class, it is called an IS-A relationship."
},
{
"code": null,
"e": 756,
"s": 643,
"text": "Has-A relationship: Whenever an instance of one class is used in another class, it is called HAS-A relationship."
},
{
"code": null,
"e": 861,
"s": 756,
"text": "IS-A Relationship is wholly related to Inheritance. For example – a kiwi is a fruit; a bulb is a device."
},
{
"code": null,
"e": 928,
"s": 861,
"text": "IS-A relationship can simply be achieved by using extends Keyword."
},
{
"code": null,
"e": 1026,
"s": 928,
"text": "IS-A relationship is additionally used for code reusability in Java and to avoid code redundancy."
},
{
"code": null,
"e": 1199,
"s": 1026,
"text": "IS-A relationship is unidirectional, which means we can say that a bulb is a device, but vice versa; a device is a bulb is not possible since all the devices are not bulbs."
},
{
"code": null,
"e": 1297,
"s": 1199,
"text": "IS-A relationship is tightly coupled, which means changing one entity will affect another entity."
},
{
"code": null,
"e": 1315,
"s": 1297,
"text": "Code Reusability."
},
{
"code": null,
"e": 1334,
"s": 1315,
"text": "Reduce redundancy."
},
{
"code": null,
"e": 1435,
"s": 1334,
"text": "IS-A relationship can simply be achieved by extending an interface or class by using extend keyword."
},
{
"code": null,
"e": 1505,
"s": 1435,
"text": "Let’s understand the IS-A relationship with the help of a flowchart –"
},
{
"code": null,
"e": 1713,
"s": 1505,
"text": "In the above flowchart, the class Bulb extends class Device, which implies that Device is the parent class of Bulb, and Class Bulb is said to have an Is-A relationship. Therefore we can say Bulb Is-A device."
},
{
"code": null,
"e": 1762,
"s": 1713,
"text": "1. Class Device has a field named as deviceName."
},
{
"code": null,
"e": 1828,
"s": 1762,
"text": "2. Class Bulb extends Device that means Bulb is a type of Device."
},
{
"code": null,
"e": 1950,
"s": 1828,
"text": "3. Since Device is the parent class which implies that class Device can store the reference of an instance of class Bulb."
},
{
"code": null,
"e": 2021,
"s": 1950,
"text": "Example: Here is the implementation of the same, which is as follows: "
},
{
"code": null,
"e": 2026,
"s": 2021,
"text": "Java"
},
{
"code": "// Java program to demonstrate the // working of the Is-A relationship import java.io.*; // parent classclass Device { private String deviceName; public void setDeviceName(String deviceName) { this.deviceName = deviceName; } public String getDeviceName() { return this.deviceName + \" is a Device\"; }} // child classclass Bulb extends Device { public static void main(String gg[]) { // parent class can store the reference // of instance of child classes Device device = new Bulb(); // set the device name to bulb System.out.println(\"Device name is Bulb\"); device.setDeviceName(\"Bulb\"); // print the device name System.out.println(device.getDeviceName()); }}",
"e": 2809,
"s": 2026,
"text": null
},
{
"code": null,
"e": 2846,
"s": 2809,
"text": "Device name is Bulb\nBulb is a Device"
},
{
"code": null,
"e": 3020,
"s": 2846,
"text": "In the above java program Bulb class inherits the Device class. Therefore, we can say that Bulb is having an IS-A relationship with the class Device. Hence Bulb is a Device."
},
{
"code": null,
"e": 3037,
"s": 3020,
"text": "java-inheritance"
},
{
"code": null,
"e": 3044,
"s": 3037,
"text": "Picked"
},
{
"code": null,
"e": 3049,
"s": 3044,
"text": "Java"
},
{
"code": null,
"e": 3054,
"s": 3049,
"text": "Java"
},
{
"code": null,
"e": 3152,
"s": 3054,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3171,
"s": 3152,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3189,
"s": 3171,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3209,
"s": 3189,
"text": "Collections in Java"
},
{
"code": null,
"e": 3224,
"s": 3209,
"text": "Stream In Java"
},
{
"code": null,
"e": 3256,
"s": 3224,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 3280,
"s": 3256,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3292,
"s": 3280,
"text": "Set in Java"
},
{
"code": null,
"e": 3312,
"s": 3292,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3333,
"s": 3312,
"text": "Introduction to Java"
}
] |
JavaScript | Errors – Throw and Try to Catch
|
27 Mar, 2019
When executing JavaScript code, errors will most definitely occur. These errors can occur due to the fault from the programmer’s side or the input is wrong or even if there is a problem with the logic of the program. But all errors can be solved and to do so we use five statements that will now be explained.
The try statement lets you test a block of code to check for errors.
The catch statement lets you handle the error if any are present.
The throw statement lets you make your own errors.
The finally statement lets you execute code, after try and catch.The finally block runs regardless of the result of the try-catch block.
Simple error example:
try { dadalert("Welcome Fellow Geek!");}catch(err) { console.log(err);}
In the above code we make use of ‘dadalert’ which is not a reserved keyword, and is neither defined hence we get the error.Output:
Another Example:
function geekFunc() { let a = 10; try { alert("Value of variable a is : " + a ); } catch ( e ) { alert("Error: " + e.description ); }}geekFunc();
In the above code, our catch block will not run as there’s no error in the above code and hence we get the output ‘Value of variable a is: 10’.Output:Try and Catch Block:
The try statement allows you to check whether a specific block of code contains an error or not.
The catch statement allows you to display the error if any are found in the try block.
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
Example:
try { dadalert("Welcome Fellow Geek!");}catch(err) { console.log(err);}
Output:
Javascript Throws BlockThe throw Statement.When any error occurs, JavaScript will stop and generate an error message. The throw statement lets you create your own custom error. Technically you can throw your custom exception (throw an error). The exceptioncan be a JavaScript Number, String, Boolean or Object. By using throw together with try and catch, youcan easily control the program flow and generate custom error messages.
Example:
try { throw new Error('Yeah... Sorry');}catch(e) { console.log(e);}
Output:The finally BlockThe finally Statement runs unconditionally after the execution of the try/catch block. Its syntax is
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
finally {
Finally Block executes regardless of the try / catch result.
}
Example:
try { alert( 'try' );} catch (e) { alert( 'catch' );} finally { alert( 'finally' );}
Output:The Finally Block can also override the message of the catch block so be careful while using it.
javascript-basics
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 364,
"s": 54,
"text": "When executing JavaScript code, errors will most definitely occur. These errors can occur due to the fault from the programmer’s side or the input is wrong or even if there is a problem with the logic of the program. But all errors can be solved and to do so we use five statements that will now be explained."
},
{
"code": null,
"e": 433,
"s": 364,
"text": "The try statement lets you test a block of code to check for errors."
},
{
"code": null,
"e": 499,
"s": 433,
"text": "The catch statement lets you handle the error if any are present."
},
{
"code": null,
"e": 550,
"s": 499,
"text": "The throw statement lets you make your own errors."
},
{
"code": null,
"e": 687,
"s": 550,
"text": "The finally statement lets you execute code, after try and catch.The finally block runs regardless of the result of the try-catch block."
},
{
"code": null,
"e": 709,
"s": 687,
"text": "Simple error example:"
},
{
"code": "try { dadalert(\"Welcome Fellow Geek!\");}catch(err) { console.log(err);}",
"e": 783,
"s": 709,
"text": null
},
{
"code": null,
"e": 914,
"s": 783,
"text": "In the above code we make use of ‘dadalert’ which is not a reserved keyword, and is neither defined hence we get the error.Output:"
},
{
"code": null,
"e": 931,
"s": 914,
"text": "Another Example:"
},
{
"code": "function geekFunc() { let a = 10; try { alert(\"Value of variable a is : \" + a ); } catch ( e ) { alert(\"Error: \" + e.description ); }}geekFunc();",
"e": 1098,
"s": 931,
"text": null
},
{
"code": null,
"e": 1269,
"s": 1098,
"text": "In the above code, our catch block will not run as there’s no error in the above code and hence we get the output ‘Value of variable a is: 10’.Output:Try and Catch Block:"
},
{
"code": null,
"e": 1366,
"s": 1269,
"text": "The try statement allows you to check whether a specific block of code contains an error or not."
},
{
"code": null,
"e": 1453,
"s": 1366,
"text": "The catch statement allows you to display the error if any are found in the try block."
},
{
"code": null,
"e": 1542,
"s": 1453,
"text": "try {\n Try Block to check for errors.\n}\ncatch(err) {\n Catch Block to display errors.\n}\n"
},
{
"code": null,
"e": 1551,
"s": 1542,
"text": "Example:"
},
{
"code": "try { dadalert(\"Welcome Fellow Geek!\");}catch(err) { console.log(err);}",
"e": 1625,
"s": 1551,
"text": null
},
{
"code": null,
"e": 1633,
"s": 1625,
"text": "Output:"
},
{
"code": null,
"e": 2063,
"s": 1633,
"text": "Javascript Throws BlockThe throw Statement.When any error occurs, JavaScript will stop and generate an error message. The throw statement lets you create your own custom error. Technically you can throw your custom exception (throw an error). The exceptioncan be a JavaScript Number, String, Boolean or Object. By using throw together with try and catch, youcan easily control the program flow and generate custom error messages."
},
{
"code": null,
"e": 2072,
"s": 2063,
"text": "Example:"
},
{
"code": "try { throw new Error('Yeah... Sorry');}catch(e) { console.log(e);}",
"e": 2146,
"s": 2072,
"text": null
},
{
"code": null,
"e": 2271,
"s": 2146,
"text": "Output:The finally BlockThe finally Statement runs unconditionally after the execution of the try/catch block. Its syntax is"
},
{
"code": null,
"e": 2437,
"s": 2271,
"text": " try {\n Try Block to check for errors.\n}\ncatch(err) {\n Catch Block to display errors.\n} \nfinally {\n Finally Block executes regardless of the try / catch result.\n}\n"
},
{
"code": null,
"e": 2446,
"s": 2437,
"text": "Example:"
},
{
"code": "try { alert( 'try' );} catch (e) { alert( 'catch' );} finally { alert( 'finally' );} ",
"e": 2547,
"s": 2446,
"text": null
},
{
"code": null,
"e": 2651,
"s": 2547,
"text": "Output:The Finally Block can also override the message of the catch block so be careful while using it."
},
{
"code": null,
"e": 2669,
"s": 2651,
"text": "javascript-basics"
},
{
"code": null,
"e": 2676,
"s": 2669,
"text": "Picked"
},
{
"code": null,
"e": 2687,
"s": 2676,
"text": "JavaScript"
},
{
"code": null,
"e": 2704,
"s": 2687,
"text": "Web Technologies"
},
{
"code": null,
"e": 2802,
"s": 2704,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2863,
"s": 2802,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2935,
"s": 2863,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2975,
"s": 2935,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3028,
"s": 2975,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 3080,
"s": 3028,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 3142,
"s": 3080,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3175,
"s": 3142,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3236,
"s": 3175,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3286,
"s": 3236,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Python | Sessions framework using django
|
24 Jun, 2019
Prerequisites: Django Installation | Introduction to Django
Sessions framework can be used to provide persistent behaviour for anonymous users in the website.Sessions are the mechanism used by Django for you store and retrieve data on a per-site-visitor basis.Django uses a cookie containing a special session id.
To enable the session in the django, you will need to make sure of two things in settings.py :
MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activatedINSTALLED_APPS has ‘django.contrib.sessions’ added.# Application definitionINSTALLED APPS = ['dhun','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]MIDDLEWARE = ['django.middleware.securitY.SecuritYMiddleware','django.contrib.sessions.middleware.SessionMiddLeware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMidd1eware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]
MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activated
INSTALLED_APPS has ‘django.contrib.sessions’ added.
# Application definitionINSTALLED APPS = ['dhun','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]MIDDLEWARE = ['django.middleware.securitY.SecuritYMiddleware','django.contrib.sessions.middleware.SessionMiddLeware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMidd1eware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]
After enabling the session, the session database table has to create and to do this run the following command:
python manage.py syncdb
After running previous command and if it didn’t find any errors then later run the command given below to finally reflect the changes saved onto the migration file onto the database.
python manage.py migrate
Now once sessions are created, then testing of the cookies has to be done. In views.py, set the test cookie in the index view, and test the cookie in your about view.
from django.shortcuts import renderfrom django.http import HttpResponsefrom .models import Album def home(request) : a = Album.objects.all() return render(request, "dhun/home.html ", {"Album":a}) def index(request) : num_authors = Author.objects.count() request.session.set_test_cookie() num_visits = request.session.get( 'num_visits', 0) request.session ['num_visits'] = num_visits + 1 context ={ 'num_books':num_books, 'num_instances':num_instances, 'num_instances available':num_instances_available, 'num_authors':num_authors, 'num_visits':num_visits, } def about(request): LANGUAGE_CODE ='en-us ' TIME_ZONE ='UTC' if request.session.test_cookie_worked(): print ("Cookie Tested !") request.session.delete_test_cookie()
To see the work done till now.
First run the localhost through this command.python manage.py runserver
python manage.py runserver
Then Open http://localhost:8000/ in the browser.
Visit the index page then visit the about page. The “Cookie Tested!” will be printed out to the console.
To know how many times the site has been visited.You have to do following two things In views.py:
Add and update the code in the index view function/li>Update the about view functionfrom django.shortcuts import renderfrom django.http import HttpResponsefrom .models import Album def home(request): a = AIbum. objects.all() return render(request, "dhun/home.html", {"album":a}) def index(request): visits = int(reques.COOKIES.get('visits', '0')) response = HttpResponse(template.render(context)) if request.COOKIES.has_key('last_visit'): last_visit = request. COOKIES [ ' last_visit'] last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S") " curr_time = datetime.now() if (curr_time—last_visit_time).days > O: response.set_cookie( 'visits ', visits + 1) response. set_cookie( ' last_visit', datetime.now()) else : response.set_cookie( ' last_visit', datetime.now()) return response def about(request) : context = RequestContext(request) if request.COOKIES.has_key(' visits '): v = request.COOKIES [' visits '] else : v = 0 return render_to_response('music/about.html', { 'visits':v}, context)
Add and update the code in the index view function/li>
Update the about view function
from django.shortcuts import renderfrom django.http import HttpResponsefrom .models import Album def home(request): a = AIbum. objects.all() return render(request, "dhun/home.html", {"album":a}) def index(request): visits = int(reques.COOKIES.get('visits', '0')) response = HttpResponse(template.render(context)) if request.COOKIES.has_key('last_visit'): last_visit = request. COOKIES [ ' last_visit'] last_visit_time = datetime.strptime(last_visit[:-7], "%Y-%m-%d %H:%M:%S") " curr_time = datetime.now() if (curr_time—last_visit_time).days > O: response.set_cookie( 'visits ', visits + 1) response. set_cookie( ' last_visit', datetime.now()) else : response.set_cookie( ' last_visit', datetime.now()) return response def about(request) : context = RequestContext(request) if request.COOKIES.has_key(' visits '): v = request.COOKIES [' visits '] else : v = 0 return render_to_response('music/about.html', { 'visits':v}, context)
Reference: https://docs.djangoproject.com/en/2.1/topics/http/sessions/
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2019"
},
{
"code": null,
"e": 114,
"s": 54,
"text": "Prerequisites: Django Installation | Introduction to Django"
},
{
"code": null,
"e": 368,
"s": 114,
"text": "Sessions framework can be used to provide persistent behaviour for anonymous users in the website.Sessions are the mechanism used by Django for you store and retrieve data on a per-site-visitor basis.Django uses a cookie containing a special session id."
},
{
"code": null,
"e": 463,
"s": 368,
"text": "To enable the session in the django, you will need to make sure of two things in settings.py :"
},
{
"code": null,
"e": 1184,
"s": 463,
"text": "MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activatedINSTALLED_APPS has ‘django.contrib.sessions’ added.# Application definitionINSTALLED APPS = ['dhun','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]MIDDLEWARE = ['django.middleware.securitY.SecuritYMiddleware','django.contrib.sessions.middleware.SessionMiddLeware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMidd1eware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]"
},
{
"code": null,
"e": 1272,
"s": 1184,
"text": "MIDDLEWARE_CLASSES has ‘django.contrib.sessions.middleware.SessionMiddleware’ activated"
},
{
"code": null,
"e": 1324,
"s": 1272,
"text": "INSTALLED_APPS has ‘django.contrib.sessions’ added."
},
{
"code": "# Application definitionINSTALLED APPS = ['dhun','django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles',]MIDDLEWARE = ['django.middleware.securitY.SecuritYMiddleware','django.contrib.sessions.middleware.SessionMiddLeware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMidd1eware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',]",
"e": 1907,
"s": 1324,
"text": null
},
{
"code": null,
"e": 2018,
"s": 1907,
"text": "After enabling the session, the session database table has to create and to do this run the following command:"
},
{
"code": null,
"e": 2042,
"s": 2018,
"text": "python manage.py syncdb"
},
{
"code": null,
"e": 2225,
"s": 2042,
"text": "After running previous command and if it didn’t find any errors then later run the command given below to finally reflect the changes saved onto the migration file onto the database."
},
{
"code": null,
"e": 2250,
"s": 2225,
"text": "python manage.py migrate"
},
{
"code": null,
"e": 2417,
"s": 2250,
"text": "Now once sessions are created, then testing of the cookies has to be done. In views.py, set the test cookie in the index view, and test the cookie in your about view."
},
{
"code": "from django.shortcuts import renderfrom django.http import HttpResponsefrom .models import Album def home(request) : a = Album.objects.all() return render(request, \"dhun/home.html \", {\"Album\":a}) def index(request) : num_authors = Author.objects.count() request.session.set_test_cookie() num_visits = request.session.get( 'num_visits', 0) request.session ['num_visits'] = num_visits + 1 context ={ 'num_books':num_books, 'num_instances':num_instances, 'num_instances available':num_instances_available, 'num_authors':num_authors, 'num_visits':num_visits, } def about(request): LANGUAGE_CODE ='en-us ' TIME_ZONE ='UTC' if request.session.test_cookie_worked(): print (\"Cookie Tested !\") request.session.delete_test_cookie()",
"e": 3236,
"s": 2417,
"text": null
},
{
"code": null,
"e": 3267,
"s": 3236,
"text": "To see the work done till now."
},
{
"code": null,
"e": 3339,
"s": 3267,
"text": "First run the localhost through this command.python manage.py runserver"
},
{
"code": null,
"e": 3366,
"s": 3339,
"text": "python manage.py runserver"
},
{
"code": null,
"e": 3415,
"s": 3366,
"text": "Then Open http://localhost:8000/ in the browser."
},
{
"code": null,
"e": 3520,
"s": 3415,
"text": "Visit the index page then visit the about page. The “Cookie Tested!” will be printed out to the console."
},
{
"code": null,
"e": 3618,
"s": 3520,
"text": "To know how many times the site has been visited.You have to do following two things In views.py:"
},
{
"code": null,
"e": 4752,
"s": 3618,
"text": "Add and update the code in the index view function/li>Update the about view functionfrom django.shortcuts import renderfrom django.http import HttpResponsefrom .models import Album def home(request): a = AIbum. objects.all() return render(request, \"dhun/home.html\", {\"album\":a}) def index(request): visits = int(reques.COOKIES.get('visits', '0')) response = HttpResponse(template.render(context)) if request.COOKIES.has_key('last_visit'): last_visit = request. COOKIES [ ' last_visit'] last_visit_time = datetime.strptime(last_visit[:-7], \"%Y-%m-%d %H:%M:%S\") \" curr_time = datetime.now() if (curr_time—last_visit_time).days > O: response.set_cookie( 'visits ', visits + 1) response. set_cookie( ' last_visit', datetime.now()) else : response.set_cookie( ' last_visit', datetime.now()) return response def about(request) : context = RequestContext(request) if request.COOKIES.has_key(' visits '): v = request.COOKIES [' visits '] else : v = 0 return render_to_response('music/about.html', { 'visits':v}, context)"
},
{
"code": null,
"e": 4807,
"s": 4752,
"text": "Add and update the code in the index view function/li>"
},
{
"code": null,
"e": 4838,
"s": 4807,
"text": "Update the about view function"
},
{
"code": "from django.shortcuts import renderfrom django.http import HttpResponsefrom .models import Album def home(request): a = AIbum. objects.all() return render(request, \"dhun/home.html\", {\"album\":a}) def index(request): visits = int(reques.COOKIES.get('visits', '0')) response = HttpResponse(template.render(context)) if request.COOKIES.has_key('last_visit'): last_visit = request. COOKIES [ ' last_visit'] last_visit_time = datetime.strptime(last_visit[:-7], \"%Y-%m-%d %H:%M:%S\") \" curr_time = datetime.now() if (curr_time—last_visit_time).days > O: response.set_cookie( 'visits ', visits + 1) response. set_cookie( ' last_visit', datetime.now()) else : response.set_cookie( ' last_visit', datetime.now()) return response def about(request) : context = RequestContext(request) if request.COOKIES.has_key(' visits '): v = request.COOKIES [' visits '] else : v = 0 return render_to_response('music/about.html', { 'visits':v}, context)",
"e": 5888,
"s": 4838,
"text": null
},
{
"code": null,
"e": 5959,
"s": 5888,
"text": "Reference: https://docs.djangoproject.com/en/2.1/topics/http/sessions/"
},
{
"code": null,
"e": 5973,
"s": 5959,
"text": "Python Django"
},
{
"code": null,
"e": 5980,
"s": 5973,
"text": "Python"
},
{
"code": null,
"e": 6078,
"s": 5980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6096,
"s": 6078,
"text": "Python Dictionary"
},
{
"code": null,
"e": 6138,
"s": 6096,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 6160,
"s": 6138,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 6186,
"s": 6160,
"text": "Python String | replace()"
},
{
"code": null,
"e": 6218,
"s": 6186,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6247,
"s": 6218,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 6274,
"s": 6247,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6295,
"s": 6274,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 6331,
"s": 6295,
"text": "Convert integer to string in Python"
}
] |
Largest subtree sum for each vertex of given N-ary Tree
|
28 Feb, 2022
Given an N-array tree of N nodes, rooted at 1, with edges in the form {u, v}, and an array values[] consisting of N integers. Each vertex i has an integer value denoted by values[i]. The task is to find the largest Subtree Sum possible for each vertex i by adding its value to a non-empty subset of its child vertices.
Examples:
Input: Edges[][] = {{1, 2}, {1, 3}, {3, 4}}, values[] = {1, -1, 0, 1}Output: 2 -1 1 1Explanation:Below is the given Tree:
1 / \ 2 3 \ 4Following subsets can be chosen for each vertex:Vertex 1: Subset of vertices {1, 3, 4} can be chosen with values {1, 0, 1}. Therefore, sum = 1 + 0 + 1 = 2.Vertex 2: Subset of vertices {2} can be chosen with values {-1}. Therefore, sum = -1.Vertex 3: Subset of vertices {3, 4} can be chosen with values {0, 1}. Therefore, sum = 0 + 1 = 1.Vertex 4: Subset of vertices {4} can be chosen with values {1}. Therefore, sum = 1.
Input: Edges[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}}, values[] = {1, -1, -2, 1, 3}Output: 5 4 -2 1 3Explanation:Below is the given Tree:
1 / \ 2 3 / \ 4 5Following subsets can be chosen for each vertex:Vertex 1: Subset of vertices {1, 4, 5} can be chosen with values {1, 1, 3}. Therefore, sum = 1 + 1 + 3 = 5.Vertex 2: Subset of vertices {4, 5} can be chosen with values {1, 3}. Therefore, sum = 1 + 3 = 4. Vertex 3: Subset of vertices {3} can be chosen with values {-2}. Therefore, sum = -2.Vertex 4: Subset of vertices {4} can be chosen with values {1}. Therefore, sum = 1.Vertex 5: Subset of vertices {5} can be chosen with values {3}. Therefore, sum = 3.
Naive Approach: The simplest approach is to traverse the subtree of each vertex i from 1 to N and perform DFS Traversal on it. For each vertex i, choose the subset of its child vertices having non-negative values. If the subset of chosen vertices is empty, then search and print the node having the minimum value such that it is the child node of vertex i. Otherwise, print the sum of node values of nodes present in the subset.
Time Complexity: O(N2)Auxiliary Space: O(N)
Efficient Approach: The idea is to use DFS Traversal and Dynamic programming approach. Follow the below steps to solve the problem:
Initialize an array ans[] of size N to store the maximum subtree sum for each vertex.
Perform DFS Traversal for each vertex and for each vertex initialize v, ans[v] with some large negative value.
If vertex v is a leaf vertex, then the answer for that vertex would be values[v]. Therefore, assign ans[v] = values[v].
Otherwise, traverse the vertices adjacent to vertex v and for each adjacent vertex u, update ans[v] as ans[v] = max(ans[u] + values[v], values[v], ans[u]).
After the above steps, print the values stored in ans[] array as the answer for each vertex.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define V 3#define M 2 // Function to perform the DFS// Traversal on the given Treevoid dfs(int v, int p, vector<int> adj[], int ans[], int vals[]){ // To check if v is leaf vertex bool isLeaf = 1; // Initialize answer for vertex v ans[v] = INT_MIN; // Traverse adjacency list of v for(int u : adj[v]) { if (u == p) continue; isLeaf = 0; dfs(u, v, adj, ans, vals); // Update maximum subtree sum ans[v] = max(ans[u] + vals[v], max(ans[u], vals[u])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; }} // Function to calculate maximum// subtree sum for each vertexvoid printAnswer(int n, int edges[V][M], int values[]){ // Stores the adjacency list vector<int> adj[n]; // Add Edges to the list for(int i = 0; i < n - 1; i++) { int u = edges[i][0] - 1; int v = edges[i][1] - 1; adj[u].push_back(v); adj[v].push_back(u); } // Stores largest subtree // sum for each vertex int ans[n] ; // Calculate answer dfs(0, -1, adj, ans, values); // Print the result for(auto x : ans) { cout << x << " "; }} // Driver Codeint main(){ // Given nodes int N = 4; // Give N edges int edges[V][M] = { { 1, 2 }, { 1, 3 }, { 3, 4 } }; // Given values int values[] = { 1, -1, 0, 1 }; // Function Call printAnswer(N, edges, values);} // This code is contributed by Princi Singh
// Java program for the above approach import java.io.*;import java.util.ArrayList; @SuppressWarnings("unchecked")class GFG { // Function to perform the DFS // Traversal on the given Tree static void dfs(int v, int p, ArrayList<Integer> adj[], int ans[], int vals[]) { // To check if v is leaf vertex boolean isLeaf = true; // Initialize answer for vertex v ans[v] = Integer.MIN_VALUE; // Traverse adjacency list of v for (int u : adj[v]) { if (u == p) continue; isLeaf = false; dfs(u, v, adj, ans, vals); // Update maximum subtree sum ans[v] = Math.max( ans[u] + vals[v], Math.max(ans[u], vals[u])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; } } // Function to calculate maximum // subtree sum for each vertex static void printAnswer( int n, int edges[][], int values[]) { // Stores the adjacency list ArrayList<Integer> adj[] = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); // Add Edges to the list for (int i = 0; i < n - 1; i++) { int u = edges[i][0] - 1; int v = edges[i][1] - 1; adj[u].add(v); adj[v].add(u); } // Stores largest subtree // sum for each vertex int ans[] = new int[n]; // Calculate answer dfs(0, -1, adj, ans, values); // Print the result for (int x : ans) { System.out.print(x + " "); } } // Driver Code public static void main(String[] args) { // Given nodes int N = 4; // Give N edges int edges[][] = new int[][] { { 1, 2 }, { 1, 3 }, { 3, 4 } }; // Given values int values[] = { 1, -1, 0, 1 }; // Function Call printAnswer(N, edges, values); }}
# Python3 program for the above approach V = 3M = 2 # Function to perform the DFS# Traversal on the given Treedef dfs(v, p): # To check if v is leaf vertex isLeaf = 1 # Initialize answer for vertex v ans[v] = -10**9 # Traverse adjacency list of v for u in adj[v]: if (u == p): continue isLeaf = 0 dfs(u, v) # Update maximum subtree sum ans[v] = max(ans[u] + vals[v],max(ans[u], vals[u])) # If v is leaf if (isLeaf): ans[v] = vals[v] # Function to calculate maximum# subtree sum for each vertexdef printAnswer(n, edges, vals): # Stores the adjacency list # vector<int> adj[n]; # Add Edges to the list for i in range(n - 1): u = edges[i][0] - 1 v = edges[i][1] - 1 adj[u].append(v) adj[v].append(u) # Calculate answer dfs(0, -1) # Print the result for x in ans: print(x, end=" ") # Driver Codeif __name__ == '__main__': # Given nodes N = 4 # Give N edges edges=[ [ 1, 2], [ 1, 3], [ 3, 4] ] adj=[[] for i in range(N)] ans=[0 for i in range(N)] # Given values vals=[1, -1, 0, 1] # Function Call printAnswer(N, edges, vals) # This code is contributed by mohit kumar 29
// C# program for the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to perform the DFS// Traversal on the given Treestatic void dfs(int v, int p, List<int> []adj, int []ans, int []vals){ // To check if v is leaf // vertex bool isLeaf = true; // Initialize answer for // vertex v ans[v] = int.MinValue; // Traverse adjacency list // of v foreach (int u in adj[v]) { if (u == p) continue; isLeaf = false; dfs(u, v, adj, ans, vals); // Update maximum subtree // sum ans[v] = Math.Max(ans[u] + vals[v], Math.Max(ans[u], vals[u])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; }} // Function to calculate maximum// subtree sum for each vertexstatic void printAnswer(int n, int [,]edges, int []values){ // Stores the adjacency list List<int> []adj = new List<int>[n]; for (int i = 0; i < n; i++) adj[i] = new List<int>(); // Add Edges to the list for (int i = 0; i < n - 1; i++) { int u = edges[i, 0] - 1; int v = edges[i, 1] - 1; adj[u].Add(v); adj[v].Add(u); } // Stores largest subtree // sum for each vertex int []ans = new int[n]; // Calculate answer dfs(0, -1, adj, ans, values); // Print the result foreach (int x in ans) { Console.Write(x + " "); }} // Driver Codepublic static void Main(String[] args){ // Given nodes int N = 4; // Give N edges int [,]edges = new int[,] {{1, 2}, {1, 3}, {3, 4}}; // Given values int []values = {1, -1, 0, 1}; // Function Call printAnswer(N, edges, values);}} // This code is contributed by gauravrajput1
<script> // JavaScript program for the above approach // Function to perform the DFS // Traversal on the given Tree function dfs(v, p, adj, ans, vals) { // To check if v is leaf // vertex let isLeaf = true; // Initialize answer for // vertex v ans[v] = Number.MIN_VALUE; // Traverse adjacency list // of v for(let u = 0; u < adj[v].length; u++) { if (adj[v][u] == p) continue; isLeaf = false; dfs(adj[v][u], v, adj, ans, vals); // Update maximum subtree // sum ans[v] = Math.max(ans[adj[v][u]] + vals[v], Math.max(ans[adj[v][u]], vals[adj[v][u]])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; } } // Function to calculate maximum // subtree sum for each vertex function printAnswer(n, edges, values) { // Stores the adjacency list let adj = new Array(n); for (let i = 0; i < n; i++) adj[i] = []; // Add Edges to the list for (let i = 0; i < n - 1; i++) { let u = edges[i][0] - 1; let v = edges[i][1] - 1; adj[u].push(v); adj[v].push(u); } // Stores largest subtree // sum for each vertex let ans = new Array(n); // Calculate answer dfs(0, -1, adj, ans, values); // Print the result for(let x = 0; x < ans.length; x++) { document.write(ans[x] + " "); } } // Given nodes let N = 4; // Give N edges let edges = [[1, 2], [1, 3], [3, 4]]; // Given values let values = [1, -1, 0, 1]; // Function Call printAnswer(N, edges, values); </script>
2 -1 1 1
Time Complexity: O(N)Auxiliary Space: O(N)
GauravRajput1
princi singh
mohit kumar 29
divyeshrabadiya07
varshagumber28
simranarora5sos
DFS
n-ary-tree
Arrays
Dynamic Programming
Tree
Arrays
Dynamic Programming
DFS
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 373,
"s": 54,
"text": "Given an N-array tree of N nodes, rooted at 1, with edges in the form {u, v}, and an array values[] consisting of N integers. Each vertex i has an integer value denoted by values[i]. The task is to find the largest Subtree Sum possible for each vertex i by adding its value to a non-empty subset of its child vertices."
},
{
"code": null,
"e": 384,
"s": 373,
"text": "Examples: "
},
{
"code": null,
"e": 506,
"s": 384,
"text": "Input: Edges[][] = {{1, 2}, {1, 3}, {3, 4}}, values[] = {1, -1, 0, 1}Output: 2 -1 1 1Explanation:Below is the given Tree:"
},
{
"code": null,
"e": 1073,
"s": 506,
"text": " 1 / \\ 2 3 \\ 4Following subsets can be chosen for each vertex:Vertex 1: Subset of vertices {1, 3, 4} can be chosen with values {1, 0, 1}. Therefore, sum = 1 + 0 + 1 = 2.Vertex 2: Subset of vertices {2} can be chosen with values {-1}. Therefore, sum = -1.Vertex 3: Subset of vertices {3, 4} can be chosen with values {0, 1}. Therefore, sum = 0 + 1 = 1.Vertex 4: Subset of vertices {4} can be chosen with values {1}. Therefore, sum = 1."
},
{
"code": null,
"e": 1209,
"s": 1073,
"text": "Input: Edges[][] = {{1, 2}, {1, 3}, {2, 4}, {2, 5}}, values[] = {1, -1, -2, 1, 3}Output: 5 4 -2 1 3Explanation:Below is the given Tree:"
},
{
"code": null,
"e": 1849,
"s": 1209,
"text": " 1 / \\ 2 3 / \\ 4 5Following subsets can be chosen for each vertex:Vertex 1: Subset of vertices {1, 4, 5} can be chosen with values {1, 1, 3}. Therefore, sum = 1 + 1 + 3 = 5.Vertex 2: Subset of vertices {4, 5} can be chosen with values {1, 3}. Therefore, sum = 1 + 3 = 4. Vertex 3: Subset of vertices {3} can be chosen with values {-2}. Therefore, sum = -2.Vertex 4: Subset of vertices {4} can be chosen with values {1}. Therefore, sum = 1.Vertex 5: Subset of vertices {5} can be chosen with values {3}. Therefore, sum = 3. "
},
{
"code": null,
"e": 2279,
"s": 1849,
"text": "Naive Approach: The simplest approach is to traverse the subtree of each vertex i from 1 to N and perform DFS Traversal on it. For each vertex i, choose the subset of its child vertices having non-negative values. If the subset of chosen vertices is empty, then search and print the node having the minimum value such that it is the child node of vertex i. Otherwise, print the sum of node values of nodes present in the subset. "
},
{
"code": null,
"e": 2324,
"s": 2279,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 2456,
"s": 2324,
"text": "Efficient Approach: The idea is to use DFS Traversal and Dynamic programming approach. Follow the below steps to solve the problem:"
},
{
"code": null,
"e": 2542,
"s": 2456,
"text": "Initialize an array ans[] of size N to store the maximum subtree sum for each vertex."
},
{
"code": null,
"e": 2653,
"s": 2542,
"text": "Perform DFS Traversal for each vertex and for each vertex initialize v, ans[v] with some large negative value."
},
{
"code": null,
"e": 2773,
"s": 2653,
"text": "If vertex v is a leaf vertex, then the answer for that vertex would be values[v]. Therefore, assign ans[v] = values[v]."
},
{
"code": null,
"e": 2929,
"s": 2773,
"text": "Otherwise, traverse the vertices adjacent to vertex v and for each adjacent vertex u, update ans[v] as ans[v] = max(ans[u] + values[v], values[v], ans[u])."
},
{
"code": null,
"e": 3022,
"s": 2929,
"text": "After the above steps, print the values stored in ans[] array as the answer for each vertex."
},
{
"code": null,
"e": 3074,
"s": 3022,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 3078,
"s": 3074,
"text": "C++"
},
{
"code": null,
"e": 3083,
"s": 3078,
"text": "Java"
},
{
"code": null,
"e": 3091,
"s": 3083,
"text": "Python3"
},
{
"code": null,
"e": 3094,
"s": 3091,
"text": "C#"
},
{
"code": null,
"e": 3105,
"s": 3094,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;#define V 3#define M 2 // Function to perform the DFS// Traversal on the given Treevoid dfs(int v, int p, vector<int> adj[], int ans[], int vals[]){ // To check if v is leaf vertex bool isLeaf = 1; // Initialize answer for vertex v ans[v] = INT_MIN; // Traverse adjacency list of v for(int u : adj[v]) { if (u == p) continue; isLeaf = 0; dfs(u, v, adj, ans, vals); // Update maximum subtree sum ans[v] = max(ans[u] + vals[v], max(ans[u], vals[u])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; }} // Function to calculate maximum// subtree sum for each vertexvoid printAnswer(int n, int edges[V][M], int values[]){ // Stores the adjacency list vector<int> adj[n]; // Add Edges to the list for(int i = 0; i < n - 1; i++) { int u = edges[i][0] - 1; int v = edges[i][1] - 1; adj[u].push_back(v); adj[v].push_back(u); } // Stores largest subtree // sum for each vertex int ans[n] ; // Calculate answer dfs(0, -1, adj, ans, values); // Print the result for(auto x : ans) { cout << x << \" \"; }} // Driver Codeint main(){ // Given nodes int N = 4; // Give N edges int edges[V][M] = { { 1, 2 }, { 1, 3 }, { 3, 4 } }; // Given values int values[] = { 1, -1, 0, 1 }; // Function Call printAnswer(N, edges, values);} // This code is contributed by Princi Singh",
"e": 4792,
"s": 3105,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*;import java.util.ArrayList; @SuppressWarnings(\"unchecked\")class GFG { // Function to perform the DFS // Traversal on the given Tree static void dfs(int v, int p, ArrayList<Integer> adj[], int ans[], int vals[]) { // To check if v is leaf vertex boolean isLeaf = true; // Initialize answer for vertex v ans[v] = Integer.MIN_VALUE; // Traverse adjacency list of v for (int u : adj[v]) { if (u == p) continue; isLeaf = false; dfs(u, v, adj, ans, vals); // Update maximum subtree sum ans[v] = Math.max( ans[u] + vals[v], Math.max(ans[u], vals[u])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; } } // Function to calculate maximum // subtree sum for each vertex static void printAnswer( int n, int edges[][], int values[]) { // Stores the adjacency list ArrayList<Integer> adj[] = new ArrayList[n]; for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); // Add Edges to the list for (int i = 0; i < n - 1; i++) { int u = edges[i][0] - 1; int v = edges[i][1] - 1; adj[u].add(v); adj[v].add(u); } // Stores largest subtree // sum for each vertex int ans[] = new int[n]; // Calculate answer dfs(0, -1, adj, ans, values); // Print the result for (int x : ans) { System.out.print(x + \" \"); } } // Driver Code public static void main(String[] args) { // Given nodes int N = 4; // Give N edges int edges[][] = new int[][] { { 1, 2 }, { 1, 3 }, { 3, 4 } }; // Given values int values[] = { 1, -1, 0, 1 }; // Function Call printAnswer(N, edges, values); }}",
"e": 6904,
"s": 4792,
"text": null
},
{
"code": "# Python3 program for the above approach V = 3M = 2 # Function to perform the DFS# Traversal on the given Treedef dfs(v, p): # To check if v is leaf vertex isLeaf = 1 # Initialize answer for vertex v ans[v] = -10**9 # Traverse adjacency list of v for u in adj[v]: if (u == p): continue isLeaf = 0 dfs(u, v) # Update maximum subtree sum ans[v] = max(ans[u] + vals[v],max(ans[u], vals[u])) # If v is leaf if (isLeaf): ans[v] = vals[v] # Function to calculate maximum# subtree sum for each vertexdef printAnswer(n, edges, vals): # Stores the adjacency list # vector<int> adj[n]; # Add Edges to the list for i in range(n - 1): u = edges[i][0] - 1 v = edges[i][1] - 1 adj[u].append(v) adj[v].append(u) # Calculate answer dfs(0, -1) # Print the result for x in ans: print(x, end=\" \") # Driver Codeif __name__ == '__main__': # Given nodes N = 4 # Give N edges edges=[ [ 1, 2], [ 1, 3], [ 3, 4] ] adj=[[] for i in range(N)] ans=[0 for i in range(N)] # Given values vals=[1, -1, 0, 1] # Function Call printAnswer(N, edges, vals) # This code is contributed by mohit kumar 29",
"e": 8173,
"s": 6904,
"text": null
},
{
"code": "// C# program for the// above approachusing System;using System.Collections.Generic;class GFG{ // Function to perform the DFS// Traversal on the given Treestatic void dfs(int v, int p, List<int> []adj, int []ans, int []vals){ // To check if v is leaf // vertex bool isLeaf = true; // Initialize answer for // vertex v ans[v] = int.MinValue; // Traverse adjacency list // of v foreach (int u in adj[v]) { if (u == p) continue; isLeaf = false; dfs(u, v, adj, ans, vals); // Update maximum subtree // sum ans[v] = Math.Max(ans[u] + vals[v], Math.Max(ans[u], vals[u])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; }} // Function to calculate maximum// subtree sum for each vertexstatic void printAnswer(int n, int [,]edges, int []values){ // Stores the adjacency list List<int> []adj = new List<int>[n]; for (int i = 0; i < n; i++) adj[i] = new List<int>(); // Add Edges to the list for (int i = 0; i < n - 1; i++) { int u = edges[i, 0] - 1; int v = edges[i, 1] - 1; adj[u].Add(v); adj[v].Add(u); } // Stores largest subtree // sum for each vertex int []ans = new int[n]; // Calculate answer dfs(0, -1, adj, ans, values); // Print the result foreach (int x in ans) { Console.Write(x + \" \"); }} // Driver Codepublic static void Main(String[] args){ // Given nodes int N = 4; // Give N edges int [,]edges = new int[,] {{1, 2}, {1, 3}, {3, 4}}; // Given values int []values = {1, -1, 0, 1}; // Function Call printAnswer(N, edges, values);}} // This code is contributed by gauravrajput1",
"e": 9959,
"s": 8173,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to perform the DFS // Traversal on the given Tree function dfs(v, p, adj, ans, vals) { // To check if v is leaf // vertex let isLeaf = true; // Initialize answer for // vertex v ans[v] = Number.MIN_VALUE; // Traverse adjacency list // of v for(let u = 0; u < adj[v].length; u++) { if (adj[v][u] == p) continue; isLeaf = false; dfs(adj[v][u], v, adj, ans, vals); // Update maximum subtree // sum ans[v] = Math.max(ans[adj[v][u]] + vals[v], Math.max(ans[adj[v][u]], vals[adj[v][u]])); } // If v is leaf if (isLeaf) { ans[v] = vals[v]; } } // Function to calculate maximum // subtree sum for each vertex function printAnswer(n, edges, values) { // Stores the adjacency list let adj = new Array(n); for (let i = 0; i < n; i++) adj[i] = []; // Add Edges to the list for (let i = 0; i < n - 1; i++) { let u = edges[i][0] - 1; let v = edges[i][1] - 1; adj[u].push(v); adj[v].push(u); } // Stores largest subtree // sum for each vertex let ans = new Array(n); // Calculate answer dfs(0, -1, adj, ans, values); // Print the result for(let x = 0; x < ans.length; x++) { document.write(ans[x] + \" \"); } } // Given nodes let N = 4; // Give N edges let edges = [[1, 2], [1, 3], [3, 4]]; // Given values let values = [1, -1, 0, 1]; // Function Call printAnswer(N, edges, values); </script>",
"e": 11702,
"s": 9959,
"text": null
},
{
"code": null,
"e": 11711,
"s": 11702,
"text": "2 -1 1 1"
},
{
"code": null,
"e": 11756,
"s": 11713,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 11770,
"s": 11756,
"text": "GauravRajput1"
},
{
"code": null,
"e": 11783,
"s": 11770,
"text": "princi singh"
},
{
"code": null,
"e": 11798,
"s": 11783,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 11816,
"s": 11798,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 11831,
"s": 11816,
"text": "varshagumber28"
},
{
"code": null,
"e": 11847,
"s": 11831,
"text": "simranarora5sos"
},
{
"code": null,
"e": 11851,
"s": 11847,
"text": "DFS"
},
{
"code": null,
"e": 11862,
"s": 11851,
"text": "n-ary-tree"
},
{
"code": null,
"e": 11869,
"s": 11862,
"text": "Arrays"
},
{
"code": null,
"e": 11889,
"s": 11869,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 11894,
"s": 11889,
"text": "Tree"
},
{
"code": null,
"e": 11901,
"s": 11894,
"text": "Arrays"
},
{
"code": null,
"e": 11921,
"s": 11901,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 11925,
"s": 11921,
"text": "DFS"
},
{
"code": null,
"e": 11930,
"s": 11925,
"text": "Tree"
}
] |
How to convert a class to another class type in C++?
|
14 Sep, 2021
Pre-requisite: Type Conversion in C++, Advanced C++ | Conversion OperatorsThrough class conversion, one can assign data that belongs to a particular class type to an object that belongs to another class type. Example: Let there be two classes ‘A’ and ‘B’. If we want to allocate the details that belong to class ‘A’ to an object of class ‘B’ then this can be achieved by –
B(object of class B) = A(object of class A) where ‘=’ has been overloaded for objects of class type ‘B’.
Class conversion can be achieved by conversion function which is done by the use of operator overloading.Example:
CPP
#include <bits/stdc++.h>using namespace std; // Source class, i.e// class that will be converted to another classclass Class_type_one { string a = "GeeksforGeeks"; public: // Member function which returns // string type data string get_string() { return (a); } // Member function to display void display() { cout << a << endl; }}; // Destination class, i.e// Class type to which source class will be convertedclass Class_type_two { string b; public: // Operator overloading which accepts data // of the Destination class and // assigns those data to the source class // Here it is for the conversion of // Class_type_two to Class_type_one void operator=(Class_type_one a) { b = a.get_string(); } // Member function for displaying // the data assigned to b. void display() { cout << b << endl; }}; int main(){ // Creating object of class Class_type_one Class_type_one a; // Creating object of class Class_type_two Class_type_two b; // CLass type conversion // using operator overloading b = a; // Displaying data of object // of class Class_type_one a.display(); // Displaying data of object // of class Class_type_two b.display(); return 0;}
GeeksforGeeks
GeeksforGeeks
A source class can be converted to a destination class by using a constructor in destination class which takes reference to source class.
Destination_class( source_class &object)
{
//assignments of members of destination class
//with members of source class using source class object
}
C++
#include <bits/stdc++.h>using namespace std; // Source class, i.e// Class which will be converted to anotherclass Class_type_one { string a = "GeeksforGeeks"; public: // Member function which returns // string type data string get_string() { return (a); } // Member function to display void display() { cout << a << endl; }}; // Destination class, i.e// class to which source class will be convertedclass Class_type_two { string b; public: // a default constructor to //create object of this class Class_type_two() { } //here we are using constructor //which takes reference of object //of source class i.e. Class_type_one //as its argument Class_type_two (Class_type_one& a) { b = a.get_string(); } // Member function for displaying // the data assigned to b. void display() { cout << b << endl; }}; int main(){ // Creating object of class Class_type_one Class_type_one a; // Creating object of class Class_type_two Class_type_two b; // CLass type conversion // using operator overloading b = a; // Displaying data of object // of class Class_type_one a.display(); // Displaying data of object // of class Class_type_two b.display(); return 0;}
GeeksforGeeks
GeeksforGeeks
Class to class conversion is also possible using casting operator in source class. Operator type will be that of destination class.
A casting operator will be member function of source class and will return object of destination class.
operator destination_class()
{
destination_class obj;
//assignment of members of destination class with members of source class
//this function is member of source class hence it can access its other data members
return obj
}
C++
#include <bits/stdc++.h>using namespace std;//Forward declaration of//destination classclass Class_type_two;// Source class, i.e// Class which will be converted to anotherclass Class_type_one { string a = "GeeksforGeeks"; public: // Member function which returns // string type data string get_string() { return (a); } // Member function to display void display() { cout << a << endl; } //declaration of casting //operator for class conversion //note that it will be of type destination class operator Class_type_two(); }; // Destination class, i.e// class type to which source class will convertedclass Class_type_two { public: string b; // Member function for displaying // the data assigned to b. void display() { cout << b << endl; }};//here we define our casting operatorClass_type_one::operator Class_type_two(){ Class_type_two obj; obj.b=a; return obj; } int main(){ // Creating object of class Class_type_one Class_type_one a; // Creating object of class Class_type_two Class_type_two b; // CLass type conversion // using operator overloading b = a; // Displaying data of object // of class Class_type_one a.display(); // Displaying data of object // of class Class_type_two b.display(); return 0;}
GeeksforGeeks
GeeksforGeeks
husain0803
rs1686740
cpp-operator-overloading
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 427,
"s": 52,
"text": "Pre-requisite: Type Conversion in C++, Advanced C++ | Conversion OperatorsThrough class conversion, one can assign data that belongs to a particular class type to an object that belongs to another class type. Example: Let there be two classes ‘A’ and ‘B’. If we want to allocate the details that belong to class ‘A’ to an object of class ‘B’ then this can be achieved by – "
},
{
"code": null,
"e": 532,
"s": 427,
"text": "B(object of class B) = A(object of class A) where ‘=’ has been overloaded for objects of class type ‘B’."
},
{
"code": null,
"e": 648,
"s": 532,
"text": "Class conversion can be achieved by conversion function which is done by the use of operator overloading.Example: "
},
{
"code": null,
"e": 652,
"s": 648,
"text": "CPP"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Source class, i.e// class that will be converted to another classclass Class_type_one { string a = \"GeeksforGeeks\"; public: // Member function which returns // string type data string get_string() { return (a); } // Member function to display void display() { cout << a << endl; }}; // Destination class, i.e// Class type to which source class will be convertedclass Class_type_two { string b; public: // Operator overloading which accepts data // of the Destination class and // assigns those data to the source class // Here it is for the conversion of // Class_type_two to Class_type_one void operator=(Class_type_one a) { b = a.get_string(); } // Member function for displaying // the data assigned to b. void display() { cout << b << endl; }}; int main(){ // Creating object of class Class_type_one Class_type_one a; // Creating object of class Class_type_two Class_type_two b; // CLass type conversion // using operator overloading b = a; // Displaying data of object // of class Class_type_one a.display(); // Displaying data of object // of class Class_type_two b.display(); return 0;}",
"e": 1943,
"s": 652,
"text": null
},
{
"code": null,
"e": 1971,
"s": 1943,
"text": "GeeksforGeeks\nGeeksforGeeks"
},
{
"code": null,
"e": 2109,
"s": 1971,
"text": "A source class can be converted to a destination class by using a constructor in destination class which takes reference to source class."
},
{
"code": null,
"e": 2150,
"s": 2109,
"text": "Destination_class( source_class &object)"
},
{
"code": null,
"e": 2152,
"s": 2150,
"text": "{"
},
{
"code": null,
"e": 2198,
"s": 2152,
"text": "//assignments of members of destination class"
},
{
"code": null,
"e": 2256,
"s": 2198,
"text": "//with members of source class using source class object "
},
{
"code": null,
"e": 2258,
"s": 2256,
"text": "}"
},
{
"code": null,
"e": 2262,
"s": 2258,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // Source class, i.e// Class which will be converted to anotherclass Class_type_one { string a = \"GeeksforGeeks\"; public: // Member function which returns // string type data string get_string() { return (a); } // Member function to display void display() { cout << a << endl; }}; // Destination class, i.e// class to which source class will be convertedclass Class_type_two { string b; public: // a default constructor to //create object of this class Class_type_two() { } //here we are using constructor //which takes reference of object //of source class i.e. Class_type_one //as its argument Class_type_two (Class_type_one& a) { b = a.get_string(); } // Member function for displaying // the data assigned to b. void display() { cout << b << endl; }}; int main(){ // Creating object of class Class_type_one Class_type_one a; // Creating object of class Class_type_two Class_type_two b; // CLass type conversion // using operator overloading b = a; // Displaying data of object // of class Class_type_one a.display(); // Displaying data of object // of class Class_type_two b.display(); return 0;}",
"e": 3582,
"s": 2262,
"text": null
},
{
"code": null,
"e": 3610,
"s": 3582,
"text": "GeeksforGeeks\nGeeksforGeeks"
},
{
"code": null,
"e": 3742,
"s": 3610,
"text": "Class to class conversion is also possible using casting operator in source class. Operator type will be that of destination class."
},
{
"code": null,
"e": 3846,
"s": 3742,
"text": "A casting operator will be member function of source class and will return object of destination class."
},
{
"code": null,
"e": 3875,
"s": 3846,
"text": "operator destination_class()"
},
{
"code": null,
"e": 3877,
"s": 3875,
"text": "{"
},
{
"code": null,
"e": 3900,
"s": 3877,
"text": "destination_class obj;"
},
{
"code": null,
"e": 3974,
"s": 3900,
"text": "//assignment of members of destination class with members of source class"
},
{
"code": null,
"e": 4059,
"s": 3974,
"text": "//this function is member of source class hence it can access its other data members"
},
{
"code": null,
"e": 4070,
"s": 4059,
"text": "return obj"
},
{
"code": null,
"e": 4072,
"s": 4070,
"text": "}"
},
{
"code": null,
"e": 4076,
"s": 4072,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std;//Forward declaration of//destination classclass Class_type_two;// Source class, i.e// Class which will be converted to anotherclass Class_type_one { string a = \"GeeksforGeeks\"; public: // Member function which returns // string type data string get_string() { return (a); } // Member function to display void display() { cout << a << endl; } //declaration of casting //operator for class conversion //note that it will be of type destination class operator Class_type_two(); }; // Destination class, i.e// class type to which source class will convertedclass Class_type_two { public: string b; // Member function for displaying // the data assigned to b. void display() { cout << b << endl; }};//here we define our casting operatorClass_type_one::operator Class_type_two(){ Class_type_two obj; obj.b=a; return obj; } int main(){ // Creating object of class Class_type_one Class_type_one a; // Creating object of class Class_type_two Class_type_two b; // CLass type conversion // using operator overloading b = a; // Displaying data of object // of class Class_type_one a.display(); // Displaying data of object // of class Class_type_two b.display(); return 0;}",
"e": 5424,
"s": 4076,
"text": null
},
{
"code": null,
"e": 5452,
"s": 5424,
"text": "GeeksforGeeks\nGeeksforGeeks"
},
{
"code": null,
"e": 5463,
"s": 5452,
"text": "husain0803"
},
{
"code": null,
"e": 5473,
"s": 5463,
"text": "rs1686740"
},
{
"code": null,
"e": 5498,
"s": 5473,
"text": "cpp-operator-overloading"
},
{
"code": null,
"e": 5502,
"s": 5498,
"text": "C++"
},
{
"code": null,
"e": 5515,
"s": 5502,
"text": "C++ Programs"
},
{
"code": null,
"e": 5519,
"s": 5515,
"text": "CPP"
},
{
"code": null,
"e": 5617,
"s": 5519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5641,
"s": 5617,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 5661,
"s": 5641,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 5694,
"s": 5661,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 5719,
"s": 5694,
"text": "std::string class in C++"
},
{
"code": null,
"e": 5763,
"s": 5719,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5798,
"s": 5763,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 5832,
"s": 5798,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 5876,
"s": 5832,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 5935,
"s": 5876,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Python | Find elements of a list by indices
|
18 Apr, 2019
Given two lists with elements and indices, write a Python program to find elements of list 1 at indices present in list 2.
Examples:
Input : lst1 = [10, 20, 30, 40, 50]
lst2 = [0, 2, 4]
Output : [10, 30, 50]
Explanation:
Output elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively.
Input : lst1 = ['Hello', 'geeks', 'for', 'geeks']
lst2 = [1, 2, 3]
Output : ['geeks', 'for', 'geeks']
Below are some Pythonic approaches to do the above task.
Approach #1 : Naive(List comprehension)
The first approach to find the desired elements is to use list comprehension. We traverse through ‘lst2’ and for each ith element, we output lst1[i].
# Python3 program to Find elements of a # list by indices present in another list def findElements(lst1, lst2): return [lst1[i] for i in lst2] # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]
Approach #2 : Using Python map()
We can also use Python map() method where we apply lst1.__getitem__ function on lst2 which return lst1[i] for each element ‘i’ of lst2.
# Python3 program to Find elements of a # list by indices present in another list def findElements(lst1, lst2): return list(map(lst1.__getitem__, lst2)) # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]
Approach #3 : Using itemgetter()
# Python3 program to Find elements of a # list by indices present in another listfrom operator import itemgetter def findElements(lst1, lst2): return list((itemgetter(*lst2)(lst1))) # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]
Approach #4 : Using numpy
# Python3 program to Find elements of a # list by indices present in another listimport numpy as np def findElements(lst1, lst2): return list(np.array(lst1)[lst2]) # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))
[10, 30, 50]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Apr, 2019"
},
{
"code": null,
"e": 151,
"s": 28,
"text": "Given two lists with elements and indices, write a Python program to find elements of list 1 at indices present in list 2."
},
{
"code": null,
"e": 161,
"s": 151,
"text": "Examples:"
},
{
"code": null,
"e": 441,
"s": 161,
"text": "Input : lst1 = [10, 20, 30, 40, 50]\n lst2 = [0, 2, 4]\nOutput : [10, 30, 50]\nExplanation: \nOutput elements at indices 0, 2 and 4 i.e 10, 30 and 50 respectively. \n\nInput : lst1 = ['Hello', 'geeks', 'for', 'geeks']\n lst2 = [1, 2, 3]\nOutput : ['geeks', 'for', 'geeks']\n"
},
{
"code": null,
"e": 499,
"s": 441,
"text": " Below are some Pythonic approaches to do the above task."
},
{
"code": null,
"e": 539,
"s": 499,
"text": "Approach #1 : Naive(List comprehension)"
},
{
"code": null,
"e": 689,
"s": 539,
"text": "The first approach to find the desired elements is to use list comprehension. We traverse through ‘lst2’ and for each ith element, we output lst1[i]."
},
{
"code": "# Python3 program to Find elements of a # list by indices present in another list def findElements(lst1, lst2): return [lst1[i] for i in lst2] # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))",
"e": 937,
"s": 689,
"text": null
},
{
"code": null,
"e": 951,
"s": 937,
"text": "[10, 30, 50]\n"
},
{
"code": null,
"e": 985,
"s": 951,
"text": " Approach #2 : Using Python map()"
},
{
"code": null,
"e": 1121,
"s": 985,
"text": "We can also use Python map() method where we apply lst1.__getitem__ function on lst2 which return lst1[i] for each element ‘i’ of lst2."
},
{
"code": "# Python3 program to Find elements of a # list by indices present in another list def findElements(lst1, lst2): return list(map(lst1.__getitem__, lst2)) # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))",
"e": 1379,
"s": 1121,
"text": null
},
{
"code": null,
"e": 1393,
"s": 1379,
"text": "[10, 30, 50]\n"
},
{
"code": null,
"e": 1427,
"s": 1393,
"text": " Approach #3 : Using itemgetter()"
},
{
"code": "# Python3 program to Find elements of a # list by indices present in another listfrom operator import itemgetter def findElements(lst1, lst2): return list((itemgetter(*lst2)(lst1))) # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))",
"e": 1715,
"s": 1427,
"text": null
},
{
"code": null,
"e": 1729,
"s": 1715,
"text": "[10, 30, 50]\n"
},
{
"code": null,
"e": 1756,
"s": 1729,
"text": " Approach #4 : Using numpy"
},
{
"code": "# Python3 program to Find elements of a # list by indices present in another listimport numpy as np def findElements(lst1, lst2): return list(np.array(lst1)[lst2]) # Driver codelst1 = [10, 20, 30, 40, 50]lst2 = [0, 2, 4]print(findElements(lst1, lst2))",
"e": 2026,
"s": 1756,
"text": null
},
{
"code": null,
"e": 2040,
"s": 2026,
"text": "[10, 30, 50]\n"
},
{
"code": null,
"e": 2061,
"s": 2040,
"text": "Python list-programs"
},
{
"code": null,
"e": 2068,
"s": 2061,
"text": "Python"
},
{
"code": null,
"e": 2084,
"s": 2068,
"text": "Python Programs"
}
] |
Find max and second max salary for a MySQL Employee table?
|
You can get max and second max salary from an Employee table using LIMIT OFFSET. The syntax is as follows −
SELECT yourColumnName1,yourColumnName2,....N from yourTableName ORDER BY
yourColumnName desc limit 2 offset 0;
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table EmployeeMaxAndSecondMaxSalary
-> (
-> EmployeeId int,
-> Employeename varchar(20),
-> EmployeeSalary int
-> );
Query OK, 0 rows affected (0.88 sec)
Insert some records in the table using insert command −
mysql> insert into EmployeeMaxAndSecondMaxSalary values(1,'John',34566);
Query OK, 1 row affected (0.20 sec)
mysql> insert into EmployeeMaxAndSecondMaxSalary values(2,'Bob',56789);
Query OK, 1 row affected (0.17 sec)
mysql> insert into EmployeeMaxAndSecondMaxSalary values(3,'Carol',44560);
Query OK, 1 row affected (0.26 sec)
mysql> insert into EmployeeMaxAndSecondMaxSalary values(4,'Sam',76456);
Query OK, 1 row affected (0.29 sec)
mysql> insert into EmployeeMaxAndSecondMaxSalary values(5,'Mike',65566);
Query OK, 1 row affected (0.14 sec)
mysql> insert into EmployeeMaxAndSecondMaxSalary values(6,'David',89990);
Query OK, 1 row affected (0.19 sec)
mysql> insert into EmployeeMaxAndSecondMaxSalary values(7,'James',68789);
Query OK, 1 row affected (0.12 sec)
mysql> insert into EmployeeMaxAndSecondMaxSalary values(8,'Robert',76543);
Query OK, 1 row affected (0.13 sec)
Display all records from the table using select statement. The query is as follows −
mysql> select *from EmployeeMaxAndSecondMaxSalary;
The following is the output −
+------------+--------------+----------------+
| EmployeeId | Employeename | EmployeeSalary |
+------------+--------------+----------------+
| 1 | John | 34566 |
| 2 | Bob | 56789 |
| 3 | Carol | 44560 |
| 4 | Sam | 76456 |
| 5 | Mike | 65566 |
| 6 | David | 89990 |
| 7 | James | 68789 |
| 8 | Robert | 76543 |
+------------+--------------+----------------+
8 rows in set (0.00 sec)
The following is the query to get the max and second max salary using limit offset −
mysql> select EmployeeId,Employeename,EmployeeSalary from EmployeeMaxAndSecondMaxSalary order by
-> EmployeeSalary desc limit 2 offset 0;
The output displays the record of 2 employees with the maximum salary −
+------------+--------------+----------------+
| EmployeeId | Employeename | EmployeeSalary |
+------------+--------------+----------------+
| 6 | David | 89990 |
| 8 | Robert | 76543 |
+------------+--------------+----------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1295,
"s": 1187,
"text": "You can get max and second max salary from an Employee table using LIMIT OFFSET. The syntax is as follows −"
},
{
"code": null,
"e": 1406,
"s": 1295,
"text": "SELECT yourColumnName1,yourColumnName2,....N from yourTableName ORDER BY\nyourColumnName desc limit 2 offset 0;"
},
{
"code": null,
"e": 1505,
"s": 1406,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows −"
},
{
"code": null,
"e": 1688,
"s": 1505,
"text": "mysql> create table EmployeeMaxAndSecondMaxSalary\n -> (\n -> EmployeeId int,\n -> Employeename varchar(20),\n -> EmployeeSalary int\n -> );\nQuery OK, 0 rows affected (0.88 sec)"
},
{
"code": null,
"e": 1744,
"s": 1688,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2626,
"s": 1744,
"text": "mysql> insert into EmployeeMaxAndSecondMaxSalary values(1,'John',34566);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into EmployeeMaxAndSecondMaxSalary values(2,'Bob',56789);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into EmployeeMaxAndSecondMaxSalary values(3,'Carol',44560);\nQuery OK, 1 row affected (0.26 sec)\n\nmysql> insert into EmployeeMaxAndSecondMaxSalary values(4,'Sam',76456);\nQuery OK, 1 row affected (0.29 sec)\n\nmysql> insert into EmployeeMaxAndSecondMaxSalary values(5,'Mike',65566);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into EmployeeMaxAndSecondMaxSalary values(6,'David',89990);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into EmployeeMaxAndSecondMaxSalary values(7,'James',68789);\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into EmployeeMaxAndSecondMaxSalary values(8,'Robert',76543);\nQuery OK, 1 row affected (0.13 sec)"
},
{
"code": null,
"e": 2711,
"s": 2626,
"text": "Display all records from the table using select statement. The query is as follows −"
},
{
"code": null,
"e": 2762,
"s": 2711,
"text": "mysql> select *from EmployeeMaxAndSecondMaxSalary;"
},
{
"code": null,
"e": 2792,
"s": 2762,
"text": "The following is the output −"
},
{
"code": null,
"e": 3381,
"s": 2792,
"text": "+------------+--------------+----------------+\n| EmployeeId | Employeename | EmployeeSalary |\n+------------+--------------+----------------+\n| 1 | John | 34566 |\n| 2 | Bob | 56789 |\n| 3 | Carol | 44560 |\n| 4 | Sam | 76456 |\n| 5 | Mike | 65566 |\n| 6 | David | 89990 |\n| 7 | James | 68789 |\n| 8 | Robert | 76543 |\n+------------+--------------+----------------+\n8 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3466,
"s": 3381,
"text": "The following is the query to get the max and second max salary using limit offset −"
},
{
"code": null,
"e": 3607,
"s": 3466,
"text": "mysql> select EmployeeId,Employeename,EmployeeSalary from EmployeeMaxAndSecondMaxSalary order by\n -> EmployeeSalary desc limit 2 offset 0;"
},
{
"code": null,
"e": 3679,
"s": 3607,
"text": "The output displays the record of 2 employees with the maximum salary −"
},
{
"code": null,
"e": 3986,
"s": 3679,
"text": "+------------+--------------+----------------+\n| EmployeeId | Employeename | EmployeeSalary |\n+------------+--------------+----------------+\n| 6 | David | 89990 |\n| 8 | Robert | 76543 |\n+------------+--------------+----------------+\n2 rows in set (0.00 sec)"
}
] |
Python program to convert floating to binary
|
15 Jun, 2022
Python doesn’t provide any inbuilt method to easily convert floating point decimal numbers to binary number. So, Let’s do this manually. Approach : To convert a floating point decimal number into binary, first convert the integer part into binary form and then fractional part into binary form and finally combine both results to get the final answer. For Integer Part, keep dividing the number by 2 and noting down the remainder until and unless the dividend is less than 2. If so, stop and copy all the remainders together. For Decimal Part, keep multiplying the decimal part with 2 until and unless 0 left as fractional part. After multiplying the first time, note down integral part and again multiply decimal part of the new value by 2. Keep doing this until reached a perfect number.
Above steps can be written as : 1(base 10) = 1(base 2) and .234(base 10) = .0011(base 2) Now, to get the binary of 1.234, merge both results as a complete number. (1)10 = (1)2 (.234)10 = (.0011)2 (1.234)10 = (1.0011...)2 (1.234)10 = (1.0011)2 [approx.]
Below is the implementation :
Python3
# Python program to convert float# decimal to binary number # Function returns octal representationdef float_bin(number, places = 3): # split() separates whole number and decimal # part and stores it in two separate variables whole, dec = str(number).split(".") # Convert both whole number and decimal # part from string type to integer type whole = int(whole) dec = int (dec) # Convert the whole number part to it's # respective binary form and remove the # "0b" from it. res = bin(whole).lstrip("0b") + "." # Iterate the number of times, we want # the number of decimal places to be for x in range(places): # Multiply the decimal value by 2 # and separate the whole number part # and decimal part whole, dec = str((decimal_converter(dec)) * 2).split(".") # Convert the decimal part # to integer again dec = int(dec) # Keep adding the integer parts # receive to the result variable res += whole return res # Function converts the value passed as# parameter to it's decimal representationdef decimal_converter(num): while num > 1: num /= 10 return num # Driver Code # Take the user input for# the floating point numbern = input("Enter your floating point value : \n") # Take user input for the number of# decimal places user want result asp = int(input("Enter the number of decimal places of the result : \n")) print(float_bin(n, places = p))
Output :
Enter your floating point value :
1.234
Enter the number of decimal places of the result :
4
1.0011
Enter your floating point value :
11.234
Enter the number of decimal places of the result :
4
1011.0011
Time Complexity : O(logn)
Auxiliary Space: O(1) if we use stack or arrays then O(logn) space will required
sweetyty
devendrasalunke
base-conversion
Bit Magic
Python
Python Programs
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find whether a given number is power of 2
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Binary representation of a given number
Josephus problem | Set 1 (A O(n) Solution)
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 820,
"s": 28,
"text": "Python doesn’t provide any inbuilt method to easily convert floating point decimal numbers to binary number. So, Let’s do this manually. Approach : To convert a floating point decimal number into binary, first convert the integer part into binary form and then fractional part into binary form and finally combine both results to get the final answer. For Integer Part, keep dividing the number by 2 and noting down the remainder until and unless the dividend is less than 2. If so, stop and copy all the remainders together. For Decimal Part, keep multiplying the decimal part with 2 until and unless 0 left as fractional part. After multiplying the first time, note down integral part and again multiply decimal part of the new value by 2. Keep doing this until reached a perfect number. "
},
{
"code": null,
"e": 1074,
"s": 820,
"text": "Above steps can be written as : 1(base 10) = 1(base 2) and .234(base 10) = .0011(base 2) Now, to get the binary of 1.234, merge both results as a complete number. (1)10 = (1)2 (.234)10 = (.0011)2 (1.234)10 = (1.0011...)2 (1.234)10 = (1.0011)2 [approx.]"
},
{
"code": null,
"e": 1105,
"s": 1074,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 1113,
"s": 1105,
"text": "Python3"
},
{
"code": "# Python program to convert float# decimal to binary number # Function returns octal representationdef float_bin(number, places = 3): # split() separates whole number and decimal # part and stores it in two separate variables whole, dec = str(number).split(\".\") # Convert both whole number and decimal # part from string type to integer type whole = int(whole) dec = int (dec) # Convert the whole number part to it's # respective binary form and remove the # \"0b\" from it. res = bin(whole).lstrip(\"0b\") + \".\" # Iterate the number of times, we want # the number of decimal places to be for x in range(places): # Multiply the decimal value by 2 # and separate the whole number part # and decimal part whole, dec = str((decimal_converter(dec)) * 2).split(\".\") # Convert the decimal part # to integer again dec = int(dec) # Keep adding the integer parts # receive to the result variable res += whole return res # Function converts the value passed as# parameter to it's decimal representationdef decimal_converter(num): while num > 1: num /= 10 return num # Driver Code # Take the user input for# the floating point numbern = input(\"Enter your floating point value : \\n\") # Take user input for the number of# decimal places user want result asp = int(input(\"Enter the number of decimal places of the result : \\n\")) print(float_bin(n, places = p))",
"e": 2593,
"s": 1113,
"text": null
},
{
"code": null,
"e": 2602,
"s": 2593,
"text": "Output :"
},
{
"code": null,
"e": 2704,
"s": 2602,
"text": "Enter your floating point value : \n1.234\nEnter the number of decimal places of the result :\n4\n\n1.0011"
},
{
"code": null,
"e": 2811,
"s": 2704,
"text": "Enter your floating point value : \n11.234\nEnter the number of decimal places of the result : \n4\n\n1011.0011"
},
{
"code": null,
"e": 2837,
"s": 2811,
"text": "Time Complexity : O(logn)"
},
{
"code": null,
"e": 2919,
"s": 2837,
"text": "Auxiliary Space: O(1) if we use stack or arrays then O(logn) space will required "
},
{
"code": null,
"e": 2928,
"s": 2919,
"text": "sweetyty"
},
{
"code": null,
"e": 2944,
"s": 2928,
"text": "devendrasalunke"
},
{
"code": null,
"e": 2960,
"s": 2944,
"text": "base-conversion"
},
{
"code": null,
"e": 2970,
"s": 2960,
"text": "Bit Magic"
},
{
"code": null,
"e": 2977,
"s": 2970,
"text": "Python"
},
{
"code": null,
"e": 2993,
"s": 2977,
"text": "Python Programs"
},
{
"code": null,
"e": 3003,
"s": 2993,
"text": "Bit Magic"
},
{
"code": null,
"e": 3101,
"s": 3003,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3154,
"s": 3101,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 3184,
"s": 3154,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 3222,
"s": 3184,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 3262,
"s": 3222,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 3305,
"s": 3262,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 3333,
"s": 3305,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 3383,
"s": 3333,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 3405,
"s": 3383,
"text": "Python map() function"
}
] |
How to read Dictionary from File in Python?
|
12 Nov, 2021
A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again.
We can read a dictionary from a file in 3 ways:
Using the json.loads() method : Converts the string of valid dictionary into json form.Using the ast.literal_eval() method : Function safer than the eval function and can be used for interconversion of all data types other than dictionary as well.Using the pickle.loads() method : We can also use Pickle module if the file is serialized into a character stream.
Using the json.loads() method : Converts the string of valid dictionary into json form.
Using the ast.literal_eval() method : Function safer than the eval function and can be used for interconversion of all data types other than dictionary as well.
Using the pickle.loads() method : We can also use Pickle module if the file is serialized into a character stream.
Input File:
Method 1 : Using json.loads() :
# importing the moduleimport json # reading the data from the filewith open('dictionary.txt') as f: data = f.read() print("Data type before reconstruction : ", type(data)) # reconstructing the data as a dictionaryjs = json.loads(data) print("Data type after reconstruction : ", type(js))print(js)
Output :
Data type before reconstruction : <class 'str'>
Data type after reconstruction : <class 'dict'>
{'Name': 'John', 'Age': 21, 'Id': 28}
Method 2 : Using ast.literal_eval() :
# importing the moduleimport ast # reading the data from the filewith open('dictionary.txt') as f: data = f.read() print("Data type before reconstruction : ", type(data)) # reconstructing the data as a dictionaryd = ast.literal_eval(data) print("Data type after reconstruction : ", type(d))print(d)
Output :
Data type before reconstruction : <class 'str'>
Data type after reconstruction : <class 'dict'>
{'Name': 'John', 'Age': 21, 'Id': 28}
Method 3 : We can use the Pickle module for the same purpose, but this method will only work if the file is serialized into a character stream and not in text format. To know more about Pickling in Python click here
# importing the moduleimport pickle # opening file in write mode (binary)file = open("dictionary.txt", "wb") my_dict = {"Name": "John", "Age": 21, "Id": 28} # serializing dictionary pickle.dump(my_dict, file) # closing the filefile.close() # reading the data from the filewith open('dictionary.txt', 'rb') as handle: data = handle.read() print("Data type before reconstruction : ", type(data)) # reconstructing the data as dictionaryd = pickle.loads(data) print("Data type after reconstruction : ", type(d))print(d)
Output :
Data type before reconstruction : <class 'bytes'>
Data type after reconstruction : <class 'dict'>
{'Name': 'John', 'Age': 21, 'Id': 28}
singghakshay
python-dict
Python
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 178,
"s": 28,
"text": "A Dictionary in Python is collection of key-value pairs, where key is always unique and oftenly we need to store a dictionary and read it back again."
},
{
"code": null,
"e": 226,
"s": 178,
"text": "We can read a dictionary from a file in 3 ways:"
},
{
"code": null,
"e": 588,
"s": 226,
"text": "Using the json.loads() method : Converts the string of valid dictionary into json form.Using the ast.literal_eval() method : Function safer than the eval function and can be used for interconversion of all data types other than dictionary as well.Using the pickle.loads() method : We can also use Pickle module if the file is serialized into a character stream."
},
{
"code": null,
"e": 676,
"s": 588,
"text": "Using the json.loads() method : Converts the string of valid dictionary into json form."
},
{
"code": null,
"e": 837,
"s": 676,
"text": "Using the ast.literal_eval() method : Function safer than the eval function and can be used for interconversion of all data types other than dictionary as well."
},
{
"code": null,
"e": 952,
"s": 837,
"text": "Using the pickle.loads() method : We can also use Pickle module if the file is serialized into a character stream."
},
{
"code": null,
"e": 964,
"s": 952,
"text": "Input File:"
},
{
"code": null,
"e": 996,
"s": 964,
"text": "Method 1 : Using json.loads() :"
},
{
"code": "# importing the moduleimport json # reading the data from the filewith open('dictionary.txt') as f: data = f.read() print(\"Data type before reconstruction : \", type(data)) # reconstructing the data as a dictionaryjs = json.loads(data) print(\"Data type after reconstruction : \", type(js))print(js)",
"e": 1304,
"s": 996,
"text": null
},
{
"code": null,
"e": 1313,
"s": 1304,
"text": "Output :"
},
{
"code": null,
"e": 1450,
"s": 1313,
"text": "Data type before reconstruction : <class 'str'>\nData type after reconstruction : <class 'dict'>\n{'Name': 'John', 'Age': 21, 'Id': 28}\n"
},
{
"code": null,
"e": 1488,
"s": 1450,
"text": "Method 2 : Using ast.literal_eval() :"
},
{
"code": "# importing the moduleimport ast # reading the data from the filewith open('dictionary.txt') as f: data = f.read() print(\"Data type before reconstruction : \", type(data)) # reconstructing the data as a dictionaryd = ast.literal_eval(data) print(\"Data type after reconstruction : \", type(d))print(d)",
"e": 1798,
"s": 1488,
"text": null
},
{
"code": null,
"e": 1807,
"s": 1798,
"text": "Output :"
},
{
"code": null,
"e": 1944,
"s": 1807,
"text": "Data type before reconstruction : <class 'str'>\nData type after reconstruction : <class 'dict'>\n{'Name': 'John', 'Age': 21, 'Id': 28}\n"
},
{
"code": null,
"e": 2160,
"s": 1944,
"text": "Method 3 : We can use the Pickle module for the same purpose, but this method will only work if the file is serialized into a character stream and not in text format. To know more about Pickling in Python click here"
},
{
"code": "# importing the moduleimport pickle # opening file in write mode (binary)file = open(\"dictionary.txt\", \"wb\") my_dict = {\"Name\": \"John\", \"Age\": 21, \"Id\": 28} # serializing dictionary pickle.dump(my_dict, file) # closing the filefile.close() # reading the data from the filewith open('dictionary.txt', 'rb') as handle: data = handle.read() print(\"Data type before reconstruction : \", type(data)) # reconstructing the data as dictionaryd = pickle.loads(data) print(\"Data type after reconstruction : \", type(d))print(d)",
"e": 2707,
"s": 2160,
"text": null
},
{
"code": null,
"e": 2716,
"s": 2707,
"text": "Output :"
},
{
"code": null,
"e": 2855,
"s": 2716,
"text": "Data type before reconstruction : <class 'bytes'>\nData type after reconstruction : <class 'dict'>\n{'Name': 'John', 'Age': 21, 'Id': 28}\n"
},
{
"code": null,
"e": 2868,
"s": 2855,
"text": "singghakshay"
},
{
"code": null,
"e": 2880,
"s": 2868,
"text": "python-dict"
},
{
"code": null,
"e": 2887,
"s": 2880,
"text": "Python"
},
{
"code": null,
"e": 2899,
"s": 2887,
"text": "python-dict"
},
{
"code": null,
"e": 2997,
"s": 2899,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3015,
"s": 2997,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3057,
"s": 3015,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3079,
"s": 3057,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3105,
"s": 3079,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3137,
"s": 3105,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3166,
"s": 3137,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3193,
"s": 3166,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3214,
"s": 3193,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3237,
"s": 3214,
"text": "Introduction To PYTHON"
}
] |
What are the HTML tags used to display the data in the tabular form ?
|
31 Oct, 2021
In this article, we will know the HTML tags that can be used to display the data in tabular form. A table is a representation of data in rows and columns, that helps to organize the complex structured data. Tables are widely used in communication, research, and data analysis. For instance, if we need to find the data from the set of information that is not organized properly, then we can’t find that specific data at a glance. In a similar way, we can use the table format using the HTML Table tag in the webpage.
The possible areas where we can use the table for displaying the data:
A complex or large amount of data can be easily converted into better form to make it more convenient.
Due to tabular representation, it makes a comparison of the data an easier task.
It creates a basis for statistical analysis.
An HTML table is defined with the “table” tag. Each table row is defined with the “tr” tag. A table header is defined with the “th” tag. By default, table headings are bold and centered. A table data/cell is defined with the “td” tag.
Syntax:
<table>
<tr><th>Table Header</th></tr>
<tr><td>Table Data</td></tr>
</table>
We will understand all the 3 tags, their individual characteristics/uses through the example.
HTML <tr> Tag: It is used to define a row in an HTML Table. It mainly consists of multiple <th> or <td> elements under it.
Syntax:
<tr>
<td>Data</td>
</tr>
HTML <th> Tag: It is used to define the header of a table. In <th> tag, the text is marked as a bold and aligned center by default.
Syntax:
<th>Table Heading</th>
HTML <td> Tag: It is used to insert or add data in each cell. In <td> tag text is regular and left-aligned by default.
Syntax:
<td>Table data</td>
Approach: Firstly, we will create a table using the <table> tag then we will divide the table into two parts: head and body of the table using the <thead> and <tbody>. Under <thead> tag, we will add all the headings of the table and under the <tbody> tag, we will use the <tr> tag for defining the table row. Under the <thead> tag, we will add the <th> tag for giving the headings to the table. Finally, under the <tbody> tag, we will define each cell by using the <td> tag.
We will understand the above concepts through the examples.
Example 1: In this example, we have created an HTML Table to store the marks of each student in a tabular form.
HTML
<!DOCTYPE html><html> <head> <title> What are the HTML tags used to display the data in the tabular form? </title> <style> table, th, td { border: 1px solid black; text-align: center; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> What are the HTML tags used to display the data in the tabular form? </h2> <table> <thead> <tr> <th>Roll No.</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Kunal</td> <td>91</td> <td>85</td> <td>96</td> </tr> <tr> <td>2</td> <td>Aryan</td> <td>96</td> <td>92</td> <td>91</td> </tr> <tr> <td>3</td> <td>Rohan</td> <td>80</td> <td>85</td> <td>98</td> </tr> <tr> <td>4</td> <td>Mohan</td> <td>94</td> <td>90</td> <td>89</td> </tr> </tbody> </table> </center></body> </html>
Output:
Example 2: This example describes the use of the HTML Table.
HTML
<!DOCTYPE html><html> <head> <title> What are the HTML tags used to display the data in the tabular form? </title> <style> table, th, td { border: 1px solid black; text-align: center; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> What are the HTML tags used to display the data in the tabular form? </h2> <table> <thead> <tr> <th>ID No.</th> <th>Name</th> <th>Entry time</th> <th>Leave time</th> </tr> </thead> <tbody> <tr> <td>C-124</td> <td>Sahaj</td> <td>6:00 am</td> <td>7:30 am</td> </tr> <tr> <td>C-102</td> <td>Vedanshu</td> <td>6:10 am</td> <td>6:55 am</td> </tr> <tr> <td>C-59</td> <td>John</td> <td>7:00 am</td> <td>8:20 am</td> </tr> <tr> <td>C-169</td> <td>Priyanshu</td> <td>7:30 am</td> <td>8:15 am</td> </tr> <tr> <td>C-145</td> <td>Yash</td> <td>7:35</td> <td>8:30</td> </tr> </tbody> </table> </center></body> </html>
Output:
HTML-Questions
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 547,
"s": 28,
"text": "In this article, we will know the HTML tags that can be used to display the data in tabular form. A table is a representation of data in rows and columns, that helps to organize the complex structured data. Tables are widely used in communication, research, and data analysis. For instance, if we need to find the data from the set of information that is not organized properly, then we can’t find that specific data at a glance. In a similar way, we can use the table format using the HTML Table tag in the webpage. "
},
{
"code": null,
"e": 618,
"s": 547,
"text": "The possible areas where we can use the table for displaying the data:"
},
{
"code": null,
"e": 721,
"s": 618,
"text": "A complex or large amount of data can be easily converted into better form to make it more convenient."
},
{
"code": null,
"e": 802,
"s": 721,
"text": "Due to tabular representation, it makes a comparison of the data an easier task."
},
{
"code": null,
"e": 847,
"s": 802,
"text": "It creates a basis for statistical analysis."
},
{
"code": null,
"e": 1082,
"s": 847,
"text": "An HTML table is defined with the “table” tag. Each table row is defined with the “tr” tag. A table header is defined with the “th” tag. By default, table headings are bold and centered. A table data/cell is defined with the “td” tag."
},
{
"code": null,
"e": 1092,
"s": 1084,
"text": "Syntax:"
},
{
"code": null,
"e": 1178,
"s": 1092,
"text": "<table>\n <tr><th>Table Header</th></tr>\n <tr><td>Table Data</td></tr>\n </table>"
},
{
"code": null,
"e": 1272,
"s": 1178,
"text": "We will understand all the 3 tags, their individual characteristics/uses through the example."
},
{
"code": null,
"e": 1395,
"s": 1272,
"text": "HTML <tr> Tag: It is used to define a row in an HTML Table. It mainly consists of multiple <th> or <td> elements under it."
},
{
"code": null,
"e": 1403,
"s": 1395,
"text": "Syntax:"
},
{
"code": null,
"e": 1432,
"s": 1403,
"text": "<tr>\n <td>Data</td>\n</tr>"
},
{
"code": null,
"e": 1564,
"s": 1432,
"text": "HTML <th> Tag: It is used to define the header of a table. In <th> tag, the text is marked as a bold and aligned center by default."
},
{
"code": null,
"e": 1572,
"s": 1564,
"text": "Syntax:"
},
{
"code": null,
"e": 1595,
"s": 1572,
"text": "<th>Table Heading</th>"
},
{
"code": null,
"e": 1714,
"s": 1595,
"text": "HTML <td> Tag: It is used to insert or add data in each cell. In <td> tag text is regular and left-aligned by default."
},
{
"code": null,
"e": 1725,
"s": 1716,
"text": "Syntax: "
},
{
"code": null,
"e": 1745,
"s": 1725,
"text": "<td>Table data</td>"
},
{
"code": null,
"e": 2221,
"s": 1745,
"text": "Approach: Firstly, we will create a table using the <table> tag then we will divide the table into two parts: head and body of the table using the <thead> and <tbody>. Under <thead> tag, we will add all the headings of the table and under the <tbody> tag, we will use the <tr> tag for defining the table row. Under the <thead> tag, we will add the <th> tag for giving the headings to the table. Finally, under the <tbody> tag, we will define each cell by using the <td> tag. "
},
{
"code": null,
"e": 2281,
"s": 2221,
"text": "We will understand the above concepts through the examples."
},
{
"code": null,
"e": 2394,
"s": 2281,
"text": "Example 1: In this example, we have created an HTML Table to store the marks of each student in a tabular form. "
},
{
"code": null,
"e": 2399,
"s": 2394,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What are the HTML tags used to display the data in the tabular form? </title> <style> table, th, td { border: 1px solid black; text-align: center; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> What are the HTML tags used to display the data in the tabular form? </h2> <table> <thead> <tr> <th>Roll No.</th> <th>Name</th> <th>Physics</th> <th>Chemistry</th> <th>Maths</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Kunal</td> <td>91</td> <td>85</td> <td>96</td> </tr> <tr> <td>2</td> <td>Aryan</td> <td>96</td> <td>92</td> <td>91</td> </tr> <tr> <td>3</td> <td>Rohan</td> <td>80</td> <td>85</td> <td>98</td> </tr> <tr> <td>4</td> <td>Mohan</td> <td>94</td> <td>90</td> <td>89</td> </tr> </tbody> </table> </center></body> </html>",
"e": 3991,
"s": 2399,
"text": null
},
{
"code": null,
"e": 3999,
"s": 3991,
"text": "Output:"
},
{
"code": null,
"e": 4060,
"s": 3999,
"text": "Example 2: This example describes the use of the HTML Table."
},
{
"code": null,
"e": 4065,
"s": 4060,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> What are the HTML tags used to display the data in the tabular form? </title> <style> table, th, td { border: 1px solid black; text-align: center; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <h2> What are the HTML tags used to display the data in the tabular form? </h2> <table> <thead> <tr> <th>ID No.</th> <th>Name</th> <th>Entry time</th> <th>Leave time</th> </tr> </thead> <tbody> <tr> <td>C-124</td> <td>Sahaj</td> <td>6:00 am</td> <td>7:30 am</td> </tr> <tr> <td>C-102</td> <td>Vedanshu</td> <td>6:10 am</td> <td>6:55 am</td> </tr> <tr> <td>C-59</td> <td>John</td> <td>7:00 am</td> <td>8:20 am</td> </tr> <tr> <td>C-169</td> <td>Priyanshu</td> <td>7:30 am</td> <td>8:15 am</td> </tr> <tr> <td>C-145</td> <td>Yash</td> <td>7:35</td> <td>8:30</td> </tr> </tbody> </table> </center></body> </html>",
"e": 5737,
"s": 4065,
"text": null
},
{
"code": null,
"e": 5745,
"s": 5737,
"text": "Output:"
},
{
"code": null,
"e": 5760,
"s": 5745,
"text": "HTML-Questions"
},
{
"code": null,
"e": 5767,
"s": 5760,
"text": "Picked"
},
{
"code": null,
"e": 5772,
"s": 5767,
"text": "HTML"
},
{
"code": null,
"e": 5789,
"s": 5772,
"text": "Web Technologies"
},
{
"code": null,
"e": 5794,
"s": 5789,
"text": "HTML"
},
{
"code": null,
"e": 5892,
"s": 5794,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5940,
"s": 5892,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 5964,
"s": 5940,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 6014,
"s": 5964,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 6053,
"s": 6014,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 6090,
"s": 6053,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 6123,
"s": 6090,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6184,
"s": 6123,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6227,
"s": 6184,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 6299,
"s": 6227,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Check if count of substrings in S with string S1 as prefix and S2 as suffix is equal to that with S2 as prefix and S1 as suffix
|
06 May, 2021
Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Examples:
Input: S = “helloworldworldhelloworld”, S1 = “hello”, S2 = “world”Output: NoExplanation:The substrings that starts with S1 (= “hello”) and ends with S2 (= “world”) are {“helloworld”, “helloworldworld”, “helloworldworldhelloworld”, “helloworld”}. Therefore, the total count is 4.The substrings that starts with S2 (= “world”) and ends with S1(= “hello”) are {“worldworldhello”, “worldhello”}.Therefore, the total count is 2.Therefore, the above two counts are not the same.
Input: S = “opencloseopencloseopen”, S1 = “open”, S2 = “close”Output: Yes
Approach: Follow the steps below to solve the problem:
Store the length of strings S, S1, and S2 in variables, say N, N1, and N2 respectively.
Initialize a variable, say count, to store the number of occurrences of substring S1 in the string S.
Initialize a variable, say ans, to store substrings that start and end with S1 and S2 respectively.
Traverse the given string S and perform the following steps:Store the substring of string S starting at the index i of size N1 in the string prefix.Store the substring of string S starting at the index i of size N2 in the string suffix.If the prefix is the same as the string S1, then increment the value of count by 1.If the suffix is the same as the string S2, then increment the value of ans by count.
Store the substring of string S starting at the index i of size N1 in the string prefix.
Store the substring of string S starting at the index i of size N2 in the string suffix.
If the prefix is the same as the string S1, then increment the value of count by 1.
If the suffix is the same as the string S2, then increment the value of ans by count.
Use the above steps, to find the number of substrings that start and end with S2 and S1 respectively. Store the count obtained in the variable say ans2.
If the values of ans and ans2 are found to be equal, then print “Yes”. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count number of// substrings that starts with// string S1 and ends with string S2int countSubstrings(string S, string S1, string S2){ // Stores the length of each string int N = S.length(); int N1 = S1.length(); int N2 = S2.length(); // Stores the count of prefixes // as S1 and suffixes as S2 int count = 0, totalcount = 0; // Traverse string S for (int i = 0; i < N; i++) { // Find the prefix at index i string prefix = S.substr(i, N1); // Find the suffix at index i string suffix = S.substr(i, N2); // If the prefix is S1 if (S1 == prefix) count++; // If the suffix is S2 if (S2 == suffix) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notvoid checkSubstrings(string S, string S1, string S2){ // Count the number of substrings int x = countSubstrings(S, S1, S2); int y = countSubstrings(S, S2, S1); // Print the result if (x == y) cout << "Yes"; else cout << "No";} // Driver Codeint main(){ string S = "opencloseopencloseopen"; string S1 = "open"; string S2 = "close"; checkSubstrings(S, S1, S2); return 0;}
// Java program for the above approachclass GFG{ // Function to count number of// substrings that starts with// string S1 and ends with string S2static int countSubstrings(String S, String S1, String S2){ // Stores the length of each string int N = S.length(); int N1 = S1.length(); int N2 = S2.length(); // Stores the count of prefixes // as S1 and suffixes as S2 int count = 0, totalcount = 0; // Traverse string S for(int i = 0; i < N; i++) { // Find the prefix at index i String prefix = S.substring( i, (i + N1 < N) ? (i + N1) : N); // Find the suffix at index i String suffix = S.substring( i, (i + N2 < N) ? (i + N2) : N); // If the prefix is S1 if (S1.equals(prefix)) count++; // If the suffix is S2 if (S2.equals(suffix)) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notstatic void checkSubstrings(String S, String S1, String S2){ // Count the number of substrings int x = countSubstrings(S, S1, S2); int y = countSubstrings(S, S2, S1); // Print the result if (x == y) System.out.println("Yes"); else System.out.println("No");} // Driver Codepublic static void main(String[] args){ String S = "opencloseopencloseopen"; String S1 = "open"; String S2 = "close"; checkSubstrings(S, S1, S2);}} // This code is contributed by abhinavjain194
# Python3 program for the above approach # Function to count number of# substrings that starts with# string S1 and ends with string S2def countSubstrings(S, S1, S2): # Stores the length of each string N = len(S) N1 = len(S1) N2 = len(S2) # Stores the count of prefixes # as S1 and suffixes as S2 count = 0 totalcount = 0 # Traverse string S for i in range(N): # Find the prefix at index i prefix = S[i: (i + N1) if (i + N1 < N) else N] # Find the suffix at index i suffix = S[i: (i + N2) if (i + N2 < N) else N] # If the prefix is S1 if S1 == prefix: count += 1 # If the suffix is S2 if S2 == suffix: totalcount += count # Return the count of substrings return totalcount # Function to check if the number of# substrings starts with S1 and ends# with S2 and vice-versa is same or notdef checkSubstrings(S, S1, S2): x = countSubstrings(S, S1, S2) y = countSubstrings(S, S2, S1) if x == y: print("Yes") else: print("No") # Driver codeS = "opencloseopencloseopen"S1 = "open"S2 = "close" checkSubstrings(S, S1, S2) # This code is contributed by abhinavjain194
// C# program for the above approachusing System; class GFG{ // Function to count number of// substrings that starts with// string S1 and ends with string S2static int countSubstrings(string S, string S1, string S2){ // Stores the length of each string int N = S.Length; int N1 = S1.Length; int N2 = S2.Length; // Stores the count of prefixes // as S1 and suffixes as S2 int count = 0, totalcount = 0; // Traverse string S for(int i = 0; i < N; i++) { // Find the prefix at index i String prefix = S.Substring( i, (i + N1 < N) ? N1 : (N - i)); // Find the suffix at index i String suffix = S.Substring( i, (i + N2 < N) ? N2 : (N - i)); // If the prefix is S1 if (S1.Equals(prefix)) count++; // If the suffix is S2 if (S2.Equals(suffix)) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notstatic void checkSubstrings(string S, string S1, string S2){ // Count the number of substrings int x = countSubstrings(S, S1, S2); int y = countSubstrings(S, S2, S1); // Print the result if (x == y) Console.Write("Yes"); else Console.Write("No");} // Driver codestatic void Main(){ string S = "opencloseopencloseopen"; string S1 = "open"; string S2 = "close"; checkSubstrings(S, S1, S2);}} // This code is contributed by abhinavjain194
<script>// Javascript program for the above approach // Function to count number of// substrings that starts with// string S1 and ends with string S2function countSubstrings(S, S1, S2){ // Stores the length of each string let N = S.length; let N1 = S1.length; let N2 = S2.length; // Stores the count of prefixes // as S1 and suffixes as S2 let count = 0, totalcount = 0; // Traverse string S for (let i = 0; i < N; i++) { // Find the prefix at index i let prefix = S.substr(i, N1); // Find the suffix at index i let suffix = S.substr(i, N2); // If the prefix is S1 if (S1 == prefix) count++; // If the suffix is S2 if (S2 == suffix) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notfunction checkSubstrings(S, S1, S2){ // Count the number of substrings let x = countSubstrings(S, S1, S2); let y = countSubstrings(S, S2, S1); // Print the result if (x == y) document.write("Yes"); else document.write("No");} // Driver Code let S = "opencloseopencloseopen"; let S1 = "open"; let S2 = "close"; checkSubstrings(S, S1, S2); // This code is contributed by gfgking</script>
Yes
Time Complexity: O(N * (N1 + N2)), where N, N1, and N2 are the length of strings S, S1, and S2 respectively.Auxiliary Space: O(1)
abhinavjain194
gfgking
prefix
substring
Suffix
Searching
Strings
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search, insert and delete in a sorted array
Given a sorted and rotated array, find if there is a pair with a given sum
Allocate minimum number of pages
Find common elements in three sorted arrays
Find whether an array is subset of another array
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Write a program to print all permutations of a given string
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 287,
"s": 28,
"text": "Given three strings S, S1, and S2, the task is to check if the number of substrings that start and end with S1 and S2 is equal to the number of substrings that start and end with S2 and S1 or not. If found to be true, then print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 297,
"s": 287,
"text": "Examples:"
},
{
"code": null,
"e": 770,
"s": 297,
"text": "Input: S = “helloworldworldhelloworld”, S1 = “hello”, S2 = “world”Output: NoExplanation:The substrings that starts with S1 (= “hello”) and ends with S2 (= “world”) are {“helloworld”, “helloworldworld”, “helloworldworldhelloworld”, “helloworld”}. Therefore, the total count is 4.The substrings that starts with S2 (= “world”) and ends with S1(= “hello”) are {“worldworldhello”, “worldhello”}.Therefore, the total count is 2.Therefore, the above two counts are not the same."
},
{
"code": null,
"e": 844,
"s": 770,
"text": "Input: S = “opencloseopencloseopen”, S1 = “open”, S2 = “close”Output: Yes"
},
{
"code": null,
"e": 899,
"s": 844,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 987,
"s": 899,
"text": "Store the length of strings S, S1, and S2 in variables, say N, N1, and N2 respectively."
},
{
"code": null,
"e": 1089,
"s": 987,
"text": "Initialize a variable, say count, to store the number of occurrences of substring S1 in the string S."
},
{
"code": null,
"e": 1189,
"s": 1089,
"text": "Initialize a variable, say ans, to store substrings that start and end with S1 and S2 respectively."
},
{
"code": null,
"e": 1594,
"s": 1189,
"text": "Traverse the given string S and perform the following steps:Store the substring of string S starting at the index i of size N1 in the string prefix.Store the substring of string S starting at the index i of size N2 in the string suffix.If the prefix is the same as the string S1, then increment the value of count by 1.If the suffix is the same as the string S2, then increment the value of ans by count."
},
{
"code": null,
"e": 1683,
"s": 1594,
"text": "Store the substring of string S starting at the index i of size N1 in the string prefix."
},
{
"code": null,
"e": 1772,
"s": 1683,
"text": "Store the substring of string S starting at the index i of size N2 in the string suffix."
},
{
"code": null,
"e": 1856,
"s": 1772,
"text": "If the prefix is the same as the string S1, then increment the value of count by 1."
},
{
"code": null,
"e": 1942,
"s": 1856,
"text": "If the suffix is the same as the string S2, then increment the value of ans by count."
},
{
"code": null,
"e": 2095,
"s": 1942,
"text": "Use the above steps, to find the number of substrings that start and end with S2 and S1 respectively. Store the count obtained in the variable say ans2."
},
{
"code": null,
"e": 2189,
"s": 2095,
"text": "If the values of ans and ans2 are found to be equal, then print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 2240,
"s": 2189,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2244,
"s": 2240,
"text": "C++"
},
{
"code": null,
"e": 2249,
"s": 2244,
"text": "Java"
},
{
"code": null,
"e": 2257,
"s": 2249,
"text": "Python3"
},
{
"code": null,
"e": 2260,
"s": 2257,
"text": "C#"
},
{
"code": null,
"e": 2271,
"s": 2260,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count number of// substrings that starts with// string S1 and ends with string S2int countSubstrings(string S, string S1, string S2){ // Stores the length of each string int N = S.length(); int N1 = S1.length(); int N2 = S2.length(); // Stores the count of prefixes // as S1 and suffixes as S2 int count = 0, totalcount = 0; // Traverse string S for (int i = 0; i < N; i++) { // Find the prefix at index i string prefix = S.substr(i, N1); // Find the suffix at index i string suffix = S.substr(i, N2); // If the prefix is S1 if (S1 == prefix) count++; // If the suffix is S2 if (S2 == suffix) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notvoid checkSubstrings(string S, string S1, string S2){ // Count the number of substrings int x = countSubstrings(S, S1, S2); int y = countSubstrings(S, S2, S1); // Print the result if (x == y) cout << \"Yes\"; else cout << \"No\";} // Driver Codeint main(){ string S = \"opencloseopencloseopen\"; string S1 = \"open\"; string S2 = \"close\"; checkSubstrings(S, S1, S2); return 0;}",
"e": 3732,
"s": 2271,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to count number of// substrings that starts with// string S1 and ends with string S2static int countSubstrings(String S, String S1, String S2){ // Stores the length of each string int N = S.length(); int N1 = S1.length(); int N2 = S2.length(); // Stores the count of prefixes // as S1 and suffixes as S2 int count = 0, totalcount = 0; // Traverse string S for(int i = 0; i < N; i++) { // Find the prefix at index i String prefix = S.substring( i, (i + N1 < N) ? (i + N1) : N); // Find the suffix at index i String suffix = S.substring( i, (i + N2 < N) ? (i + N2) : N); // If the prefix is S1 if (S1.equals(prefix)) count++; // If the suffix is S2 if (S2.equals(suffix)) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notstatic void checkSubstrings(String S, String S1, String S2){ // Count the number of substrings int x = countSubstrings(S, S1, S2); int y = countSubstrings(S, S2, S1); // Print the result if (x == y) System.out.println(\"Yes\"); else System.out.println(\"No\");} // Driver Codepublic static void main(String[] args){ String S = \"opencloseopencloseopen\"; String S1 = \"open\"; String S2 = \"close\"; checkSubstrings(S, S1, S2);}} // This code is contributed by abhinavjain194",
"e": 5384,
"s": 3732,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count number of# substrings that starts with# string S1 and ends with string S2def countSubstrings(S, S1, S2): # Stores the length of each string N = len(S) N1 = len(S1) N2 = len(S2) # Stores the count of prefixes # as S1 and suffixes as S2 count = 0 totalcount = 0 # Traverse string S for i in range(N): # Find the prefix at index i prefix = S[i: (i + N1) if (i + N1 < N) else N] # Find the suffix at index i suffix = S[i: (i + N2) if (i + N2 < N) else N] # If the prefix is S1 if S1 == prefix: count += 1 # If the suffix is S2 if S2 == suffix: totalcount += count # Return the count of substrings return totalcount # Function to check if the number of# substrings starts with S1 and ends# with S2 and vice-versa is same or notdef checkSubstrings(S, S1, S2): x = countSubstrings(S, S1, S2) y = countSubstrings(S, S2, S1) if x == y: print(\"Yes\") else: print(\"No\") # Driver codeS = \"opencloseopencloseopen\"S1 = \"open\"S2 = \"close\" checkSubstrings(S, S1, S2) # This code is contributed by abhinavjain194",
"e": 6654,
"s": 5384,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to count number of// substrings that starts with// string S1 and ends with string S2static int countSubstrings(string S, string S1, string S2){ // Stores the length of each string int N = S.Length; int N1 = S1.Length; int N2 = S2.Length; // Stores the count of prefixes // as S1 and suffixes as S2 int count = 0, totalcount = 0; // Traverse string S for(int i = 0; i < N; i++) { // Find the prefix at index i String prefix = S.Substring( i, (i + N1 < N) ? N1 : (N - i)); // Find the suffix at index i String suffix = S.Substring( i, (i + N2 < N) ? N2 : (N - i)); // If the prefix is S1 if (S1.Equals(prefix)) count++; // If the suffix is S2 if (S2.Equals(suffix)) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notstatic void checkSubstrings(string S, string S1, string S2){ // Count the number of substrings int x = countSubstrings(S, S1, S2); int y = countSubstrings(S, S2, S1); // Print the result if (x == y) Console.Write(\"Yes\"); else Console.Write(\"No\");} // Driver codestatic void Main(){ string S = \"opencloseopencloseopen\"; string S1 = \"open\"; string S2 = \"close\"; checkSubstrings(S, S1, S2);}} // This code is contributed by abhinavjain194",
"e": 8282,
"s": 6654,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to count number of// substrings that starts with// string S1 and ends with string S2function countSubstrings(S, S1, S2){ // Stores the length of each string let N = S.length; let N1 = S1.length; let N2 = S2.length; // Stores the count of prefixes // as S1 and suffixes as S2 let count = 0, totalcount = 0; // Traverse string S for (let i = 0; i < N; i++) { // Find the prefix at index i let prefix = S.substr(i, N1); // Find the suffix at index i let suffix = S.substr(i, N2); // If the prefix is S1 if (S1 == prefix) count++; // If the suffix is S2 if (S2 == suffix) totalcount += count; } // Return the count of substrings return totalcount;} // Function to check if the number of// substrings starts with S1 and ends// with S2 and vice-versa is same or notfunction checkSubstrings(S, S1, S2){ // Count the number of substrings let x = countSubstrings(S, S1, S2); let y = countSubstrings(S, S2, S1); // Print the result if (x == y) document.write(\"Yes\"); else document.write(\"No\");} // Driver Code let S = \"opencloseopencloseopen\"; let S1 = \"open\"; let S2 = \"close\"; checkSubstrings(S, S1, S2); // This code is contributed by gfgking</script>",
"e": 9660,
"s": 8282,
"text": null
},
{
"code": null,
"e": 9664,
"s": 9660,
"text": "Yes"
},
{
"code": null,
"e": 9794,
"s": 9664,
"text": "Time Complexity: O(N * (N1 + N2)), where N, N1, and N2 are the length of strings S, S1, and S2 respectively.Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9809,
"s": 9794,
"text": "abhinavjain194"
},
{
"code": null,
"e": 9817,
"s": 9809,
"text": "gfgking"
},
{
"code": null,
"e": 9824,
"s": 9817,
"text": "prefix"
},
{
"code": null,
"e": 9834,
"s": 9824,
"text": "substring"
},
{
"code": null,
"e": 9841,
"s": 9834,
"text": "Suffix"
},
{
"code": null,
"e": 9851,
"s": 9841,
"text": "Searching"
},
{
"code": null,
"e": 9859,
"s": 9851,
"text": "Strings"
},
{
"code": null,
"e": 9869,
"s": 9859,
"text": "Searching"
},
{
"code": null,
"e": 9877,
"s": 9869,
"text": "Strings"
},
{
"code": null,
"e": 9975,
"s": 9877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10019,
"s": 9975,
"text": "Search, insert and delete in a sorted array"
},
{
"code": null,
"e": 10094,
"s": 10019,
"text": "Given a sorted and rotated array, find if there is a pair with a given sum"
},
{
"code": null,
"e": 10127,
"s": 10094,
"text": "Allocate minimum number of pages"
},
{
"code": null,
"e": 10171,
"s": 10127,
"text": "Find common elements in three sorted arrays"
},
{
"code": null,
"e": 10220,
"s": 10171,
"text": "Find whether an array is subset of another array"
},
{
"code": null,
"e": 10266,
"s": 10220,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10291,
"s": 10266,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 10306,
"s": 10291,
"text": "C++ Data Types"
},
{
"code": null,
"e": 10366,
"s": 10306,
"text": "Write a program to print all permutations of a given string"
}
] |
How to create a table with fixed header and scrollable body ? - GeeksforGeeks
|
25 Mar, 2021
The purpose of this article is to create a table with a fixed header and scrollable body. We can create such a table with either of the two approaches.
By setting the position property to “sticky” and specifying “0” as a value of the top property for the <th> element.By setting the display to “block” for both <thead> and <tbody> element so that we can apply the height and overflow properties to <tbody>.
By setting the position property to “sticky” and specifying “0” as a value of the top property for the <th> element.
By setting the display to “block” for both <thead> and <tbody> element so that we can apply the height and overflow properties to <tbody>.
Note:
The position property states the type of positioning for an element.
The display property states that how an element should be displayed.
Example: Below is the code which illustrates the formation of table with position property.
HTML
<!DOCTYPE html><html> <head> <style> .fixTableHead { overflow-y: auto; height: 110px; } .fixTableHead thead th { position: sticky; top: 0; } table { border-collapse: collapse; width: 100%; } th, td { padding: 8px 15px; border: 2px solid #529432; } th { background: #ABDD93; } </style></head> <body> <div class="fixTableHead"> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> <tbody> <tr> <td>1.1</td> <td>2.1</td> </tr> <tr> <td>1.2</td> <td>2.2</td> </tr> <tr> <td>1.3</td> <td>2.3</td> </tr> <tr> <td>1.4</td> <td>2.4</td> </tr> <tr> <td>1.5</td> <td>2.5</td> </tr> </tbody> </table> </div></body> </html>
Output:
Example 2: Below is the code which illustrates the formation of table with display property.
HTML
<!DOCTYPE html><html> <head> <style> .tableFixHead { width: 500px; table-layout: fixed; border-collapse: collapse; } .tableFixHead tbody { display: block; width: 100%; overflow: auto; height: 50px; } .tableFixHead thead tr { display: block; } .tableFixHead th, .tableFixHead td { padding: 5px 10px; width: 200px; } th { background: #ABDD93; } </style></head> <body> <div class="tableFixHead"> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> <tbody> <tr> <td>1.1</td> <td>2.1</td> </tr> <tr> <td>1.2</td> <td>2.2</td> </tr> <tr> <td>1.3</td> <td>2.3</td> </tr> <tr> <td>1.4</td> <td>2.4</td> </tr> <tr> <td>1.5</td> <td>2.5</td> </tr> </tbody> </table> </div></body> </html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
HTML-Questions
HTML-Tags
Picked
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
Types of CSS (Cascading Style Sheet)
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 31345,
"s": 31317,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 31497,
"s": 31345,
"text": "The purpose of this article is to create a table with a fixed header and scrollable body. We can create such a table with either of the two approaches."
},
{
"code": null,
"e": 31752,
"s": 31497,
"text": "By setting the position property to “sticky” and specifying “0” as a value of the top property for the <th> element.By setting the display to “block” for both <thead> and <tbody> element so that we can apply the height and overflow properties to <tbody>."
},
{
"code": null,
"e": 31869,
"s": 31752,
"text": "By setting the position property to “sticky” and specifying “0” as a value of the top property for the <th> element."
},
{
"code": null,
"e": 32008,
"s": 31869,
"text": "By setting the display to “block” for both <thead> and <tbody> element so that we can apply the height and overflow properties to <tbody>."
},
{
"code": null,
"e": 32015,
"s": 32008,
"text": "Note: "
},
{
"code": null,
"e": 32084,
"s": 32015,
"text": "The position property states the type of positioning for an element."
},
{
"code": null,
"e": 32153,
"s": 32084,
"text": "The display property states that how an element should be displayed."
},
{
"code": null,
"e": 32245,
"s": 32153,
"text": "Example: Below is the code which illustrates the formation of table with position property."
},
{
"code": null,
"e": 32250,
"s": 32245,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .fixTableHead { overflow-y: auto; height: 110px; } .fixTableHead thead th { position: sticky; top: 0; } table { border-collapse: collapse; width: 100%; } th, td { padding: 8px 15px; border: 2px solid #529432; } th { background: #ABDD93; } </style></head> <body> <div class=\"fixTableHead\"> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> <tbody> <tr> <td>1.1</td> <td>2.1</td> </tr> <tr> <td>1.2</td> <td>2.2</td> </tr> <tr> <td>1.3</td> <td>2.3</td> </tr> <tr> <td>1.4</td> <td>2.4</td> </tr> <tr> <td>1.5</td> <td>2.5</td> </tr> </tbody> </table> </div></body> </html>",
"e": 33196,
"s": 32250,
"text": null
},
{
"code": null,
"e": 33204,
"s": 33196,
"text": "Output:"
},
{
"code": null,
"e": 33297,
"s": 33204,
"text": "Example 2: Below is the code which illustrates the formation of table with display property."
},
{
"code": null,
"e": 33302,
"s": 33297,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .tableFixHead { width: 500px; table-layout: fixed; border-collapse: collapse; } .tableFixHead tbody { display: block; width: 100%; overflow: auto; height: 50px; } .tableFixHead thead tr { display: block; } .tableFixHead th, .tableFixHead td { padding: 5px 10px; width: 200px; } th { background: #ABDD93; } </style></head> <body> <div class=\"tableFixHead\"> <table> <thead> <tr> <th>Col 1</th> <th>Col 2</th> </tr> </thead> <tbody> <tr> <td>1.1</td> <td>2.1</td> </tr> <tr> <td>1.2</td> <td>2.2</td> </tr> <tr> <td>1.3</td> <td>2.3</td> </tr> <tr> <td>1.4</td> <td>2.4</td> </tr> <tr> <td>1.5</td> <td>2.5</td> </tr> </tbody> </table> </div></body> </html>",
"e": 34310,
"s": 33302,
"text": null
},
{
"code": null,
"e": 34318,
"s": 34310,
"text": "Output:"
},
{
"code": null,
"e": 34455,
"s": 34318,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 34471,
"s": 34455,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 34486,
"s": 34471,
"text": "HTML-Questions"
},
{
"code": null,
"e": 34496,
"s": 34486,
"text": "HTML-Tags"
},
{
"code": null,
"e": 34503,
"s": 34496,
"text": "Picked"
},
{
"code": null,
"e": 34507,
"s": 34503,
"text": "CSS"
},
{
"code": null,
"e": 34524,
"s": 34507,
"text": "Web Technologies"
},
{
"code": null,
"e": 34622,
"s": 34524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34631,
"s": 34622,
"text": "Comments"
},
{
"code": null,
"e": 34644,
"s": 34631,
"text": "Old Comments"
},
{
"code": null,
"e": 34706,
"s": 34644,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 34756,
"s": 34706,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 34804,
"s": 34756,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 34862,
"s": 34804,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 34899,
"s": 34862,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 34955,
"s": 34899,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 34988,
"s": 34955,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35050,
"s": 34988,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35093,
"s": 35050,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Espresso Testing Framework - Architecture
|
In this chapter, let us learn the terms of espresso testing framework, how to write a simple espresso test case and the complete workflow or architecture of the espresso testing framework.
Espresso provides a large number of classes to test user interface and the user interaction of an android application. They can be grouped into five categories as specified below −
Android testing framework provides a runner, AndroidJUnitRunner to run the espresso test cases written in JUnit3 and JUnit4 style test cases. It is specific to android application and it transparently handles loading the espresso test cases and the application under test both in actual device or emulator, execute the test cases and report the result of the test cases. To use AndroidJUnitRunner in the test case, we need to annotate the test class using @RunWith annotation and then pass the AndroidJUnitRunner argument as specified below −
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
}
Android testing framework provides a rule, ActivityTestRule to launch an android activity before executing the test cases. It launches the activity before each method annotated with @Test` and @Before. It will terminate the activity after method annotated with @After. A sample code is as follows,
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
Here, MainActivity is the activity to be launched before running a test case and destroyed after the particular test case is run.
Espresso provides large number of view matcher classes (in androidx.test.espresso.matcher.ViewMatchers package) to match and find UI elements / views in an android activity screen’s view hierarchy. Espresso’s method onView takes a single argument of type Matcher (View matchers), finds the corresponding UI view and returns corresponding ViewInteraction object. ViewInteraction object returned by onView method can be further used to invoke actions like click on the matched view or can be used to assert the matched view. A sample code to find the view with text, “Hello World!” is as follows,
ViewInteraction viewInteraction = Espresso.onView(withText("Hello World!"));
Here, withText is a matcher, which can be used to match UI view having text “Hello World!”
Espresso provides large number of view action classes (in androidx.test.espresso.action.ViewActions) to invoke the different action on the selected / matched view. Once onView matches and returns ViewInteraction object, any action can be invoked by calling “perform” method of ViewInteraction object and pass it with proper view actions. A sample code to click the matched view is as follows,
ViewInteraction viewInteraction = Espresso.onView(withText("Hello World!"));
viewInteraction.perform(click());
Here, the click action of the matched view will be invoked.
Similar to view matchers and view actions, Espresso provides a large number of view assertion (in androidx.test.espresso.assertion.ViewAssertions package) to assert the matched view is what we expected. Once onView matches and returns the ViewInteraction object, any assert can be checked using check method of ViewInteraction by passing it with proper view assertion. A sample code to assert that the matched view is as follows,
ViewInteraction viewInteraction = Espresso.onView(withText("Hello World!"));
viewInteraction.check(matches(withId(R.id.text_view)));
Here, matches accept the view matcher and return view assertion, which can be checked by check method of ViewInteraction.
Let us understand how the espresso testing framework works and how it provides options to do any kind of user interaction in a simple and flexible way. Workflow of an espresso test case is as described below,
As we learned earlier, Android JUnit runner, AndroidJUnit4 will run the android test cases. The espresso test cases need to be marked with @RunWith(AndroidJUnut.class). First, AndroidJUnit4 will prepare the environment to run the test cases. It starts either the connected android device or emulator, installs the application and makes sure the application to be tested is in ready state. It will run the test cases and report the results.
As we learned earlier, Android JUnit runner, AndroidJUnit4 will run the android test cases. The espresso test cases need to be marked with @RunWith(AndroidJUnut.class). First, AndroidJUnit4 will prepare the environment to run the test cases. It starts either the connected android device or emulator, installs the application and makes sure the application to be tested is in ready state. It will run the test cases and report the results.
Espresso needs at least a single JUnit rule of type ActivityTestRule to specify the activity. Android JUnit runner will start the activity to be launched using ActivityTestRule.
Espresso needs at least a single JUnit rule of type ActivityTestRule to specify the activity. Android JUnit runner will start the activity to be launched using ActivityTestRule.
Every test case needs a minimum of single onView or onDate (used to find data based views like AdapterView) method invocation to match and find the desired view. onView or onData returns ViewInteraction object.
Every test case needs a minimum of single onView or onDate (used to find data based views like AdapterView) method invocation to match and find the desired view. onView or onData returns ViewInteraction object.
Once ViewInteraction object is returned, we can either invoke an action of the selected view or check the view for our expected view using assertion.
Once ViewInteraction object is returned, we can either invoke an action of the selected view or check the view for our expected view using assertion.
Action can be invoked using perform method of ViewInteraction object by passing any one of the available view actions.
Action can be invoked using perform method of ViewInteraction object by passing any one of the available view actions.
Assertion can be invoked using check method of ViewInteraction object by passing any one of the available view assertions.
Assertion can be invoked using check method of ViewInteraction object by passing any one of the available view assertions.
The diagram representation of the Workflow is as follows,
Let us write a simple test case to find the text view having “Hello World!” text in our “HelloWorldApp” application and then assert it using view assertion. The complete code is as follows,
package com.tutorialspoint.espressosamples.helloworldapp;
import android.content.Context;
import androidx.test.InstrumentationRegistry;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.matcher.ViewMatchers.withText;;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Rule
public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void view_isCorrect() {
onView(withText("Hello World!")).check(matches(isDisplayed()));
}
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.tutorialspoint.espressosamples.helloworldapp", appContext.getPackageName());
}
}
Here, we have used withText view matchers to find the text view having “Hello World!” text and matches view assertion to assert that the text view is properly displayed. Once the test case is invoked in Android Studio, it will run the test case and report the success message as below.
17 Lectures
1.5 hours
Anuja Jain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2165,
"s": 1976,
"text": "In this chapter, let us learn the terms of espresso testing framework, how to write a simple espresso test case and the complete workflow or architecture of the espresso testing framework."
},
{
"code": null,
"e": 2346,
"s": 2165,
"text": "Espresso provides a large number of classes to test user interface and the user interaction of an android application. They can be grouped into five categories as specified below −"
},
{
"code": null,
"e": 2889,
"s": 2346,
"text": "Android testing framework provides a runner, AndroidJUnitRunner to run the espresso test cases written in JUnit3 and JUnit4 style test cases. It is specific to android application and it transparently handles loading the espresso test cases and the application under test both in actual device or emulator, execute the test cases and report the result of the test cases. To use AndroidJUnitRunner in the test case, we need to annotate the test class using @RunWith annotation and then pass the AndroidJUnitRunner argument as specified below −"
},
{
"code": null,
"e": 2964,
"s": 2889,
"text": "@RunWith(AndroidJUnit4.class)\n public class ExampleInstrumentedTest {\n}\n"
},
{
"code": null,
"e": 3262,
"s": 2964,
"text": "Android testing framework provides a rule, ActivityTestRule to launch an android activity before executing the test cases. It launches the activity before each method annotated with @Test` and @Before. It will terminate the activity after method annotated with @After. A sample code is as follows,"
},
{
"code": null,
"e": 3371,
"s": 3262,
"text": "@Rule\npublic ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);\n"
},
{
"code": null,
"e": 3501,
"s": 3371,
"text": "Here, MainActivity is the activity to be launched before running a test case and destroyed after the particular test case is run."
},
{
"code": null,
"e": 4096,
"s": 3501,
"text": "Espresso provides large number of view matcher classes (in androidx.test.espresso.matcher.ViewMatchers package) to match and find UI elements / views in an android activity screen’s view hierarchy. Espresso’s method onView takes a single argument of type Matcher (View matchers), finds the corresponding UI view and returns corresponding ViewInteraction object. ViewInteraction object returned by onView method can be further used to invoke actions like click on the matched view or can be used to assert the matched view. A sample code to find the view with text, “Hello World!” is as follows,"
},
{
"code": null,
"e": 4174,
"s": 4096,
"text": "ViewInteraction viewInteraction = Espresso.onView(withText(\"Hello World!\"));\n"
},
{
"code": null,
"e": 4265,
"s": 4174,
"text": "Here, withText is a matcher, which can be used to match UI view having text “Hello World!”"
},
{
"code": null,
"e": 4658,
"s": 4265,
"text": "Espresso provides large number of view action classes (in androidx.test.espresso.action.ViewActions) to invoke the different action on the selected / matched view. Once onView matches and returns ViewInteraction object, any action can be invoked by calling “perform” method of ViewInteraction object and pass it with proper view actions. A sample code to click the matched view is as follows,"
},
{
"code": null,
"e": 4770,
"s": 4658,
"text": "ViewInteraction viewInteraction = Espresso.onView(withText(\"Hello World!\"));\nviewInteraction.perform(click());\n"
},
{
"code": null,
"e": 4830,
"s": 4770,
"text": "Here, the click action of the matched view will be invoked."
},
{
"code": null,
"e": 5260,
"s": 4830,
"text": "Similar to view matchers and view actions, Espresso provides a large number of view assertion (in androidx.test.espresso.assertion.ViewAssertions package) to assert the matched view is what we expected. Once onView matches and returns the ViewInteraction object, any assert can be checked using check method of ViewInteraction by passing it with proper view assertion. A sample code to assert that the matched view is as follows,"
},
{
"code": null,
"e": 5394,
"s": 5260,
"text": "ViewInteraction viewInteraction = Espresso.onView(withText(\"Hello World!\"));\nviewInteraction.check(matches(withId(R.id.text_view)));\n"
},
{
"code": null,
"e": 5516,
"s": 5394,
"text": "Here, matches accept the view matcher and return view assertion, which can be checked by check method of ViewInteraction."
},
{
"code": null,
"e": 5725,
"s": 5516,
"text": "Let us understand how the espresso testing framework works and how it provides options to do any kind of user interaction in a simple and flexible way. Workflow of an espresso test case is as described below,"
},
{
"code": null,
"e": 6165,
"s": 5725,
"text": "As we learned earlier, Android JUnit runner, AndroidJUnit4 will run the android test cases. The espresso test cases need to be marked with @RunWith(AndroidJUnut.class). First, AndroidJUnit4 will prepare the environment to run the test cases. It starts either the connected android device or emulator, installs the application and makes sure the application to be tested is in ready state. It will run the test cases and report the results."
},
{
"code": null,
"e": 6605,
"s": 6165,
"text": "As we learned earlier, Android JUnit runner, AndroidJUnit4 will run the android test cases. The espresso test cases need to be marked with @RunWith(AndroidJUnut.class). First, AndroidJUnit4 will prepare the environment to run the test cases. It starts either the connected android device or emulator, installs the application and makes sure the application to be tested is in ready state. It will run the test cases and report the results."
},
{
"code": null,
"e": 6783,
"s": 6605,
"text": "Espresso needs at least a single JUnit rule of type ActivityTestRule to specify the activity. Android JUnit runner will start the activity to be launched using ActivityTestRule."
},
{
"code": null,
"e": 6961,
"s": 6783,
"text": "Espresso needs at least a single JUnit rule of type ActivityTestRule to specify the activity. Android JUnit runner will start the activity to be launched using ActivityTestRule."
},
{
"code": null,
"e": 7172,
"s": 6961,
"text": "Every test case needs a minimum of single onView or onDate (used to find data based views like AdapterView) method invocation to match and find the desired view. onView or onData returns ViewInteraction object."
},
{
"code": null,
"e": 7383,
"s": 7172,
"text": "Every test case needs a minimum of single onView or onDate (used to find data based views like AdapterView) method invocation to match and find the desired view. onView or onData returns ViewInteraction object."
},
{
"code": null,
"e": 7533,
"s": 7383,
"text": "Once ViewInteraction object is returned, we can either invoke an action of the selected view or check the view for our expected view using assertion."
},
{
"code": null,
"e": 7683,
"s": 7533,
"text": "Once ViewInteraction object is returned, we can either invoke an action of the selected view or check the view for our expected view using assertion."
},
{
"code": null,
"e": 7802,
"s": 7683,
"text": "Action can be invoked using perform method of ViewInteraction object by passing any one of the available view actions."
},
{
"code": null,
"e": 7921,
"s": 7802,
"text": "Action can be invoked using perform method of ViewInteraction object by passing any one of the available view actions."
},
{
"code": null,
"e": 8044,
"s": 7921,
"text": "Assertion can be invoked using check method of ViewInteraction object by passing any one of the available view assertions."
},
{
"code": null,
"e": 8167,
"s": 8044,
"text": "Assertion can be invoked using check method of ViewInteraction object by passing any one of the available view assertions."
},
{
"code": null,
"e": 8225,
"s": 8167,
"text": "The diagram representation of the Workflow is as follows,"
},
{
"code": null,
"e": 8415,
"s": 8225,
"text": "Let us write a simple test case to find the text view having “Hello World!” text in our “HelloWorldApp” application and then assert it using view assertion. The complete code is as follows,"
},
{
"code": null,
"e": 9666,
"s": 8415,
"text": "package com.tutorialspoint.espressosamples.helloworldapp;\n\nimport android.content.Context;\nimport androidx.test.InstrumentationRegistry;\nimport androidx.test.rule.ActivityTestRule;\nimport androidx.test.runner.AndroidJUnit4;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\nimport static androidx.test.espresso.Espresso.onView;\nimport static androidx.test.espresso.matcher.ViewMatchers.withText;;\nimport static androidx.test.espresso.assertion.ViewAssertions.matches;\nimport static org.junit.Assert.*;\n/**\n * Instrumented test, which will execute on an Android device.\n *\n * @see <a href=\"http://d.android.com/tools/testing\">Testing documentation</a>\n*/\n@RunWith(AndroidJUnit4.class)\npublic class ExampleInstrumentedTest {\n @Rule\n public ActivityTestRule<MainActivity> mActivityTestRule = new ActivityTestRule<>(MainActivity.class);\n @Test\n public void view_isCorrect() {\n onView(withText(\"Hello World!\")).check(matches(isDisplayed()));\n }\n @Test\n public void useAppContext() {\n // Context of the app under test.\n Context appContext = InstrumentationRegistry.getTargetContext();\n assertEquals(\"com.tutorialspoint.espressosamples.helloworldapp\", appContext.getPackageName());\n }\n}"
},
{
"code": null,
"e": 9952,
"s": 9666,
"text": "Here, we have used withText view matchers to find the text view having “Hello World!” text and matches view assertion to assert that the text view is properly displayed. Once the test case is invoked in Android Studio, it will run the test case and report the success message as below."
},
{
"code": null,
"e": 9987,
"s": 9952,
"text": "\n 17 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9999,
"s": 9987,
"text": " Anuja Jain"
},
{
"code": null,
"e": 10006,
"s": 9999,
"text": " Print"
},
{
"code": null,
"e": 10017,
"s": 10006,
"text": " Add Notes"
}
] |
How to create FileFilter for JFileChooser in Java and display File Type accordingly?
|
To create FileFilter, use the FileNamExtensionFilter class. The following is an example to display File Type in JFileChooser −
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
public class SwingDemo {
public static void main(String[] args) {
JFileChooser file = new JFileChooser();
file.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter extFilter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
file.addChoosableFileFilter(extFilter);
file.showOpenDialog(null);
}
}
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "To create FileFilter, use the FileNamExtensionFilter class. The following is an example to display File Type in JFileChooser −"
},
{
"code": null,
"e": 1624,
"s": 1189,
"text": "import javax.swing.JFileChooser;\nimport javax.swing.filechooser.FileNameExtensionFilter;\npublic class SwingDemo {\n public static void main(String[] args) {\n JFileChooser file = new JFileChooser();\n file.setAcceptAllFileFilterUsed(false);\n FileNameExtensionFilter extFilter = new FileNameExtensionFilter(\"JPEG file\", \"jpg\", \"jpeg\");\n file.addChoosableFileFilter(extFilter);\n file.showOpenDialog(null);\n }\n}"
}
] |
How to get substring between two similar characters in JavaScript?
|
Let’s say we have the following string with some colons −
var values="This is:the first program in JavaScript:After that I will do Data Structure program";
We need to get the substring between the colon. The output should be −
the first program in JavaScript
For this, use the concept of split().
Following is the code −
var values="This is:the first program in JavaScript:After that I will do Data Structure program";
var result=[];
result=values.split(":");
console.log(result[1]);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo273.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo273.js
the first program in JavaScript
|
[
{
"code": null,
"e": 1120,
"s": 1062,
"text": "Let’s say we have the following string with some colons −"
},
{
"code": null,
"e": 1218,
"s": 1120,
"text": "var values=\"This is:the first program in JavaScript:After that I will do Data Structure program\";"
},
{
"code": null,
"e": 1289,
"s": 1218,
"text": "We need to get the substring between the colon. The output should be −"
},
{
"code": null,
"e": 1322,
"s": 1289,
"text": "the first program in JavaScript\n"
},
{
"code": null,
"e": 1360,
"s": 1322,
"text": "For this, use the concept of split()."
},
{
"code": null,
"e": 1384,
"s": 1360,
"text": "Following is the code −"
},
{
"code": null,
"e": 1547,
"s": 1384,
"text": "var values=\"This is:the first program in JavaScript:After that I will do Data Structure program\";\nvar result=[];\nresult=values.split(\":\");\nconsole.log(result[1]);"
},
{
"code": null,
"e": 1613,
"s": 1547,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1632,
"s": 1613,
"text": "node fileName.js.\n"
},
{
"code": null,
"e": 1666,
"s": 1632,
"text": "Here, my file name is demo273.js."
},
{
"code": null,
"e": 1718,
"s": 1666,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 1800,
"s": 1718,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo273.js\nthe first program in JavaScript"
}
] |
Print the longest prefix of the given string which is also the suffix of the same string in C Program.
|
Given a string in which we have to check that the length of the longest prefix which is also a suffix of the string like there is a string “abcab” so here “ab” is of length 2 and is the longest substring with same prefix and suffix.
Input: str[] = { “aabbccdaabbcc” }
Output: 6
Input: abdab
Output: 2
If we will start the pointer from start and end of the string than they will get overlapped at some point so instead of doing that we will break the string from middle and start matching left and right string. If they are equal return size of any one of the matched string else try for shorter lengths on both the sides.
int longest(char str[], int n)
START
STEP 1 : DECLARE length AS 0 AND i AS n/2
STEP 2 : IF n < 2 THEN
RETURN 1
STEP 3 :LOOP WHILE TILL str[i]!='\0'
IF str[i] == str[length] THEN,
INCREMENT length BY 1
INCREMENT i BY 1
ELSE
IF length == 0 THEN,
INCREMENT i BY 1
ELSE
DECREMENT length BY 1
END IF
END IF
END WHILE
RETURN length
STOP
#include <stdio.h>
int longest(char str[], int n){
int length = 0, i = n/2;
if( n < 2 )
return 1;
while( str[i]!='\0' ){
//When we find the character like prefix in suffix,
//we will move the length and i to count the length of the similar prefix and suffix
if (str[i] == str[length]){
++length;
++i;
} else //When prefix and suffix not equal{
if(length == 0)
++i;
else
--length;
}
}
return length;
}
int main(int argc, char const *argv[]){
char str[] = {"abccmmabcc"};
int n = sizeof(str)/sizeof(str[0]);
int length = longest(str, n);
printf("Length = %d", length);
return 0;
}
If we run above program then it will generate following output:
Length = 4
|
[
{
"code": null,
"e": 1295,
"s": 1062,
"text": "Given a string in which we have to check that the length of the longest prefix which is also a suffix of the string like there is a string “abcab” so here “ab” is of length 2 and is the longest substring with same prefix and suffix."
},
{
"code": null,
"e": 1363,
"s": 1295,
"text": "Input: str[] = { “aabbccdaabbcc” }\nOutput: 6\nInput: abdab\nOutput: 2"
},
{
"code": null,
"e": 1684,
"s": 1363,
"text": "If we will start the pointer from start and end of the string than they will get overlapped at some point so instead of doing that we will break the string from middle and start matching left and right string. If they are equal return size of any one of the matched string else try for shorter lengths on both the sides."
},
{
"code": null,
"e": 2075,
"s": 1684,
"text": "int longest(char str[], int n)\nSTART\nSTEP 1 : DECLARE length AS 0 AND i AS n/2\nSTEP 2 : IF n < 2 THEN\n RETURN 1\nSTEP 3 :LOOP WHILE TILL str[i]!='\\0'\n IF str[i] == str[length] THEN,\n INCREMENT length BY 1\n INCREMENT i BY 1\n ELSE\n IF length == 0 THEN,\n INCREMENT i BY 1\n ELSE\n DECREMENT length BY 1\n END IF\n END IF\nEND WHILE\nRETURN length\nSTOP"
},
{
"code": null,
"e": 2780,
"s": 2075,
"text": "#include <stdio.h>\nint longest(char str[], int n){\n int length = 0, i = n/2;\n if( n < 2 )\n return 1;\n while( str[i]!='\\0' ){\n //When we find the character like prefix in suffix,\n //we will move the length and i to count the length of the similar prefix and suffix\n if (str[i] == str[length]){\n ++length;\n ++i;\n } else //When prefix and suffix not equal{\n if(length == 0)\n ++i;\n else\n --length;\n }\n }\n return length;\n}\nint main(int argc, char const *argv[]){\n char str[] = {\"abccmmabcc\"};\n int n = sizeof(str)/sizeof(str[0]);\n int length = longest(str, n);\n printf(\"Length = %d\", length);\n return 0;\n}"
},
{
"code": null,
"e": 2844,
"s": 2780,
"text": "If we run above program then it will generate following output:"
},
{
"code": null,
"e": 2855,
"s": 2844,
"text": "Length = 4"
}
] |
Java DatabaseMetaData getProcedures() method with example
|
This method retrieves the description of the stored procedures of a database/catalog. It accepts 3 parameters −
catalog: A string parameter representing the name of the catalog (database in general) in which the procedure exists. Pass "" to get the description of the primary key columns in tables with no catalog and, pass null if you don't want to use catalog and thus narrow the search.
catalog: A string parameter representing the name of the catalog (database in general) in which the procedure exists. Pass "" to get the description of the primary key columns in tables with no catalog and, pass null if you don't want to use catalog and thus narrow the search.
schemaPattern: A String parameter representing the name (or, name pattern) of the schema, pass "" in case of no schema and, pass null if you don't want to use schema.
schemaPattern: A String parameter representing the name (or, name pattern) of the schema, pass "" in case of no schema and, pass null if you don't want to use schema.
procedureNamePattern: A String parameter representing the name of the procedure for which you need the description.
procedureNamePattern: A String parameter representing the name of the procedure for which you need the description.
This method returns a ResultSet object describing specified procedure. This object holds values for the following details (as column names) −
To get the description of the stored procedures in the database −
Make sure your database is up and running.
Make sure your database is up and running.
Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database.
Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database.
Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables.
Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables.
Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface.
Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface.
Finally, get ResultSet object holding the description of the required procedure, by invoking the getProcedureColumns() method of the DatabaseMetaData interface .
Finally, get ResultSet object holding the description of the required procedure, by invoking the getProcedureColumns() method of the DatabaseMetaData interface .
Let us create a procedure with name myprocedure in the MySQL database using the CREATE statement as shown below −
CREATE PROCEDURE myprocedure(
IN Product_Name VARCHAR(255),
IN Name_Of_Customer VARCHAR(255),
IN Month_Of_Dispatch VARCHAR(255),
IN Price INT, IN Location VARCHAR(255))
BEGIN
insert into Dispatches values (
Product_Name,
Name_Of_Customer,
Month_Of_Dispatch,
Price,
Location);
Following JDBC program establishes connection with MySQL database, retrieves the description of the above created procedure.
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseMetaData_getProcedures {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, "root", "password");
System.out.println("Connection established......");
//Retrieving the meta data object
DatabaseMetaData metaData = con.getMetaData();
//Retrieving the columns in the database
ResultSet procedures = metaData.getProcedures(null, null, "myprocedure");
//Printing the column name and size
while (procedures.next()) {
System.out.println("Catalog name: "+procedures.getString("PROCEDURE_CAT"));
System.out.println("Procedure name: "+procedures.getString("PROCEDURE_NAME"));
System.out.println("Type of the procedure: "+procedures.getShort("PROCEDURE_TYPE"));
System.out.println("Specific name of the procedure: "+procedures.getString("SPECIFIC_NAME"));
System.out.println(" ");
}
}
}
Connection established......
Procedure name: myprocedure
Column name: Product_Name
Type name: VARCHAR
Precision: 255
Radix: 10
Procedure name: myprocedure
Column name: Name_Of_Customer
Type name: VARCHAR
Precision: 255
Radix: 10
Procedure name: myprocedure
Column name: Month_Of_Dispatch
Type name: VARCHAR
Precision: 255
Radix: 10
Procedure name: myprocedure
Column name: Price
Type name: INT
Precision: 10
Radix: 10
Procedure name: myprocedure
Column name: Location
Type name: VARCHAR
Precision: 255
Radix: 10
|
[
{
"code": null,
"e": 1174,
"s": 1062,
"text": "This method retrieves the description of the stored procedures of a database/catalog. It accepts 3 parameters −"
},
{
"code": null,
"e": 1452,
"s": 1174,
"text": "catalog: A string parameter representing the name of the catalog (database in general) in which the procedure exists. Pass \"\" to get the description of the primary key columns in tables with no catalog and, pass null if you don't want to use catalog and thus narrow the search."
},
{
"code": null,
"e": 1730,
"s": 1452,
"text": "catalog: A string parameter representing the name of the catalog (database in general) in which the procedure exists. Pass \"\" to get the description of the primary key columns in tables with no catalog and, pass null if you don't want to use catalog and thus narrow the search."
},
{
"code": null,
"e": 1897,
"s": 1730,
"text": "schemaPattern: A String parameter representing the name (or, name pattern) of the schema, pass \"\" in case of no schema and, pass null if you don't want to use schema."
},
{
"code": null,
"e": 2064,
"s": 1897,
"text": "schemaPattern: A String parameter representing the name (or, name pattern) of the schema, pass \"\" in case of no schema and, pass null if you don't want to use schema."
},
{
"code": null,
"e": 2180,
"s": 2064,
"text": "procedureNamePattern: A String parameter representing the name of the procedure for which you need the description."
},
{
"code": null,
"e": 2296,
"s": 2180,
"text": "procedureNamePattern: A String parameter representing the name of the procedure for which you need the description."
},
{
"code": null,
"e": 2438,
"s": 2296,
"text": "This method returns a ResultSet object describing specified procedure. This object holds values for the following details (as column names) −"
},
{
"code": null,
"e": 2504,
"s": 2438,
"text": "To get the description of the stored procedures in the database −"
},
{
"code": null,
"e": 2547,
"s": 2504,
"text": "Make sure your database is up and running."
},
{
"code": null,
"e": 2590,
"s": 2547,
"text": "Make sure your database is up and running."
},
{
"code": null,
"e": 2749,
"s": 2590,
"text": "Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database."
},
{
"code": null,
"e": 2908,
"s": 2749,
"text": "Register the driver using the registerDriver() method of the DriverManager class. Pass an object of the driver class corresponding to the underlying database."
},
{
"code": null,
"e": 3094,
"s": 2908,
"text": "Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables."
},
{
"code": null,
"e": 3280,
"s": 3094,
"text": "Get the connection object using the getConnection() method of the DriverManager class. Pass the URL the database and, user name, password of a user in the database, as String variables."
},
{
"code": null,
"e": 3411,
"s": 3280,
"text": "Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface."
},
{
"code": null,
"e": 3542,
"s": 3411,
"text": "Get the DatabaseMetaData object with respect to the current connection using the getMetaData() method of the Connection interface."
},
{
"code": null,
"e": 3704,
"s": 3542,
"text": "Finally, get ResultSet object holding the description of the required procedure, by invoking the getProcedureColumns() method of the DatabaseMetaData interface ."
},
{
"code": null,
"e": 3866,
"s": 3704,
"text": "Finally, get ResultSet object holding the description of the required procedure, by invoking the getProcedureColumns() method of the DatabaseMetaData interface ."
},
{
"code": null,
"e": 3980,
"s": 3866,
"text": "Let us create a procedure with name myprocedure in the MySQL database using the CREATE statement as shown below −"
},
{
"code": null,
"e": 4286,
"s": 3980,
"text": "CREATE PROCEDURE myprocedure(\n IN Product_Name VARCHAR(255),\n IN Name_Of_Customer VARCHAR(255),\n IN Month_Of_Dispatch VARCHAR(255),\n IN Price INT, IN Location VARCHAR(255))\n BEGIN\ninsert into Dispatches values (\n Product_Name,\n Name_Of_Customer,\n Month_Of_Dispatch,\n Price,\n Location);"
},
{
"code": null,
"e": 4411,
"s": 4286,
"text": "Following JDBC program establishes connection with MySQL database, retrieves the description of the above created procedure."
},
{
"code": null,
"e": 5704,
"s": 4411,
"text": "import java.sql.Connection;\nimport java.sql.DatabaseMetaData;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\npublic class DatabaseMetaData_getProcedures {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String url = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(url, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Retrieving the meta data object\n DatabaseMetaData metaData = con.getMetaData();\n //Retrieving the columns in the database\n ResultSet procedures = metaData.getProcedures(null, null, \"myprocedure\");\n //Printing the column name and size\n while (procedures.next()) {\n System.out.println(\"Catalog name: \"+procedures.getString(\"PROCEDURE_CAT\"));\n System.out.println(\"Procedure name: \"+procedures.getString(\"PROCEDURE_NAME\"));\n System.out.println(\"Type of the procedure: \"+procedures.getShort(\"PROCEDURE_TYPE\"));\n System.out.println(\"Specific name of the procedure: \"+procedures.getString(\"SPECIFIC_NAME\"));\n System.out.println(\" \");\n }\n }\n}"
},
{
"code": null,
"e": 6216,
"s": 5704,
"text": "Connection established......\nProcedure name: myprocedure\nColumn name: Product_Name\nType name: VARCHAR\nPrecision: 255\nRadix: 10\nProcedure name: myprocedure\nColumn name: Name_Of_Customer\nType name: VARCHAR\nPrecision: 255\nRadix: 10\nProcedure name: myprocedure\nColumn name: Month_Of_Dispatch\nType name: VARCHAR\nPrecision: 255\nRadix: 10\nProcedure name: myprocedure\nColumn name: Price\nType name: INT\nPrecision: 10\nRadix: 10\nProcedure name: myprocedure\nColumn name: Location\nType name: VARCHAR\nPrecision: 255\nRadix: 10"
}
] |
Logical Operators in C++
|
The concept of logical operators is simple. They allow a program to make a decision based on multiple conditions. Each operand is considered a condition that can be evaluated to a true or false value. Then the value of the conditions is used to determine the overall value of the op1 operator op2 or !op1 grouping.
The logical OR operator (||) returns the boolean value true if either or both operands are true and returns false otherwise. The operands are implicitly converted to type bool prior to evaluation, and the result is of type bool. Logical OR has left-to-right associativity. The operands to the logical OR operator need not be of the same type, but they must be of integral or pointer type. The operands are commonly relational or equality expressions.
The first operand is completely evaluated and all side effects are completed before continuing evaluation of the logical OR expression. The second operand is evaluated only if the first operand evaluates to false (0). This eliminates needless evaluation of the second operand when the logical OR expression is true.
The logical AND operator (&&) returns the boolean value true if both operands are true and return false otherwise. The operands are implicitly converted to type bool prior to evaluation, and the result is of type bool. Logical AND has left-to-right associativity. The operands to the logical AND operator need not be of the same type, but they must be of integral or pointer type. The operands are commonly relational or equality expressions.
The first operand is completely evaluated and all side effects are completed before continuing evaluation of the logical AND expression. The second operand is evaluated only if the first operand evaluates to true (nonzero). This evaluation eliminates needless evaluation of the second operand when the logical AND expression is false.
The logical negation operator (!) reverses the meaning of its operand. The operand must be of arithmetic or pointer type (or an expression that evaluates to arithmetic or pointer type). The operand is implicitly converted to type bool. The result is true if the converted operand is false; the result is false if the converted operand is true. The result is of type bool.
#include<iostream>
using namespace std;
int main() {
bool x = true, y = false;
cout << (x || y) << endl;
cout << (x && y) << endl;
cout << (!x) << endl;
return 0;
}
This will give the output −
1
0
0
This is because one of the 2 is false, so and is false, one is true so or is true and not of true(x) is false, ie, 0.
|
[
{
"code": null,
"e": 1377,
"s": 1062,
"text": "The concept of logical operators is simple. They allow a program to make a decision based on multiple conditions. Each operand is considered a condition that can be evaluated to a true or false value. Then the value of the conditions is used to determine the overall value of the op1 operator op2 or !op1 grouping."
},
{
"code": null,
"e": 1828,
"s": 1377,
"text": "The logical OR operator (||) returns the boolean value true if either or both operands are true and returns false otherwise. The operands are implicitly converted to type bool prior to evaluation, and the result is of type bool. Logical OR has left-to-right associativity. The operands to the logical OR operator need not be of the same type, but they must be of integral or pointer type. The operands are commonly relational or equality expressions."
},
{
"code": null,
"e": 2144,
"s": 1828,
"text": "The first operand is completely evaluated and all side effects are completed before continuing evaluation of the logical OR expression. The second operand is evaluated only if the first operand evaluates to false (0). This eliminates needless evaluation of the second operand when the logical OR expression is true."
},
{
"code": null,
"e": 2587,
"s": 2144,
"text": "The logical AND operator (&&) returns the boolean value true if both operands are true and return false otherwise. The operands are implicitly converted to type bool prior to evaluation, and the result is of type bool. Logical AND has left-to-right associativity. The operands to the logical AND operator need not be of the same type, but they must be of integral or pointer type. The operands are commonly relational or equality expressions."
},
{
"code": null,
"e": 2922,
"s": 2587,
"text": "The first operand is completely evaluated and all side effects are completed before continuing evaluation of the logical AND expression. The second operand is evaluated only if the first operand evaluates to true (nonzero). This evaluation eliminates needless evaluation of the second operand when the logical AND expression is false."
},
{
"code": null,
"e": 3294,
"s": 2922,
"text": "The logical negation operator (!) reverses the meaning of its operand. The operand must be of arithmetic or pointer type (or an expression that evaluates to arithmetic or pointer type). The operand is implicitly converted to type bool. The result is true if the converted operand is false; the result is false if the converted operand is true. The result is of type bool."
},
{
"code": null,
"e": 3474,
"s": 3294,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n bool x = true, y = false;\n cout << (x || y) << endl;\n cout << (x && y) << endl;\n cout << (!x) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 3502,
"s": 3474,
"text": "This will give the output −"
},
{
"code": null,
"e": 3508,
"s": 3502,
"text": "1\n0\n0"
},
{
"code": null,
"e": 3626,
"s": 3508,
"text": "This is because one of the 2 is false, so and is false, one is true so or is true and not of true(x) is false, ie, 0."
}
] |
JavaScript - Date getMonth() Method
|
Javascript date getMonth() method returns the month in the specified date according to local time. The value returned by getMonth() is an integer between 0 and 11. 0 corresponds to January, 1 to February, and so on.
Its syntax is as follows −
Date.getMonth()
Returns the Month in the specified date according to local time.
Try the following example.
<html>
<head>
<title>JavaScript getMonth Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date( "December 25, 1995 23:15:00" );
document.write("getMonth() : " + dt.getMonth() );
</script>
</body>
</html>
getMonth() : 11
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2682,
"s": 2466,
"text": "Javascript date getMonth() method returns the month in the specified date according to local time. The value returned by getMonth() is an integer between 0 and 11. 0 corresponds to January, 1 to February, and so on."
},
{
"code": null,
"e": 2709,
"s": 2682,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2726,
"s": 2709,
"text": "Date.getMonth()\n"
},
{
"code": null,
"e": 2791,
"s": 2726,
"text": "Returns the Month in the specified date according to local time."
},
{
"code": null,
"e": 2818,
"s": 2791,
"text": "Try the following example."
},
{
"code": null,
"e": 3112,
"s": 2818,
"text": "<html>\n <head>\n <title>JavaScript getMonth Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date( \"December 25, 1995 23:15:00\" );\n document.write(\"getMonth() : \" + dt.getMonth() ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3130,
"s": 3112,
"text": "getMonth() : 11 \n"
},
{
"code": null,
"e": 3165,
"s": 3130,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3179,
"s": 3165,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3213,
"s": 3179,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3227,
"s": 3213,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3262,
"s": 3227,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3279,
"s": 3262,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3314,
"s": 3279,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3331,
"s": 3314,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3364,
"s": 3331,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3392,
"s": 3364,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3426,
"s": 3392,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3454,
"s": 3426,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3461,
"s": 3454,
"text": " Print"
},
{
"code": null,
"e": 3472,
"s": 3461,
"text": " Add Notes"
}
] |
What does an auto keyword do in C++?
|
Auto was a keyword that C++ "inherited" from C that had been there nearly forever, but virtually never used. All this changed with the introduction of auto to do type deduction from the context in C++11. Before C++ 11, each data type needs to be explicitly declared at compile time, limiting the values of an expression at runtime but after a new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself.
With type inference capabilities, we can spend less time having to write out things compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the runtime of the program.
The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime.
#include<iostream>
#incllude<vector>
using namespace std;
int main() {
vector<int> vec(10); // Auto deduce type to be iterator of a vector of ints.
for(auto it = vec.begin(); it != vec.end(); vec ++)
{
cin >> *it;
}
return 0;
}
|
[
{
"code": null,
"e": 1530,
"s": 1062,
"text": "Auto was a keyword that C++ \"inherited\" from C that had been there nearly forever, but virtually never used. All this changed with the introduction of auto to do type deduction from the context in C++11. Before C++ 11, each data type needs to be explicitly declared at compile time, limiting the values of an expression at runtime but after a new version of C++, many keywords are included which allows a programmer to leave the type deduction to the compiler itself."
},
{
"code": null,
"e": 1786,
"s": 1530,
"text": "With type inference capabilities, we can spend less time having to write out things compiler already knows. As all the types are deduced in compiler phase only, the time for compilation increases slightly but it does not affect the runtime of the program."
},
{
"code": null,
"e": 2030,
"s": 1786,
"text": "The auto keyword specifies that the type of the variable that is begin declared will automatically be deduced from its initializer and for functions if their return type is auto then that will be evaluated by return type expression at runtime."
},
{
"code": null,
"e": 2286,
"s": 2030,
"text": "#include<iostream>\n#incllude<vector>\nusing namespace std;\n\nint main() {\n vector<int> vec(10); // Auto deduce type to be iterator of a vector of ints.\n for(auto it = vec.begin(); it != vec.end(); vec ++)\n {\n cin >> *it;\n }\n return 0;\n}"
}
] |
How to create your own Custom Object Detector | by Eloy Marín | Towards Data Science
|
This article aims to help beginners that want to develop their own custom object detector for the first time, guiding them through all the key points to train a successful model.
The example shown will be trained with ImageAI, an open-source Python library which allows you to train a model with a few lines of code.
In this article, we will go over all the necessary steps to create a custom object detector from gathering data to finally testing our model.
The steps of the whole process are:
Gathering dataLabeling your datasetData augmentationTraining modelEvaluating model
Gathering data
Labeling your dataset
Data augmentation
Training model
Evaluating model
Before we can train our model, we need to gather lots of data, in this case, images. A minimum of 200 images should be fine, depending on the complexity of the detector.
If we want our model to be as robust as possible, our images should differ from each other in terms of lighting and background, so the model can generalize better.
These images can either be taken from your phone or obtained from the Internet.
Here you can see a subset of my Pill Detector model:
After gathering data, we need to resize our images because some of them may be pretty big. Smaller images will mean our model will train faster.
To do so, I wrote the following script:
This is the most tedious step since you’ll need to label in every image every single object that you want your model to detect.
You can label your data with LabelImg library. Run the following command to install it from terminal.
pip3 install labelImg
Once installed, we can proceed to start labeling our dataset by running the following command.
labelImg path_to_images/
Then, you’ll have to create a rectangular box with its corresponding label for every object in the image.
Once you’ve labeled all objects in an image, you must save it in PascalVOC format, generating a .xml file.
Having a large dataset is crucial for the performance of our Deep Learning model, so we can augment the data we already have with the imgaug library.
This github repo explains and provides code about how to augment images alongside their bounding boxes. This process can be divided into three steps:
Convert .xml files into one .csv fileApply data augmentation pipelineConvert resulting .csv file into multiple .xml files
Convert .xml files into one .csv file
Apply data augmentation pipeline
Convert resulting .csv file into multiple .xml files
First of all, we define a function to convert our .xml files into one .csv file:
And then we define another function to do the inverse process:
Then, we define a data augmentation pipeline with imgaug, for example, the following one.
Finally, we apply this pipeline to our dataset and save both augmented images and their augmented labels. You should also define image_aug() and bbs_obj_to_df() functions, which can be found in this github repo.
After all this preprocessing, we can finally train our model with ImageAI.
First of all, we need to install the library.
pip3 install imageai
To use transfer learning, you can download the model here.
Then we will need to split our dataset into train and validation folders.
dataset├─ train│ └── images│ └── annotations└─ validation ├── images ├── annotations
We can do this with the following lines of code:
And then we can train with the following script.
Once we trained our detector, we can evaluate how every model checkpoint performs via its mAP.
The output should look similar to this:
Finally, we can use our model in production for detecting objects in a single image.
You can adjust the minimum_percentage_probability parameter to show detected objects with more or less confidence, obtaining a result like the following.
Now I’d like to hear from you, let me know how it worked!
Thanks for reading!
|
[
{
"code": null,
"e": 350,
"s": 171,
"text": "This article aims to help beginners that want to develop their own custom object detector for the first time, guiding them through all the key points to train a successful model."
},
{
"code": null,
"e": 488,
"s": 350,
"text": "The example shown will be trained with ImageAI, an open-source Python library which allows you to train a model with a few lines of code."
},
{
"code": null,
"e": 630,
"s": 488,
"text": "In this article, we will go over all the necessary steps to create a custom object detector from gathering data to finally testing our model."
},
{
"code": null,
"e": 666,
"s": 630,
"text": "The steps of the whole process are:"
},
{
"code": null,
"e": 749,
"s": 666,
"text": "Gathering dataLabeling your datasetData augmentationTraining modelEvaluating model"
},
{
"code": null,
"e": 764,
"s": 749,
"text": "Gathering data"
},
{
"code": null,
"e": 786,
"s": 764,
"text": "Labeling your dataset"
},
{
"code": null,
"e": 804,
"s": 786,
"text": "Data augmentation"
},
{
"code": null,
"e": 819,
"s": 804,
"text": "Training model"
},
{
"code": null,
"e": 836,
"s": 819,
"text": "Evaluating model"
},
{
"code": null,
"e": 1006,
"s": 836,
"text": "Before we can train our model, we need to gather lots of data, in this case, images. A minimum of 200 images should be fine, depending on the complexity of the detector."
},
{
"code": null,
"e": 1170,
"s": 1006,
"text": "If we want our model to be as robust as possible, our images should differ from each other in terms of lighting and background, so the model can generalize better."
},
{
"code": null,
"e": 1250,
"s": 1170,
"text": "These images can either be taken from your phone or obtained from the Internet."
},
{
"code": null,
"e": 1303,
"s": 1250,
"text": "Here you can see a subset of my Pill Detector model:"
},
{
"code": null,
"e": 1448,
"s": 1303,
"text": "After gathering data, we need to resize our images because some of them may be pretty big. Smaller images will mean our model will train faster."
},
{
"code": null,
"e": 1488,
"s": 1448,
"text": "To do so, I wrote the following script:"
},
{
"code": null,
"e": 1616,
"s": 1488,
"text": "This is the most tedious step since you’ll need to label in every image every single object that you want your model to detect."
},
{
"code": null,
"e": 1718,
"s": 1616,
"text": "You can label your data with LabelImg library. Run the following command to install it from terminal."
},
{
"code": null,
"e": 1740,
"s": 1718,
"text": "pip3 install labelImg"
},
{
"code": null,
"e": 1835,
"s": 1740,
"text": "Once installed, we can proceed to start labeling our dataset by running the following command."
},
{
"code": null,
"e": 1860,
"s": 1835,
"text": "labelImg path_to_images/"
},
{
"code": null,
"e": 1966,
"s": 1860,
"text": "Then, you’ll have to create a rectangular box with its corresponding label for every object in the image."
},
{
"code": null,
"e": 2073,
"s": 1966,
"text": "Once you’ve labeled all objects in an image, you must save it in PascalVOC format, generating a .xml file."
},
{
"code": null,
"e": 2223,
"s": 2073,
"text": "Having a large dataset is crucial for the performance of our Deep Learning model, so we can augment the data we already have with the imgaug library."
},
{
"code": null,
"e": 2373,
"s": 2223,
"text": "This github repo explains and provides code about how to augment images alongside their bounding boxes. This process can be divided into three steps:"
},
{
"code": null,
"e": 2495,
"s": 2373,
"text": "Convert .xml files into one .csv fileApply data augmentation pipelineConvert resulting .csv file into multiple .xml files"
},
{
"code": null,
"e": 2533,
"s": 2495,
"text": "Convert .xml files into one .csv file"
},
{
"code": null,
"e": 2566,
"s": 2533,
"text": "Apply data augmentation pipeline"
},
{
"code": null,
"e": 2619,
"s": 2566,
"text": "Convert resulting .csv file into multiple .xml files"
},
{
"code": null,
"e": 2700,
"s": 2619,
"text": "First of all, we define a function to convert our .xml files into one .csv file:"
},
{
"code": null,
"e": 2763,
"s": 2700,
"text": "And then we define another function to do the inverse process:"
},
{
"code": null,
"e": 2853,
"s": 2763,
"text": "Then, we define a data augmentation pipeline with imgaug, for example, the following one."
},
{
"code": null,
"e": 3065,
"s": 2853,
"text": "Finally, we apply this pipeline to our dataset and save both augmented images and their augmented labels. You should also define image_aug() and bbs_obj_to_df() functions, which can be found in this github repo."
},
{
"code": null,
"e": 3140,
"s": 3065,
"text": "After all this preprocessing, we can finally train our model with ImageAI."
},
{
"code": null,
"e": 3186,
"s": 3140,
"text": "First of all, we need to install the library."
},
{
"code": null,
"e": 3207,
"s": 3186,
"text": "pip3 install imageai"
},
{
"code": null,
"e": 3266,
"s": 3207,
"text": "To use transfer learning, you can download the model here."
},
{
"code": null,
"e": 3340,
"s": 3266,
"text": "Then we will need to split our dataset into train and validation folders."
},
{
"code": null,
"e": 3435,
"s": 3340,
"text": "dataset├─ train│ └── images│ └── annotations└─ validation ├── images ├── annotations"
},
{
"code": null,
"e": 3484,
"s": 3435,
"text": "We can do this with the following lines of code:"
},
{
"code": null,
"e": 3533,
"s": 3484,
"text": "And then we can train with the following script."
},
{
"code": null,
"e": 3628,
"s": 3533,
"text": "Once we trained our detector, we can evaluate how every model checkpoint performs via its mAP."
},
{
"code": null,
"e": 3668,
"s": 3628,
"text": "The output should look similar to this:"
},
{
"code": null,
"e": 3753,
"s": 3668,
"text": "Finally, we can use our model in production for detecting objects in a single image."
},
{
"code": null,
"e": 3907,
"s": 3753,
"text": "You can adjust the minimum_percentage_probability parameter to show detected objects with more or less confidence, obtaining a result like the following."
},
{
"code": null,
"e": 3965,
"s": 3907,
"text": "Now I’d like to hear from you, let me know how it worked!"
}
] |
How does PowerShell Remoting work?
|
There are several ways to connect to remote computer cmdlets. These computers can be in the same
domain, different domains, or for the workgroups using PowerShell. Here, we will mainly focus on the
inbuilt parameter, Invoke-Command, and to execute PSSession command remotely.
Many cmdlets in PowerShell supports the -ComputerName parameter, which describes the remote computer names. For example, Get-Service, Get-Process, and Get-WMIObject, etc.. cmdlets.
If the remote server is in the same domain then you just need to simply add -ComputerName credentials.
Get-Service Spooler -ComputerName Test1-Win2k12
PS C:\Users\Administrator> Get-Service Spooler -ComputerName Test1-Win2k12
Status Name DisplayName
------ ---- -----------
Running Spooler Print Spooler
Or to get the Computer BIOS information using WMI,
Get-WmiObject win32_bios -ComputerName Test1-win2k12
PS C:\Users\Administrator> Get-WmiObject win32_bios -ComputerName Test1-win2k12
SMBIOSBIOSVersion : 6.00
Manufacturer : Phoenix Technologies LTD
Name : PhoenixBIOS 4.0 Release 6.0
SerialNumber : VMware-56 4d 0d 7f 8a 7e f6 fa-f2 55 1d b6 a3 52 80 9f
Version : INTEL - 6040000
But if your remote server is in a different domain then you may get the following authentication error
message.
PS C:\> Get-Service -ComputerName Test1-Win2k12
Get-Service : Cannot open Service Control Manager on computer 'Test1-
Win2k12'. This operation might require other privileges.
At line:1 char:1
+ Get-Service -ComputerName Test1-Win2k12
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-
Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShe
ll.Commands.GetServiceCommand
To get rid out of the domain and standalone server authentication issue, many cmdlets support -Credential parameter which is the credentials for the destination server. For example, Copy-Item cmdlet, which has the -Credential parameter, in such case, you can directly pass the remote server credentials and the command works.
Copy-Item 'C:\Temp\Encoding Time.csv' -Destination \\Test1-Win2k12\C$\Temp -
Credential $creds
But many commands like Get-Service, Get-Process, etc. don’t support the -Credential parameter, in that case, you need to use the other two methods described below.
Invoke-Command is one of the most convenient methods to process commands on the remote computer. You need to provide a computer name and script block to run your commands remotely.
Example
Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{Get-Service Spooler}
PS C:\Users\Administrator> Invoke-Command -ComputerName Test1-Win2k12 -
ScriptBlock{Get-Service Spooler}
Status Name DisplayName PSComputerName
------ ---- ----------- --------------
Running Spooler Print Spooler Test1-Win2k12
In the above example, we assume that Test1-Win2k12 is in the same domain so no more additional credentials required to connect to the remote server. If the server is in the different domain or workgroup, -Credential parameter supported by Invoke-Command should be used. For example,
$creds = Get-Credential
Invoke-Command -ComputerName Test2-Win2k12 -ScriptBlock{Get-Service Spooler} -
Credential $creds
Status Name DisplayName PSComputerName
------ ---- ----------- --------------
Running Spooler Print Spooler Test2-Win2k12
With the PSSession method, you can either enter into PSSession and run the command or you can store
the session into a session variable and when running command pass this session variable so that the
command can run remotely.
When you use the Enter-PSSession cmdlet you can directly connect to domain join computers or
provide the credentials using -Credential parameter in the cmdlet for the different domain or
Workgroup computers.
For the domain-joined computers.
Enter-PSSession Test1-Win2k12
Once you run the command followed by the computer name, you will notice the Computer name in
front of the path, which indicates you are now into the remote shell and then you can run the command.
PS C:\Users\Administrator> Enter-PSSession Test1-Win2k12
[Test1-Win2k12]: PS C:\Users\Administrator.LABDOMAIN\Documents>
[Test1-Win2k12]: PS C:\Users\Administrator.LABDOMAIN\Documents> Get-Service
Spooler
Status Name DisplayName
------ ---- -----------
Running Spooler Print Spooler
If your computer is in the different workgroup then pass the Credentials in the cmdlet. For example,
Enter-PSSession Test2-Win2k12 -Credential (Get-Credential)
[Test2-Win2k12]: PS C:\Users\Administrator\Documents> Hostname
Test2-Win2k12
You can end the existing session using the Exit-PSSession command.
You can also use the session variable to connect to the server remotely. To do that, you need to use the New-PSSession cmdlet and followed by the remote computer name and have to store that session in the new variable and later this variable can be used by the supported cmdlet like Invoke-Command or Enter-PSSession.
For example,
$sess = New-PSSession Test1-Win2k12
When you check the value of $sess variable,
You can use this variable to retrieve the outputs from cmdlets on Test1-Win2k12 machine.
Invoke-Command -Session $sess -ScriptBlock{Get-Service Spooler}
PS C:\Users\Administrator> Invoke-Command -Session $sess -ScriptBlock{Get-
Service Spooler}
Status Name DisplayName PSComputerName
------ ---- ----------- --------------
Running Spooler Print Spooler Test1-Win2k12
|
[
{
"code": null,
"e": 1338,
"s": 1062,
"text": "There are several ways to connect to remote computer cmdlets. These computers can be in the same\ndomain, different domains, or for the workgroups using PowerShell. Here, we will mainly focus on the\ninbuilt parameter, Invoke-Command, and to execute PSSession command remotely."
},
{
"code": null,
"e": 1519,
"s": 1338,
"text": "Many cmdlets in PowerShell supports the -ComputerName parameter, which describes the remote computer names. For example, Get-Service, Get-Process, and Get-WMIObject, etc.. cmdlets."
},
{
"code": null,
"e": 1622,
"s": 1519,
"text": "If the remote server is in the same domain then you just need to simply add -ComputerName credentials."
},
{
"code": null,
"e": 1670,
"s": 1622,
"text": "Get-Service Spooler -ComputerName Test1-Win2k12"
},
{
"code": null,
"e": 1879,
"s": 1670,
"text": "PS C:\\Users\\Administrator> Get-Service Spooler -ComputerName Test1-Win2k12\nStatus Name DisplayName\n------ ---- -----------\nRunning Spooler Print Spooler"
},
{
"code": null,
"e": 1930,
"s": 1879,
"text": "Or to get the Computer BIOS information using WMI,"
},
{
"code": null,
"e": 1983,
"s": 1930,
"text": "Get-WmiObject win32_bios -ComputerName Test1-win2k12"
},
{
"code": null,
"e": 2318,
"s": 1983,
"text": "PS C:\\Users\\Administrator> Get-WmiObject win32_bios -ComputerName Test1-win2k12\nSMBIOSBIOSVersion : 6.00\nManufacturer : Phoenix Technologies LTD\nName : PhoenixBIOS 4.0 Release 6.0\nSerialNumber : VMware-56 4d 0d 7f 8a 7e f6 fa-f2 55 1d b6 a3 52 80 9f\nVersion : INTEL - 6040000"
},
{
"code": null,
"e": 2430,
"s": 2318,
"text": "But if your remote server is in a different domain then you may get the following authentication error\nmessage."
},
{
"code": null,
"e": 2912,
"s": 2430,
"text": "PS C:\\> Get-Service -ComputerName Test1-Win2k12\nGet-Service : Cannot open Service Control Manager on computer 'Test1-\nWin2k12'. This operation might require other privileges.\nAt line:1 char:1\n + Get-Service -ComputerName Test1-Win2k12\n + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n + CategoryInfo : NotSpecified: (:) [Get-\nService], InvalidOperationException\n + FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShe\nll.Commands.GetServiceCommand"
},
{
"code": null,
"e": 3238,
"s": 2912,
"text": "To get rid out of the domain and standalone server authentication issue, many cmdlets support -Credential parameter which is the credentials for the destination server. For example, Copy-Item cmdlet, which has the -Credential parameter, in such case, you can directly pass the remote server credentials and the command works."
},
{
"code": null,
"e": 3333,
"s": 3238,
"text": "Copy-Item 'C:\\Temp\\Encoding Time.csv' -Destination \\\\Test1-Win2k12\\C$\\Temp -\nCredential $creds"
},
{
"code": null,
"e": 3497,
"s": 3333,
"text": "But many commands like Get-Service, Get-Process, etc. don’t support the -Credential parameter, in that case, you need to use the other two methods described below."
},
{
"code": null,
"e": 3678,
"s": 3497,
"text": "Invoke-Command is one of the most convenient methods to process commands on the remote computer. You need to provide a computer name and script block to run your commands remotely."
},
{
"code": null,
"e": 3686,
"s": 3678,
"text": "Example"
},
{
"code": null,
"e": 3763,
"s": 3686,
"text": "Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{Get-Service Spooler}"
},
{
"code": null,
"e": 4044,
"s": 3763,
"text": "PS C:\\Users\\Administrator> Invoke-Command -ComputerName Test1-Win2k12 -\nScriptBlock{Get-Service Spooler}\nStatus Name DisplayName PSComputerName\n------ ---- ----------- --------------\nRunning Spooler Print Spooler Test1-Win2k12"
},
{
"code": null,
"e": 4327,
"s": 4044,
"text": "In the above example, we assume that Test1-Win2k12 is in the same domain so no more additional credentials required to connect to the remote server. If the server is in the different domain or workgroup, -Credential parameter supported by Invoke-Command should be used. For example,"
},
{
"code": null,
"e": 4448,
"s": 4327,
"text": "$creds = Get-Credential\nInvoke-Command -ComputerName Test2-Win2k12 -ScriptBlock{Get-Service Spooler} -\nCredential $creds"
},
{
"code": null,
"e": 4618,
"s": 4448,
"text": "Status Name DisplayName PSComputerName\n------ ---- ----------- --------------\nRunning Spooler Print Spooler Test2-Win2k12"
},
{
"code": null,
"e": 4844,
"s": 4618,
"text": "With the PSSession method, you can either enter into PSSession and run the command or you can store\nthe session into a session variable and when running command pass this session variable so that the\ncommand can run remotely."
},
{
"code": null,
"e": 5052,
"s": 4844,
"text": "When you use the Enter-PSSession cmdlet you can directly connect to domain join computers or\nprovide the credentials using -Credential parameter in the cmdlet for the different domain or\nWorkgroup computers."
},
{
"code": null,
"e": 5085,
"s": 5052,
"text": "For the domain-joined computers."
},
{
"code": null,
"e": 5115,
"s": 5085,
"text": "Enter-PSSession Test1-Win2k12"
},
{
"code": null,
"e": 5311,
"s": 5115,
"text": "Once you run the command followed by the computer name, you will notice the Computer name in\nfront of the path, which indicates you are now into the remote shell and then you can run the command."
},
{
"code": null,
"e": 5632,
"s": 5311,
"text": "PS C:\\Users\\Administrator> Enter-PSSession Test1-Win2k12\n[Test1-Win2k12]: PS C:\\Users\\Administrator.LABDOMAIN\\Documents>\n[Test1-Win2k12]: PS C:\\Users\\Administrator.LABDOMAIN\\Documents> Get-Service\nSpooler\nStatus Name DisplayName\n------ ---- -----------\nRunning Spooler Print Spooler"
},
{
"code": null,
"e": 5733,
"s": 5632,
"text": "If your computer is in the different workgroup then pass the Credentials in the cmdlet. For example,"
},
{
"code": null,
"e": 5792,
"s": 5733,
"text": "Enter-PSSession Test2-Win2k12 -Credential (Get-Credential)"
},
{
"code": null,
"e": 5869,
"s": 5792,
"text": "[Test2-Win2k12]: PS C:\\Users\\Administrator\\Documents> Hostname\nTest2-Win2k12"
},
{
"code": null,
"e": 5936,
"s": 5869,
"text": "You can end the existing session using the Exit-PSSession command."
},
{
"code": null,
"e": 6254,
"s": 5936,
"text": "You can also use the session variable to connect to the server remotely. To do that, you need to use the New-PSSession cmdlet and followed by the remote computer name and have to store that session in the new variable and later this variable can be used by the supported cmdlet like Invoke-Command or Enter-PSSession."
},
{
"code": null,
"e": 6267,
"s": 6254,
"text": "For example,"
},
{
"code": null,
"e": 6303,
"s": 6267,
"text": "$sess = New-PSSession Test1-Win2k12"
},
{
"code": null,
"e": 6347,
"s": 6303,
"text": "When you check the value of $sess variable,"
},
{
"code": null,
"e": 6436,
"s": 6347,
"text": "You can use this variable to retrieve the outputs from cmdlets on Test1-Win2k12 machine."
},
{
"code": null,
"e": 6765,
"s": 6436,
"text": "Invoke-Command -Session $sess -ScriptBlock{Get-Service Spooler}\nPS C:\\Users\\Administrator> Invoke-Command -Session $sess -ScriptBlock{Get-\nService Spooler}\nStatus Name DisplayName PSComputerName\n------ ---- ----------- --------------\nRunning Spooler Print Spooler Test1-Win2k12"
}
] |
How can I create a stored procedure to update values in a MySQL table?
|
We can create a stored procedure with IN operator to update values in a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −
mysql> Select * from student_info;
+------+---------+------------+------------+
| id | Name | Address | Subject |
+------+---------+------------+------------+
| 101 | YashPal | Amritsar | History |
| 105 | Gaurav | Jaipur | Literature |
| 110 | Rahul | Chandigarh | History |
| 125 | Raman | Bangalore | Computers |
+------+---------+------------+------------+
4 rows in set (0.01 sec)
Now, by creating the procedure named ‘update_studentinfo’ as follow, we can update the values in ‘student_info’ table −
mysql> DELIMITER // ;
mysql> Create Procedure Update_studentinfo ( IN p_id INT, IN p_address varchar(20))
-> BEGIN
-> UPDATE student_info
-> SET
-> address = p_address WHERE id = p_id;
-> END //
Query OK, 0 rows affected (0.13 sec)
Now, invoke the procedure with the values we want to update in the table as follows −
mysql> Delimiter ; //
mysql> CALL Update_studentinfo(125, 'Shimla');
Query OK, 1 row affected (0.14 sec)
mysql> Select * from student_info;
+------+---------+------------+------------+
| id | Name | Address | Subject |
+------+---------+------------+------------+
| 101 | YashPal | Amritsar | History |
| 105 | Gaurav | Jaipur | Literature |
| 110 | Rahul | Chandigarh | History |
| 125 | Raman | Shimla | Computers |
+------+---------+------------+------------+
4 rows in set (0.00 sec)
The above result set shows that the address of record having id = 125 updated in the table.
|
[
{
"code": null,
"e": 1254,
"s": 1062,
"text": "We can create a stored procedure with IN operator to update values in a MySQL table. To make it understand we are taking an example of a table named ‘student_info’ having the following data −"
},
{
"code": null,
"e": 1674,
"s": 1254,
"text": "mysql> Select * from student_info;\n+------+---------+------------+------------+\n| id | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n| 125 | Raman | Bangalore | Computers |\n+------+---------+------------+------------+\n4 rows in set (0.01 sec)"
},
{
"code": null,
"e": 1794,
"s": 1674,
"text": "Now, by creating the procedure named ‘update_studentinfo’ as follow, we can update the values in ‘student_info’ table −"
},
{
"code": null,
"e": 2041,
"s": 1794,
"text": "mysql> DELIMITER // ;\nmysql> Create Procedure Update_studentinfo ( IN p_id INT, IN p_address varchar(20))\n -> BEGIN\n -> UPDATE student_info\n -> SET\n -> address = p_address WHERE id = p_id;\n -> END //\nQuery OK, 0 rows affected (0.13 sec)"
},
{
"code": null,
"e": 2127,
"s": 2041,
"text": "Now, invoke the procedure with the values we want to update in the table as follows −"
},
{
"code": null,
"e": 2653,
"s": 2127,
"text": "mysql> Delimiter ; //\nmysql> CALL Update_studentinfo(125, 'Shimla');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> Select * from student_info;\n+------+---------+------------+------------+\n| id | Name | Address | Subject |\n+------+---------+------------+------------+\n| 101 | YashPal | Amritsar | History |\n| 105 | Gaurav | Jaipur | Literature |\n| 110 | Rahul | Chandigarh | History |\n| 125 | Raman | Shimla | Computers |\n+------+---------+------------+------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2745,
"s": 2653,
"text": "The above result set shows that the address of record having id = 125 updated in the table."
}
] |
How to detect long press in Android?
|
This example demonstrates how do I detect long Press in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textStyle="bold"
android:text="Hold touch to detect Long Press"/>
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
GestureDetector gestureDetector;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gestureDetector = new GestureDetector(this, new GestureListener());
}
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
Toast.makeText(MainActivity.this, "Long pressed", Toast.LENGTH_SHORT).show();
}
}
public boolean onTouchEvent(MotionEvent event) {
gestureDetector.onTouchEvent(event);
return super.onTouchEvent(event);
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code.
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "This example demonstrates how do I detect long Press in android."
},
{
"code": null,
"e": 1256,
"s": 1127,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1321,
"s": 1256,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1843,
"s": 1321,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:textStyle=\"bold\"\n android:text=\"Hold touch to detect Long Press\"/>\n</RelativeLayout>"
},
{
"code": null,
"e": 1900,
"s": 1843,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2819,
"s": 1900,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.GestureDetector;\nimport android.view.MotionEvent;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n GestureDetector gestureDetector;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n gestureDetector = new GestureDetector(this, new GestureListener());\n }\n private class GestureListener extends GestureDetector.SimpleOnGestureListener {\n @Override\n public void onLongPress(MotionEvent e) {\n super.onLongPress(e);\n Toast.makeText(MainActivity.this, \"Long pressed\", Toast.LENGTH_SHORT).show();\n }\n }\n public boolean onTouchEvent(MotionEvent event) {\n gestureDetector.onTouchEvent(event);\n return super.onTouchEvent(event);\n }\n}"
},
{
"code": null,
"e": 2874,
"s": 2819,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3544,
"s": 2874,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3892,
"s": 3544,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 3933,
"s": 3892,
"text": "Click here to download the project code."
}
] |
C Program for Naive algorithm for Pattern Searching
|
Pattern matching in C− We have to find if a string is present in another string, as an example, the string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e. position it is present at) is displayed. We tend to create a function that receives 2 character arrays and returns the position if matching happens otherwise returns -1.
Input: txt = "HERE IS A NICE CAP"
pattern = "NICE"
Output: Pattern found at index 10
Input: txt = "XYZXACAADXYZXYZX"
pattern = "XYZX"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
We are solving this problem with Naive Pattern Searching. This algorithm is useful for smaller texts. Naive is a simple and inefficient way to see wherever one string occurs within another is to examine every place it could be at, one by one, to examine if it's there.
The time complexity of the Naive Algorithm is O(mn), where m is the size of the pattern to be searched and n is the size of the container string.
Pattern searching is a very crucial problem in computer science. Whenever we seek for a string in notepad/word file or browser or database or in some information,
pattern searching algorithms are used to show the search results.
naive_algorithm(pattern, text)
Input − The text and the pattern
Output − locations, where the pattern is present in the text
Start
pat_len := pattern Size
str_len := string size
for i := 0 to (str_len - pat_len), do
for j := 0 to pat_len, do
if text[i+j] ≠ pattern[j], then
break
if j == patLen, then
display the position i, as there pattern found
End
Live Demo
#include <stdio.h>
#include <string.h>
int main (){
char txt[] = "tutorialsPointisthebestplatformforprogrammers";
char pat[] = "a";
int M = strlen (pat);
int N = strlen (txt);
for (int i = 0; i <= N - M; i++){
int j;
for (j = 0; j < M; j++)
if (txt[i + j] != pat[j])
break;
if (j == M)
printf ("Pattern matches at index %d \n", i);
}
return 0;
}
Pattern matches at 6
Pattern matches at 25
Pattern matches at 39
|
[
{
"code": null,
"e": 1439,
"s": 1062,
"text": "Pattern matching in C− We have to find if a string is present in another string, as an example, the string \"algorithm” is present within the string \"naive algorithm\". If it is found, then its location (i.e. position it is present at) is displayed. We tend to create a function that receives 2 character arrays and returns the position if matching happens otherwise returns -1."
},
{
"code": null,
"e": 1669,
"s": 1439,
"text": "Input: txt = \"HERE IS A NICE CAP\"\n pattern = \"NICE\"\nOutput: Pattern found at index 10\nInput: txt = \"XYZXACAADXYZXYZX\"\n pattern = \"XYZX\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12"
},
{
"code": null,
"e": 1938,
"s": 1669,
"text": "We are solving this problem with Naive Pattern Searching. This algorithm is useful for smaller texts. Naive is a simple and inefficient way to see wherever one string occurs within another is to examine every place it could be at, one by one, to examine if it's there."
},
{
"code": null,
"e": 2084,
"s": 1938,
"text": "The time complexity of the Naive Algorithm is O(mn), where m is the size of the pattern to be searched and n is the size of the container string."
},
{
"code": null,
"e": 2313,
"s": 2084,
"text": "Pattern searching is a very crucial problem in computer science. Whenever we seek for a string in notepad/word file or browser or database or in some information,\npattern searching algorithms are used to show the search results."
},
{
"code": null,
"e": 2344,
"s": 2313,
"text": "naive_algorithm(pattern, text)"
},
{
"code": null,
"e": 2377,
"s": 2344,
"text": "Input − The text and the pattern"
},
{
"code": null,
"e": 2438,
"s": 2377,
"text": "Output − locations, where the pattern is present in the text"
},
{
"code": null,
"e": 2705,
"s": 2438,
"text": "Start\n pat_len := pattern Size\n str_len := string size\n for i := 0 to (str_len - pat_len), do\n for j := 0 to pat_len, do\n if text[i+j] ≠ pattern[j], then\n break\n if j == patLen, then\n display the position i, as there pattern found\nEnd"
},
{
"code": null,
"e": 2716,
"s": 2705,
"text": " Live Demo"
},
{
"code": null,
"e": 3125,
"s": 2716,
"text": "#include <stdio.h>\n#include <string.h>\nint main (){\n char txt[] = \"tutorialsPointisthebestplatformforprogrammers\";\n char pat[] = \"a\";\n int M = strlen (pat);\n int N = strlen (txt);\n for (int i = 0; i <= N - M; i++){\n int j;\n for (j = 0; j < M; j++)\n if (txt[i + j] != pat[j])\n break;\n if (j == M)\n printf (\"Pattern matches at index %d \\n\", i);\n }\n return 0;\n}"
},
{
"code": null,
"e": 3190,
"s": 3125,
"text": "Pattern matches at 6\nPattern matches at 25\nPattern matches at 39"
}
] |
GCDs of given index ranges in an array - GeeksforGeeks
|
23 Jan, 2020
Given an array a[0 . . . n-1]. We should be able to efficiently find the GCD from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1.
Example :
Input : a[] = {2, 3, 60, 90, 50};
Index Ranges : {1, 3}, {2, 4}, {0, 2}
Output: GCDs of given ranges are 3, 10, 1
Method 1 (Simple)
A simple solution is to run a loop from qs to qe and find GCD in given range. This solution takes O(n) time in worst case.
Method 2 (2D Array)
Another solution is to create a 2D array where an entry [i, j] stores the GCD in range arr[i..j]. GCD of a given range can now be calculated in O(1) time, but preprocessing takes O(n^2) time. Also, this approach needs O(n^2) extra space which may become huge for large input arrays.
Method 3 (Segment Tree)
Prerequisites : Segment Tree Set 1, Segment Tree Set 2Segment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for GCD query is O(Logn). The extra space required is O(n) to store the segment tree.
Representation of Segment trees
Leaf Nodes are the elements of the input array.
Each internal node represents GCD of all leaves under it.
Array representation of tree is used to represent Segment Trees i.e., for each node at index i,
Left child is at index 2*i+1
Right child at 2*i+2 and the parent is at floor((i-1)/2).
Construction of Segment Tree from given array
Begin with a segment arr[0 . . . n-1] and keep dividing into two halves. Every time we divide the current segment into two halves (if it has not yet become a segment of length 1), then call the same procedure on both halves, and for each such segment, we store the GCD value in a segment tree node.
All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree (every node has 0 or two children) because we always divide segments in two halves at every level.
Since the constructed tree is always full binary tree with n leaves, there will be n-1 internal nodes. So total number of nodes will be 2*n – 1.
Height of the segment tree will be &lceillog2n&rceil. Since the tree is represented using array and relation between parent and child indexes must be maintained, size of memory allocated for segment tree will be 2*2⌈log2n⌉ – 1
Query for GCD of given range
/ qs --> query start index, qe --> query end index
int GCD(node, qs, qe)
{
if range of node is within qs and qe
return value in node
else if range of node is completely
outside qs and qe
return INFINITE
else
return GCD( GCD(node's left child, qs, qe),
GCD(node's right child, qs, qe) )
}
Below is Implementation of this method.
C++
Java
C#
// C++ Program to find GCD of a number in a given Range// using segment Trees#include <bits/stdc++.h>using namespace std; // To store segment treeint *st; /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int findGcd(int ss, int se, int qs, int qe, int si){ if (ss>qe || se < qs) return 0; if (qs<=ss && qe>=se) return st[si]; int mid = ss+(se-ss)/2; return __gcd(findGcd(ss, mid, qs, qe, si*2+1), findGcd(mid+1, se, qs, qe, si*2+2));} //Finding The gcd of given Rangeint findRangeGcd(int ss, int se, int arr[],int n){ if (ss<0 || se > n-1 || ss>se) { cout << "Invalid Arguments" << "\n"; return -1; } return findGcd(0, n-1, ss, se, 0);} // A recursive function that constructs Segment Tree for// array[ss..se]. si is index of current node in segment// tree stint constructST(int arr[], int ss, int se, int si){ if (ss==se) { st[si] = arr[ss]; return st[si]; } int mid = ss+(se-ss)/2; st[si] = __gcd(constructST(arr, ss, mid, si*2+1), constructST(arr, mid+1, se, si*2+2)); return st[si];} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */int *constructSegmentTree(int arr[], int n){ int height = (int)(ceil(log2(n))); int size = 2*(int)pow(2, height)-1; st = new int[size]; constructST(arr, 0, n-1, 0); return st;} // Driver program to test above functionsint main(){ int a[] = {2, 3, 6, 9, 5}; int n = sizeof(a)/sizeof(a[0]); // Build segment tree from given array constructSegmentTree(a, n); // Starting index of range. These indexes are 0 based. int l = 1; // Last index of range.These indexes are 0 based. int r = 3; cout << "GCD of the given range is:"; cout << findRangeGcd(l, r, a, n) << "\n"; return 0;}
// Java Program to find GCD of a number in a given Range// using segment Treesimport java.io.*; public class Main{ private static int[] st; // Array to store segment tree /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ public static int[] constructSegmentTree(int[] arr) { int height = (int)Math.ceil(Math.log(arr.length)/Math.log(2)); int size = 2*(int)Math.pow(2, height)-1; st = new int[size]; constructST(arr, 0, arr.length-1, 0); return st; } // A recursive function that constructs Segment // Tree for array[ss..se]. si is index of current // node in segment tree st public static int constructST(int[] arr, int ss, int se, int si) { if (ss==se) { st[si] = arr[ss]; return st[si]; } int mid = ss+(se-ss)/2; st[si] = gcd(constructST(arr, ss, mid, si*2+1), constructST(arr, mid+1, se, si*2+2)); return st[si]; } // Function to find gcd of 2 numbers. private static int gcd(int a, int b) { if (a < b) { // If b greater than a swap a and b int temp = b; b = a; a = temp; } if (b==0) return a; return gcd(b,a%b); } //Finding The gcd of given Range public static int findRangeGcd(int ss, int se, int[] arr) { int n = arr.length; if (ss<0 || se > n-1 || ss>se) throw new IllegalArgumentException("Invalid arguments"); return findGcd(0, n-1, ss, se, 0); } /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[si] qs & qe --> Starting and ending indexes of query range */ public static int findGcd(int ss, int se, int qs, int qe, int si) { if (ss>qe || se < qs) return 0; if (qs<=ss && qe>=se) return st[si]; int mid = ss+(se-ss)/2; return gcd(findGcd(ss, mid, qs, qe, si*2+1), findGcd(mid+1, se, qs, qe, si*2+2)); } // Driver Code public static void main(String[] args)throws IOException { int[] a = {2, 3, 6, 9, 5}; constructSegmentTree(a); int l = 1; // Starting index of range. int r = 3; //Last index of range. System.out.print("GCD of the given range is: "); System.out.print(findRangeGcd(l, r, a)); }}
// C# Program to find GCD of a number in a given Range// using segment Treesusing System; class GFG{ private static int[] st; // Array to store segment tree /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ public static int[] constructSegmentTree(int[] arr) { int height = (int)Math.Ceiling(Math.Log(arr.Length)/Math.Log(2)); int size = 2*(int)Math.Pow(2, height) - 1; st = new int[size]; constructST(arr, 0, arr.Length - 1, 0); return st; } // A recursive function that constructs Segment // Tree for array[ss..se]. si is index of current // node in segment tree st public static int constructST(int[] arr, int ss, int se, int si) { if (ss == se) { st[si] = arr[ss]; return st[si]; } int mid = ss + (se - ss) / 2; st[si] = gcd(constructST(arr, ss, mid, si * 2 + 1), constructST(arr, mid + 1, se, si * 2 + 2)); return st[si]; } // Function to find gcd of 2 numbers. private static int gcd(int a, int b) { if (a < b) { // If b greater than a swap a and b int temp = b; b = a; a = temp; } if (b == 0) return a; return gcd(b,a % b); } // Finding The gcd of given Range public static int findRangeGcd(int ss, int se, int[] arr) { int n = arr.Length; if (ss < 0 || se > n-1 || ss > se) { Console.WriteLine("Invalid arguments"); return int.MinValue; } return findGcd(0, n - 1, ss, se, 0); } /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[si] qs & qe --> Starting and ending indexes of query range */ public static int findGcd(int ss, int se, int qs, int qe, int si) { if (ss > qe || se < qs) return 0; if (qs <= ss && qe >= se) return st[si]; int mid = ss + (se - ss)/2; return gcd(findGcd(ss, mid, qs, qe, si * 2 + 1), findGcd(mid + 1, se, qs, qe, si * 2 + 2)); } // Driver Code public static void Main(String[] args) { int[] a = {2, 3, 6, 9, 5}; constructSegmentTree(a); int l = 1; // Starting index of range. int r = 3; //Last index of range. Console.Write("GCD of the given range is: "); Console.Write(findRangeGcd(l, r, a)); }} // This code has been contributed by 29AjayKumar
GCD of the given range is: 3
Time Complexity: Time Complexity for tree construction is O(n * log(min(a, b))), where n is the number of modes and a and b are nodes whose GCD is calculated during merge operation. There are total 2n-1 nodes, and value of every node is calculated only once in tree construction. Time complexity to query is O(Log n * Log n).
This article is contributed by Nikhil Tekwani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
array-range-queries
Segment-Tree
Advanced Data Structure
Segment-Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Agents in Artificial Intelligence
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Disjoint Set Data Structures
Red-Black Tree | Set 2 (Insert)
Segment Tree | Set 1 (Sum of given range)
Insert Operation in B-Tree
Design a Chess Game
Red-Black Tree | Set 3 (Delete)
Difference between B tree and B+ tree
|
[
{
"code": null,
"e": 25218,
"s": 25190,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 25369,
"s": 25218,
"text": "Given an array a[0 . . . n-1]. We should be able to efficiently find the GCD from index qs (query start) to qe (query end) where 0 <= qs <= qe <= n-1."
},
{
"code": null,
"e": 25379,
"s": 25369,
"text": "Example :"
},
{
"code": null,
"e": 25502,
"s": 25379,
"text": "Input : a[] = {2, 3, 60, 90, 50};\n Index Ranges : {1, 3}, {2, 4}, {0, 2}\nOutput: GCDs of given ranges are 3, 10, 1\n"
},
{
"code": null,
"e": 25524,
"s": 25506,
"text": "Method 1 (Simple)"
},
{
"code": null,
"e": 25647,
"s": 25524,
"text": "A simple solution is to run a loop from qs to qe and find GCD in given range. This solution takes O(n) time in worst case."
},
{
"code": null,
"e": 25667,
"s": 25647,
"text": "Method 2 (2D Array)"
},
{
"code": null,
"e": 25950,
"s": 25667,
"text": "Another solution is to create a 2D array where an entry [i, j] stores the GCD in range arr[i..j]. GCD of a given range can now be calculated in O(1) time, but preprocessing takes O(n^2) time. Also, this approach needs O(n^2) extra space which may become huge for large input arrays."
},
{
"code": null,
"e": 25976,
"s": 25952,
"text": "Method 3 (Segment Tree)"
},
{
"code": null,
"e": 26247,
"s": 25976,
"text": "Prerequisites : Segment Tree Set 1, Segment Tree Set 2Segment tree can be used to do preprocessing and query in moderate time. With segment tree, preprocessing time is O(n) and time to for GCD query is O(Logn). The extra space required is O(n) to store the segment tree."
},
{
"code": null,
"e": 26279,
"s": 26247,
"text": "Representation of Segment trees"
},
{
"code": null,
"e": 26327,
"s": 26279,
"text": "Leaf Nodes are the elements of the input array."
},
{
"code": null,
"e": 26385,
"s": 26327,
"text": "Each internal node represents GCD of all leaves under it."
},
{
"code": null,
"e": 26481,
"s": 26385,
"text": "Array representation of tree is used to represent Segment Trees i.e., for each node at index i,"
},
{
"code": null,
"e": 26510,
"s": 26481,
"text": "Left child is at index 2*i+1"
},
{
"code": null,
"e": 26568,
"s": 26510,
"text": "Right child at 2*i+2 and the parent is at floor((i-1)/2)."
},
{
"code": null,
"e": 26614,
"s": 26568,
"text": "Construction of Segment Tree from given array"
},
{
"code": null,
"e": 26913,
"s": 26614,
"text": "Begin with a segment arr[0 . . . n-1] and keep dividing into two halves. Every time we divide the current segment into two halves (if it has not yet become a segment of length 1), then call the same procedure on both halves, and for each such segment, we store the GCD value in a segment tree node."
},
{
"code": null,
"e": 27146,
"s": 26913,
"text": "All levels of the constructed segment tree will be completely filled except the last level. Also, the tree will be a Full Binary Tree (every node has 0 or two children) because we always divide segments in two halves at every level."
},
{
"code": null,
"e": 27291,
"s": 27146,
"text": "Since the constructed tree is always full binary tree with n leaves, there will be n-1 internal nodes. So total number of nodes will be 2*n – 1."
},
{
"code": null,
"e": 27518,
"s": 27291,
"text": "Height of the segment tree will be &lceillog2n&rceil. Since the tree is represented using array and relation between parent and child indexes must be maintained, size of memory allocated for segment tree will be 2*2⌈log2n⌉ – 1"
},
{
"code": null,
"e": 27547,
"s": 27518,
"text": "Query for GCD of given range"
},
{
"code": null,
"e": 27889,
"s": 27547,
"text": "/ qs --> query start index, qe --> query end index\nint GCD(node, qs, qe)\n{\n if range of node is within qs and qe\n return value in node\n else if range of node is completely \n outside qs and qe\n return INFINITE\n else\n return GCD( GCD(node's left child, qs, qe), \n GCD(node's right child, qs, qe) )\n}\n"
},
{
"code": null,
"e": 27930,
"s": 27889,
"text": "Below is Implementation of this method."
},
{
"code": null,
"e": 27934,
"s": 27930,
"text": "C++"
},
{
"code": null,
"e": 27939,
"s": 27934,
"text": "Java"
},
{
"code": null,
"e": 27942,
"s": 27939,
"text": "C#"
},
{
"code": "// C++ Program to find GCD of a number in a given Range// using segment Trees#include <bits/stdc++.h>using namespace std; // To store segment treeint *st; /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[index] qs & qe --> Starting and ending indexes of query range */int findGcd(int ss, int se, int qs, int qe, int si){ if (ss>qe || se < qs) return 0; if (qs<=ss && qe>=se) return st[si]; int mid = ss+(se-ss)/2; return __gcd(findGcd(ss, mid, qs, qe, si*2+1), findGcd(mid+1, se, qs, qe, si*2+2));} //Finding The gcd of given Rangeint findRangeGcd(int ss, int se, int arr[],int n){ if (ss<0 || se > n-1 || ss>se) { cout << \"Invalid Arguments\" << \"\\n\"; return -1; } return findGcd(0, n-1, ss, se, 0);} // A recursive function that constructs Segment Tree for// array[ss..se]. si is index of current node in segment// tree stint constructST(int arr[], int ss, int se, int si){ if (ss==se) { st[si] = arr[ss]; return st[si]; } int mid = ss+(se-ss)/2; st[si] = __gcd(constructST(arr, ss, mid, si*2+1), constructST(arr, mid+1, se, si*2+2)); return st[si];} /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */int *constructSegmentTree(int arr[], int n){ int height = (int)(ceil(log2(n))); int size = 2*(int)pow(2, height)-1; st = new int[size]; constructST(arr, 0, n-1, 0); return st;} // Driver program to test above functionsint main(){ int a[] = {2, 3, 6, 9, 5}; int n = sizeof(a)/sizeof(a[0]); // Build segment tree from given array constructSegmentTree(a, n); // Starting index of range. These indexes are 0 based. int l = 1; // Last index of range.These indexes are 0 based. int r = 3; cout << \"GCD of the given range is:\"; cout << findRangeGcd(l, r, a, n) << \"\\n\"; return 0;}",
"e": 30256,
"s": 27942,
"text": null
},
{
"code": "// Java Program to find GCD of a number in a given Range// using segment Treesimport java.io.*; public class Main{ private static int[] st; // Array to store segment tree /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ public static int[] constructSegmentTree(int[] arr) { int height = (int)Math.ceil(Math.log(arr.length)/Math.log(2)); int size = 2*(int)Math.pow(2, height)-1; st = new int[size]; constructST(arr, 0, arr.length-1, 0); return st; } // A recursive function that constructs Segment // Tree for array[ss..se]. si is index of current // node in segment tree st public static int constructST(int[] arr, int ss, int se, int si) { if (ss==se) { st[si] = arr[ss]; return st[si]; } int mid = ss+(se-ss)/2; st[si] = gcd(constructST(arr, ss, mid, si*2+1), constructST(arr, mid+1, se, si*2+2)); return st[si]; } // Function to find gcd of 2 numbers. private static int gcd(int a, int b) { if (a < b) { // If b greater than a swap a and b int temp = b; b = a; a = temp; } if (b==0) return a; return gcd(b,a%b); } //Finding The gcd of given Range public static int findRangeGcd(int ss, int se, int[] arr) { int n = arr.length; if (ss<0 || se > n-1 || ss>se) throw new IllegalArgumentException(\"Invalid arguments\"); return findGcd(0, n-1, ss, se, 0); } /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[si] qs & qe --> Starting and ending indexes of query range */ public static int findGcd(int ss, int se, int qs, int qe, int si) { if (ss>qe || se < qs) return 0; if (qs<=ss && qe>=se) return st[si]; int mid = ss+(se-ss)/2; return gcd(findGcd(ss, mid, qs, qe, si*2+1), findGcd(mid+1, se, qs, qe, si*2+2)); } // Driver Code public static void main(String[] args)throws IOException { int[] a = {2, 3, 6, 9, 5}; constructSegmentTree(a); int l = 1; // Starting index of range. int r = 3; //Last index of range. System.out.print(\"GCD of the given range is: \"); System.out.print(findRangeGcd(l, r, a)); }}",
"e": 33128,
"s": 30256,
"text": null
},
{
"code": "// C# Program to find GCD of a number in a given Range// using segment Treesusing System; class GFG{ private static int[] st; // Array to store segment tree /* Function to construct segment tree from given array. This function allocates memory for segment tree and calls constructSTUtil() to fill the allocated memory */ public static int[] constructSegmentTree(int[] arr) { int height = (int)Math.Ceiling(Math.Log(arr.Length)/Math.Log(2)); int size = 2*(int)Math.Pow(2, height) - 1; st = new int[size]; constructST(arr, 0, arr.Length - 1, 0); return st; } // A recursive function that constructs Segment // Tree for array[ss..se]. si is index of current // node in segment tree st public static int constructST(int[] arr, int ss, int se, int si) { if (ss == se) { st[si] = arr[ss]; return st[si]; } int mid = ss + (se - ss) / 2; st[si] = gcd(constructST(arr, ss, mid, si * 2 + 1), constructST(arr, mid + 1, se, si * 2 + 2)); return st[si]; } // Function to find gcd of 2 numbers. private static int gcd(int a, int b) { if (a < b) { // If b greater than a swap a and b int temp = b; b = a; a = temp; } if (b == 0) return a; return gcd(b,a % b); } // Finding The gcd of given Range public static int findRangeGcd(int ss, int se, int[] arr) { int n = arr.Length; if (ss < 0 || se > n-1 || ss > se) { Console.WriteLine(\"Invalid arguments\"); return int.MinValue; } return findGcd(0, n - 1, ss, se, 0); } /* A recursive function to get gcd of given range of array indexes. The following are parameters for this function. st --> Pointer to segment tree si --> Index of current node in the segment tree. Initially 0 is passed as root is always at index 0 ss & se --> Starting and ending indexes of the segment represented by current node, i.e., st[si] qs & qe --> Starting and ending indexes of query range */ public static int findGcd(int ss, int se, int qs, int qe, int si) { if (ss > qe || se < qs) return 0; if (qs <= ss && qe >= se) return st[si]; int mid = ss + (se - ss)/2; return gcd(findGcd(ss, mid, qs, qe, si * 2 + 1), findGcd(mid + 1, se, qs, qe, si * 2 + 2)); } // Driver Code public static void Main(String[] args) { int[] a = {2, 3, 6, 9, 5}; constructSegmentTree(a); int l = 1; // Starting index of range. int r = 3; //Last index of range. Console.Write(\"GCD of the given range is: \"); Console.Write(findRangeGcd(l, r, a)); }} // This code has been contributed by 29AjayKumar",
"e": 36103,
"s": 33128,
"text": null
},
{
"code": null,
"e": 36133,
"s": 36103,
"text": " GCD of the given range is: 3"
},
{
"code": null,
"e": 36459,
"s": 36133,
"text": "Time Complexity: Time Complexity for tree construction is O(n * log(min(a, b))), where n is the number of modes and a and b are nodes whose GCD is calculated during merge operation. There are total 2n-1 nodes, and value of every node is calculated only once in tree construction. Time complexity to query is O(Log n * Log n)."
},
{
"code": null,
"e": 36728,
"s": 36459,
"text": "This article is contributed by Nikhil Tekwani. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 36853,
"s": 36728,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 36865,
"s": 36853,
"text": "29AjayKumar"
},
{
"code": null,
"e": 36885,
"s": 36865,
"text": "array-range-queries"
},
{
"code": null,
"e": 36898,
"s": 36885,
"text": "Segment-Tree"
},
{
"code": null,
"e": 36922,
"s": 36898,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 36935,
"s": 36922,
"text": "Segment-Tree"
},
{
"code": null,
"e": 37033,
"s": 36935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37042,
"s": 37033,
"text": "Comments"
},
{
"code": null,
"e": 37055,
"s": 37042,
"text": "Old Comments"
},
{
"code": null,
"e": 37089,
"s": 37055,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 37129,
"s": 37089,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 37157,
"s": 37129,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 37186,
"s": 37157,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 37218,
"s": 37186,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 37260,
"s": 37218,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 37287,
"s": 37260,
"text": "Insert Operation in B-Tree"
},
{
"code": null,
"e": 37307,
"s": 37287,
"text": "Design a Chess Game"
},
{
"code": null,
"e": 37339,
"s": 37307,
"text": "Red-Black Tree | Set 3 (Delete)"
}
] |
Asynchronous programming in C# using Async and Await keyword
|
Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits and it takes more time. The application stops responding. Using the asynchronous approach, the applications continue with other tasks as well.
The async and await keywords in C# are used in async programming. Using them, you can work with .NET Framework resources, .NET Core, etc. Asynchronous methods defined using the async keyword are called async methods.
An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding to messages if the processing takes more time than expected.
Let us see what is discussed above −
private void OnRequestDownload(object sender, RoutedEventArgs e) {
var req = HttpWebRequest.Create(_requestedUri);
var res = req.GetResponse();
}
To solve the above issue, use the async and await keywords −
private async void OnRequestDownload(object sender, RoutedEventArgs e) {
var req= HttpWebRequest.Create(_requestedUri);
var res = await req.GetResponseAsync();
}
|
[
{
"code": null,
"e": 1408,
"s": 1062,
"text": "Asynchronous programming in C# is an efficient approach towards activities blocked or access is delayed. If an activity is blocked like this in a synchronous process, then the complete application waits and it takes more time. The application stops responding. Using the asynchronous approach, the applications continue with other tasks as well."
},
{
"code": null,
"e": 1626,
"s": 1408,
"text": "The async and await keywords in C# are used in async programming. Using them, you can work with .NET Framework resources, .NET Core, etc. Asynchronous methods defined using the async keyword are called async methods."
},
{
"code": null,
"e": 1941,
"s": 1626,
"text": "An application with a GUI, check the content of the queue and if an unprocessed task is there, it takes it out and processes it first. The code executes synchronously and the unprocessed task is completed first. The application will show stop responding to messages if the processing takes more time than expected."
},
{
"code": null,
"e": 1978,
"s": 1941,
"text": "Let us see what is discussed above −"
},
{
"code": null,
"e": 2130,
"s": 1978,
"text": "private void OnRequestDownload(object sender, RoutedEventArgs e) {\n var req = HttpWebRequest.Create(_requestedUri);\n var res = req.GetResponse();\n}"
},
{
"code": null,
"e": 2191,
"s": 2130,
"text": "To solve the above issue, use the async and await keywords −"
},
{
"code": null,
"e": 2359,
"s": 2191,
"text": "private async void OnRequestDownload(object sender, RoutedEventArgs e) {\n var req= HttpWebRequest.Create(_requestedUri);\n var res = await req.GetResponseAsync();\n}"
}
] |
How to get hour, minutes and seconds in android using offset time API class?
|
This example demonstrate about How to get hour, minutes and seconds in android using offset time API class.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Local Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
In the above code, we have taken textview to show hour, minutes and seconds.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.time.OffsetTime;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.date);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
OffsetTime offset = OffsetTime.now();
textView.setText(String.valueOf(offset.getHour() + " : " + offset.getMinute() + " : " + offset.getSecond()));
}
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, it is showing current hour, minutes and seconds.
Click here to download the project code
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "This example demonstrate about How to get hour, minutes and seconds in android using offset time API class."
},
{
"code": null,
"e": 1299,
"s": 1170,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1364,
"s": 1299,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2142,
"s": 1364,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/date\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Local Date\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>"
},
{
"code": null,
"e": 2219,
"s": 2142,
"text": "In the above code, we have taken textview to show hour, minutes and seconds."
},
{
"code": null,
"e": 2276,
"s": 2219,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2975,
"s": 2276,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.TextView;\n\nimport java.time.OffsetTime;\n\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView = findViewById(R.id.date);\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {\n OffsetTime offset = OffsetTime.now();\n textView.setText(String.valueOf(offset.getHour() + \" : \" + offset.getMinute() + \" : \" + offset.getSecond()));\n }\n }\n}"
},
{
"code": null,
"e": 3322,
"s": 2975,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3392,
"s": 3322,
"text": "In the above result, it is showing current hour, minutes and seconds."
},
{
"code": null,
"e": 3432,
"s": 3392,
"text": "Click here to download the project code"
}
] |
The Definitive Way To Sort Arrays In Spark 3.0 | by German Schiavon Matteo | Towards Data Science
|
Earlier last year(2020) I had the need to sort an array, and I found that there were two functions, very similar in name, but different in functionality.
These are array_sort and sort_array.
Which one to use? At first, I felt confused, Why would there be two functions to do the same?
Well, the difference is that array_sort :
def array_sort(e: Column):Sorts the input array in ascending order and null elements will be placed at the end of the returned array.
While sort_array :
def sort_array(e: Column, asc: Boolean)Sorts the input array for the given column in ascending or descending order elements.Null elements will be placed at the beginning of the returned array in ascending order or at the end of the returned array in descending order.
After seeing this I decided to open a pull request to unify this behaviour in only array_sort , but after some discussion with the committers, they decided that it would be a good idea to add a way to sort arrays given a comparator function, to match Presto array functions.
Obviously, this was a lot harder than the initial idea of unifying the behaviour of the two functions, but with the help of the committers/reviewers got merged.
Enough history, let’s see how the new array_sort works in Spark 3.0
It receives a comparator function, in this function you will define the logic used to compare the elements of the array.
So what?
The comparator is really powerful when you want to order an array with custom logic or to compare arrays of structs choosing the field that you want to use in the sorting.
Okay, but how?
Let’s define our DataFrame with an array of structs
case class Person(name: String, age: Int)val df = Seq(Array(Person(“andrew”, 23), Person(“juan”,28), Person(“peter”, 22))).toDF
If we print the schema and show the content:
> df.printSchemaroot |-- value: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- name: string (nullable = true) | | |-- age: integer (nullable = false)> df.show(false)+---------------------------------------+|value |+---------------------------------------+|[[andrew, 23], [juan, 28], [peter, 22]]|+---------------------------------------+
Now let’s order the DataFrame using the name column:
df.withColumn("arr_sorted", expr("array_sort(value,(l, r) -> case when l.name > r.name then -1 when l.name < r.name then 1 else 0 end)"))
Now let’s see the content
+---------------------------------------+|arr_sorted |+---------------------------------------+|[[peter, 22], [juan, 28], [andrew, 23]]|+---------------------------------------+
Nice! we got the array sorted by name!
Is there another way to do it?
Yes! You can do it more programatically, by registering a UDF with the comparator logic.
What?
Okay, imagine that now you want to order the array by the name length, then you would do something like this:
spark.udf.register("fStringLength", (x: Person, y: Person) => { if (x.name.length < y.name.length) -1 else if (x.name.length == y.name.length) 0 else 1})
And then, call the UDF
df.selectExpr(“array_sort(value, (x, y) -> fStringLength(x, y)) as arr_sorted”).show(false)
There you go! Array sorted by name length
+---------------------------------------+|arr_sorted |+---------------------------------------+|[[juan, 28], [peter, 22], [andrew, 23]]|+---------------------------------------+
I hope the newarray_sort is more clear after reading the post, it is definitely a powerful function of Spark 3.0
There are multiple ways to sort arrays in Spark, the new function brings a new set to possibilities sorting complex arrays.
|
[
{
"code": null,
"e": 325,
"s": 171,
"text": "Earlier last year(2020) I had the need to sort an array, and I found that there were two functions, very similar in name, but different in functionality."
},
{
"code": null,
"e": 362,
"s": 325,
"text": "These are array_sort and sort_array."
},
{
"code": null,
"e": 456,
"s": 362,
"text": "Which one to use? At first, I felt confused, Why would there be two functions to do the same?"
},
{
"code": null,
"e": 498,
"s": 456,
"text": "Well, the difference is that array_sort :"
},
{
"code": null,
"e": 632,
"s": 498,
"text": "def array_sort(e: Column):Sorts the input array in ascending order and null elements will be placed at the end of the returned array."
},
{
"code": null,
"e": 651,
"s": 632,
"text": "While sort_array :"
},
{
"code": null,
"e": 919,
"s": 651,
"text": "def sort_array(e: Column, asc: Boolean)Sorts the input array for the given column in ascending or descending order elements.Null elements will be placed at the beginning of the returned array in ascending order or at the end of the returned array in descending order."
},
{
"code": null,
"e": 1194,
"s": 919,
"text": "After seeing this I decided to open a pull request to unify this behaviour in only array_sort , but after some discussion with the committers, they decided that it would be a good idea to add a way to sort arrays given a comparator function, to match Presto array functions."
},
{
"code": null,
"e": 1355,
"s": 1194,
"text": "Obviously, this was a lot harder than the initial idea of unifying the behaviour of the two functions, but with the help of the committers/reviewers got merged."
},
{
"code": null,
"e": 1423,
"s": 1355,
"text": "Enough history, let’s see how the new array_sort works in Spark 3.0"
},
{
"code": null,
"e": 1544,
"s": 1423,
"text": "It receives a comparator function, in this function you will define the logic used to compare the elements of the array."
},
{
"code": null,
"e": 1553,
"s": 1544,
"text": "So what?"
},
{
"code": null,
"e": 1725,
"s": 1553,
"text": "The comparator is really powerful when you want to order an array with custom logic or to compare arrays of structs choosing the field that you want to use in the sorting."
},
{
"code": null,
"e": 1740,
"s": 1725,
"text": "Okay, but how?"
},
{
"code": null,
"e": 1792,
"s": 1740,
"text": "Let’s define our DataFrame with an array of structs"
},
{
"code": null,
"e": 1920,
"s": 1792,
"text": "case class Person(name: String, age: Int)val df = Seq(Array(Person(“andrew”, 23), Person(“juan”,28), Person(“peter”, 22))).toDF"
},
{
"code": null,
"e": 1965,
"s": 1920,
"text": "If we print the schema and show the content:"
},
{
"code": null,
"e": 2380,
"s": 1965,
"text": "> df.printSchemaroot |-- value: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- name: string (nullable = true) | | |-- age: integer (nullable = false)> df.show(false)+---------------------------------------+|value |+---------------------------------------+|[[andrew, 23], [juan, 28], [peter, 22]]|+---------------------------------------+"
},
{
"code": null,
"e": 2433,
"s": 2380,
"text": "Now let’s order the DataFrame using the name column:"
},
{
"code": null,
"e": 2571,
"s": 2433,
"text": "df.withColumn(\"arr_sorted\", expr(\"array_sort(value,(l, r) -> case when l.name > r.name then -1 when l.name < r.name then 1 else 0 end)\"))"
},
{
"code": null,
"e": 2597,
"s": 2571,
"text": "Now let’s see the content"
},
{
"code": null,
"e": 2803,
"s": 2597,
"text": "+---------------------------------------+|arr_sorted |+---------------------------------------+|[[peter, 22], [juan, 28], [andrew, 23]]|+---------------------------------------+"
},
{
"code": null,
"e": 2842,
"s": 2803,
"text": "Nice! we got the array sorted by name!"
},
{
"code": null,
"e": 2873,
"s": 2842,
"text": "Is there another way to do it?"
},
{
"code": null,
"e": 2962,
"s": 2873,
"text": "Yes! You can do it more programatically, by registering a UDF with the comparator logic."
},
{
"code": null,
"e": 2968,
"s": 2962,
"text": "What?"
},
{
"code": null,
"e": 3078,
"s": 2968,
"text": "Okay, imagine that now you want to order the array by the name length, then you would do something like this:"
},
{
"code": null,
"e": 3235,
"s": 3078,
"text": "spark.udf.register(\"fStringLength\", (x: Person, y: Person) => { if (x.name.length < y.name.length) -1 else if (x.name.length == y.name.length) 0 else 1})"
},
{
"code": null,
"e": 3258,
"s": 3235,
"text": "And then, call the UDF"
},
{
"code": null,
"e": 3350,
"s": 3258,
"text": "df.selectExpr(“array_sort(value, (x, y) -> fStringLength(x, y)) as arr_sorted”).show(false)"
},
{
"code": null,
"e": 3392,
"s": 3350,
"text": "There you go! Array sorted by name length"
},
{
"code": null,
"e": 3598,
"s": 3392,
"text": "+---------------------------------------+|arr_sorted |+---------------------------------------+|[[juan, 28], [peter, 22], [andrew, 23]]|+---------------------------------------+"
},
{
"code": null,
"e": 3711,
"s": 3598,
"text": "I hope the newarray_sort is more clear after reading the post, it is definitely a powerful function of Spark 3.0"
}
] |
How to convert JSON text to JavaScript JSON object?
|
The JSON parse() method is used for converting a JSON text to a JavaScript object.
Following is the code for converting JSON text to JavaScript JSON object −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.sample {
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>JSON parse() Method</h1>
<div class="sample">
{"name":"Rohan", "sports":["Cricket","Football"], "country":"India"}
</div>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to parse the above JSON string
</h3>
<script>
let sampleEle = document.querySelector(".sample");
let resultEle = document.querySelector(".result");
let parsedJson = JSON.parse(sampleEle.innerHTML);
document.querySelector(".Btn").addEventListener("click", () => {
resultEle.innerHTML = "Name = " + parsedJson.name + "<br>";
resultEle.innerHTML += "Country = " + parsedJson.country + "<br>";
resultEle.innerHTML += "Sports = " + parsedJson.sports;
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the “CLICK HERE” button −
|
[
{
"code": null,
"e": 1145,
"s": 1062,
"text": "The JSON parse() method is used for converting a JSON text to a JavaScript object."
},
{
"code": null,
"e": 1220,
"s": 1145,
"text": "Following is the code for converting JSON text to JavaScript JSON object −"
},
{
"code": null,
"e": 1231,
"s": 1220,
"text": " Live Demo"
},
{
"code": null,
"e": 2324,
"s": 1231,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample {\n font-size: 18px;\n font-weight: 500;\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>JSON parse() Method</h1>\n<div class=\"sample\">\n{\"name\":\"Rohan\", \"sports\":[\"Cricket\",\"Football\"], \"country\":\"India\"}\n</div>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to parse the above JSON string\n</h3>\n<script>\n let sampleEle = document.querySelector(\".sample\");\n let resultEle = document.querySelector(\".result\");\n let parsedJson = JSON.parse(sampleEle.innerHTML);\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n resultEle.innerHTML = \"Name = \" + parsedJson.name + \"<br>\";\n resultEle.innerHTML += \"Country = \" + parsedJson.country + \"<br>\";\n resultEle.innerHTML += \"Sports = \" + parsedJson.sports;\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2375,
"s": 2324,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2413,
"s": 2375,
"text": "On clicking the “CLICK HERE” button −"
}
] |
Modes of Writing a Perl Code - GeeksforGeeks
|
23 May, 2019
Perl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. At the beginning level, Perl was developed only for the system management and text handling but in later versions, Perl got the ability to handle regular expressions, and network sockets, etc. Since Perl is a lot similar to other widely used languages syntactically, it is easier to code and learn in Perl.
Perl is a free-form language which means it can be written, formatted and indented as per user’s requirement. A Perl program consists of a sequence of statements, loops, subroutines, etc. that allows moving around within the code easily. Every statement in a Perl code must end with a semicolon(;). Like other languages, Perl also supports multiple modes of writing and executing a Perl Code. These modes can be categorized on the basis of their writing compatibility and mode of execution in the following ways:
Interactive Mode
Script Mode
One-Liner Mode
These modes can be Run on the command line with the use of perl keyword or on the Online IDEs in the form of a block of code. Perl also provides an inbuilt IDE of its own along with the installation package.
Interactive mode of writing a Perl code means the direct interaction with the interpreter. Interactive mode is a good way to get started as it helps to check the flow of code line by line and makes the debugging process easier. Interactive Mode in Perl can be used on the Command line with the use of Perl Debugger. This interpreter is commonly known as REPL– Read, Evaluate, Print, Loop.Interactive mode provides an instant development and execution of code without the need to create a temporary file to store the source code. Perl’s inbuilt command line or the Windows command prompt can be used as a REPL with the help of Perl Debugger. This debugger can be used on a Perl program with the help of the following command:
perl -de1
This command will open the debugger mode in the Perl command line as shown below:
In the Interactive mode of Writing a Perl Code, the user has to write the code line by line and it gets executed at the same time.Example: If we need to add two numbers and display the result then that can be done in the Interactive mode in the following manner:
Interactive mode in Perl can be Run on the command line itself without the use of Perl debugger. This can be done with the use of the following command:
perl -e Code_statement;
This statement uses the -e flag to avoid the creation of a script and allows the code to Run on the command line without the debugger.Example:This method of writing in an Interactive mode will not allow the user to write a Multiline code as in the debugger. If a program is long then this mode will not be preferred.
Interactive mode is good for the beginner programmers to learn the basics of programming, but if you are working with more than a few lines of code then this mode can become clumsy and tedious.
Script Mode in Perl is used to write Perl programs which have more than a few lines of code and are a bit complex for the Interactive mode. Script mode in Perl can be used by the help of a text editor to write the Perl program and to save it in a file called a script and then execute the saved file by using the command line. This file must be saved with a .pl extension and should be placed in the same folder of which the directory path is given to the command line. This script is further run in the command line using the command:
perl File_Name.pl
Example: Code is written in a text editor(notepad, etc.) and is saved as Perl_program.pl script.Now, run the following command in the Command line to execute the Script saved as Perl_program.pl
perl Perl_program.pl
Output:Script Mode in Perl, unlike the Interactive mode, cannot produce output for the expression individually. In the Interactive mode, the expression gets evaluated and the value is displayed by itself but in the Script mode, the expression will be evaluated but it will not display any result until asked to do so.
Script mode is also implemented in the online IDEs, which are used to write and execute the perl code without manually storing them in a File. In these IDEs, the code when compiled gets stored into the memory in the form of a temporary file which is of use only till the code is being executed and the IDE is open in the browser. Once refreshed, this temporary file is deleted and the space occupied in the memory is freed.Online IDEs have made the execution of Codes easier as they need less effort as compared to the Script mode in which the files are to be stored in the system’s memory. This makes the code compilation and execution faster. These online IDEs in spite of being an ease to the programmer also come with certain limitations, like, these IDEs can’t perform the File Handling operations until and unless the file is uploaded on their server which might be a risk to some Important data. Such kind of File handling operations can be easily done on the command line compilers.Following is an example of a Perl code of addition of two numbers running on an Online IDE:
#!/usr/bin/perl# Program to add two numbers # Assigning values to variables$var1 = 10;$var2 = 25; # Evaluating the result$result = $var1 + $var2; # Printing the resultprint "Result after addition is: $result";
Result after addition is: 35
Perl also provides a one-liner mode, which allows to type and execute a very short script of code directly on the command line. This is done to avoid the creation of Files to store the script for codes which are not very lengthy. These codes can be typed on a single line in the command line mode with the help of the following command:
perl -e
This command is used to write and execute the one-liner code in the command line by writing it in the double quotes. The -e flag in the upgiven command tells the compiler that the script of the code is not stored in any kind of file but is written in the double codes immediately after this flag.Example:
In Linux/Unix, these double quotes are replaced with single quotes and vice versa.
These one-liners can be very useful for making changes very quickly like finding information, changing file contents, etc. Some programmers avoid using one-liners because they might become clumsy when script is a bit lengthy. While some programmers enjoy doing this because one-liners are faster than the scripts because there is no need to store them into files.
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Perl Tutorial - Learn Perl With Examples
Perl | Hashes
Perl | Opening and Reading a File
Perl | Basic Syntax of a Perl Program
Perl | Multidimensional Hashes
How to Install Perl on Windows?
Perl | CGI Programming
Perl | Sorting of Arrays
Perl | Operators | Set - 1
Perl | Data Types
|
[
{
"code": null,
"e": 23679,
"s": 23651,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 24137,
"s": 23679,
"text": "Perl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. At the beginning level, Perl was developed only for the system management and text handling but in later versions, Perl got the ability to handle regular expressions, and network sockets, etc. Since Perl is a lot similar to other widely used languages syntactically, it is easier to code and learn in Perl."
},
{
"code": null,
"e": 24650,
"s": 24137,
"text": "Perl is a free-form language which means it can be written, formatted and indented as per user’s requirement. A Perl program consists of a sequence of statements, loops, subroutines, etc. that allows moving around within the code easily. Every statement in a Perl code must end with a semicolon(;). Like other languages, Perl also supports multiple modes of writing and executing a Perl Code. These modes can be categorized on the basis of their writing compatibility and mode of execution in the following ways:"
},
{
"code": null,
"e": 24667,
"s": 24650,
"text": "Interactive Mode"
},
{
"code": null,
"e": 24679,
"s": 24667,
"text": "Script Mode"
},
{
"code": null,
"e": 24694,
"s": 24679,
"text": "One-Liner Mode"
},
{
"code": null,
"e": 24903,
"s": 24694,
"text": "These modes can be Run on the command line with the use of perl keyword or on the Online IDEs in the form of a block of code. Perl also provides an inbuilt IDE of its own along with the installation package. "
},
{
"code": null,
"e": 25628,
"s": 24903,
"text": "Interactive mode of writing a Perl code means the direct interaction with the interpreter. Interactive mode is a good way to get started as it helps to check the flow of code line by line and makes the debugging process easier. Interactive Mode in Perl can be used on the Command line with the use of Perl Debugger. This interpreter is commonly known as REPL– Read, Evaluate, Print, Loop.Interactive mode provides an instant development and execution of code without the need to create a temporary file to store the source code. Perl’s inbuilt command line or the Windows command prompt can be used as a REPL with the help of Perl Debugger. This debugger can be used on a Perl program with the help of the following command:"
},
{
"code": null,
"e": 25638,
"s": 25628,
"text": "perl -de1"
},
{
"code": null,
"e": 25720,
"s": 25638,
"text": "This command will open the debugger mode in the Perl command line as shown below:"
},
{
"code": null,
"e": 25983,
"s": 25720,
"text": "In the Interactive mode of Writing a Perl Code, the user has to write the code line by line and it gets executed at the same time.Example: If we need to add two numbers and display the result then that can be done in the Interactive mode in the following manner:"
},
{
"code": null,
"e": 26136,
"s": 25983,
"text": "Interactive mode in Perl can be Run on the command line itself without the use of Perl debugger. This can be done with the use of the following command:"
},
{
"code": null,
"e": 26160,
"s": 26136,
"text": "perl -e Code_statement;"
},
{
"code": null,
"e": 26477,
"s": 26160,
"text": "This statement uses the -e flag to avoid the creation of a script and allows the code to Run on the command line without the debugger.Example:This method of writing in an Interactive mode will not allow the user to write a Multiline code as in the debugger. If a program is long then this mode will not be preferred."
},
{
"code": null,
"e": 26672,
"s": 26477,
"text": "Interactive mode is good for the beginner programmers to learn the basics of programming, but if you are working with more than a few lines of code then this mode can become clumsy and tedious. "
},
{
"code": null,
"e": 27208,
"s": 26672,
"text": "Script Mode in Perl is used to write Perl programs which have more than a few lines of code and are a bit complex for the Interactive mode. Script mode in Perl can be used by the help of a text editor to write the Perl program and to save it in a file called a script and then execute the saved file by using the command line. This file must be saved with a .pl extension and should be placed in the same folder of which the directory path is given to the command line. This script is further run in the command line using the command:"
},
{
"code": null,
"e": 27226,
"s": 27208,
"text": "perl File_Name.pl"
},
{
"code": null,
"e": 27420,
"s": 27226,
"text": "Example: Code is written in a text editor(notepad, etc.) and is saved as Perl_program.pl script.Now, run the following command in the Command line to execute the Script saved as Perl_program.pl"
},
{
"code": null,
"e": 27441,
"s": 27420,
"text": "perl Perl_program.pl"
},
{
"code": null,
"e": 27759,
"s": 27441,
"text": "Output:Script Mode in Perl, unlike the Interactive mode, cannot produce output for the expression individually. In the Interactive mode, the expression gets evaluated and the value is displayed by itself but in the Script mode, the expression will be evaluated but it will not display any result until asked to do so."
},
{
"code": null,
"e": 28841,
"s": 27759,
"text": "Script mode is also implemented in the online IDEs, which are used to write and execute the perl code without manually storing them in a File. In these IDEs, the code when compiled gets stored into the memory in the form of a temporary file which is of use only till the code is being executed and the IDE is open in the browser. Once refreshed, this temporary file is deleted and the space occupied in the memory is freed.Online IDEs have made the execution of Codes easier as they need less effort as compared to the Script mode in which the files are to be stored in the system’s memory. This makes the code compilation and execution faster. These online IDEs in spite of being an ease to the programmer also come with certain limitations, like, these IDEs can’t perform the File Handling operations until and unless the file is uploaded on their server which might be a risk to some Important data. Such kind of File handling operations can be easily done on the command line compilers.Following is an example of a Perl code of addition of two numbers running on an Online IDE:"
},
{
"code": "#!/usr/bin/perl# Program to add two numbers # Assigning values to variables$var1 = 10;$var2 = 25; # Evaluating the result$result = $var1 + $var2; # Printing the resultprint \"Result after addition is: $result\";",
"e": 29054,
"s": 28841,
"text": null
},
{
"code": null,
"e": 29084,
"s": 29054,
"text": "Result after addition is: 35\n"
},
{
"code": null,
"e": 29423,
"s": 29086,
"text": "Perl also provides a one-liner mode, which allows to type and execute a very short script of code directly on the command line. This is done to avoid the creation of Files to store the script for codes which are not very lengthy. These codes can be typed on a single line in the command line mode with the help of the following command:"
},
{
"code": null,
"e": 29431,
"s": 29423,
"text": "perl -e"
},
{
"code": null,
"e": 29736,
"s": 29431,
"text": "This command is used to write and execute the one-liner code in the command line by writing it in the double quotes. The -e flag in the upgiven command tells the compiler that the script of the code is not stored in any kind of file but is written in the double codes immediately after this flag.Example:"
},
{
"code": null,
"e": 29819,
"s": 29736,
"text": "In Linux/Unix, these double quotes are replaced with single quotes and vice versa."
},
{
"code": null,
"e": 30183,
"s": 29819,
"text": "These one-liners can be very useful for making changes very quickly like finding information, changing file contents, etc. Some programmers avoid using one-liners because they might become clumsy when script is a bit lengthy. While some programmers enjoy doing this because one-liners are faster than the scripts because there is no need to store them into files."
},
{
"code": null,
"e": 30188,
"s": 30183,
"text": "Perl"
},
{
"code": null,
"e": 30193,
"s": 30188,
"text": "Perl"
},
{
"code": null,
"e": 30291,
"s": 30193,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30300,
"s": 30291,
"text": "Comments"
},
{
"code": null,
"e": 30313,
"s": 30300,
"text": "Old Comments"
},
{
"code": null,
"e": 30354,
"s": 30313,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 30368,
"s": 30354,
"text": "Perl | Hashes"
},
{
"code": null,
"e": 30402,
"s": 30368,
"text": "Perl | Opening and Reading a File"
},
{
"code": null,
"e": 30440,
"s": 30402,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 30471,
"s": 30440,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 30503,
"s": 30471,
"text": "How to Install Perl on Windows?"
},
{
"code": null,
"e": 30526,
"s": 30503,
"text": "Perl | CGI Programming"
},
{
"code": null,
"e": 30551,
"s": 30526,
"text": "Perl | Sorting of Arrays"
},
{
"code": null,
"e": 30578,
"s": 30551,
"text": "Perl | Operators | Set - 1"
}
] |
Jasmine JavaScript Testing - toBe vs toEqual
|
Arrays can be compared in 2 ways −
They refer to the same array object in memory.
They refer to the same array object in memory.
They may refer to different objects but their contents are all equal.
They may refer to different objects but their contents are all equal.
For case 1, jasmine provides the toBe method. This checks for reference.
For example,
describe("Array Equality", () => {
it("should check for array reference equility", () => {
let arr = [1, 2, 3];
let arr2 = arr
// Runs successfully
expect(arr).toBe(arr2);
// Fails as references are not equal
expect(arr).toBe([1, 2, 3]);
});
});
This will give the output −
1) Array Equality should check for array equility
Message:
Expected [ 1, 2, 3 ] to be [ 1, 2, 3 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe().
For case 2 we can use the toEqual method and deep compare the arrays. For
example,
describe("Array Equality", () => {
it("should check for array reference equility", () => {
let arr = [1, 2, 3];
let arr2 = arr;
// Runs successfully
expect(arr).toEqual(arr2);
// Runs successfully
expect(arr).toEqual([1, 2, 3]);
});
});
This will give the output −
1 spec, 0 failures
|
[
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Arrays can be compared in 2 ways −"
},
{
"code": null,
"e": 1144,
"s": 1097,
"text": "They refer to the same array object in memory."
},
{
"code": null,
"e": 1191,
"s": 1144,
"text": "They refer to the same array object in memory."
},
{
"code": null,
"e": 1261,
"s": 1191,
"text": "They may refer to different objects but their contents are all equal."
},
{
"code": null,
"e": 1331,
"s": 1261,
"text": "They may refer to different objects but their contents are all equal."
},
{
"code": null,
"e": 1417,
"s": 1331,
"text": "For case 1, jasmine provides the toBe method. This checks for reference.\nFor example,"
},
{
"code": null,
"e": 1705,
"s": 1417,
"text": "describe(\"Array Equality\", () => {\n it(\"should check for array reference equility\", () => {\n let arr = [1, 2, 3];\n let arr2 = arr\n // Runs successfully\n expect(arr).toBe(arr2);\n // Fails as references are not equal\n expect(arr).toBe([1, 2, 3]);\n });\n});"
},
{
"code": null,
"e": 1733,
"s": 1705,
"text": "This will give the output −"
},
{
"code": null,
"e": 1903,
"s": 1733,
"text": "1) Array Equality should check for array equility\nMessage:\n Expected [ 1, 2, 3 ] to be [ 1, 2, 3 ]. Tip: To check for deep equality, use .toEqual() instead of .toBe()."
},
{
"code": null,
"e": 1986,
"s": 1903,
"text": "For case 2 we can use the toEqual method and deep compare the arrays. For\nexample,"
},
{
"code": null,
"e": 2265,
"s": 1986,
"text": "describe(\"Array Equality\", () => {\n it(\"should check for array reference equility\", () => {\n let arr = [1, 2, 3];\n let arr2 = arr;\n // Runs successfully\n expect(arr).toEqual(arr2);\n // Runs successfully\n expect(arr).toEqual([1, 2, 3]);\n });\n});"
},
{
"code": null,
"e": 2293,
"s": 2265,
"text": "This will give the output −"
},
{
"code": null,
"e": 2312,
"s": 2293,
"text": "1 spec, 0 failures"
}
] |
Python 3 - Functions
|
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.
You can define functions to provide the required functionality. Here are simple rules to define a function in Python.
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the documentation string of the function or docstring.
The first statement of a function can be an optional statement - the documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
def functionname( parameters ):
"function_docstring"
function_suite
return [expression]
By default, parameters have a positional behavior and you need to inform them in the same order that they were defined.
The following function takes a string as input parameter and prints it on standard screen.
def printme( str ):
"This prints a passed string into this function"
print (str)
return
Defining a function gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is an example to call the printme() function −
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme("This is first call to the user defined function!")
printme("Again second call to the same function")
When the above code is executed, it produces the following result −
This is first call to the user defined function!
Again second call to the same function
All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −
#!/usr/bin/python3
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
print ("Values inside the function before change: ", mylist)
mylist[2]=50
print ("Values inside the function after change: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
Here, we are maintaining reference of the passed object and appending values in the same object. Therefore, this would produce the following result −
Values inside the function before change: [10, 20, 30]
Values inside the function after change: [10, 20, 50]
Values outside the function: [10, 20, 50]
There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function.
#!/usr/bin/python3
# Function definition is here
def changeme( mylist ):
"This changes a passed list into this function"
mylist = [1,2,3,4] # This would assi new reference in mylist
print ("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
You can call a function by using the following types of formal arguments −
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.
To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme()
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −
#!/usr/bin/python3
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme( str = "My string")
When the above code is executed, it produces the following result −
My string
The following example gives a clearer picture. Note that the order of parameters does not matter.
#!/usr/bin/python3
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age = 50, name = "miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −
#!/usr/bin/python3
# Function definition is here
def printinfo( name, age = 35 ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age = 50, name = "miki" )
printinfo( name = "miki" )
When the above code is executed, it produces the following result −
Name: miki
Age 50
Name: miki
Age 35
You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.
Syntax for a function with non-keyword variable arguments is given below −
def functionname([formal_args,] *var_args_tuple ):
"function_docstring"
function_suite
return [expression]
An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −
#!/usr/bin/python3
# Function definition is here
def printinfo( arg1, *vartuple ):
"This prints a variable passed arguments"
print ("Output is: ")
print (arg1)
for var in vartuple:
print (var)
return
# Now you can call printinfo function
printinfo( 10 )
printinfo( 70, 60, 50 )
When the above code is executed, it produces the following result −
Output is:
10
Output is:
70
60
50
These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions.
An anonymous function cannot be a direct call to print because lambda requires an expression.
An anonymous function cannot be a direct call to print because lambda requires an expression.
Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace.
Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons.
Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons.
The syntax of lambda functions contains only a single statement, which is as follows −
lambda [arg1 [,arg2,.....argn]]:expression
Following is an example to show how lambda form of function works −
#!/usr/bin/python3
# Function definition is here
sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
print ("Value of total : ", sum( 10, 20 ))
print ("Value of total : ", sum( 20, 20 ))
When the above code is executed, it produces the following result −
Value of total : 30
Value of total : 40
The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.
All the examples given below are not returning any value. You can return a value from a function as follows −
#!/usr/bin/python3
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2
print ("Inside the function : ", total)
return total
# Now you can call sum function
total = sum( 10, 20 )
print ("Outside the function : ", total )
When the above code is executed, it produces the following result −
Inside the function : 30
Outside the function : 30
All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −
Global variables
Local variables
Variables that are defined inside a function body have a local scope, and those defined outside have a global scope.
This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −
#!/usr/bin/python3
total = 0 # This is global variable.
# Function definition is here
def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total
# Now you can call sum function
sum( 10, 20 )
print ("Outside the function global total : ", total )
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2532,
"s": 2340,
"text": "A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing."
},
{
"code": null,
"e": 2708,
"s": 2532,
"text": "As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions."
},
{
"code": null,
"e": 2826,
"s": 2708,
"text": "You can define functions to provide the required functionality. Here are simple rules to define a function in Python."
},
{
"code": null,
"e": 2924,
"s": 2826,
"text": "Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) )."
},
{
"code": null,
"e": 3022,
"s": 2924,
"text": "Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) )."
},
{
"code": null,
"e": 3156,
"s": 3022,
"text": "Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses."
},
{
"code": null,
"e": 3290,
"s": 3156,
"text": "Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses."
},
{
"code": null,
"e": 3410,
"s": 3290,
"text": "The first statement of a function can be an optional statement - the documentation string of the function or docstring."
},
{
"code": null,
"e": 3530,
"s": 3410,
"text": "The first statement of a function can be an optional statement - the documentation string of the function or docstring."
},
{
"code": null,
"e": 3608,
"s": 3530,
"text": "The code block within every function starts with a colon (:) and is indented."
},
{
"code": null,
"e": 3686,
"s": 3608,
"text": "The code block within every function starts with a colon (:) and is indented."
},
{
"code": null,
"e": 3856,
"s": 3686,
"text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None."
},
{
"code": null,
"e": 4026,
"s": 3856,
"text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None."
},
{
"code": null,
"e": 4124,
"s": 4026,
"text": "def functionname( parameters ):\n \"function_docstring\"\n function_suite\n return [expression]\n"
},
{
"code": null,
"e": 4244,
"s": 4124,
"text": "By default, parameters have a positional behavior and you need to inform them in the same order that they were defined."
},
{
"code": null,
"e": 4335,
"s": 4244,
"text": "The following function takes a string as input parameter and prints it on standard screen."
},
{
"code": null,
"e": 4432,
"s": 4335,
"text": "def printme( str ):\n \"This prints a passed string into this function\"\n print (str)\n return"
},
{
"code": null,
"e": 4569,
"s": 4432,
"text": "Defining a function gives it a name, specifies the parameters that are to be included in the function and structures the blocks of code."
},
{
"code": null,
"e": 4770,
"s": 4569,
"text": "Once the basic structure of a function is finalized, you can execute it by calling it from another function or directly from the Python prompt. Following is an example to call the printme() function −"
},
{
"code": null,
"e": 5064,
"s": 4770,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print (str)\n return\n\n# Now you can call printme function\nprintme(\"This is first call to the user defined function!\")\nprintme(\"Again second call to the same function\")"
},
{
"code": null,
"e": 5132,
"s": 5064,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 5221,
"s": 5132,
"text": "This is first call to the user defined function!\nAgain second call to the same function\n"
},
{
"code": null,
"e": 5434,
"s": 5221,
"text": "All parameters (arguments) in the Python language are passed by reference. It means if you change what a parameter refers to within a function, the change also reflects back in the calling function. For example −"
},
{
"code": null,
"e": 5841,
"s": 5434,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n print (\"Values inside the function before change: \", mylist)\n \n mylist[2]=50\n print (\"Values inside the function after change: \", mylist)\n return\n\n# Now you can call changeme function\nmylist = [10,20,30]\nchangeme( mylist )\nprint (\"Values outside the function: \", mylist)"
},
{
"code": null,
"e": 5991,
"s": 5841,
"text": "Here, we are maintaining reference of the passed object and appending values in the same object. Therefore, this would produce the following result −"
},
{
"code": null,
"e": 6146,
"s": 5991,
"text": "Values inside the function before change: [10, 20, 30]\nValues inside the function after change: [10, 20, 50]\nValues outside the function: [10, 20, 50]\n"
},
{
"code": null,
"e": 6283,
"s": 6146,
"text": "There is one more example where argument is being passed by reference and the reference is being overwritten inside the called function."
},
{
"code": null,
"e": 6657,
"s": 6283,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef changeme( mylist ):\n \"This changes a passed list into this function\"\n mylist = [1,2,3,4] # This would assi new reference in mylist\n print (\"Values inside the function: \", mylist)\n return\n\n# Now you can call changeme function\nmylist = [10,20,30]\nchangeme( mylist )\nprint (\"Values outside the function: \", mylist)"
},
{
"code": null,
"e": 6861,
"s": 6657,
"text": "The parameter mylist is local to the function changeme. Changing mylist within the function does not affect mylist. The function accomplishes nothing and finally this would produce the following result −"
},
{
"code": null,
"e": 6947,
"s": 6861,
"text": "Values inside the function: [1, 2, 3, 4]\nValues outside the function: [10, 20, 30]\n"
},
{
"code": null,
"e": 7022,
"s": 6947,
"text": "You can call a function by using the following types of formal arguments −"
},
{
"code": null,
"e": 7041,
"s": 7022,
"text": "Required arguments"
},
{
"code": null,
"e": 7059,
"s": 7041,
"text": "Keyword arguments"
},
{
"code": null,
"e": 7077,
"s": 7059,
"text": "Default arguments"
},
{
"code": null,
"e": 7103,
"s": 7077,
"text": "Variable-length arguments"
},
{
"code": null,
"e": 7292,
"s": 7103,
"text": "Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition."
},
{
"code": null,
"e": 7413,
"s": 7292,
"text": "To call the function printme(), you definitely need to pass one argument, otherwise it gives a syntax error as follows −"
},
{
"code": null,
"e": 7607,
"s": 7413,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print (str)\n return\n\n# Now you can call printme function\nprintme()"
},
{
"code": null,
"e": 7676,
"s": 7607,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 7825,
"s": 7676,
"text": "Traceback (most recent call last):\n File \"test.py\", line 11, in <module>\n printme();\nTypeError: printme() takes exactly 1 argument (0 given)\n"
},
{
"code": null,
"e": 7988,
"s": 7825,
"text": "Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name."
},
{
"code": null,
"e": 8236,
"s": 7988,
"text": "This allows you to skip arguments or place them out of order because the Python interpreter is able to use the keywords provided to match the values with parameters. You can also make keyword calls to the printme() function in the following ways −"
},
{
"code": null,
"e": 8448,
"s": 8236,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef printme( str ):\n \"This prints a passed string into this function\"\n print (str)\n return\n\n# Now you can call printme function\nprintme( str = \"My string\")"
},
{
"code": null,
"e": 8517,
"s": 8448,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 8528,
"s": 8517,
"text": "My string\n"
},
{
"code": null,
"e": 8626,
"s": 8528,
"text": "The following example gives a clearer picture. Note that the order of parameters does not matter."
},
{
"code": null,
"e": 8889,
"s": 8626,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef printinfo( name, age ):\n \"This prints a passed info into this function\"\n print (\"Name: \", name)\n print (\"Age \", age)\n return\n\n# Now you can call printinfo function\nprintinfo( age = 50, name = \"miki\" )"
},
{
"code": null,
"e": 8958,
"s": 8889,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 8979,
"s": 8958,
"text": "Name: miki\nAge 50\n"
},
{
"code": null,
"e": 9211,
"s": 8979,
"text": "A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed −"
},
{
"code": null,
"e": 9506,
"s": 9211,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef printinfo( name, age = 35 ):\n \"This prints a passed info into this function\"\n print (\"Name: \", name)\n print (\"Age \", age)\n return\n\n# Now you can call printinfo function\nprintinfo( age = 50, name = \"miki\" )\nprintinfo( name = \"miki\" )"
},
{
"code": null,
"e": 9575,
"s": 9506,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 9616,
"s": 9575,
"text": "Name: miki\nAge 50\nName: miki\nAge 35\n"
},
{
"code": null,
"e": 9856,
"s": 9616,
"text": "You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments."
},
{
"code": null,
"e": 9931,
"s": 9856,
"text": "Syntax for a function with non-keyword variable arguments is given below −"
},
{
"code": null,
"e": 10048,
"s": 9931,
"text": "def functionname([formal_args,] *var_args_tuple ):\n \"function_docstring\"\n function_suite\n return [expression]\n"
},
{
"code": null,
"e": 10283,
"s": 10048,
"text": "An asterisk (*) is placed before the variable name that holds the values of all nonkeyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call. Following is a simple example −"
},
{
"code": null,
"e": 10588,
"s": 10283,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef printinfo( arg1, *vartuple ):\n \"This prints a variable passed arguments\"\n print (\"Output is: \")\n print (arg1)\n \n for var in vartuple:\n print (var)\n return\n\n# Now you can call printinfo function\nprintinfo( 10 )\nprintinfo( 70, 60, 50 )"
},
{
"code": null,
"e": 10657,
"s": 10588,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 10692,
"s": 10657,
"text": "Output is:\n10\nOutput is:\n70\n60\n50\n"
},
{
"code": null,
"e": 10876,
"s": 10692,
"text": "These functions are called anonymous because they are not declared in the standard manner by using the def keyword. You can use the lambda keyword to create small anonymous functions."
},
{
"code": null,
"e": 11032,
"s": 10876,
"text": "Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions."
},
{
"code": null,
"e": 11188,
"s": 11032,
"text": "Lambda forms can take any number of arguments but return just one value in the form of an expression. They cannot contain commands or multiple expressions."
},
{
"code": null,
"e": 11282,
"s": 11188,
"text": "An anonymous function cannot be a direct call to print because lambda requires an expression."
},
{
"code": null,
"e": 11376,
"s": 11282,
"text": "An anonymous function cannot be a direct call to print because lambda requires an expression."
},
{
"code": null,
"e": 11528,
"s": 11376,
"text": "Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace."
},
{
"code": null,
"e": 11680,
"s": 11528,
"text": "Lambda functions have their own local namespace and cannot access variables other than those in their parameter list and those in the global namespace."
},
{
"code": null,
"e": 11910,
"s": 11680,
"text": "Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons."
},
{
"code": null,
"e": 12140,
"s": 11910,
"text": "Although it appears that lambdas are a one-line version of a function, they are not equivalent to inline statements in C or C++, whose purpose is to stack allocation by passing function, during invocation for performance reasons."
},
{
"code": null,
"e": 12227,
"s": 12140,
"text": "The syntax of lambda functions contains only a single statement, which is as follows −"
},
{
"code": null,
"e": 12271,
"s": 12227,
"text": "lambda [arg1 [,arg2,.....argn]]:expression\n"
},
{
"code": null,
"e": 12339,
"s": 12271,
"text": "Following is an example to show how lambda form of function works −"
},
{
"code": null,
"e": 12550,
"s": 12339,
"text": "#!/usr/bin/python3\n\n# Function definition is here\nsum = lambda arg1, arg2: arg1 + arg2\n\n# Now you can call sum as a function\nprint (\"Value of total : \", sum( 10, 20 ))\nprint (\"Value of total : \", sum( 20, 20 ))"
},
{
"code": null,
"e": 12619,
"s": 12550,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 12662,
"s": 12619,
"text": "Value of total : 30\nValue of total : 40\n"
},
{
"code": null,
"e": 12832,
"s": 12662,
"text": "The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None."
},
{
"code": null,
"e": 12942,
"s": 12832,
"text": "All the examples given below are not returning any value. You can return a value from a function as follows −"
},
{
"code": null,
"e": 13241,
"s": 12942,
"text": "#!/usr/bin/python3\n\n# Function definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2\n print (\"Inside the function : \", total)\n return total\n\n# Now you can call sum function\ntotal = sum( 10, 20 )\nprint (\"Outside the function : \", total )"
},
{
"code": null,
"e": 13310,
"s": 13241,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 13364,
"s": 13310,
"text": "Inside the function : 30\nOutside the function : 30\n"
},
{
"code": null,
"e": 13499,
"s": 13364,
"text": "All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable."
},
{
"code": null,
"e": 13659,
"s": 13499,
"text": "The scope of a variable determines the portion of the program where you can access a particular identifier. There are two basic scopes of variables in Python −"
},
{
"code": null,
"e": 13676,
"s": 13659,
"text": "Global variables"
},
{
"code": null,
"e": 13692,
"s": 13676,
"text": "Local variables"
},
{
"code": null,
"e": 13809,
"s": 13692,
"text": "Variables that are defined inside a function body have a local scope, and those defined outside have a global scope."
},
{
"code": null,
"e": 14112,
"s": 13809,
"text": "This means that local variables can be accessed only inside the function in which they are declared, whereas global variables can be accessed throughout the program body by all functions. When you call a function, the variables declared inside it are brought into scope. Following is a simple example −"
},
{
"code": null,
"e": 14500,
"s": 14112,
"text": "#!/usr/bin/python3\n\ntotal = 0 # This is global variable.\n# Function definition is here\ndef sum( arg1, arg2 ):\n # Add both the parameters and return them.\"\n total = arg1 + arg2; # Here total is local variable.\n print (\"Inside the function local total : \", total)\n return total\n\n# Now you can call sum function\nsum( 10, 20 )\nprint (\"Outside the function global total : \", total )"
},
{
"code": null,
"e": 14569,
"s": 14500,
"text": "When the above code is executed, it produces the following result −"
},
{
"code": null,
"e": 14647,
"s": 14569,
"text": "Inside the function local total : 30\nOutside the function global total : 0\n"
},
{
"code": null,
"e": 14684,
"s": 14647,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 14700,
"s": 14684,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 14733,
"s": 14700,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 14752,
"s": 14733,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 14787,
"s": 14752,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 14809,
"s": 14787,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 14843,
"s": 14809,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 14871,
"s": 14843,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 14906,
"s": 14871,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 14920,
"s": 14906,
"text": " Lets Kode It"
},
{
"code": null,
"e": 14953,
"s": 14920,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 14970,
"s": 14953,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 14977,
"s": 14970,
"text": " Print"
},
{
"code": null,
"e": 14988,
"s": 14977,
"text": " Add Notes"
}
] |
Geek-onacci Number || | Practice | GeeksforGeeks
|
Geek created a random series and given a name geek-onacci series. Given four integers A, B, C, N. A, B, C represents the first three numbers of geek-onacci series. Find the Nth number of the series. The nth number of geek-onacci series is a sum of the last three numbers (summation of N-1th, N-2th, and N-3th geek-onacci numbers)
Note: The answer can be very large. So, output answer modulo 109 + 7.
Input:
1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
2. The first line of each test case contains four space-separated integers A, B, C, and N.
Output: For each test case, print Nth geek-onacci number
Constraints:
1. 1 <= T <= 102
2. 1 <= A, B, C <= 105
3. 4 <= N <= 104
Example:
Input:
3
1 3 2 4
1 3 2 5
1 3 2 6
Output:
6
11
19
0
mohammedfahad17086 days ago
#include <iostream>using namespace std;
int geek(int a,int b,int c,int N){ int count =3; int sum=0; while(count<N){ sum = ((a + b) % 1000000007 + c ) % 1000000007; a=b; b=c; c=sum; count++; } return c;}int main() { int n;cin>>n;int a,b,c,N;for(int i=0;i<n;i++){ cin>>a>>b>>c>>N; cout<<geek(a,b,c,N)<<endl;}return 0;}
0
Debojyoti Sinha1 year ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.01
#include <bits stdc++.h="">using namespace std;int geekonacciNumber(int A, int B, int C, int N){ int D; for(int i = 4; i <= N; i++) { D = ((A + B) % 1000000007 + C ) % 1000000007; A = B; B = C; C = D; } return D;}int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; while(T--) { int A, B, C, N; cin >> A >> B >> C >> N; cout << geekonacciNumber(A, B, C, N) << "\n"; } return 0;}
0
Rahul sharma1 year ago
Rahul sharma
0
Rahul sharma
This comment was deleted.
0
Rahul sharma
This comment was deleted.
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 628,
"s": 226,
"text": "Geek created a random series and given a name geek-onacci series. Given four integers A, B, C, N. A, B, C represents the first three numbers of geek-onacci series. Find the Nth number of the series. The nth number of geek-onacci series is a sum of the last three numbers (summation of N-1th, N-2th, and N-3th geek-onacci numbers)\n\nNote: The answer can be very large. So, output answer modulo 109 + 7. "
},
{
"code": null,
"e": 1035,
"s": 628,
"text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains four space-separated integers A, B, C, and N.\n\nOutput: For each test case, print Nth geek-onacci number\n\nConstraints:\n1. 1 <= T <= 102\n2. 1 <= A, B, C <= 105\n3. 4 <= N <= 104\n\nExample:\nInput:\n3\n1 3 2 4\n1 3 2 5\n1 3 2 6"
},
{
"code": null,
"e": 1051,
"s": 1035,
"text": "Output:\n6\n11\n19"
},
{
"code": null,
"e": 1053,
"s": 1051,
"text": "0"
},
{
"code": null,
"e": 1081,
"s": 1053,
"text": "mohammedfahad17086 days ago"
},
{
"code": null,
"e": 1121,
"s": 1081,
"text": "#include <iostream>using namespace std;"
},
{
"code": null,
"e": 1456,
"s": 1121,
"text": " int geek(int a,int b,int c,int N){ int count =3; int sum=0; while(count<N){ sum = ((a + b) % 1000000007 + c ) % 1000000007; a=b; b=c; c=sum; count++; } return c;}int main() { int n;cin>>n;int a,b,c,N;for(int i=0;i<n;i++){ cin>>a>>b>>c>>N; cout<<geek(a,b,c,N)<<endl;}return 0;}"
},
{
"code": null,
"e": 1458,
"s": 1456,
"text": "0"
},
{
"code": null,
"e": 1484,
"s": 1458,
"text": "Debojyoti Sinha1 year ago"
},
{
"code": null,
"e": 1500,
"s": 1484,
"text": "Debojyoti Sinha"
},
{
"code": null,
"e": 1549,
"s": 1500,
"text": "Correct Answer.Correct AnswerExecution Time:0.01"
},
{
"code": null,
"e": 2078,
"s": 1549,
"text": "#include <bits stdc++.h=\"\">using namespace std;int geekonacciNumber(int A, int B, int C, int N){ int D; for(int i = 4; i <= N; i++) { D = ((A + B) % 1000000007 + C ) % 1000000007; A = B; B = C; C = D; } return D;}int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int T; cin >> T; while(T--) { int A, B, C, N; cin >> A >> B >> C >> N; cout << geekonacciNumber(A, B, C, N) << \"\\n\"; } return 0;}"
},
{
"code": null,
"e": 2080,
"s": 2078,
"text": "0"
},
{
"code": null,
"e": 2103,
"s": 2080,
"text": "Rahul sharma1 year ago"
},
{
"code": null,
"e": 2116,
"s": 2103,
"text": "Rahul sharma"
},
{
"code": null,
"e": 2118,
"s": 2116,
"text": "0"
},
{
"code": null,
"e": 2131,
"s": 2118,
"text": "Rahul sharma"
},
{
"code": null,
"e": 2157,
"s": 2131,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2159,
"s": 2157,
"text": "0"
},
{
"code": null,
"e": 2172,
"s": 2159,
"text": "Rahul sharma"
},
{
"code": null,
"e": 2198,
"s": 2172,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2344,
"s": 2198,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 2380,
"s": 2344,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2390,
"s": 2380,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2400,
"s": 2390,
"text": "\nContest\n"
},
{
"code": null,
"e": 2463,
"s": 2400,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2611,
"s": 2463,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 2819,
"s": 2611,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 2925,
"s": 2819,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Convert from String to float in Java
|
To convert String to float, use the valueOf() method.
Let’s say we have the following string value.
String str = "0.8";
Converting the string to float.
Float floatVal = Float.valueOf(str).floatValue();
The following is the complete example.
Live Demo
public class Demo {
public static void main(String args[]) {
String str = "0.8";
Float floatVal = Float.valueOf(str).floatValue();
System.out.println("Float: "+floatVal);
}
}
Float: 0.8
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "To convert String to float, use the valueOf() method."
},
{
"code": null,
"e": 1162,
"s": 1116,
"text": "Let’s say we have the following string value."
},
{
"code": null,
"e": 1182,
"s": 1162,
"text": "String str = \"0.8\";"
},
{
"code": null,
"e": 1214,
"s": 1182,
"text": "Converting the string to float."
},
{
"code": null,
"e": 1264,
"s": 1214,
"text": "Float floatVal = Float.valueOf(str).floatValue();"
},
{
"code": null,
"e": 1303,
"s": 1264,
"text": "The following is the complete example."
},
{
"code": null,
"e": 1314,
"s": 1303,
"text": " Live Demo"
},
{
"code": null,
"e": 1513,
"s": 1314,
"text": "public class Demo {\n public static void main(String args[]) {\n String str = \"0.8\";\n Float floatVal = Float.valueOf(str).floatValue();\n System.out.println(\"Float: \"+floatVal);\n }\n}"
},
{
"code": null,
"e": 1524,
"s": 1513,
"text": "Float: 0.8"
}
] |
Introduction to the Hurst exponent — with code in Python | by Eryk Lewinson | Towards Data Science
|
In finance, some of the most commonly used trading strategies are based on momentum and mean-reversion. I will try to provide a quick explanation of the two.
In momentum-based strategies, the investors try to capitalize on the continuance of the existing market trend. For example, in the last period of interest, a certain company was doing well and the stock price was steadily rising over time. In such a case, the investors might make a bet that the price will continue to rise and thus enter a long position. Or vice versa for a short position. Naturally, the strategies are not that simple and the entry and exit decisions are most often made based on a series of technical indicators.
Mean-reversion assumes that properties such as stock returns and volatility will revert to their long-term average over time. Mathematically, such a time series is referred to as an Ornstein-Uhlenbeck process. In such strategies, investors try to make money by assuming that after some extreme events (either positive or negative), the stock price will revert to the long-term pattern.
We can quite easily identify those two patterns on the plot depicting the stock price evolution over time. However, when building automatic trading strategies it is not feasible to go over each and every stock manually and decide which pattern is visible on the plot. That is why we need to use some sort of an automated approach to determining which of the two patterns we can observe in the given stock price.
In this article, I will present how to use the Hurst exponent to identify if a given time series (not only financial time series such as stock price or returns) is trending, mean-reverting, or simply a random walk.
We can use the Hurst exponent (H) as a measure for long-term memory of a time series, that is, to measure the amount by which that series deviates from a random walk. The scalar represents the relative tendency of a time series either to regress strongly to the mean (mean-reverting pattern) or to cluster in a certain direction (trending pattern).
The values of the Hurst exponent range between 0 and 1. Based on the value of H, we can classify any time series into one of the three categories:
H < 0.5 — a mean-reverting (anti-persistent) series. The closer the value is to 0, the stronger the mean-reversion process is. In practice, it means that a high value is followed by a low value and vice-versa.
H = 0.5 — a geometric random walk.
H > 0.5 — a trending (persistent) series. The closer the value is to 1, the stronger the trend. In practice, it means that a high value is followed by a higher one.
There are at least a few methods of calculating the Hurst exponent. Unfortunately, they do not always agree on the conclusion (you can see an example of such a case here).
In this article, I will only show the simplest implementation, which is based on estimating the rate of the diffusive behavior based on the variance of log prices.
First, let’s define x as the logarithm of stock prices S.
The variance for an arbitrary lag (denoted by τ) can be expressed as:
If the stock prices follow a geometric Brownian motion (GBM, random walk), the variance would vary linearly with the lag τ:
However, the stock prices do not always follow a GBM. In cases of deviations from a random walk (so when some form of autocorrelation exists), the variance for a given lag is no longer proportional to the lag itself, but it gains an anomalous exponent. The new relationship looks as follows:
Where H again stands for the Hurst exponent.
Another possible approach to calculating the Hurst exponent is based on the rescaled range (R/S) analysis. To keep the article brief, I will not describe all the required steps here, but will refer you to a step-by-step instruction. It was shown in the literature that using the R/S statistic leads to superior results as compared to other methods such as the analysis of autocorrelations, variance ratios, etc. However, it also has a shortcoming of being very sensitive to short-range dependence.
As always, we need to import some libraries first. This time, however, we will not rely entirely on a library, but create a function for calculating the Hurst exponent ourselves.
Then, we prepare the data. As a real-life example, we will use 10 years’ worth of historical prices of S&P 500. We can easily download the prices using the yfinance library. If you are interested in more details on the library, please check out my other article.
We will also generate some artificial data to reflect all three cases which the Hurst exponent can identify: mean-reverting, random walk, and trending. We do so in the following snippet.
I would say the series clearly show the patterns we wanted them to show. Maybe the trending one is a bit of an overkill, but at the very least it should be easy to correctly classify.
The next step is to define a function used for calculating the Hurst exponent.
To calculate the Hurst exponent, we first calculate the standard deviation of the differences between a series and its lagged version, for a range of possible lags. We then estimate the Hurst exponent as the slope of the log-log plot of the number of lags versus the mentioned standard deviations.
The number of lags is somewhat arbitrary. The default value of 20 is based on Matlab’s implementation of the Hurst function. However, it is reported in the literature that if we set the number of lags too high, the results might be inaccurate. We will investigate that soon enough.
Let’s start with the S&P 500 data. In general, we can see on the plot that the series is trending — with some exceptions, the overall trend is positive. We calculate the Hurst exponent using a selection of max lag values to see how it impacts the value of the exponent.
With the default value of 20, the S&P 500 series seems to be lightly mean-reverting. As we increase the number of lags, the mean-reversion is only stronger (the value of the exponent decreases towards 0).
Hurst exponent with 20 lags: 0.4394 Hurst exponent with 100 lags: 0.3834 Hurst exponent with 300 lags: 0.3257 Hurst exponent with 500 lags: 0.3231 Hurst exponent with 1000 lags: 0.1795
Please bear in mind that those values are obtained for the 10-year series. If we narrow it down to a certain time period, the conclusions could be vastly different! This is also something to remember while using the Hurst exponent in practice.
Now it is time to repeat the exercise for the artificially generated series. Let’s see if the conclusions based on the Hurst exponent will match the expectations.
Hurst exponents with 20 lags ---- mean_rev: 0.0064 gbm: 0.4539 trending: 0.8715 Hurst exponents with 100 lags ---- mean_rev: -0.0021 gbm: 0.5401 trending: 0.8442 Hurst exponents with 300 lags ---- mean_rev: 0.0002 gbm: 0.5691 trending: 0.7463 Hurst exponents with 500 lags ---- mean_rev: 0.0015 gbm: 0.4854 trending: 0.6662
The conclusions for the mean-reverting series are most consistent over all the values of the lags. We should just note that the negative value for the maximum lag of 100 is probably due to some approximations and by design, it should stop at 0.
For the random walk series, the value of the exponent oscillates around the intended 0.5.
Lastly, the trending series is correctly identified by the Hurst exponent for all the selected lags, however, as we increase the lag the value of the exponent decreases toward 0.5, which would indicate a random walk.
We can conclude that overall the results are close enough to the initial expectations, however, the maximum value of the lags we consider can impact our conclusions. This analysis shows that a given series can be neither purely mean-reverting nor trending. The state of the regime depends on whether we are looking at shorter or longer-term (by looking at a different range of lags). That is why it’s best to get some feeling for working with the Hurst exponent before actually trying to create trading strategies based on it.
Lastly, as mentioned before, there are quite a few ways to calculate the Hurst exponent. For an implementation of the Hurst exponent based on the rescaled range (R/S) analysis, you can check out the hurst library (repository). I have not used it in this article, as the library is not in active development (the last update was 2 years ago). However, you can definitely give it a go.
the Hurst exponent is a measure of the memory in a time series and is used to classify the series as mean-reverting, trending, or a random walk.
depending on the choice of the maximum lag parameter (i.e., whether we are looking are short or long term), the results can differ significantly.
there are a few ways to calculate the Hurst exponent, the two most popular ones are based on anomalous diffusion and rescaled range analysis.
You can find the code used for this article on my GitHub. Also, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments.
Disclaimer: Affiliate link ahead
I have recently encountered the Hurst exponent while going through a MOOC on momentum-based trading strategies. Quantra is a platform that offers interactive courses with a focus on Python for Quantitative Finance. I wrote a short article showcasing some of the platform’s features and describing my personal experience.
If you liked this article, you might also be interested in one of the following:
towardsdatascience.com
towardsdatascience.com
Kroha, P., & Skoula, M. (2018, March). Hurst Exponent and Trading Signals Derived from Market Time Series. In ICEIS (1) (pp. 371–378).
Hurst, H. E. (1951). Long term storage capacity of reservoirs. ASCE Transactions, 116(776), 770–808.
|
[
{
"code": null,
"e": 330,
"s": 172,
"text": "In finance, some of the most commonly used trading strategies are based on momentum and mean-reversion. I will try to provide a quick explanation of the two."
},
{
"code": null,
"e": 864,
"s": 330,
"text": "In momentum-based strategies, the investors try to capitalize on the continuance of the existing market trend. For example, in the last period of interest, a certain company was doing well and the stock price was steadily rising over time. In such a case, the investors might make a bet that the price will continue to rise and thus enter a long position. Or vice versa for a short position. Naturally, the strategies are not that simple and the entry and exit decisions are most often made based on a series of technical indicators."
},
{
"code": null,
"e": 1250,
"s": 864,
"text": "Mean-reversion assumes that properties such as stock returns and volatility will revert to their long-term average over time. Mathematically, such a time series is referred to as an Ornstein-Uhlenbeck process. In such strategies, investors try to make money by assuming that after some extreme events (either positive or negative), the stock price will revert to the long-term pattern."
},
{
"code": null,
"e": 1662,
"s": 1250,
"text": "We can quite easily identify those two patterns on the plot depicting the stock price evolution over time. However, when building automatic trading strategies it is not feasible to go over each and every stock manually and decide which pattern is visible on the plot. That is why we need to use some sort of an automated approach to determining which of the two patterns we can observe in the given stock price."
},
{
"code": null,
"e": 1877,
"s": 1662,
"text": "In this article, I will present how to use the Hurst exponent to identify if a given time series (not only financial time series such as stock price or returns) is trending, mean-reverting, or simply a random walk."
},
{
"code": null,
"e": 2226,
"s": 1877,
"text": "We can use the Hurst exponent (H) as a measure for long-term memory of a time series, that is, to measure the amount by which that series deviates from a random walk. The scalar represents the relative tendency of a time series either to regress strongly to the mean (mean-reverting pattern) or to cluster in a certain direction (trending pattern)."
},
{
"code": null,
"e": 2373,
"s": 2226,
"text": "The values of the Hurst exponent range between 0 and 1. Based on the value of H, we can classify any time series into one of the three categories:"
},
{
"code": null,
"e": 2583,
"s": 2373,
"text": "H < 0.5 — a mean-reverting (anti-persistent) series. The closer the value is to 0, the stronger the mean-reversion process is. In practice, it means that a high value is followed by a low value and vice-versa."
},
{
"code": null,
"e": 2618,
"s": 2583,
"text": "H = 0.5 — a geometric random walk."
},
{
"code": null,
"e": 2783,
"s": 2618,
"text": "H > 0.5 — a trending (persistent) series. The closer the value is to 1, the stronger the trend. In practice, it means that a high value is followed by a higher one."
},
{
"code": null,
"e": 2955,
"s": 2783,
"text": "There are at least a few methods of calculating the Hurst exponent. Unfortunately, they do not always agree on the conclusion (you can see an example of such a case here)."
},
{
"code": null,
"e": 3119,
"s": 2955,
"text": "In this article, I will only show the simplest implementation, which is based on estimating the rate of the diffusive behavior based on the variance of log prices."
},
{
"code": null,
"e": 3177,
"s": 3119,
"text": "First, let’s define x as the logarithm of stock prices S."
},
{
"code": null,
"e": 3247,
"s": 3177,
"text": "The variance for an arbitrary lag (denoted by τ) can be expressed as:"
},
{
"code": null,
"e": 3371,
"s": 3247,
"text": "If the stock prices follow a geometric Brownian motion (GBM, random walk), the variance would vary linearly with the lag τ:"
},
{
"code": null,
"e": 3663,
"s": 3371,
"text": "However, the stock prices do not always follow a GBM. In cases of deviations from a random walk (so when some form of autocorrelation exists), the variance for a given lag is no longer proportional to the lag itself, but it gains an anomalous exponent. The new relationship looks as follows:"
},
{
"code": null,
"e": 3708,
"s": 3663,
"text": "Where H again stands for the Hurst exponent."
},
{
"code": null,
"e": 4206,
"s": 3708,
"text": "Another possible approach to calculating the Hurst exponent is based on the rescaled range (R/S) analysis. To keep the article brief, I will not describe all the required steps here, but will refer you to a step-by-step instruction. It was shown in the literature that using the R/S statistic leads to superior results as compared to other methods such as the analysis of autocorrelations, variance ratios, etc. However, it also has a shortcoming of being very sensitive to short-range dependence."
},
{
"code": null,
"e": 4385,
"s": 4206,
"text": "As always, we need to import some libraries first. This time, however, we will not rely entirely on a library, but create a function for calculating the Hurst exponent ourselves."
},
{
"code": null,
"e": 4648,
"s": 4385,
"text": "Then, we prepare the data. As a real-life example, we will use 10 years’ worth of historical prices of S&P 500. We can easily download the prices using the yfinance library. If you are interested in more details on the library, please check out my other article."
},
{
"code": null,
"e": 4835,
"s": 4648,
"text": "We will also generate some artificial data to reflect all three cases which the Hurst exponent can identify: mean-reverting, random walk, and trending. We do so in the following snippet."
},
{
"code": null,
"e": 5019,
"s": 4835,
"text": "I would say the series clearly show the patterns we wanted them to show. Maybe the trending one is a bit of an overkill, but at the very least it should be easy to correctly classify."
},
{
"code": null,
"e": 5098,
"s": 5019,
"text": "The next step is to define a function used for calculating the Hurst exponent."
},
{
"code": null,
"e": 5396,
"s": 5098,
"text": "To calculate the Hurst exponent, we first calculate the standard deviation of the differences between a series and its lagged version, for a range of possible lags. We then estimate the Hurst exponent as the slope of the log-log plot of the number of lags versus the mentioned standard deviations."
},
{
"code": null,
"e": 5678,
"s": 5396,
"text": "The number of lags is somewhat arbitrary. The default value of 20 is based on Matlab’s implementation of the Hurst function. However, it is reported in the literature that if we set the number of lags too high, the results might be inaccurate. We will investigate that soon enough."
},
{
"code": null,
"e": 5948,
"s": 5678,
"text": "Let’s start with the S&P 500 data. In general, we can see on the plot that the series is trending — with some exceptions, the overall trend is positive. We calculate the Hurst exponent using a selection of max lag values to see how it impacts the value of the exponent."
},
{
"code": null,
"e": 6153,
"s": 5948,
"text": "With the default value of 20, the S&P 500 series seems to be lightly mean-reverting. As we increase the number of lags, the mean-reversion is only stronger (the value of the exponent decreases towards 0)."
},
{
"code": null,
"e": 6338,
"s": 6153,
"text": "Hurst exponent with 20 lags: 0.4394 Hurst exponent with 100 lags: 0.3834 Hurst exponent with 300 lags: 0.3257 Hurst exponent with 500 lags: 0.3231 Hurst exponent with 1000 lags: 0.1795"
},
{
"code": null,
"e": 6582,
"s": 6338,
"text": "Please bear in mind that those values are obtained for the 10-year series. If we narrow it down to a certain time period, the conclusions could be vastly different! This is also something to remember while using the Hurst exponent in practice."
},
{
"code": null,
"e": 6745,
"s": 6582,
"text": "Now it is time to repeat the exercise for the artificially generated series. Let’s see if the conclusions based on the Hurst exponent will match the expectations."
},
{
"code": null,
"e": 7069,
"s": 6745,
"text": "Hurst exponents with 20 lags ---- mean_rev: 0.0064 gbm: 0.4539 trending: 0.8715 Hurst exponents with 100 lags ---- mean_rev: -0.0021 gbm: 0.5401 trending: 0.8442 Hurst exponents with 300 lags ---- mean_rev: 0.0002 gbm: 0.5691 trending: 0.7463 Hurst exponents with 500 lags ---- mean_rev: 0.0015 gbm: 0.4854 trending: 0.6662"
},
{
"code": null,
"e": 7314,
"s": 7069,
"text": "The conclusions for the mean-reverting series are most consistent over all the values of the lags. We should just note that the negative value for the maximum lag of 100 is probably due to some approximations and by design, it should stop at 0."
},
{
"code": null,
"e": 7404,
"s": 7314,
"text": "For the random walk series, the value of the exponent oscillates around the intended 0.5."
},
{
"code": null,
"e": 7621,
"s": 7404,
"text": "Lastly, the trending series is correctly identified by the Hurst exponent for all the selected lags, however, as we increase the lag the value of the exponent decreases toward 0.5, which would indicate a random walk."
},
{
"code": null,
"e": 8148,
"s": 7621,
"text": "We can conclude that overall the results are close enough to the initial expectations, however, the maximum value of the lags we consider can impact our conclusions. This analysis shows that a given series can be neither purely mean-reverting nor trending. The state of the regime depends on whether we are looking at shorter or longer-term (by looking at a different range of lags). That is why it’s best to get some feeling for working with the Hurst exponent before actually trying to create trading strategies based on it."
},
{
"code": null,
"e": 8532,
"s": 8148,
"text": "Lastly, as mentioned before, there are quite a few ways to calculate the Hurst exponent. For an implementation of the Hurst exponent based on the rescaled range (R/S) analysis, you can check out the hurst library (repository). I have not used it in this article, as the library is not in active development (the last update was 2 years ago). However, you can definitely give it a go."
},
{
"code": null,
"e": 8677,
"s": 8532,
"text": "the Hurst exponent is a measure of the memory in a time series and is used to classify the series as mean-reverting, trending, or a random walk."
},
{
"code": null,
"e": 8823,
"s": 8677,
"text": "depending on the choice of the maximum lag parameter (i.e., whether we are looking are short or long term), the results can differ significantly."
},
{
"code": null,
"e": 8965,
"s": 8823,
"text": "there are a few ways to calculate the Hurst exponent, the two most popular ones are based on anomalous diffusion and rescaled range analysis."
},
{
"code": null,
"e": 9122,
"s": 8965,
"text": "You can find the code used for this article on my GitHub. Also, any constructive feedback is welcome. You can reach out to me on Twitter or in the comments."
},
{
"code": null,
"e": 9155,
"s": 9122,
"text": "Disclaimer: Affiliate link ahead"
},
{
"code": null,
"e": 9476,
"s": 9155,
"text": "I have recently encountered the Hurst exponent while going through a MOOC on momentum-based trading strategies. Quantra is a platform that offers interactive courses with a focus on Python for Quantitative Finance. I wrote a short article showcasing some of the platform’s features and describing my personal experience."
},
{
"code": null,
"e": 9557,
"s": 9476,
"text": "If you liked this article, you might also be interested in one of the following:"
},
{
"code": null,
"e": 9580,
"s": 9557,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9603,
"s": 9580,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9738,
"s": 9603,
"text": "Kroha, P., & Skoula, M. (2018, March). Hurst Exponent and Trading Signals Derived from Market Time Series. In ICEIS (1) (pp. 371–378)."
}
] |
Count of total anagram substrings - GeeksforGeeks
|
29 Apr, 2020
Given a string of lower alphabet characters, count total substring of this string which are anagram to each other.
Examples:
Input : str = “xyyx”
Output : 4
Total substrings of this string which
are anagram to each other are 4 which
can be enumerated as,
{“x”, “x”}, {"y", "y"}, {“xy”, “yx”},
{“xyy”, “yyx”}
Input : str = "geeg"
Output : 4
The idea is to create a map. We use character frequencies as keys and corresponding counts as values. We can solve this problem by iterating over all substrings and counting frequencies of characters in every substring. We can update frequencies of characters while looping over substrings i.e. there won’t be an extra loop for counting frequency of characters.In below code, a map of key ‘vector type’ and value ‘int type’ is taken for storing occurrence of ‘frequency array of length 26’ of substring characters. Once occurrence ‘o’ of each frequency array is stored, total anagrams will be the sum of o*(o-1)/2 for all different frequency arrays because if a particular substring has ‘o’ anagrams in string total o*(o-1)/2 anagram pairs can be formed.
Below is the implementation of above idea.
C++
Java
Python3
C#
// C++ program to count total anagram// substring of a string#include <bits/stdc++.h>using namespace std; // Total number of lowercase characters#define MAX_CHAR 26 // Utility method to return integer index// of character 'c'int toNum(char c){ return (c - 'a');} // Returns count of total number of anagram// substrings of string strint countOfAnagramSubstring(string str){ int N = str.length(); // To store counts of substrings with given // set of frequencies. map<vector<int>, int> mp; // loop for starting index of substring for (int i=0; i<N; i++) { vector<int> freq(MAX_CHAR, 0); // loop for length of substring for (int j=i; j<N; j++) { // update freq array of current // substring freq[toNum(str[j])]++; // increase count corresponding // to this freq array mp[freq]++; } } // loop over all different freq array and // aggregate substring count int result = 0; for (auto it=mp.begin(); it!=mp.end(); it++) { int freq = it->second; result += ((freq) * (freq-1))/2; } return result;} // Driver code to test above methodsint main(){ string str = "xyyx"; cout << countOfAnagramSubstring(str) << endl; return 0;}
import java.util.Arrays;import java.util.HashMap; public class anagramPairCount { public static void main(String[] args) { subString("kkkk"); } static void subString(String s){ HashMap<String, Integer> map= new HashMap<>(); for(int i = 0; i < s.length(); i++){ for(int j = i; j < s.length(); j++){ char[] valC = s.substring(i, j+1).toCharArray(); Arrays.sort(valC); String val = new String(valC); if (map.containsKey(val)) map.put(val, map.get(val)+1); else map.put(val, 1); } } int anagramPairCount = 0; for(String key: map.keySet()){ int n = map.get(key); anagramPairCount += (n * (n-1))/2; } System.out.println(anagramPairCount); }}
# Python3 program to count total anagram# substring of a stringdef countOfAnagramSubstring(s): # Returns total number of anagram # substrings in s n = len(s) mp = dict() # loop for length of substring for i in range(n): sb = '' for j in range(i, n): sb = ''.join(sorted(sb + s[j])) mp[sb] = mp.get(sb, 0) # increase count corresponding # to this dict array mp[sb] += 1 anas = 0 # loop over all different dictionary # items and aggregate substring count for k, v in mp.items(): anas += (v*(v-1))//2 return anas # Driver Codes = "xyyx"print(countOfAnagramSubstring(s)) # This code is contributed by fgaim
using System;using System.Collections.Generic; public class anagramPairCount { public static void Main() { subString("kkkk"); } static void subString(String s){ Dictionary<string, int> map= new Dictionary<string, int>(); for(int i = 0; i < s.Length; i++){ for(int j = i; j < s.Length; j++){ char[] valC = s.Substring(i, j+1-i).ToCharArray(); Array.Sort(valC); string val = new string(valC); if (map.ContainsKey(val)) map[val]=map[val]+1; else map.Add(val, 1); } } int anagramPairCount = 0; foreach(string key in map.Keys){ int n = map[key]; anagramPairCount += (n * (n-1))/2; } Console.Write(anagramPairCount); }} // This code is contributed by AbhiThakur
4
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
hacker1
ManojKumar120
abhaysingh290895
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python program to check if a string is palindrome or not
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different methods to reverse a string in C/C++
KMP Algorithm for Pattern Searching
Convert string to char array in C++
Array of Strings in C++ (5 Different Ways to Create)
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Reverse words in a given string
Length of the longest substring without repeating characters
|
[
{
"code": null,
"e": 24647,
"s": 24619,
"text": "\n29 Apr, 2020"
},
{
"code": null,
"e": 24762,
"s": 24647,
"text": "Given a string of lower alphabet characters, count total substring of this string which are anagram to each other."
},
{
"code": null,
"e": 24772,
"s": 24762,
"text": "Examples:"
},
{
"code": null,
"e": 24993,
"s": 24772,
"text": "Input : str = “xyyx”\nOutput : 4\nTotal substrings of this string which\nare anagram to each other are 4 which \ncan be enumerated as,\n{“x”, “x”}, {\"y\", \"y\"}, {“xy”, “yx”}, \n{“xyy”, “yyx”}\n\nInput : str = \"geeg\"\nOutput : 4\n"
},
{
"code": null,
"e": 25748,
"s": 24993,
"text": "The idea is to create a map. We use character frequencies as keys and corresponding counts as values. We can solve this problem by iterating over all substrings and counting frequencies of characters in every substring. We can update frequencies of characters while looping over substrings i.e. there won’t be an extra loop for counting frequency of characters.In below code, a map of key ‘vector type’ and value ‘int type’ is taken for storing occurrence of ‘frequency array of length 26’ of substring characters. Once occurrence ‘o’ of each frequency array is stored, total anagrams will be the sum of o*(o-1)/2 for all different frequency arrays because if a particular substring has ‘o’ anagrams in string total o*(o-1)/2 anagram pairs can be formed."
},
{
"code": null,
"e": 25791,
"s": 25748,
"text": "Below is the implementation of above idea."
},
{
"code": null,
"e": 25795,
"s": 25791,
"text": "C++"
},
{
"code": null,
"e": 25800,
"s": 25795,
"text": "Java"
},
{
"code": null,
"e": 25808,
"s": 25800,
"text": "Python3"
},
{
"code": null,
"e": 25811,
"s": 25808,
"text": "C#"
},
{
"code": "// C++ program to count total anagram// substring of a string#include <bits/stdc++.h>using namespace std; // Total number of lowercase characters#define MAX_CHAR 26 // Utility method to return integer index// of character 'c'int toNum(char c){ return (c - 'a');} // Returns count of total number of anagram// substrings of string strint countOfAnagramSubstring(string str){ int N = str.length(); // To store counts of substrings with given // set of frequencies. map<vector<int>, int> mp; // loop for starting index of substring for (int i=0; i<N; i++) { vector<int> freq(MAX_CHAR, 0); // loop for length of substring for (int j=i; j<N; j++) { // update freq array of current // substring freq[toNum(str[j])]++; // increase count corresponding // to this freq array mp[freq]++; } } // loop over all different freq array and // aggregate substring count int result = 0; for (auto it=mp.begin(); it!=mp.end(); it++) { int freq = it->second; result += ((freq) * (freq-1))/2; } return result;} // Driver code to test above methodsint main(){ string str = \"xyyx\"; cout << countOfAnagramSubstring(str) << endl; return 0;}",
"e": 27114,
"s": 25811,
"text": null
},
{
"code": "import java.util.Arrays;import java.util.HashMap; public class anagramPairCount { public static void main(String[] args) { subString(\"kkkk\"); } static void subString(String s){ HashMap<String, Integer> map= new HashMap<>(); for(int i = 0; i < s.length(); i++){ for(int j = i; j < s.length(); j++){ char[] valC = s.substring(i, j+1).toCharArray(); Arrays.sort(valC); String val = new String(valC); if (map.containsKey(val)) map.put(val, map.get(val)+1); else map.put(val, 1); } } int anagramPairCount = 0; for(String key: map.keySet()){ int n = map.get(key); anagramPairCount += (n * (n-1))/2; } System.out.println(anagramPairCount); }}",
"e": 27982,
"s": 27114,
"text": null
},
{
"code": "# Python3 program to count total anagram# substring of a stringdef countOfAnagramSubstring(s): # Returns total number of anagram # substrings in s n = len(s) mp = dict() # loop for length of substring for i in range(n): sb = '' for j in range(i, n): sb = ''.join(sorted(sb + s[j])) mp[sb] = mp.get(sb, 0) # increase count corresponding # to this dict array mp[sb] += 1 anas = 0 # loop over all different dictionary # items and aggregate substring count for k, v in mp.items(): anas += (v*(v-1))//2 return anas # Driver Codes = \"xyyx\"print(countOfAnagramSubstring(s)) # This code is contributed by fgaim",
"e": 28731,
"s": 27982,
"text": null
},
{
"code": "using System;using System.Collections.Generic; public class anagramPairCount { public static void Main() { subString(\"kkkk\"); } static void subString(String s){ Dictionary<string, int> map= new Dictionary<string, int>(); for(int i = 0; i < s.Length; i++){ for(int j = i; j < s.Length; j++){ char[] valC = s.Substring(i, j+1-i).ToCharArray(); Array.Sort(valC); string val = new string(valC); if (map.ContainsKey(val)) map[val]=map[val]+1; else map.Add(val, 1); } } int anagramPairCount = 0; foreach(string key in map.Keys){ int n = map[key]; anagramPairCount += (n * (n-1))/2; } Console.Write(anagramPairCount); }} // This code is contributed by AbhiThakur",
"e": 29621,
"s": 28731,
"text": null
},
{
"code": null,
"e": 29624,
"s": 29621,
"text": "4\n"
},
{
"code": null,
"e": 29927,
"s": 29624,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30052,
"s": 29927,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30060,
"s": 30052,
"text": "hacker1"
},
{
"code": null,
"e": 30074,
"s": 30060,
"text": "ManojKumar120"
},
{
"code": null,
"e": 30091,
"s": 30074,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 30099,
"s": 30091,
"text": "Strings"
},
{
"code": null,
"e": 30107,
"s": 30099,
"text": "Strings"
},
{
"code": null,
"e": 30205,
"s": 30107,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30214,
"s": 30205,
"text": "Comments"
},
{
"code": null,
"e": 30227,
"s": 30214,
"text": "Old Comments"
},
{
"code": null,
"e": 30284,
"s": 30227,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 30359,
"s": 30284,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 30406,
"s": 30359,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 30442,
"s": 30406,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 30478,
"s": 30442,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 30531,
"s": 30478,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 30569,
"s": 30531,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 30599,
"s": 30569,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 30631,
"s": 30599,
"text": "Reverse words in a given string"
}
] |
Calculate volume and surface area of Torus - GeeksforGeeks
|
06 Sep, 2021
This article is about the surface and mathematical concept of a torus. A 3D shape made by revolving a small circle (radius r) along a line made by a bigger circle (radius R).
Torus
Property:
It can be made by revolving a small circle (radius r) along a line made by a bigger circle (radius R).It is not a polyhedronIt has no vertices or edges
It can be made by revolving a small circle (radius r) along a line made by a bigger circle (radius R).
It is not a polyhedron
It has no vertices or edges
Surface Area The surface area of a Torus is given by the formula –
Surface Area = 4 × Pi^2 × R × r
Where r is the radius of the small circle and R is the radius of bigger circle and Pi is constant Pi=3.14159.
Volume The volume of a cone is given by the formula –
Volume = 2 × Pi^2 × R × r^2
Where r is the radius of the small circle and R is the radius of bigger circle and Pi is constant Pi=3.14159.
Examples:
Input : r=3, R=7
Output :
Volume: 1243.568195
Surface: 829.045464
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to calculate volume// and surface area of Torus#include<bits/stdc++.h>using namespace std; int main(){ // radius of inner circle double r = 3; // distance from origin to center of inner circle // radius of black circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; cout<<"Volume: "<<Volume<<endl; double Surface = 4 * pi * pi * R * r; cout<<"Surface: "<<Surface<<endl;}
// C program to calculate volume // and surface area of Torus#include <stdio.h>int main(){ // radius of inner circle double r = 3; // distance from origin to center of inner circle // radius of black circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; printf("Volume: %f", Volume); double Surface = 4 * pi * pi * R * r; printf("\nSurface: %f", Surface);}
// Java program to calculate volume // and surface area of Torusclass Test { public static void main(String args[]) { // radius of inner circle double r = 3; // distance from origin to center of inner circle // radius of black circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; System.out.printf("Volume: %f", Volume); double Surface = 4 * pi * pi * R * r; System.out.printf("\nSurface: %f", Surface); }}
# Python3 program to calculate volume# and surface area of Torus# radius of inner circler = 3 # distance from origin to center of inner circle# radius of black circle in figureR = 7 # Value of Pipi = 3.14159Volume = (float)(2 * pi * pi * R * r * r);print("Volume: ", Volume);Surface = (float)(4 * pi * pi * R * r);print("Surface: ", Surface);
// C# program to calculate volume // and surface area of Torus using System; class GFG { // Driver Codepublic static void Main() { // radius of inner circle double r = 3; // distance from origin to center // of inner circle radius of black // circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; Console.WriteLine("Volume: {0}", Volume); double Surface = 4 * pi * pi * R * r; Console.WriteLine("Surface: {0}", Surface); } } // This code is contributed by Soumik
<?php// PHP program to calculate volume // and surface area of Torus // radius of inner circle $r = 3; // distance from origin to center // of inner circle radius of black// circle in figure $R = 7; // Value of Pi $pi = (float)3.14159; $Volume = 0; $Volume = 2 * $pi * $pi * $R * $r * $r; echo "Volume: ", $Volume, "\n"; $Surface = 4 * $pi * $pi * $R * $r; echo "Surface: ", $Surface, "\n"; // This code is contributed by ajit?>
<script> // Javascript program to calculate volume// and surface area of Torus // radius of inner circlevar r = 3; // distance from origin to center of inner circle// radius of black circle in figurevar R = 7; // Value of Pivar pi = 3.14159;var Volume = 0;Volume = 2 * pi * pi * R * r * r;document.write("Volume: " + Volume + "<br>"); var Surface = 4 * pi * pi * R * r;document.write("Surface: " + Surface); </script>
Volume: 1243.568195
Surface: 829.045464
SURENDRA_GANGWAR
SoumikMondal
jit_t
rrrtnx
rs1686740
area-volume-programs
Technical Scripter 2018
Mathematical
Technical Scripter
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Find all factors of a natural number | Set 1
Check if a number is Palindrome
Program to print prime numbers from 1 to N.
Program to add two binary strings
Program to multiply two matrices
Fizz Buzz Implementation
Find pair with maximum GCD in an array
Find Union and Intersection of two unsorted arrays
Count all possible paths from top left to bottom right of a mXn matrix
Count ways to reach the n'th stair
|
[
{
"code": null,
"e": 24301,
"s": 24273,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 24478,
"s": 24301,
"text": "This article is about the surface and mathematical concept of a torus. A 3D shape made by revolving a small circle (radius r) along a line made by a bigger circle (radius R). "
},
{
"code": null,
"e": 24484,
"s": 24478,
"text": "Torus"
},
{
"code": null,
"e": 24494,
"s": 24484,
"text": "Property:"
},
{
"code": null,
"e": 24646,
"s": 24494,
"text": "It can be made by revolving a small circle (radius r) along a line made by a bigger circle (radius R).It is not a polyhedronIt has no vertices or edges"
},
{
"code": null,
"e": 24749,
"s": 24646,
"text": "It can be made by revolving a small circle (radius r) along a line made by a bigger circle (radius R)."
},
{
"code": null,
"e": 24772,
"s": 24749,
"text": "It is not a polyhedron"
},
{
"code": null,
"e": 24800,
"s": 24772,
"text": "It has no vertices or edges"
},
{
"code": null,
"e": 24867,
"s": 24800,
"text": "Surface Area The surface area of a Torus is given by the formula –"
},
{
"code": null,
"e": 24899,
"s": 24867,
"text": "Surface Area = 4 × Pi^2 × R × r"
},
{
"code": null,
"e": 25011,
"s": 24899,
"text": "Where r is the radius of the small circle and R is the radius of bigger circle and Pi is constant Pi=3.14159. "
},
{
"code": null,
"e": 25065,
"s": 25011,
"text": "Volume The volume of a cone is given by the formula –"
},
{
"code": null,
"e": 25093,
"s": 25065,
"text": "Volume = 2 × Pi^2 × R × r^2"
},
{
"code": null,
"e": 25203,
"s": 25093,
"text": "Where r is the radius of the small circle and R is the radius of bigger circle and Pi is constant Pi=3.14159."
},
{
"code": null,
"e": 25213,
"s": 25203,
"text": "Examples:"
},
{
"code": null,
"e": 25289,
"s": 25213,
"text": "Input : r=3, R=7\nOutput :\n Volume: 1243.568195\n Surface: 829.045464"
},
{
"code": null,
"e": 25295,
"s": 25291,
"text": "C++"
},
{
"code": null,
"e": 25297,
"s": 25295,
"text": "C"
},
{
"code": null,
"e": 25302,
"s": 25297,
"text": "Java"
},
{
"code": null,
"e": 25310,
"s": 25302,
"text": "Python3"
},
{
"code": null,
"e": 25313,
"s": 25310,
"text": "C#"
},
{
"code": null,
"e": 25317,
"s": 25313,
"text": "PHP"
},
{
"code": null,
"e": 25328,
"s": 25317,
"text": "Javascript"
},
{
"code": "// C++ program to calculate volume// and surface area of Torus#include<bits/stdc++.h>using namespace std; int main(){ // radius of inner circle double r = 3; // distance from origin to center of inner circle // radius of black circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; cout<<\"Volume: \"<<Volume<<endl; double Surface = 4 * pi * pi * R * r; cout<<\"Surface: \"<<Surface<<endl;}",
"e": 25829,
"s": 25328,
"text": null
},
{
"code": "// C program to calculate volume // and surface area of Torus#include <stdio.h>int main(){ // radius of inner circle double r = 3; // distance from origin to center of inner circle // radius of black circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; printf(\"Volume: %f\", Volume); double Surface = 4 * pi * pi * R * r; printf(\"\\nSurface: %f\", Surface);}",
"e": 26300,
"s": 25829,
"text": null
},
{
"code": "// Java program to calculate volume // and surface area of Torusclass Test { public static void main(String args[]) { // radius of inner circle double r = 3; // distance from origin to center of inner circle // radius of black circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; System.out.printf(\"Volume: %f\", Volume); double Surface = 4 * pi * pi * R * r; System.out.printf(\"\\nSurface: %f\", Surface); }}",
"e": 26883,
"s": 26300,
"text": null
},
{
"code": "# Python3 program to calculate volume# and surface area of Torus# radius of inner circler = 3 # distance from origin to center of inner circle# radius of black circle in figureR = 7 # Value of Pipi = 3.14159Volume = (float)(2 * pi * pi * R * r * r);print(\"Volume: \", Volume);Surface = (float)(4 * pi * pi * R * r);print(\"Surface: \", Surface);",
"e": 27228,
"s": 26883,
"text": null
},
{
"code": "// C# program to calculate volume // and surface area of Torus using System; class GFG { // Driver Codepublic static void Main() { // radius of inner circle double r = 3; // distance from origin to center // of inner circle radius of black // circle in figure double R = 7; // Value of Pi float pi = (float)3.14159; double Volume = 0; Volume = 2 * pi * pi * R * r * r; Console.WriteLine(\"Volume: {0}\", Volume); double Surface = 4 * pi * pi * R * r; Console.WriteLine(\"Surface: {0}\", Surface); } } // This code is contributed by Soumik",
"e": 27831,
"s": 27228,
"text": null
},
{
"code": "<?php// PHP program to calculate volume // and surface area of Torus // radius of inner circle $r = 3; // distance from origin to center // of inner circle radius of black// circle in figure $R = 7; // Value of Pi $pi = (float)3.14159; $Volume = 0; $Volume = 2 * $pi * $pi * $R * $r * $r; echo \"Volume: \", $Volume, \"\\n\"; $Surface = 4 * $pi * $pi * $R * $r; echo \"Surface: \", $Surface, \"\\n\"; // This code is contributed by ajit?>",
"e": 28278,
"s": 27831,
"text": null
},
{
"code": "<script> // Javascript program to calculate volume// and surface area of Torus // radius of inner circlevar r = 3; // distance from origin to center of inner circle// radius of black circle in figurevar R = 7; // Value of Pivar pi = 3.14159;var Volume = 0;Volume = 2 * pi * pi * R * r * r;document.write(\"Volume: \" + Volume + \"<br>\"); var Surface = 4 * pi * pi * R * r;document.write(\"Surface: \" + Surface); </script>",
"e": 28702,
"s": 28278,
"text": null
},
{
"code": null,
"e": 28742,
"s": 28702,
"text": "Volume: 1243.568195\nSurface: 829.045464"
},
{
"code": null,
"e": 28761,
"s": 28744,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 28774,
"s": 28761,
"text": "SoumikMondal"
},
{
"code": null,
"e": 28780,
"s": 28774,
"text": "jit_t"
},
{
"code": null,
"e": 28787,
"s": 28780,
"text": "rrrtnx"
},
{
"code": null,
"e": 28797,
"s": 28787,
"text": "rs1686740"
},
{
"code": null,
"e": 28818,
"s": 28797,
"text": "area-volume-programs"
},
{
"code": null,
"e": 28842,
"s": 28818,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 28855,
"s": 28842,
"text": "Mathematical"
},
{
"code": null,
"e": 28874,
"s": 28855,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28887,
"s": 28874,
"text": "Mathematical"
},
{
"code": null,
"e": 28985,
"s": 28887,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28994,
"s": 28985,
"text": "Comments"
},
{
"code": null,
"e": 29007,
"s": 28994,
"text": "Old Comments"
},
{
"code": null,
"e": 29052,
"s": 29007,
"text": "Find all factors of a natural number | Set 1"
},
{
"code": null,
"e": 29084,
"s": 29052,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 29128,
"s": 29084,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 29162,
"s": 29128,
"text": "Program to add two binary strings"
},
{
"code": null,
"e": 29195,
"s": 29162,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 29220,
"s": 29195,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 29259,
"s": 29220,
"text": "Find pair with maximum GCD in an array"
},
{
"code": null,
"e": 29310,
"s": 29259,
"text": "Find Union and Intersection of two unsorted arrays"
},
{
"code": null,
"e": 29381,
"s": 29310,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
}
] |
Android WebView in Kotlin - GeeksforGeeks
|
07 May, 2021
WebView is a view that is used to display web pages inside the app. It is used to turn the app into a web application. In this article let’s display the https://www.geeksforgeeks.org/ inside the Android Application using Kotlin.
Note: To implement Android WebView in Java please refer How to use WebView in Android using Java.
Class Hierarchy
kotlin.Any
android.view.View
android.view.ViewGroup
android.widget.AbsoluteLayout
android.webkit.WebView
Approach
Step 1: Create a new project
To create a new project in android studio please refer, how to Create/Start a New Project in Android Studio.
Step 2: Modify activity_main.xml
This is used to set the front end of the Application, we place the WebView in the front end.
XML
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Place Web-view on the Screen --> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"></WebView> </androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Modify MainActivity.kt
This is the back end of the Application, here we assign values to the views and actions to the views.
Kotlin
package com.example.webview_kotlin import android.os.Bundleimport android.webkit.WebViewClientimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // WebViewClient allows you to handle // onPageFinished and override Url loading. webView.webViewClient = WebViewClient() // this will load the url of the website webView.loadUrl("https://www.geeksforgeeks.org/") // this will enable the javascript settings webView.settings.javaScriptEnabled = true // if you want to enable zoom feature webView.settings.setSupportZoom(true) } // if you press Back button this code will work override fun onBackPressed() { // if your webview can go back it will go back if (webView.canGoBack()) webView.goBack() // if your webview cannot go back // it will exit the application else super.onBackPressed() }}
Step 4: Modify AndroidManifest.xml
In AndroidManifest.xml, one needs to include the below permission, in order to access the internet.
XML
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.webview_kotlin"> <!-- Give permission for app to access the Internet --> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application></manifest>
Output: Run on Emulator
When we run the application either on the Emulator or on the Android Smartphone we can see this as our output. Remember to turn on the internet on your device.
anikakapoor
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Broadcast Receiver in Android With Example
Android RecyclerView in Kotlin
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
Kotlin Setters and Getters
Kotlin Android Tutorial
How to Add and Customize Back Button of Action Bar in Android?
How to Change the Color of Status Bar in an Android App?
Kotlin Higher-Order Functions
How to Get Current Location in Android?
|
[
{
"code": null,
"e": 25812,
"s": 25784,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 26041,
"s": 25812,
"text": "WebView is a view that is used to display web pages inside the app. It is used to turn the app into a web application. In this article let’s display the https://www.geeksforgeeks.org/ inside the Android Application using Kotlin."
},
{
"code": null,
"e": 26139,
"s": 26041,
"text": "Note: To implement Android WebView in Java please refer How to use WebView in Android using Java."
},
{
"code": null,
"e": 26155,
"s": 26139,
"text": "Class Hierarchy"
},
{
"code": null,
"e": 26310,
"s": 26155,
"text": "kotlin.Any\n android.view.View\n android.view.ViewGroup\n android.widget.AbsoluteLayout\n android.webkit.WebView"
},
{
"code": null,
"e": 26320,
"s": 26310,
"text": "Approach "
},
{
"code": null,
"e": 26349,
"s": 26320,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 26460,
"s": 26351,
"text": "To create a new project in android studio please refer, how to Create/Start a New Project in Android Studio."
},
{
"code": null,
"e": 26495,
"s": 26462,
"text": "Step 2: Modify activity_main.xml"
},
{
"code": null,
"e": 26590,
"s": 26497,
"text": "This is used to set the front end of the Application, we place the WebView in the front end."
},
{
"code": null,
"e": 26596,
"s": 26592,
"text": "XML"
},
{
"code": "<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Place Web-view on the Screen --> <WebView android:id=\"@+id/webView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"></WebView> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 27110,
"s": 26596,
"text": null
},
{
"code": null,
"e": 27141,
"s": 27110,
"text": "Step 3: Modify MainActivity.kt"
},
{
"code": null,
"e": 27243,
"s": 27141,
"text": "This is the back end of the Application, here we assign values to the views and actions to the views."
},
{
"code": null,
"e": 27250,
"s": 27243,
"text": "Kotlin"
},
{
"code": "package com.example.webview_kotlin import android.os.Bundleimport android.webkit.WebViewClientimport androidx.appcompat.app.AppCompatActivityimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // WebViewClient allows you to handle // onPageFinished and override Url loading. webView.webViewClient = WebViewClient() // this will load the url of the website webView.loadUrl(\"https://www.geeksforgeeks.org/\") // this will enable the javascript settings webView.settings.javaScriptEnabled = true // if you want to enable zoom feature webView.settings.setSupportZoom(true) } // if you press Back button this code will work override fun onBackPressed() { // if your webview can go back it will go back if (webView.canGoBack()) webView.goBack() // if your webview cannot go back // it will exit the application else super.onBackPressed() }}",
"e": 28411,
"s": 27250,
"text": null
},
{
"code": null,
"e": 28446,
"s": 28411,
"text": "Step 4: Modify AndroidManifest.xml"
},
{
"code": null,
"e": 28546,
"s": 28446,
"text": "In AndroidManifest.xml, one needs to include the below permission, in order to access the internet."
},
{
"code": null,
"e": 28550,
"s": 28546,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.webview_kotlin\"> <!-- Give permission for app to access the Internet --> <uses-permission android:name=\"android.permission.INTERNET\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application></manifest>",
"e": 29363,
"s": 28550,
"text": null
},
{
"code": null,
"e": 29389,
"s": 29363,
"text": " Output: Run on Emulator "
},
{
"code": null,
"e": 29550,
"s": 29389,
"text": "When we run the application either on the Emulator or on the Android Smartphone we can see this as our output. Remember to turn on the internet on your device. "
},
{
"code": null,
"e": 29566,
"s": 29554,
"text": "anikakapoor"
},
{
"code": null,
"e": 29573,
"s": 29566,
"text": "Picked"
},
{
"code": null,
"e": 29580,
"s": 29573,
"text": "Kotlin"
},
{
"code": null,
"e": 29678,
"s": 29580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29721,
"s": 29678,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29752,
"s": 29721,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 29794,
"s": 29752,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29836,
"s": 29794,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 29863,
"s": 29836,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 29887,
"s": 29863,
"text": "Kotlin Android Tutorial"
},
{
"code": null,
"e": 29950,
"s": 29887,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 30007,
"s": 29950,
"text": "How to Change the Color of Status Bar in an Android App?"
},
{
"code": null,
"e": 30037,
"s": 30007,
"text": "Kotlin Higher-Order Functions"
}
] |
How to get text from each cell of an HTML table using Selenium?
|
We can get text from each cell of an HTML table with Selenium webdriver.A <table> tag is used to define a table in an html document. A table consists of rows represented by <tr> and columns represented by <td>. The table headers are identified by <th> tag.
Let us consider a table from which we will get text from each cell.
Let us see the html code representation for the above table−
To retrieve the rows count of the table, we will use−
List<WebElement> rows =driver.findElements(By.tagName("tr"));
int rws_cnt= rows.size();
To retrieve the columns count of the table, we will use−
List<WebElement> cols =driver.findElements(By.tagName("td"));
int cols_cnt= cols.size();
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class TableCellValue{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String u="https://sqengineer.com/practice-sites/practice-tables-selenium/";
driver.get(u);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify table
WebElement t = driver.findElement(By.xpath("//*[@id='table1']/tbody"));
// count rows with size() method
List<WebElement> rws = t.findElements(By.tagName("tr"));
int rws_cnt = rws.size();
//iterate rows of table
for (int i = 0;i < rws_cnt; i++) {
// count columns with size() method
List<WebElement> cols = rws.get(i).findElements(By.tagName("td"));
int cols_cnt = cols.size();
//iterate cols of table
for (int j = 0;j < cols_cnt; j++) {
// get cell text with getText()
String c = cols.get(j).getText();
System.out.println("The cell value is: " + c);
}
}
driver.quit();
}
}
|
[
{
"code": null,
"e": 1319,
"s": 1062,
"text": "We can get text from each cell of an HTML table with Selenium webdriver.A <table> tag is used to define a table in an html document. A table consists of rows represented by <tr> and columns represented by <td>. The table headers are identified by <th> tag."
},
{
"code": null,
"e": 1387,
"s": 1319,
"text": "Let us consider a table from which we will get text from each cell."
},
{
"code": null,
"e": 1448,
"s": 1387,
"text": "Let us see the html code representation for the above table−"
},
{
"code": null,
"e": 1502,
"s": 1448,
"text": "To retrieve the rows count of the table, we will use−"
},
{
"code": null,
"e": 1564,
"s": 1502,
"text": "List<WebElement> rows =driver.findElements(By.tagName(\"tr\"));"
},
{
"code": null,
"e": 1590,
"s": 1564,
"text": "int rws_cnt= rows.size();"
},
{
"code": null,
"e": 1647,
"s": 1590,
"text": "To retrieve the columns count of the table, we will use−"
},
{
"code": null,
"e": 1709,
"s": 1647,
"text": "List<WebElement> cols =driver.findElements(By.tagName(\"td\"));"
},
{
"code": null,
"e": 1736,
"s": 1709,
"text": "int cols_cnt= cols.size();"
},
{
"code": null,
"e": 3071,
"s": 1736,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\n\npublic class TableCellValue{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String u=\"https://sqengineer.com/practice-sites/practice-tables-selenium/\";\n driver.get(u);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify table\n WebElement t = driver.findElement(By.xpath(\"//*[@id='table1']/tbody\"));\n // count rows with size() method\n List<WebElement> rws = t.findElements(By.tagName(\"tr\"));\n int rws_cnt = rws.size();\n //iterate rows of table\n for (int i = 0;i < rws_cnt; i++) {\n // count columns with size() method\n List<WebElement> cols = rws.get(i).findElements(By.tagName(\"td\"));\n int cols_cnt = cols.size();\n //iterate cols of table\n for (int j = 0;j < cols_cnt; j++) {\n // get cell text with getText()\n String c = cols.get(j).getText();\n System.out.println(\"The cell value is: \" + c);\n }\n}\n driver.quit();\n }\n}"
}
] |
Minimum sum of absolute difference of pairs of two arrays
|
08 Jul, 2022
Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p should not be equal to q.
Examples:
Input : a[] = {3, 2, 1}
b[] = {2, 1, 3}
Output : 0
Explanation :
1st pairing: |3 - 2| + |2 - 1| + |1 - 3|
= 1 + 1 + 2 = 4
2nd pairing: |3 - 2| + |1 - 1| + |2 - 3|
= 1 + 0 + 1 = 2
3rd pairing: |2 - 2| + |3 - 1| + |1 - 3|
= 0 + 2 + 2 = 4
4th pairing: |1 - 2| + |2 - 1| + |3 - 3|
= 1 + 1 + 0 = 2
5th pairing: |2 - 2| + |1 - 1| + |3 - 3|
= 0 + 0 + 0 = 0
6th pairing: |1 - 2| + |3 - 1| + |2 - 3|
= 1 + 2 + 1 = 4
Therefore, 5th pairing has minimum sum of
absolute difference.
Input : n = 4
a[] = {4, 1, 8, 7}
b[] = {2, 3, 6, 5}
Output : 6
The solution to the problem is a simple greedy approach. It consists of two steps.
Step 1 : Sort both the arrays in O (n log n) time.
Step 2 : Find absolute difference of each pair of corresponding elements (elements at same index) of both arrays and add the result to the sum S. The time complexity of this step is O(n).
Hence, the overall time complexity of the program is O(n log n).
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum sum of absolute// differences of two arrays.#include <bits/stdc++.h>using namespace std; // Returns minimum possible pairwise absolute// difference of two arrays.long long int findMinSum(long long int a[],long long int b[], int n){ // Sort both arrays sort(a, a+n); sort(b, b+n); // Find sum of absolute differences long long int sum= 0 ; for (int i=0; i<n; i++) sum = sum + abs(a[i]-b[i]); return sum;} // Driver codeint main(){ // Both a[] and b[] must be of same size. long long int a[] = {4, 1, 8, 7}; long long int b[] = {2, 3, 6, 5}; int n = sizeof(a)/sizeof(a[0]); printf("%lld\n", findMinSum(a, b, n)); return 0;}
// C program to find minimum sum of absolute// differences of two arrays.#include <stdio.h>#include<stdlib.h> void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of thesub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} // Returns minimum possible pairwise absolute// difference of two arrays.int findMinSum(int a[],int b[], int n){ // Sort both arrays mergeSort(a,0,n-1); mergeSort(b,0,n-1); // Find sum of absolute differences int sum= 0 ; for (int i=0; i<n; i++) sum = sum + abs(a[i]-b[i]); return sum;} // Driver codeint main(){ // Both a[] and b[] must be of same size. int a[] = {4, 1, 8, 7}; int b[] = {2, 3, 6, 5}; int n = sizeof(a)/sizeof(a[0]); printf("%d\n", findMinSum(a, b, n)); return 0;} // This code is contributed by rexomkar.
// Java program to find minimum sum of// absolute differences of two arrays.import java.util.Arrays; class MinSum{ // Returns minimum possible pairwise // absolute difference of two arrays. static long findMinSum(long a[], long b[], long n) { // Sort both arrays Arrays.sort(a); Arrays.sort(b); // Find sum of absolute differences long sum = 0 ; for (int i = 0; i < n; i++) sum = sum + Math.abs(a[i] - b[i]); return sum; } // Driver code public static void main(String[] args) { // Both a[] and b[] must be of same size. long a[] = {4, 1, 8, 7}; long b[] = {2, 3, 6, 5}; int n = a.length; System.out.println(findMinSum(a, b, n)); } } // This code is contributed by Raghav Sharma
# Python3 program to find minimum sum# of absolute differences of two arrays.def findMinSum(a, b, n): # Sort both arrays a.sort() b.sort() # Find sum of absolute differences sum = 0 for i in range(n): sum = sum + abs(a[i] - b[i]) return sum # Driver program # Both a[] and b[] must be of same size.a = [4, 1, 8, 7]b = [2, 3, 6, 5]n = len(a) print(findMinSum(a, b, n)) # This code is contributed by Anant Agarwal.
// C# program to find minimum sum of// absolute differences of two arrays.using System; class MinSum { // Returns minimum possible pairwise // absolute difference of two arrays. static long findMinSum(long []a, long []b, long n) { // Sort both arrays Array.Sort(a); Array.Sort(b); // Find sum of absolute differences long sum = 0 ; for (int i = 0; i < n; i++) sum = sum + Math.Abs(a[i] - b[i]); return sum; } // Driver code public static void Main(String[] args) { // Both a[] and b[] must be of same size. long []a = {4, 1, 8, 7}; long []b = {2, 3, 6, 5}; int n = a.Length; Console.Write(findMinSum(a, b, n)); }} // This code is contributed by parashar...
<?php// PHP program to find minimum sum// of absolute differences of two// arrays. // Returns minimum possible pairwise// absolute difference of two arrays.function findMinSum($a, $b, $n){ // Sort both arrays sort($a); sort($a, $n); sort($b); sort($b, $n); // Find sum of absolute // differences $sum= 0 ; for ($i = 0; $i < $n; $i++) $sum = $sum + abs($a[$i] - $b[$i]); return $sum;} // Driver Code // Both a[] and b[] must // be of same size. $a = array(4, 1, 8, 7); $b = array(2, 3, 6, 5); $n = sizeof($a); echo(findMinSum($a, $b, $n)); // This code is contributed by nitin mittal.?>
<script> // JavaScript program for the above approach // Function to return the minimum number // Returns minimum possible pairwise// absolute difference of two arrays. function findMinSum(a, b, n) { // Sort both arrays a.sort(); b.sort(); // Find sum of absolute differences let sum = 0 ; for (let i = 0; i < n; i++) sum = sum + Math.abs(a[i] - b[i]); return sum; } // Driver Code // Both a[] and b[] must be of same size. let a = [4, 1, 8, 7]; let b = [2, 3, 6, 5]; let n = a.length; document.write(findMinSum(a, b, n)); // This code is contributed by code_hunt.</script>
6
Time Complexity: O(n * logn)Auxiliary Space: O(1)
This article is contributed by Sahil Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
parashar
nitin mittal
subhammahato348
code_hunt
shreyanshdokania
samim2000
kk9826225
rexomkar
hardikkoriintern
Arrays
Greedy
Sorting
Arrays
Greedy
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 380,
"s": 53,
"text": "Given two arrays a[] and b[] of equal length n. The task is to pair each element of array a to an element in array b, such that sum S of absolute differences of all the pairs is minimum.Suppose, two elements a[i] and a[j] (i != j) of a are paired with elements b[p] and b[q] of b respectively, then p should not be equal to q."
},
{
"code": null,
"e": 391,
"s": 380,
"text": "Examples: "
},
{
"code": null,
"e": 1016,
"s": 391,
"text": "Input : a[] = {3, 2, 1}\n b[] = {2, 1, 3}\nOutput : 0\nExplanation :\n 1st pairing: |3 - 2| + |2 - 1| + |1 - 3|\n = 1 + 1 + 2 = 4\n 2nd pairing: |3 - 2| + |1 - 1| + |2 - 3|\n = 1 + 0 + 1 = 2\n 3rd pairing: |2 - 2| + |3 - 1| + |1 - 3|\n = 0 + 2 + 2 = 4\n 4th pairing: |1 - 2| + |2 - 1| + |3 - 3|\n = 1 + 1 + 0 = 2\n 5th pairing: |2 - 2| + |1 - 1| + |3 - 3|\n = 0 + 0 + 0 = 0\n 6th pairing: |1 - 2| + |3 - 1| + |2 - 3|\n = 1 + 2 + 1 = 4\n Therefore, 5th pairing has minimum sum of\n absolute difference.\n\nInput : n = 4\n a[] = {4, 1, 8, 7}\n b[] = {2, 3, 6, 5}\nOutput : 6"
},
{
"code": null,
"e": 1100,
"s": 1016,
"text": "The solution to the problem is a simple greedy approach. It consists of two steps. "
},
{
"code": null,
"e": 1152,
"s": 1100,
"text": "Step 1 : Sort both the arrays in O (n log n) time. "
},
{
"code": null,
"e": 1340,
"s": 1152,
"text": "Step 2 : Find absolute difference of each pair of corresponding elements (elements at same index) of both arrays and add the result to the sum S. The time complexity of this step is O(n)."
},
{
"code": null,
"e": 1406,
"s": 1340,
"text": "Hence, the overall time complexity of the program is O(n log n). "
},
{
"code": null,
"e": 1410,
"s": 1406,
"text": "C++"
},
{
"code": null,
"e": 1412,
"s": 1410,
"text": "C"
},
{
"code": null,
"e": 1417,
"s": 1412,
"text": "Java"
},
{
"code": null,
"e": 1425,
"s": 1417,
"text": "Python3"
},
{
"code": null,
"e": 1428,
"s": 1425,
"text": "C#"
},
{
"code": null,
"e": 1432,
"s": 1428,
"text": "PHP"
},
{
"code": null,
"e": 1443,
"s": 1432,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum sum of absolute// differences of two arrays.#include <bits/stdc++.h>using namespace std; // Returns minimum possible pairwise absolute// difference of two arrays.long long int findMinSum(long long int a[],long long int b[], int n){ // Sort both arrays sort(a, a+n); sort(b, b+n); // Find sum of absolute differences long long int sum= 0 ; for (int i=0; i<n; i++) sum = sum + abs(a[i]-b[i]); return sum;} // Driver codeint main(){ // Both a[] and b[] must be of same size. long long int a[] = {4, 1, 8, 7}; long long int b[] = {2, 3, 6, 5}; int n = sizeof(a)/sizeof(a[0]); printf(\"%lld\\n\", findMinSum(a, b, n)); return 0;}",
"e": 2144,
"s": 1443,
"text": null
},
{
"code": "// C program to find minimum sum of absolute// differences of two arrays.#include <stdio.h>#include<stdlib.h> void merge(int arr[], int l, int m, int r){ int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; }} /* l is for left index and r is right index of thesub-array of arr to be sorted */void mergeSort(int arr[], int l, int r){ if (l < r) { // Same as (l+r)/2, but avoids overflow for // large l and h int m = l + (r - l) / 2; // Sort first and second halves mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); }} // Returns minimum possible pairwise absolute// difference of two arrays.int findMinSum(int a[],int b[], int n){ // Sort both arrays mergeSort(a,0,n-1); mergeSort(b,0,n-1); // Find sum of absolute differences int sum= 0 ; for (int i=0; i<n; i++) sum = sum + abs(a[i]-b[i]); return sum;} // Driver codeint main(){ // Both a[] and b[] must be of same size. int a[] = {4, 1, 8, 7}; int b[] = {2, 3, 6, 5}; int n = sizeof(a)/sizeof(a[0]); printf(\"%d\\n\", findMinSum(a, b, n)); return 0;} // This code is contributed by rexomkar.",
"e": 3996,
"s": 2144,
"text": null
},
{
"code": "// Java program to find minimum sum of// absolute differences of two arrays.import java.util.Arrays; class MinSum{ // Returns minimum possible pairwise // absolute difference of two arrays. static long findMinSum(long a[], long b[], long n) { // Sort both arrays Arrays.sort(a); Arrays.sort(b); // Find sum of absolute differences long sum = 0 ; for (int i = 0; i < n; i++) sum = sum + Math.abs(a[i] - b[i]); return sum; } // Driver code public static void main(String[] args) { // Both a[] and b[] must be of same size. long a[] = {4, 1, 8, 7}; long b[] = {2, 3, 6, 5}; int n = a.length; System.out.println(findMinSum(a, b, n)); } } // This code is contributed by Raghav Sharma",
"e": 4818,
"s": 3996,
"text": null
},
{
"code": "# Python3 program to find minimum sum# of absolute differences of two arrays.def findMinSum(a, b, n): # Sort both arrays a.sort() b.sort() # Find sum of absolute differences sum = 0 for i in range(n): sum = sum + abs(a[i] - b[i]) return sum # Driver program # Both a[] and b[] must be of same size.a = [4, 1, 8, 7]b = [2, 3, 6, 5]n = len(a) print(findMinSum(a, b, n)) # This code is contributed by Anant Agarwal.",
"e": 5271,
"s": 4818,
"text": null
},
{
"code": "// C# program to find minimum sum of// absolute differences of two arrays.using System; class MinSum { // Returns minimum possible pairwise // absolute difference of two arrays. static long findMinSum(long []a, long []b, long n) { // Sort both arrays Array.Sort(a); Array.Sort(b); // Find sum of absolute differences long sum = 0 ; for (int i = 0; i < n; i++) sum = sum + Math.Abs(a[i] - b[i]); return sum; } // Driver code public static void Main(String[] args) { // Both a[] and b[] must be of same size. long []a = {4, 1, 8, 7}; long []b = {2, 3, 6, 5}; int n = a.Length; Console.Write(findMinSum(a, b, n)); }} // This code is contributed by parashar...",
"e": 6105,
"s": 5271,
"text": null
},
{
"code": "<?php// PHP program to find minimum sum// of absolute differences of two// arrays. // Returns minimum possible pairwise// absolute difference of two arrays.function findMinSum($a, $b, $n){ // Sort both arrays sort($a); sort($a, $n); sort($b); sort($b, $n); // Find sum of absolute // differences $sum= 0 ; for ($i = 0; $i < $n; $i++) $sum = $sum + abs($a[$i] - $b[$i]); return $sum;} // Driver Code // Both a[] and b[] must // be of same size. $a = array(4, 1, 8, 7); $b = array(2, 3, 6, 5); $n = sizeof($a); echo(findMinSum($a, $b, $n)); // This code is contributed by nitin mittal.?>",
"e": 6782,
"s": 6105,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to return the minimum number // Returns minimum possible pairwise// absolute difference of two arrays. function findMinSum(a, b, n) { // Sort both arrays a.sort(); b.sort(); // Find sum of absolute differences let sum = 0 ; for (let i = 0; i < n; i++) sum = sum + Math.abs(a[i] - b[i]); return sum; } // Driver Code // Both a[] and b[] must be of same size. let a = [4, 1, 8, 7]; let b = [2, 3, 6, 5]; let n = a.length; document.write(findMinSum(a, b, n)); // This code is contributed by code_hunt.</script>",
"e": 7457,
"s": 6782,
"text": null
},
{
"code": null,
"e": 7460,
"s": 7457,
"text": "6\n"
},
{
"code": null,
"e": 7510,
"s": 7460,
"text": "Time Complexity: O(n * logn)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7805,
"s": 7510,
"text": "This article is contributed by Sahil Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 7814,
"s": 7805,
"text": "parashar"
},
{
"code": null,
"e": 7827,
"s": 7814,
"text": "nitin mittal"
},
{
"code": null,
"e": 7843,
"s": 7827,
"text": "subhammahato348"
},
{
"code": null,
"e": 7853,
"s": 7843,
"text": "code_hunt"
},
{
"code": null,
"e": 7870,
"s": 7853,
"text": "shreyanshdokania"
},
{
"code": null,
"e": 7880,
"s": 7870,
"text": "samim2000"
},
{
"code": null,
"e": 7890,
"s": 7880,
"text": "kk9826225"
},
{
"code": null,
"e": 7899,
"s": 7890,
"text": "rexomkar"
},
{
"code": null,
"e": 7916,
"s": 7899,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 7923,
"s": 7916,
"text": "Arrays"
},
{
"code": null,
"e": 7930,
"s": 7923,
"text": "Greedy"
},
{
"code": null,
"e": 7938,
"s": 7930,
"text": "Sorting"
},
{
"code": null,
"e": 7945,
"s": 7938,
"text": "Arrays"
},
{
"code": null,
"e": 7952,
"s": 7945,
"text": "Greedy"
},
{
"code": null,
"e": 7960,
"s": 7952,
"text": "Sorting"
}
] |
How to Create Todo List in Angular 7 ?
|
14 May, 2020
The ToDo app is used to help us to remember some important task. We just add the task and when accomplished, delete them. This to-do list uses various Bootstrap classes that make our web application not only attractive but also responsive.
Approach:
Create a new angular app using following command:ng new my-todo-listMove inside the app by cd and run. After that open local host and check if the app is working.cd my-todo-list
ng serveInstall bootstrap using the following command:npm install bootstrapEdit style.css file in the project@import 'bootstrap/dist/css/bootstrap.css';Open src/app folder and start editing app.component.html<!--Division for GeeksForGeeks heading--><div class="container-fluid"> <div class="row bg-success justify-content-center align-items-center" style="height:80px"> <div class="col-3"></div> <div class="col-6 text-light h2"> GeeksForGeeks </div> </div> <!--Division for taking input from user --> <div class="row mt-1" style="height:80px;"> <div class="col-3 d-none col-md-3 d-md-block"></div> <div class="col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3"> <input [(ngModel)]="newTask" type="text" value="" class="col-7 form-control" style="width:300px;"> <div class="col-1"></div> <button (click)="addToList()" class="btn btn-light text-success"> ADD TASK </button> </div> <div class="col-3 d-none col-md-3 d-md-block"></div> </div> <!--Tasks added repeated divisions--> <div *ngFor="let x of items; let index = index;" class="row mt-1" style="height:100px;"> <div class="col-3 d-none col-md-3 d-md-block"></div> <div class="col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3"> <div class="col-9 text-light h3">{{x}}</div> <input (click)="deleteTask(index)" type="button" value="Delete" class="col-2 btn btn-danger"> </div> <div class="col-3 d-none col-md-3 d-md-block"></div> </div></div>Open app.component.ts file and write functions for adding and deleting tasks.import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { /* An empty array that is responsible to add a division */ public items = []; /* A two-way binding performed which pushes text on division */ public newTask; /* When input is empty, it will not create a new division */ public addToList() { if (this.newTask == '') { } else { this.items.push(this.newTask); this.newTask = ''; } } /* This function takes to input the task, that has to be deleted*/ public deleteTask(index) { this.items.splice(index, 1); }}For working with forms that is taking input we have to import FormsModule in app.module.ts file.import { FormsModule } from '@angular/forms'
Create a new angular app using following command:ng new my-todo-list
ng new my-todo-list
Move inside the app by cd and run. After that open local host and check if the app is working.cd my-todo-list
ng serve
cd my-todo-list
ng serve
Install bootstrap using the following command:npm install bootstrapEdit style.css file in the project@import 'bootstrap/dist/css/bootstrap.css';
npm install bootstrap
Edit style.css file in the project
@import 'bootstrap/dist/css/bootstrap.css';
Open src/app folder and start editing app.component.html<!--Division for GeeksForGeeks heading--><div class="container-fluid"> <div class="row bg-success justify-content-center align-items-center" style="height:80px"> <div class="col-3"></div> <div class="col-6 text-light h2"> GeeksForGeeks </div> </div> <!--Division for taking input from user --> <div class="row mt-1" style="height:80px;"> <div class="col-3 d-none col-md-3 d-md-block"></div> <div class="col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3"> <input [(ngModel)]="newTask" type="text" value="" class="col-7 form-control" style="width:300px;"> <div class="col-1"></div> <button (click)="addToList()" class="btn btn-light text-success"> ADD TASK </button> </div> <div class="col-3 d-none col-md-3 d-md-block"></div> </div> <!--Tasks added repeated divisions--> <div *ngFor="let x of items; let index = index;" class="row mt-1" style="height:100px;"> <div class="col-3 d-none col-md-3 d-md-block"></div> <div class="col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3"> <div class="col-9 text-light h3">{{x}}</div> <input (click)="deleteTask(index)" type="button" value="Delete" class="col-2 btn btn-danger"> </div> <div class="col-3 d-none col-md-3 d-md-block"></div> </div></div>
<!--Division for GeeksForGeeks heading--><div class="container-fluid"> <div class="row bg-success justify-content-center align-items-center" style="height:80px"> <div class="col-3"></div> <div class="col-6 text-light h2"> GeeksForGeeks </div> </div> <!--Division for taking input from user --> <div class="row mt-1" style="height:80px;"> <div class="col-3 d-none col-md-3 d-md-block"></div> <div class="col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3"> <input [(ngModel)]="newTask" type="text" value="" class="col-7 form-control" style="width:300px;"> <div class="col-1"></div> <button (click)="addToList()" class="btn btn-light text-success"> ADD TASK </button> </div> <div class="col-3 d-none col-md-3 d-md-block"></div> </div> <!--Tasks added repeated divisions--> <div *ngFor="let x of items; let index = index;" class="row mt-1" style="height:100px;"> <div class="col-3 d-none col-md-3 d-md-block"></div> <div class="col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3"> <div class="col-9 text-light h3">{{x}}</div> <input (click)="deleteTask(index)" type="button" value="Delete" class="col-2 btn btn-danger"> </div> <div class="col-3 d-none col-md-3 d-md-block"></div> </div></div>
Open app.component.ts file and write functions for adding and deleting tasks.import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { /* An empty array that is responsible to add a division */ public items = []; /* A two-way binding performed which pushes text on division */ public newTask; /* When input is empty, it will not create a new division */ public addToList() { if (this.newTask == '') { } else { this.items.push(this.newTask); this.newTask = ''; } } /* This function takes to input the task, that has to be deleted*/ public deleteTask(index) { this.items.splice(index, 1); }}
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { /* An empty array that is responsible to add a division */ public items = []; /* A two-way binding performed which pushes text on division */ public newTask; /* When input is empty, it will not create a new division */ public addToList() { if (this.newTask == '') { } else { this.items.push(this.newTask); this.newTask = ''; } } /* This function takes to input the task, that has to be deleted*/ public deleteTask(index) { this.items.splice(index, 1); }}
For working with forms that is taking input we have to import FormsModule in app.module.ts file.import { FormsModule } from '@angular/forms'
import { FormsModule } from '@angular/forms'
Output:
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
How to bundle an Angular app for production?
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 268,
"s": 28,
"text": "The ToDo app is used to help us to remember some important task. We just add the task and when accomplished, delete them. This to-do list uses various Bootstrap classes that make our web application not only attractive but also responsive."
},
{
"code": null,
"e": 278,
"s": 268,
"text": "Approach:"
},
{
"code": null,
"e": 3311,
"s": 278,
"text": "Create a new angular app using following command:ng new my-todo-listMove inside the app by cd and run. After that open local host and check if the app is working.cd my-todo-list\nng serveInstall bootstrap using the following command:npm install bootstrapEdit style.css file in the project@import 'bootstrap/dist/css/bootstrap.css';Open src/app folder and start editing app.component.html<!--Division for GeeksForGeeks heading--><div class=\"container-fluid\"> <div class=\"row bg-success justify-content-center align-items-center\" style=\"height:80px\"> <div class=\"col-3\"></div> <div class=\"col-6 text-light h2\"> GeeksForGeeks </div> </div> <!--Division for taking input from user --> <div class=\"row mt-1\" style=\"height:80px;\"> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> <div class=\"col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3\"> <input [(ngModel)]=\"newTask\" type=\"text\" value=\"\" class=\"col-7 form-control\" style=\"width:300px;\"> <div class=\"col-1\"></div> <button (click)=\"addToList()\" class=\"btn btn-light text-success\"> ADD TASK </button> </div> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> </div> <!--Tasks added repeated divisions--> <div *ngFor=\"let x of items; let index = index;\" class=\"row mt-1\" style=\"height:100px;\"> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> <div class=\"col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3\"> <div class=\"col-9 text-light h3\">{{x}}</div> <input (click)=\"deleteTask(index)\" type=\"button\" value=\"Delete\" class=\"col-2 btn btn-danger\"> </div> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> </div></div>Open app.component.ts file and write functions for adding and deleting tasks.import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { /* An empty array that is responsible to add a division */ public items = []; /* A two-way binding performed which pushes text on division */ public newTask; /* When input is empty, it will not create a new division */ public addToList() { if (this.newTask == '') { } else { this.items.push(this.newTask); this.newTask = ''; } } /* This function takes to input the task, that has to be deleted*/ public deleteTask(index) { this.items.splice(index, 1); }}For working with forms that is taking input we have to import FormsModule in app.module.ts file.import { FormsModule } from '@angular/forms'"
},
{
"code": null,
"e": 3380,
"s": 3311,
"text": "Create a new angular app using following command:ng new my-todo-list"
},
{
"code": null,
"e": 3400,
"s": 3380,
"text": "ng new my-todo-list"
},
{
"code": null,
"e": 3519,
"s": 3400,
"text": "Move inside the app by cd and run. After that open local host and check if the app is working.cd my-todo-list\nng serve"
},
{
"code": null,
"e": 3544,
"s": 3519,
"text": "cd my-todo-list\nng serve"
},
{
"code": null,
"e": 3689,
"s": 3544,
"text": "Install bootstrap using the following command:npm install bootstrapEdit style.css file in the project@import 'bootstrap/dist/css/bootstrap.css';"
},
{
"code": null,
"e": 3711,
"s": 3689,
"text": "npm install bootstrap"
},
{
"code": null,
"e": 3746,
"s": 3711,
"text": "Edit style.css file in the project"
},
{
"code": "@import 'bootstrap/dist/css/bootstrap.css';",
"e": 3790,
"s": 3746,
"text": null
},
{
"code": null,
"e": 5512,
"s": 3790,
"text": "Open src/app folder and start editing app.component.html<!--Division for GeeksForGeeks heading--><div class=\"container-fluid\"> <div class=\"row bg-success justify-content-center align-items-center\" style=\"height:80px\"> <div class=\"col-3\"></div> <div class=\"col-6 text-light h2\"> GeeksForGeeks </div> </div> <!--Division for taking input from user --> <div class=\"row mt-1\" style=\"height:80px;\"> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> <div class=\"col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3\"> <input [(ngModel)]=\"newTask\" type=\"text\" value=\"\" class=\"col-7 form-control\" style=\"width:300px;\"> <div class=\"col-1\"></div> <button (click)=\"addToList()\" class=\"btn btn-light text-success\"> ADD TASK </button> </div> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> </div> <!--Tasks added repeated divisions--> <div *ngFor=\"let x of items; let index = index;\" class=\"row mt-1\" style=\"height:100px;\"> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> <div class=\"col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3\"> <div class=\"col-9 text-light h3\">{{x}}</div> <input (click)=\"deleteTask(index)\" type=\"button\" value=\"Delete\" class=\"col-2 btn btn-danger\"> </div> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> </div></div>"
},
{
"code": "<!--Division for GeeksForGeeks heading--><div class=\"container-fluid\"> <div class=\"row bg-success justify-content-center align-items-center\" style=\"height:80px\"> <div class=\"col-3\"></div> <div class=\"col-6 text-light h2\"> GeeksForGeeks </div> </div> <!--Division for taking input from user --> <div class=\"row mt-1\" style=\"height:80px;\"> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> <div class=\"col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3\"> <input [(ngModel)]=\"newTask\" type=\"text\" value=\"\" class=\"col-7 form-control\" style=\"width:300px;\"> <div class=\"col-1\"></div> <button (click)=\"addToList()\" class=\"btn btn-light text-success\"> ADD TASK </button> </div> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> </div> <!--Tasks added repeated divisions--> <div *ngFor=\"let x of items; let index = index;\" class=\"row mt-1\" style=\"height:100px;\"> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> <div class=\"col-12 col-md-6 bg-success d-flex justify-content-center align-items-center text-light h3\"> <div class=\"col-9 text-light h3\">{{x}}</div> <input (click)=\"deleteTask(index)\" type=\"button\" value=\"Delete\" class=\"col-2 btn btn-danger\"> </div> <div class=\"col-3 d-none col-md-3 d-md-block\"></div> </div></div>",
"e": 7178,
"s": 5512,
"text": null
},
{
"code": null,
"e": 8020,
"s": 7178,
"text": "Open app.component.ts file and write functions for adding and deleting tasks.import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { /* An empty array that is responsible to add a division */ public items = []; /* A two-way binding performed which pushes text on division */ public newTask; /* When input is empty, it will not create a new division */ public addToList() { if (this.newTask == '') { } else { this.items.push(this.newTask); this.newTask = ''; } } /* This function takes to input the task, that has to be deleted*/ public deleteTask(index) { this.items.splice(index, 1); }}"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { /* An empty array that is responsible to add a division */ public items = []; /* A two-way binding performed which pushes text on division */ public newTask; /* When input is empty, it will not create a new division */ public addToList() { if (this.newTask == '') { } else { this.items.push(this.newTask); this.newTask = ''; } } /* This function takes to input the task, that has to be deleted*/ public deleteTask(index) { this.items.splice(index, 1); }}",
"e": 8785,
"s": 8020,
"text": null
},
{
"code": null,
"e": 8926,
"s": 8785,
"text": "For working with forms that is taking input we have to import FormsModule in app.module.ts file.import { FormsModule } from '@angular/forms'"
},
{
"code": null,
"e": 8971,
"s": 8926,
"text": "import { FormsModule } from '@angular/forms'"
},
{
"code": null,
"e": 8979,
"s": 8971,
"text": "Output:"
},
{
"code": null,
"e": 8994,
"s": 8979,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 9001,
"s": 8994,
"text": "Picked"
},
{
"code": null,
"e": 9011,
"s": 9001,
"text": "AngularJS"
},
{
"code": null,
"e": 9028,
"s": 9011,
"text": "Web Technologies"
},
{
"code": null,
"e": 9055,
"s": 9028,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 9153,
"s": 9055,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9184,
"s": 9153,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 9208,
"s": 9184,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 9253,
"s": 9208,
"text": "How to bundle an Angular app for production?"
},
{
"code": null,
"e": 9295,
"s": 9253,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 9330,
"s": 9295,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 9363,
"s": 9330,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 9425,
"s": 9363,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 9486,
"s": 9425,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 9536,
"s": 9486,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Difference between isset() and array_key_exists() Function in PHP
|
09 Oct, 2018
isset() function
The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
Syntax:
bool isset( $var, mixed )
Parameters: This function accepts more than one parameters. The first parameter of this function is $var. This parameter is used to store the value of variable.
Program:
<?php // Declare an array$array = array(); // Use isset functionecho isset($array['geeks']) ? 'array is set.' : 'array is not set.';?>
array is not set.
array_key_exists() Function
This is also a predefined function in PHP which checks whether an index or a particular key exists in an array or not. It does not evaluate the value of the key for any null values. It returns false if it does not find the key in the array and true in all other possible cases.
Syntax:
bool array_key_exists( $key, $array )
Parameters: This function accepts two parameters as mentioned above and described below:
$key: This parameter is used to store the value to be check.
$array: This parameter is used to store an array with keys to check.
Program:
<?php // Create an array$array = array( 'name' => null,); // Use array_key_exists functionecho array_key_exists('name', $array) ? 'array key exists' : 'array key does not exist';?>
array key exists
Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null. Also isset() doesn’t render error when array/variable does not exist, while array_key_exists does.
PHP-function
Picked
PHP
PHP Programs
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Oct, 2018"
},
{
"code": null,
"e": 69,
"s": 52,
"text": "isset() function"
},
{
"code": null,
"e": 341,
"s": 69,
"text": "The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases."
},
{
"code": null,
"e": 349,
"s": 341,
"text": "Syntax:"
},
{
"code": null,
"e": 375,
"s": 349,
"text": "bool isset( $var, mixed )"
},
{
"code": null,
"e": 536,
"s": 375,
"text": "Parameters: This function accepts more than one parameters. The first parameter of this function is $var. This parameter is used to store the value of variable."
},
{
"code": null,
"e": 545,
"s": 536,
"text": "Program:"
},
{
"code": "<?php // Declare an array$array = array(); // Use isset functionecho isset($array['geeks']) ? 'array is set.' : 'array is not set.';?>",
"e": 687,
"s": 545,
"text": null
},
{
"code": null,
"e": 706,
"s": 687,
"text": "array is not set.\n"
},
{
"code": null,
"e": 734,
"s": 706,
"text": "array_key_exists() Function"
},
{
"code": null,
"e": 1012,
"s": 734,
"text": "This is also a predefined function in PHP which checks whether an index or a particular key exists in an array or not. It does not evaluate the value of the key for any null values. It returns false if it does not find the key in the array and true in all other possible cases."
},
{
"code": null,
"e": 1020,
"s": 1012,
"text": "Syntax:"
},
{
"code": null,
"e": 1058,
"s": 1020,
"text": "bool array_key_exists( $key, $array )"
},
{
"code": null,
"e": 1147,
"s": 1058,
"text": "Parameters: This function accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 1208,
"s": 1147,
"text": "$key: This parameter is used to store the value to be check."
},
{
"code": null,
"e": 1277,
"s": 1208,
"text": "$array: This parameter is used to store an array with keys to check."
},
{
"code": null,
"e": 1286,
"s": 1277,
"text": "Program:"
},
{
"code": "<?php // Create an array$array = array( 'name' => null,); // Use array_key_exists functionecho array_key_exists('name', $array) ? 'array key exists' : 'array key does not exist';?>",
"e": 1474,
"s": 1286,
"text": null
},
{
"code": null,
"e": 1492,
"s": 1474,
"text": "array key exists\n"
},
{
"code": null,
"e": 1892,
"s": 1492,
"text": "Difference between isset() and array_key_exists() Function: The main difference between isset() and array_key_exists() function is that the array_key_exists() function will definitely tells if a key exists in an array, whereas isset() will only return true if the key/variable exists and is not null. Also isset() doesn’t render error when array/variable does not exist, while array_key_exists does."
},
{
"code": null,
"e": 1905,
"s": 1892,
"text": "PHP-function"
},
{
"code": null,
"e": 1912,
"s": 1905,
"text": "Picked"
},
{
"code": null,
"e": 1916,
"s": 1912,
"text": "PHP"
},
{
"code": null,
"e": 1929,
"s": 1916,
"text": "PHP Programs"
},
{
"code": null,
"e": 1933,
"s": 1929,
"text": "PHP"
}
] |
PyQt5 QDateEdit – Getting Input Date
|
25 May, 2021
In this article we will see how we can get the input date of the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records, which can be done with the help of setDate method.In order to do this we use date method with the QDateEdit object
Syntax : date.date()Argument : It takes no argumentReturn : It returns QDate object
Below is the implementation
Python3
# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # date d = QDate(2020, 6, 10) # setting date to the date edit date.setDate(d) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry label.setGeometry(100, 150, 200, 60) # making label multiline label.setWordWrap(True) # getting current date value = date.date() # setting text to the label label.setText("Date : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
sweetyty
Python PyQt-QDateEdit
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 May, 2021"
},
{
"code": null,
"e": 409,
"s": 28,
"text": "In this article we will see how we can get the input date of the QDateEdit. User can set date to the date edit with the help of cursor and the keyboard but sometimes there is a need of setting initial date or date programmatically for showing date in the records, which can be done with the help of setDate method.In order to do this we use date method with the QDateEdit object "
},
{
"code": null,
"e": 495,
"s": 409,
"text": "Syntax : date.date()Argument : It takes no argumentReturn : It returns QDate object "
},
{
"code": null,
"e": 525,
"s": 495,
"text": "Below is the implementation "
},
{
"code": null,
"e": 533,
"s": 525,
"text": "Python3"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import *from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import *from PyQt5.QtCore import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating a QDateEdit widget date = QDateEdit(self) # setting geometry of the date edit date.setGeometry(100, 100, 150, 40) # date d = QDate(2020, 6, 10) # setting date to the date edit date.setDate(d) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry label.setGeometry(100, 150, 200, 60) # making label multiline label.setWordWrap(True) # getting current date value = date.date() # setting text to the label label.setText(\"Date : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 1826,
"s": 533,
"text": null
},
{
"code": null,
"e": 1837,
"s": 1826,
"text": "Output : "
},
{
"code": null,
"e": 1848,
"s": 1839,
"text": "sweetyty"
},
{
"code": null,
"e": 1870,
"s": 1848,
"text": "Python PyQt-QDateEdit"
},
{
"code": null,
"e": 1881,
"s": 1870,
"text": "Python-gui"
},
{
"code": null,
"e": 1893,
"s": 1881,
"text": "Python-PyQt"
},
{
"code": null,
"e": 1900,
"s": 1893,
"text": "Python"
}
] |
Program to make Indian Flag in Python | Step by Step
|
07 Nov, 2018
Here, We’ll be making Indian Flag in Python using Spyder tool which is a part of Anaconda interface. It is the beginner’s practice problem for python programmers.
Prerequisite: The only prerequisite for this code is little knowledge of basic python programming. You may install anaconda from here if you don’t have any interpreter for python.
Approach: We will be using simple characteristic equations of lines and circles in this code. It is recommended to try on your own before getting to the solution altogether.
Import these 3 packages for the functions used in this code.
import skimage # for using image processing functions
import os
from skimage import io # for using imshow function
1. Read an image of at least the expected dimensions of the flag.
image2 = io.imread('C:\Users\geeksforgeeks\Desktop\index.jpg')
2. Let us assume the dimensions of the flag to be 189px high and 267px wide.
x = 189/2
y = 267/2
r = 189/6
3. Start two for loops to iterate to every pixel of the image.
for i in range(0, 189):
for j in range(0, 267):
Inside the inner loop perform 3-(a) and 3-(b).
3-(a). By dividing the image into 3 equal part height-wise color the image in orange, white and green.
if i in range(0, 189/3):
image2[i][j] = [255, 128, 64] # Color coding for Orange
elif i in range(189/3, 189*2/3):
image2[i][j] = [255, 255, 255] # Color coding for White
else:
image2[i][j] = [0, 128, 0] # Color coding for Green
io.imshow(image2)
3-(b). Now it’s time to draw the circle at the center for the Ashoka Chakra, using equation of circle.
if (( pow((x-i), 2) + pow((y-j), 2) ) = pow(r-2, 2)):
image2[i][j] = [0, 0, 255]
io.imshow(image2)
4. To draw spokes of the Chakra, we need to use equation of lines which stays inside the circle only, here I have drawn 4 x 2 spokes, however all 24 spokes can be drawn by using 12 equations as each line leads to two opposite spokes.
for i in range(189/3, 189*2/3):
for j in range(267/3, 267*2/3):
if ((i == 189/2) or (j == 267/2) or (i+39 == j or
(i+39+j == 266))) and (( pow((x-i), 2) +
pow((y-j), 2) ) <= pow(r, 2)) :
image2[i][j] = [0, 0, 255]
5. It’s time to view our image now so we will use <imshow function.
io.imshow(image2)
And Over Indian Flag in just 5 steps.
The overall code will look something like this...
"""@author: geeksforgeeks"""# Packagesimport skimageimport osfrom skimage import io # Reading image fileimage2 = io.imread('C:\Users\KRISHNA\Desktop\index.jpg') # Setting dimensions boundariesx = 189 / 2y = 267 / 2r = 189 / 6 # Iterating to all the pixels in the set boundariesfor i in range(0, 189): for j in range(0, 267): if i in range(0, 189 / 3): image2[i][j] = [255, 128, 64] # Orange Color elif i in range(189 / 3, 189 * 2 / 3): image2[i][j] = [255, 255, 255] # White Color else: image2[i][j] = [0, 128, 0] # Green Color # Equation for 2px thick ring if (( pow((x-i), 2) + pow((y-j), 2) ) <= pow(r + 1, 2)) and(( pow((x-i), 2) + pow((y-j), 2) ) >= pow(r-2, 2)): image2[i][j] = [0, 0, 255] # Blue Color # Iterating within the ring for i in range(189 / 3, 189 * 2 / 3): for j in range(267 / 3, 267 * 2 / 3): # Equation to draw 4 straight lines if ((i == 189 / 2) or (j == 267 / 2) or (i + 39 == j or (i + 39 + j == 266))) and (( pow((x-i), 2) + pow((y-j), 2) ) <= pow(r, 2)) : image2[i][j] = [0, 0, 255] # Blue Color io.imshow(image2) # Output
Output:
Output
programming-puzzle
python-utility
Competitive Programming
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Nov, 2018"
},
{
"code": null,
"e": 217,
"s": 54,
"text": "Here, We’ll be making Indian Flag in Python using Spyder tool which is a part of Anaconda interface. It is the beginner’s practice problem for python programmers."
},
{
"code": null,
"e": 397,
"s": 217,
"text": "Prerequisite: The only prerequisite for this code is little knowledge of basic python programming. You may install anaconda from here if you don’t have any interpreter for python."
},
{
"code": null,
"e": 571,
"s": 397,
"text": "Approach: We will be using simple characteristic equations of lines and circles in this code. It is recommended to try on your own before getting to the solution altogether."
},
{
"code": null,
"e": 632,
"s": 571,
"text": "Import these 3 packages for the functions used in this code."
},
{
"code": null,
"e": 768,
"s": 632,
"text": "import skimage # for using image processing functions\nimport os\nfrom skimage import io # for using imshow function\n"
},
{
"code": null,
"e": 834,
"s": 768,
"text": "1. Read an image of at least the expected dimensions of the flag."
},
{
"code": null,
"e": 898,
"s": 834,
"text": "image2 = io.imread('C:\\Users\\geeksforgeeks\\Desktop\\index.jpg')\n"
},
{
"code": null,
"e": 975,
"s": 898,
"text": "2. Let us assume the dimensions of the flag to be 189px high and 267px wide."
},
{
"code": null,
"e": 1006,
"s": 975,
"text": "x = 189/2\ny = 267/2\nr = 189/6\n"
},
{
"code": null,
"e": 1069,
"s": 1006,
"text": "3. Start two for loops to iterate to every pixel of the image."
},
{
"code": null,
"e": 1122,
"s": 1069,
"text": "for i in range(0, 189):\n for j in range(0, 267):\n"
},
{
"code": null,
"e": 1169,
"s": 1122,
"text": "Inside the inner loop perform 3-(a) and 3-(b)."
},
{
"code": null,
"e": 1272,
"s": 1169,
"text": "3-(a). By dividing the image into 3 equal part height-wise color the image in orange, white and green."
},
{
"code": null,
"e": 1574,
"s": 1272,
"text": "if i in range(0, 189/3):\n image2[i][j] = [255, 128, 64] # Color coding for Orange \n elif i in range(189/3, 189*2/3):\n image2[i][j] = [255, 255, 255] # Color coding for White\n else:\n image2[i][j] = [0, 128, 0] # Color coding for Green\n"
},
{
"code": null,
"e": 1592,
"s": 1574,
"text": "io.imshow(image2)"
},
{
"code": null,
"e": 1695,
"s": 1592,
"text": "3-(b). Now it’s time to draw the circle at the center for the Ashoka Chakra, using equation of circle."
},
{
"code": null,
"e": 1789,
"s": 1695,
"text": "if (( pow((x-i), 2) + pow((y-j), 2) ) = pow(r-2, 2)):\n image2[i][j] = [0, 0, 255]\n"
},
{
"code": null,
"e": 1807,
"s": 1789,
"text": "io.imshow(image2)"
},
{
"code": null,
"e": 2041,
"s": 1807,
"text": "4. To draw spokes of the Chakra, we need to use equation of lines which stays inside the circle only, here I have drawn 4 x 2 spokes, however all 24 spokes can be drawn by using 12 equations as each line leads to two opposite spokes."
},
{
"code": null,
"e": 2321,
"s": 2041,
"text": "for i in range(189/3, 189*2/3):\n for j in range(267/3, 267*2/3):\n if ((i == 189/2) or (j == 267/2) or (i+39 == j or\n (i+39+j == 266))) and (( pow((x-i), 2) + \n pow((y-j), 2) ) <= pow(r, 2)) :\n image2[i][j] = [0, 0, 255]\n\n"
},
{
"code": null,
"e": 2389,
"s": 2321,
"text": "5. It’s time to view our image now so we will use <imshow function."
},
{
"code": null,
"e": 2408,
"s": 2389,
"text": "io.imshow(image2)\n"
},
{
"code": null,
"e": 2446,
"s": 2408,
"text": "And Over Indian Flag in just 5 steps."
},
{
"code": null,
"e": 2496,
"s": 2446,
"text": "The overall code will look something like this..."
},
{
"code": "\"\"\"@author: geeksforgeeks\"\"\"# Packagesimport skimageimport osfrom skimage import io # Reading image fileimage2 = io.imread('C:\\Users\\KRISHNA\\Desktop\\index.jpg') # Setting dimensions boundariesx = 189 / 2y = 267 / 2r = 189 / 6 # Iterating to all the pixels in the set boundariesfor i in range(0, 189): for j in range(0, 267): if i in range(0, 189 / 3): image2[i][j] = [255, 128, 64] # Orange Color elif i in range(189 / 3, 189 * 2 / 3): image2[i][j] = [255, 255, 255] # White Color else: image2[i][j] = [0, 128, 0] # Green Color # Equation for 2px thick ring if (( pow((x-i), 2) + pow((y-j), 2) ) <= pow(r + 1, 2)) and(( pow((x-i), 2) + pow((y-j), 2) ) >= pow(r-2, 2)): image2[i][j] = [0, 0, 255] # Blue Color # Iterating within the ring for i in range(189 / 3, 189 * 2 / 3): for j in range(267 / 3, 267 * 2 / 3): # Equation to draw 4 straight lines if ((i == 189 / 2) or (j == 267 / 2) or (i + 39 == j or (i + 39 + j == 266))) and (( pow((x-i), 2) + pow((y-j), 2) ) <= pow(r, 2)) : image2[i][j] = [0, 0, 255] # Blue Color io.imshow(image2) # Output",
"e": 3754,
"s": 2496,
"text": null
},
{
"code": null,
"e": 3762,
"s": 3754,
"text": "Output:"
},
{
"code": null,
"e": 3769,
"s": 3762,
"text": "Output"
},
{
"code": null,
"e": 3788,
"s": 3769,
"text": "programming-puzzle"
},
{
"code": null,
"e": 3803,
"s": 3788,
"text": "python-utility"
},
{
"code": null,
"e": 3827,
"s": 3803,
"text": "Competitive Programming"
},
{
"code": null,
"e": 3843,
"s": 3827,
"text": "Python Programs"
}
] |
Collect all coins in minimum number of steps
|
26 Apr, 2021
Given many stacks of coins which are arranged adjacently. We need to collect all these coins in the minimum number of steps where in one step we can collect one horizontal line of coins or vertical line of coins and collected coins should be continuous.Examples :
Input : height[] = [2 1 2 5 1]
Each value of this array corresponds to
the height of stack that is we are given
five stack of coins, where in first stack
2 coins are there then in second stack
1 coin is there and so on.
Output : 4
We can collect all above coins in 4 steps
which are shown in below diagram.
Each step is shown by different color.
First, we have collected last horizontal
line of coins after which stacks remains
as [1 0 1 4 0] after that, another horizontal
line of coins is collected from stack 3
and 4 then a vertical line from stack 4
and at the end a horizontal line from
stack 1. Total steps are 4.
We can solve this problem using divide and conquer method. We can see that it is always beneficial to remove horizontal lines from below. Suppose we are working on stacks from l index to r index in a recursion step, each time we will choose minimum height, remove those many horizontal lines after which stack will be broken into two parts, l to minimum and minimum +1 till r and we will call recursively in those subarrays. Another thing is we can also collect coins using vertical lines so we will choose minimum between the result of recursive calls and (r – l) because using (r – l) vertical lines we can always collect all coins. As each time we are calling each subarray and finding minimum of that, total time complexity of the solution will be O(N2)
C++
Java
Python 3
C#
PHP
Javascript
// C++ program to find minimum number of// steps to collect stack of coins#include <bits/stdc++.h>using namespace std; // recursive method to collect coins from// height array l to r, with height h already// collectedint minStepsRecur(int height[], int l, int r, int h){ // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to get minimum height // index int m = l; for (int i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h);} // method returns minimum number of step to// collect coin from stack, with height in// height[] arrayint minSteps(int height[], int N){ return minStepsRecur(height, 0, N, 0);} // Driver code to test above methodsint main(){ int height[] = { 2, 1, 2, 5, 1 }; int N = sizeof(height) / sizeof(int); cout << minSteps(height, N) << endl; return 0;}
// Java Code to Collect all coins in// minimum number of stepsimport java.util.*; class GFG { // recursive method to collect coins from // height array l to r, with height h already // collected public static int minStepsRecur(int height[], int l, int r, int h) { // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to get minimum height // index int m = l; for (int i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return Math.min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h); } // method returns minimum number of step to // collect coin from stack, with height in // height[] array public static int minSteps(int height[], int N) { return minStepsRecur(height, 0, N, 0); } /* Driver program to test above function */ public static void main(String[] args) { int height[] = { 2, 1, 2, 5, 1 }; int N = height.length; System.out.println(minSteps(height, N)); }} // This code is contributed by Arnav Kr. Mandal.
# Python 3 program to find# minimum number of steps# to collect stack of coins # recursive method to collect# coins from height array l to# r, with height h already# collecteddef minStepsRecur(height, l, r, h): # if l is more than r, # no steps needed if l >= r: return 0; # loop over heights to # get minimum height index m = l for i in range(l, r): if height[i] < height[m]: m = i # choose minimum from, # 1) collecting coins using # all vertical lines (total r - l) # 2) collecting coins using # lower horizontal lines and # recursively on left and # right segments return min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h) # method returns minimum number# of step to collect coin from# stack, with height in height[] arraydef minSteps(height, N): return minStepsRecur(height, 0, N, 0) # Driver codeheight = [ 2, 1, 2, 5, 1 ]N = len(height)print(minSteps(height, N)) # This code is contributed# by ChitraNayal
// C# Code to Collect all coins in// minimum number of stepsusing System; class GFG { // recursive method to collect coins from // height array l to r, with height h already // collected public static int minStepsRecur(int[] height, int l, int r, int h) { // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to // get minimum height index int m = l; for (int i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return Math.Min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h); } // method returns minimum number of step to // collect coin from stack, with height in // height[] array public static int minSteps(int[] height, int N) { return minStepsRecur(height, 0, N, 0); } /* Driver program to test above function */ public static void Main() { int[] height = { 2, 1, 2, 5, 1 }; int N = height.Length; Console.Write(minSteps(height, N)); }} // This code is contributed by nitin mittal
<?php// PHP program to find minimum number of// steps to collect stack of coins // recursive method to collect// coins from height array l to// r, with height h already// collectedfunction minStepsRecur($height, $l, $r, $h){ // if l is more than r, // no steps needed if ($l >= $r) return 0; // loop over heights to // get minimum height // index $m = $l; for ($i = $l; $i < $r; $i++) if ($height[$i] < $height[$m]) $m = $i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return min($r - $l, minStepsRecur($height, $l, $m, $height[$m]) + minStepsRecur($height, $m + 1, $r, $height[$m]) + $height[$m] - $h);} // method returns minimum number of step to// collect coin from stack, with height in// height[] arrayfunction minSteps($height, $N){ return minStepsRecur($height, 0, $N, 0);} // Driver Code $height = array(2, 1, 2, 5, 1); $N = sizeof($height); echo minSteps($height, $N) ; // This code is contributed by nitin mittal.?>
<script>// Javascript Code to Collect all coins in// minimum number of steps // recursive method to collect coins from // height array l to r, with height h already // collected function minStepsRecur(height,l,r,h) { // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to get minimum height // index let m = l; for (let i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return Math.min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h); } // method returns minimum number of step to // collect coin from stack, with height in // height[] array function minSteps(height,N) { return minStepsRecur(height, 0, N, 0); } /* Driver program to test above function */ let height=[2, 1, 2, 5, 1 ]; let N = height.length; document.write(minSteps(height, N)); // This code is contributed by avanitrachhadiya2155</script>
Output:
4
This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nitin mittal
ukasp
avanitrachhadiya2155
Divide and Conquer
Divide and Conquer
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 318,
"s": 52,
"text": "Given many stacks of coins which are arranged adjacently. We need to collect all these coins in the minimum number of steps where in one step we can collect one horizontal line of coins or vertical line of coins and collected coins should be continuous.Examples : "
},
{
"code": null,
"e": 945,
"s": 318,
"text": "Input : height[] = [2 1 2 5 1]\nEach value of this array corresponds to\nthe height of stack that is we are given\nfive stack of coins, where in first stack\n2 coins are there then in second stack \n1 coin is there and so on.\nOutput : 4\nWe can collect all above coins in 4 steps \nwhich are shown in below diagram.\nEach step is shown by different color.\n\n\n\nFirst, we have collected last horizontal\nline of coins after which stacks remains\nas [1 0 1 4 0] after that, another horizontal\nline of coins is collected from stack 3 \nand 4 then a vertical line from stack 4 \nand at the end a horizontal line from\nstack 1. Total steps are 4."
},
{
"code": null,
"e": 1707,
"s": 947,
"text": "We can solve this problem using divide and conquer method. We can see that it is always beneficial to remove horizontal lines from below. Suppose we are working on stacks from l index to r index in a recursion step, each time we will choose minimum height, remove those many horizontal lines after which stack will be broken into two parts, l to minimum and minimum +1 till r and we will call recursively in those subarrays. Another thing is we can also collect coins using vertical lines so we will choose minimum between the result of recursive calls and (r – l) because using (r – l) vertical lines we can always collect all coins. As each time we are calling each subarray and finding minimum of that, total time complexity of the solution will be O(N2) "
},
{
"code": null,
"e": 1711,
"s": 1707,
"text": "C++"
},
{
"code": null,
"e": 1716,
"s": 1711,
"text": "Java"
},
{
"code": null,
"e": 1725,
"s": 1716,
"text": "Python 3"
},
{
"code": null,
"e": 1728,
"s": 1725,
"text": "C#"
},
{
"code": null,
"e": 1732,
"s": 1728,
"text": "PHP"
},
{
"code": null,
"e": 1743,
"s": 1732,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum number of// steps to collect stack of coins#include <bits/stdc++.h>using namespace std; // recursive method to collect coins from// height array l to r, with height h already// collectedint minStepsRecur(int height[], int l, int r, int h){ // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to get minimum height // index int m = l; for (int i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h);} // method returns minimum number of step to// collect coin from stack, with height in// height[] arrayint minSteps(int height[], int N){ return minStepsRecur(height, 0, N, 0);} // Driver code to test above methodsint main(){ int height[] = { 2, 1, 2, 5, 1 }; int N = sizeof(height) / sizeof(int); cout << minSteps(height, N) << endl; return 0;}",
"e": 2989,
"s": 1743,
"text": null
},
{
"code": "// Java Code to Collect all coins in// minimum number of stepsimport java.util.*; class GFG { // recursive method to collect coins from // height array l to r, with height h already // collected public static int minStepsRecur(int height[], int l, int r, int h) { // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to get minimum height // index int m = l; for (int i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return Math.min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h); } // method returns minimum number of step to // collect coin from stack, with height in // height[] array public static int minSteps(int height[], int N) { return minStepsRecur(height, 0, N, 0); } /* Driver program to test above function */ public static void main(String[] args) { int height[] = { 2, 1, 2, 5, 1 }; int N = height.length; System.out.println(minSteps(height, N)); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 4518,
"s": 2989,
"text": null
},
{
"code": "# Python 3 program to find# minimum number of steps# to collect stack of coins # recursive method to collect# coins from height array l to# r, with height h already# collecteddef minStepsRecur(height, l, r, h): # if l is more than r, # no steps needed if l >= r: return 0; # loop over heights to # get minimum height index m = l for i in range(l, r): if height[i] < height[m]: m = i # choose minimum from, # 1) collecting coins using # all vertical lines (total r - l) # 2) collecting coins using # lower horizontal lines and # recursively on left and # right segments return min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h) # method returns minimum number# of step to collect coin from# stack, with height in height[] arraydef minSteps(height, N): return minStepsRecur(height, 0, N, 0) # Driver codeheight = [ 2, 1, 2, 5, 1 ]N = len(height)print(minSteps(height, N)) # This code is contributed# by ChitraNayal",
"e": 5601,
"s": 4518,
"text": null
},
{
"code": "// C# Code to Collect all coins in// minimum number of stepsusing System; class GFG { // recursive method to collect coins from // height array l to r, with height h already // collected public static int minStepsRecur(int[] height, int l, int r, int h) { // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to // get minimum height index int m = l; for (int i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return Math.Min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h); } // method returns minimum number of step to // collect coin from stack, with height in // height[] array public static int minSteps(int[] height, int N) { return minStepsRecur(height, 0, N, 0); } /* Driver program to test above function */ public static void Main() { int[] height = { 2, 1, 2, 5, 1 }; int N = height.Length; Console.Write(minSteps(height, N)); }} // This code is contributed by nitin mittal",
"e": 7098,
"s": 5601,
"text": null
},
{
"code": "<?php// PHP program to find minimum number of// steps to collect stack of coins // recursive method to collect// coins from height array l to// r, with height h already// collectedfunction minStepsRecur($height, $l, $r, $h){ // if l is more than r, // no steps needed if ($l >= $r) return 0; // loop over heights to // get minimum height // index $m = $l; for ($i = $l; $i < $r; $i++) if ($height[$i] < $height[$m]) $m = $i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return min($r - $l, minStepsRecur($height, $l, $m, $height[$m]) + minStepsRecur($height, $m + 1, $r, $height[$m]) + $height[$m] - $h);} // method returns minimum number of step to// collect coin from stack, with height in// height[] arrayfunction minSteps($height, $N){ return minStepsRecur($height, 0, $N, 0);} // Driver Code $height = array(2, 1, 2, 5, 1); $N = sizeof($height); echo minSteps($height, $N) ; // This code is contributed by nitin mittal.?>",
"e": 8362,
"s": 7098,
"text": null
},
{
"code": "<script>// Javascript Code to Collect all coins in// minimum number of steps // recursive method to collect coins from // height array l to r, with height h already // collected function minStepsRecur(height,l,r,h) { // if l is more than r, no steps needed if (l >= r) return 0; // loop over heights to get minimum height // index let m = l; for (let i = l; i < r; i++) if (height[i] < height[m]) m = i; /* choose minimum from, 1) collecting coins using all vertical lines (total r - l) 2) collecting coins using lower horizontal lines and recursively on left and right segments */ return Math.min(r - l, minStepsRecur(height, l, m, height[m]) + minStepsRecur(height, m + 1, r, height[m]) + height[m] - h); } // method returns minimum number of step to // collect coin from stack, with height in // height[] array function minSteps(height,N) { return minStepsRecur(height, 0, N, 0); } /* Driver program to test above function */ let height=[2, 1, 2, 5, 1 ]; let N = height.length; document.write(minSteps(height, N)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 9743,
"s": 8362,
"text": null
},
{
"code": null,
"e": 9753,
"s": 9743,
"text": "Output: "
},
{
"code": null,
"e": 9755,
"s": 9753,
"text": "4"
},
{
"code": null,
"e": 10183,
"s": 9755,
"text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 10196,
"s": 10183,
"text": "nitin mittal"
},
{
"code": null,
"e": 10202,
"s": 10196,
"text": "ukasp"
},
{
"code": null,
"e": 10223,
"s": 10202,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 10242,
"s": 10223,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 10261,
"s": 10242,
"text": "Divide and Conquer"
}
] |
TextTable module in Python
|
11 Oct, 2020
It is a python module, which helps us to print table on terminal. It is one of the basic python modules for reading and writing text tables in ASCII code. It aims to make the interface as similar as possible like csv module in Python. The texttable module supports both fixed-size tables (where column sizes are pre-determined) and dynamic-size tables (where columns can added or removed).
Installation:
pip install texttable
Step-by-step Approach:
Import required module.
Python3
# Import required moduleimport texttable
Create an object of texttable()
Python3
# Creating objecttableObj = texttable.Texttable(self,max width) # max_width must be an integer,whose value is maximum width of the table# if set to 0, size is unlimited (self adjustible according to text inside cell),# therefore cells won't be wrapped so it's recommended to use 0
Use set_cols_align() method to create columns.
Python3
# Creating columnstableObj.set_cols_align(["l", "l", "r", "c"]) # Set the desired columns alignment:# "l" refers to column flushed left# "c" refers to column centered# "r" refers to column flushed right
Use set_cols_dtype() to set datatype of each column. However, this step is optional.
Python3
# Set datatypetableObj.set_cols_dtype(["t", "i", "f", "a"]) # texttable objects supports five types of data types:# "t" refers to text# "f" refers to decimal# "e" refers to exponent# "i" refers to integer# "a" refers to automatic
Use set_cols_valign() to adjust columns.
Python3
# Adjust ColumnstableObj.set_cols_valign(["t", "t", "m", "b"]) # Set the desired columns vertical alignment the elements of the # array should be either "t", "m" or "b":# "t" refers to column aligned on the top of the cell# "m" refers to column aligned on the middle of the cell# "b" refers to column aligned on the bottom of the cell
Use add_rows() method to insert rows into the table
Python3
# Adding rowstable.add_rows([ ["Text_Heading", "Int_Heading", "Float_Heading", "Auto_Heading"], ["Data1", 9, 1.23456789, "GFG"], ["Data2", 1, 9.87654321, "g4g"], ]) # add_rows(self, rows, header=True):# The 'rows' argument can be either an iterator returning arrays, or a# by-dimensional array.# 'header' specifies if the first row should be used as the header of the table
Use draw() method to display the table.
Python3
print(tableObj.draw())
The table illustration would be something like this:
Below is a program based on the above approach:
Python3
# Import required moduleimport texttable # Create texttable objecttableObj = texttable.Texttable() # Set columnstableObj.set_cols_align(["l", "r", "c"]) # Set datatype of each columntableObj.set_cols_dtype(["a", "i", "t"]) # Adjust columnstableObj.set_cols_valign(["t", "m", "b"]) # Insert rowstableObj.add_rows([ ["ORGANIZATION", "ESTABLISHED", "CEO"], ["Google", 1998, "Sundar Pichai"], ["Microsoft", 1975, "Satya Nadella"], ["Nokia", 1865, "Rajeev Suri"], ["Geeks for Geeks", 2008, "Sandeep Jain"], ["HackerRank", 2007, "Vivek Ravisankar"] ]) # Display tableprint(tableObj.draw())
Output:
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Oct, 2020"
},
{
"code": null,
"e": 418,
"s": 28,
"text": "It is a python module, which helps us to print table on terminal. It is one of the basic python modules for reading and writing text tables in ASCII code. It aims to make the interface as similar as possible like csv module in Python. The texttable module supports both fixed-size tables (where column sizes are pre-determined) and dynamic-size tables (where columns can added or removed)."
},
{
"code": null,
"e": 432,
"s": 418,
"text": "Installation:"
},
{
"code": null,
"e": 455,
"s": 432,
"text": "pip install texttable\n"
},
{
"code": null,
"e": 478,
"s": 455,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 502,
"s": 478,
"text": "Import required module."
},
{
"code": null,
"e": 510,
"s": 502,
"text": "Python3"
},
{
"code": "# Import required moduleimport texttable",
"e": 551,
"s": 510,
"text": null
},
{
"code": null,
"e": 583,
"s": 551,
"text": "Create an object of texttable()"
},
{
"code": null,
"e": 591,
"s": 583,
"text": "Python3"
},
{
"code": "# Creating objecttableObj = texttable.Texttable(self,max width) # max_width must be an integer,whose value is maximum width of the table# if set to 0, size is unlimited (self adjustible according to text inside cell),# therefore cells won't be wrapped so it's recommended to use 0",
"e": 873,
"s": 591,
"text": null
},
{
"code": null,
"e": 920,
"s": 873,
"text": "Use set_cols_align() method to create columns."
},
{
"code": null,
"e": 928,
"s": 920,
"text": "Python3"
},
{
"code": "# Creating columnstableObj.set_cols_align([\"l\", \"l\", \"r\", \"c\"]) # Set the desired columns alignment:# \"l\" refers to column flushed left# \"c\" refers to column centered# \"r\" refers to column flushed right",
"e": 1133,
"s": 928,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1133,
"text": "Use set_cols_dtype() to set datatype of each column. However, this step is optional."
},
{
"code": null,
"e": 1226,
"s": 1218,
"text": "Python3"
},
{
"code": "# Set datatypetableObj.set_cols_dtype([\"t\", \"i\", \"f\", \"a\"]) # texttable objects supports five types of data types:# \"t\" refers to text# \"f\" refers to decimal# \"e\" refers to exponent# \"i\" refers to integer# \"a\" refers to automatic",
"e": 1457,
"s": 1226,
"text": null
},
{
"code": null,
"e": 1498,
"s": 1457,
"text": "Use set_cols_valign() to adjust columns."
},
{
"code": null,
"e": 1506,
"s": 1498,
"text": "Python3"
},
{
"code": "# Adjust ColumnstableObj.set_cols_valign([\"t\", \"t\", \"m\", \"b\"]) # Set the desired columns vertical alignment the elements of the # array should be either \"t\", \"m\" or \"b\":# \"t\" refers to column aligned on the top of the cell# \"m\" refers to column aligned on the middle of the cell# \"b\" refers to column aligned on the bottom of the cell ",
"e": 1850,
"s": 1506,
"text": null
},
{
"code": null,
"e": 1902,
"s": 1850,
"text": "Use add_rows() method to insert rows into the table"
},
{
"code": null,
"e": 1910,
"s": 1902,
"text": "Python3"
},
{
"code": "# Adding rowstable.add_rows([ [\"Text_Heading\", \"Int_Heading\", \"Float_Heading\", \"Auto_Heading\"], [\"Data1\", 9, 1.23456789, \"GFG\"], [\"Data2\", 1, 9.87654321, \"g4g\"], ]) # add_rows(self, rows, header=True):# The 'rows' argument can be either an iterator returning arrays, or a# by-dimensional array.# 'header' specifies if the first row should be used as the header of the table",
"e": 2313,
"s": 1910,
"text": null
},
{
"code": null,
"e": 2353,
"s": 2313,
"text": "Use draw() method to display the table."
},
{
"code": null,
"e": 2361,
"s": 2353,
"text": "Python3"
},
{
"code": "print(tableObj.draw())",
"e": 2384,
"s": 2361,
"text": null
},
{
"code": null,
"e": 2437,
"s": 2384,
"text": "The table illustration would be something like this:"
},
{
"code": null,
"e": 2485,
"s": 2437,
"text": "Below is a program based on the above approach:"
},
{
"code": null,
"e": 2493,
"s": 2485,
"text": "Python3"
},
{
"code": "# Import required moduleimport texttable # Create texttable objecttableObj = texttable.Texttable() # Set columnstableObj.set_cols_align([\"l\", \"r\", \"c\"]) # Set datatype of each columntableObj.set_cols_dtype([\"a\", \"i\", \"t\"]) # Adjust columnstableObj.set_cols_valign([\"t\", \"m\", \"b\"]) # Insert rowstableObj.add_rows([ [\"ORGANIZATION\", \"ESTABLISHED\", \"CEO\"], [\"Google\", 1998, \"Sundar Pichai\"], [\"Microsoft\", 1975, \"Satya Nadella\"], [\"Nokia\", 1865, \"Rajeev Suri\"], [\"Geeks for Geeks\", 2008, \"Sandeep Jain\"], [\"HackerRank\", 2007, \"Vivek Ravisankar\"] ]) # Display tableprint(tableObj.draw())",
"e": 3132,
"s": 2493,
"text": null
},
{
"code": null,
"e": 3140,
"s": 3132,
"text": "Output:"
},
{
"code": null,
"e": 3155,
"s": 3140,
"text": "python-modules"
},
{
"code": null,
"e": 3162,
"s": 3155,
"text": "Python"
}
] |
lzma.LZMACompressor() in Python
|
26 Mar, 2020
With the help of lzma.LZMACompressor() method, we can get compressor to compress the bytes of string by using lzma.LZMACompressor() method.
Syntax : lzma.LZMACompressor()Return : Return compressed string.
Example #1 :In this example we can see that by using lzma.LZMACompressor() method, we are able to compress the string in the byte format by using this method.
# import lzma and compressimport lzma s = b'This is GFG author, and final year student.'print(len(s)) # using lzma.LZMACompressor() methodcompressor = lzma.LZMACompressor()t = compressor.compress(s)print(len(t))
Output :
4324
Example #2 :
# import lzma and compressimport lzma s = b'GeeksForGeeks@12345678'print(len(s)) # using lzma.LZMACompressor() methodcompressor = lzma.LZMACompressor()t = compressor.compress(s)print(len(t))
Output :
2224
Python-lzma
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2020"
},
{
"code": null,
"e": 168,
"s": 28,
"text": "With the help of lzma.LZMACompressor() method, we can get compressor to compress the bytes of string by using lzma.LZMACompressor() method."
},
{
"code": null,
"e": 233,
"s": 168,
"text": "Syntax : lzma.LZMACompressor()Return : Return compressed string."
},
{
"code": null,
"e": 392,
"s": 233,
"text": "Example #1 :In this example we can see that by using lzma.LZMACompressor() method, we are able to compress the string in the byte format by using this method."
},
{
"code": "# import lzma and compressimport lzma s = b'This is GFG author, and final year student.'print(len(s)) # using lzma.LZMACompressor() methodcompressor = lzma.LZMACompressor()t = compressor.compress(s)print(len(t))",
"e": 606,
"s": 392,
"text": null
},
{
"code": null,
"e": 615,
"s": 606,
"text": "Output :"
},
{
"code": null,
"e": 620,
"s": 615,
"text": "4324"
},
{
"code": null,
"e": 633,
"s": 620,
"text": "Example #2 :"
},
{
"code": "# import lzma and compressimport lzma s = b'GeeksForGeeks@12345678'print(len(s)) # using lzma.LZMACompressor() methodcompressor = lzma.LZMACompressor()t = compressor.compress(s)print(len(t))",
"e": 826,
"s": 633,
"text": null
},
{
"code": null,
"e": 835,
"s": 826,
"text": "Output :"
},
{
"code": null,
"e": 840,
"s": 835,
"text": "2224"
},
{
"code": null,
"e": 852,
"s": 840,
"text": "Python-lzma"
},
{
"code": null,
"e": 859,
"s": 852,
"text": "Python"
},
{
"code": null,
"e": 957,
"s": 859,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 989,
"s": 957,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1016,
"s": 989,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1037,
"s": 1016,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1060,
"s": 1037,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1091,
"s": 1060,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1147,
"s": 1091,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1189,
"s": 1147,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1231,
"s": 1189,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1270,
"s": 1231,
"text": "Python | Get unique values from a list"
}
] |
Randomized Algorithms | Set 1 (Introduction and Analysis)
|
28 Sep, 2020
An algorithm that uses random numbers to decide what to do next anywhere in its logic is called a Randomized Algorithm. For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). And in Karger’s algorithm, we randomly pick an edge.
Some randomized algorithms have deterministic time complexity. For example, this implementation of Karger’s algorithm has time complexity is O(E). Such algorithms are called Monte Carlo Algorithms and are easier to analyse for worst case. On the other hand, time complexity of other randomized algorithms (other than Las Vegas) is dependent on value of random variable. Such Randomized algorithms are called Las Vegas Algorithms. These algorithms are typically analysed for expected worst case. To compute expected time taken in worst case, all possible values of the used random variable needs to be considered in worst case and time taken by every possible value needs to be evaluated. Average of all evaluated times is the expected worst case time complexity. Below facts are generally helpful in analysis os such algorithms. Linearity of Expectation Expected Number of Trials until Success.
For example consider below a randomized version of QuickSort.
A Central Pivot is a pivot that divides the array in such a way that one side has at-least 1/4 elements.
// Sorts an array arr[low..high]
randQuickSort(arr[], low, high)
1. If low >= high, then EXIT.
2. While pivot 'x' is not a Central Pivot.
(i) Choose uniformly at random a number from [low..high].
Let the randomly picked number number be x.
(ii) Count elements in arr[low..high] that are smaller
than arr[x]. Let this count be sc.
(iii) Count elements in arr[low..high] that are greater
than arr[x]. Let this count be gc.
(iv) Let n = (high-low+1). If sc >= n/4 and
gc >= n/4, then x is a central pivot.
3. Partition arr[low..high] around the pivot x.
4. // Recur for smaller elements
randQuickSort(arr, low, sc-1)
5. // Recur for greater elements
randQuickSort(arr, high-gc+1, high)
The important thing in our analysis is, time taken by step 2 is O(n).
How many times while loop runs before finding a central pivot? The probability that the randomly chosen element is central pivot is 1/n.
Therefore, expected number of times the while loop runs is n (See this for details)
Thus, the expected time complexity of step 2 is O(n).
What is overall Time Complexity in Worst Case? In worst case, each partition divides array such that one side has n/4 elements and other side has 3n/4 elements. The worst case height of recursion tree is Log 3/4 n which is O(Log n).
T(n) < T(n/4) + T(3n/4) + O(n)
T(n) < 2T(3n/4) + O(n)
Solution of above recurrence is O(n Log n)
Note that the above randomized algorithm is not the best way to implement randomized Quick Sort. The idea here is to simplify the analysis as it is simple to analyse. Typically, randomized Quick Sort is implemented by randomly picking a pivot (no loop). Or by shuffling array elements. Expected worst case time complexity of this algorithm is also O(n Log n), but analysis is complex, the MIT prof himself mentions same in his lecture here.
Randomized Algorithms | Set 2 (Classification and Applications)
References: http://www.tcs.tifr.res.in/~workshop/nitrkl_igga/randomized-lecture.pdf
This article is contributed by Ashish Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
thefunnypet123
Randomized
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Sep, 2020"
},
{
"code": null,
"e": 349,
"s": 54,
"text": "An algorithm that uses random numbers to decide what to do next anywhere in its logic is called a Randomized Algorithm. For example, in Randomized Quick Sort, we use a random number to pick the next pivot (or we randomly shuffle the array). And in Karger’s algorithm, we randomly pick an edge. "
},
{
"code": null,
"e": 1247,
"s": 351,
"text": "Some randomized algorithms have deterministic time complexity. For example, this implementation of Karger’s algorithm has time complexity is O(E). Such algorithms are called Monte Carlo Algorithms and are easier to analyse for worst case. On the other hand, time complexity of other randomized algorithms (other than Las Vegas) is dependent on value of random variable. Such Randomized algorithms are called Las Vegas Algorithms. These algorithms are typically analysed for expected worst case. To compute expected time taken in worst case, all possible values of the used random variable needs to be considered in worst case and time taken by every possible value needs to be evaluated. Average of all evaluated times is the expected worst case time complexity. Below facts are generally helpful in analysis os such algorithms. Linearity of Expectation Expected Number of Trials until Success. "
},
{
"code": null,
"e": 1310,
"s": 1247,
"text": "For example consider below a randomized version of QuickSort. "
},
{
"code": null,
"e": 1416,
"s": 1310,
"text": "A Central Pivot is a pivot that divides the array in such a way that one side has at-least 1/4 elements. "
},
{
"code": null,
"e": 2163,
"s": 1418,
"text": "// Sorts an array arr[low..high]\nrandQuickSort(arr[], low, high)\n\n1. If low >= high, then EXIT.\n\n2. While pivot 'x' is not a Central Pivot.\n (i) Choose uniformly at random a number from [low..high]. \n Let the randomly picked number number be x.\n (ii) Count elements in arr[low..high] that are smaller \n than arr[x]. Let this count be sc.\n (iii) Count elements in arr[low..high] that are greater \n than arr[x]. Let this count be gc.\n (iv) Let n = (high-low+1). If sc >= n/4 and\n gc >= n/4, then x is a central pivot.\n\n3. Partition arr[low..high] around the pivot x.\n\n4. // Recur for smaller elements\n randQuickSort(arr, low, sc-1) \n\n5. // Recur for greater elements\n randQuickSort(arr, high-gc+1, high) \n\n"
},
{
"code": null,
"e": 2234,
"s": 2163,
"text": "The important thing in our analysis is, time taken by step 2 is O(n). "
},
{
"code": null,
"e": 2372,
"s": 2234,
"text": "How many times while loop runs before finding a central pivot? The probability that the randomly chosen element is central pivot is 1/n. "
},
{
"code": null,
"e": 2457,
"s": 2372,
"text": "Therefore, expected number of times the while loop runs is n (See this for details) "
},
{
"code": null,
"e": 2512,
"s": 2457,
"text": "Thus, the expected time complexity of step 2 is O(n). "
},
{
"code": null,
"e": 2746,
"s": 2512,
"text": "What is overall Time Complexity in Worst Case? In worst case, each partition divides array such that one side has n/4 elements and other side has 3n/4 elements. The worst case height of recursion tree is Log 3/4 n which is O(Log n). "
},
{
"code": null,
"e": 2847,
"s": 2746,
"text": "T(n) < T(n/4) + T(3n/4) + O(n)\nT(n) < 2T(3n/4) + O(n)\n\nSolution of above recurrence is O(n Log n) \n\n"
},
{
"code": null,
"e": 3289,
"s": 2847,
"text": "Note that the above randomized algorithm is not the best way to implement randomized Quick Sort. The idea here is to simplify the analysis as it is simple to analyse. Typically, randomized Quick Sort is implemented by randomly picking a pivot (no loop). Or by shuffling array elements. Expected worst case time complexity of this algorithm is also O(n Log n), but analysis is complex, the MIT prof himself mentions same in his lecture here. "
},
{
"code": null,
"e": 3354,
"s": 3289,
"text": "Randomized Algorithms | Set 2 (Classification and Applications) "
},
{
"code": null,
"e": 3439,
"s": 3354,
"text": "References: http://www.tcs.tifr.res.in/~workshop/nitrkl_igga/randomized-lecture.pdf "
},
{
"code": null,
"e": 3610,
"s": 3439,
"text": "This article is contributed by Ashish Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 3625,
"s": 3610,
"text": "thefunnypet123"
},
{
"code": null,
"e": 3636,
"s": 3625,
"text": "Randomized"
}
] |
Lexicographically smallest string formed by removing duplicates
|
13 Jun, 2022
Given a string S consisting of lowercase alphabets, the task is to find the lexicographically smallest string that can be obtained by removing duplicates from the given string S.
Examples:
Input: S = “yzxyz”Output: xyzExplanation: Removing the duplicate characters at indices 0 and 1 in the given string, the remaining string “xyz” consists only of unique alphabets only and is the smallest possible string in lexicographical order.
Input: S = “acbc”Output: “abc”Explanation: Removing the duplicate characters at index 3 in the given string, the remaining string “abc” consists only of unique alphabets only and is the smallest possible string in lexicographical order.
Approach: Follow the steps below to solve the problem:
Initialize a string res to store the resultant string.
Store the frequency of each character present in the given string in an array freq[].
Maintain an array vis[] for marking the characters that are already present in the resultant string res.
Traverse the given string S and for each character S[i], perform the following:Decrease the frequency of the current character by 1.If the current character is not marked visited in the array vis[], then perform the following:If the last letter of res is less than S[i], add S[i] to res.If the last letter of res is greater than S[i] and the count of the last letter of res exceeds 0, then remove that character and mark visit[S[i]] as 0 and continue this step till the above condition is satisfied.After breaking out from the above condition, add S[i] to res and mark visit[S[i]] as 1.
Decrease the frequency of the current character by 1.
If the current character is not marked visited in the array vis[], then perform the following:If the last letter of res is less than S[i], add S[i] to res.If the last letter of res is greater than S[i] and the count of the last letter of res exceeds 0, then remove that character and mark visit[S[i]] as 0 and continue this step till the above condition is satisfied.After breaking out from the above condition, add S[i] to res and mark visit[S[i]] as 1.
If the last letter of res is less than S[i], add S[i] to res.
If the last letter of res is greater than S[i] and the count of the last letter of res exceeds 0, then remove that character and mark visit[S[i]] as 0 and continue this step till the above condition is satisfied.
After breaking out from the above condition, add S[i] to res and mark visit[S[i]] as 1.
After completing the above steps, print the string res as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringstring removeDuplicateLetters(string s){ // Stores the frequency of characters int cnt[26] = { 0 }; // Mark visited characters int vis[26] = { 0 }; int n = s.size(); // Stores count of each character for (int i = 0; i < n; i++) cnt[s[i] - 'a']++; // Stores the resultant string string res = ""; for (int i = 0; i < n; i++) { // Decrease the count of // current character cnt[s[i] - 'a']--; // If character is not already // in answer if (!vis[s[i] - 'a']) { // Last character > S[i] // and its count > 0 while (res.size() > 0 && res.back() > s[i] && cnt[res.back() - 'a'] > 0) { // Mark letter unvisited vis[res.back() - 'a'] = 0; res.pop_back(); } // Add s[i] in res and // mark it visited res += s[i]; vis[s[i] - 'a'] = 1; } } // Return the resultant string return res;} // Driver Codeint main(){ // Given string S string S = "acbc"; // Function Call cout << removeDuplicateLetters(S); return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringstatic String removeDuplicateLetters(String s){ // Stores the frequency of characters int[] cnt = new int[26]; // Mark visited characters int[] vis = new int[26]; int n = s.length(); // Stores count of each character for(int i = 0; i < n; i++) cnt[s.charAt(i) - 'a']++; // Stores the resultant string String res = ""; for(int i = 0; i < n; i++) { // Decrease the count of // current character cnt[s.charAt(i) - 'a']--; // If character is not already // in answer if (vis[s.charAt(i) - 'a'] == 0) { // Last character > S[i] // and its count > 0 int size = res.length(); while (size > 0 && res.charAt(size - 1) > s.charAt(i) && cnt[res.charAt(size - 1) - 'a'] > 0) { // Mark letter unvisited vis[res.charAt(size - 1) - 'a'] = 0; res = res.substring(0, size - 1); size--; } // Add s[i] in res and // mark it visited res += s.charAt(i); vis[s.charAt(i) - 'a'] = 1; } } // Return the resultant string return res;} // Driver Codepublic static void main(String[] args){ // Given string S String S = "acbc"; // Function Call System.out.println(removeDuplicateLetters(S));}} // This code is contributed by akhilsaini
# Python3 program for the above approach # Function that finds lexicographically# smallest after removing the# duplicates from the given stringdef removeDuplicateLetters(s): # Stores the frequency of characters cnt = [0] * 26 # Mark visited characters vis = [0] * 26 n = len(s) # Stores count of each character for i in s: cnt[ord(i) - ord('a')] += 1 # Stores the resultant string res = [] for i in range(n): # Decrease the count of # current character cnt[ord(s[i]) - ord('a')] -= 1 # If character is not already # in answer if (not vis[ord(s[i]) - ord('a')]): # Last character > S[i] # and its count > 0 while (len(res) > 0 and res[-1] > s[i] and cnt[ord(res[-1]) - ord('a')] > 0): # Mark letter unvisited vis[ord(res[-1]) - ord('a')] = 0 del res[-1] # Add s[i] in res and # mark it visited res += s[i] vis[ord(s[i]) - ord('a')] = 1 # Return the resultant string return "".join(res) # Driver Codeif __name__ == '__main__': # Given S S = "acbc" # Function Call print(removeDuplicateLetters(S)) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{ // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringstatic string removeDuplicateLetters(string s){ // Stores the frequency of characters int[] cnt = new int[26]; // Mark visited characters int[] vis = new int[26]; int n = s.Length; // Stores count of each character for(int i = 0; i < n; i++) cnt[s[i] - 'a']++; // Stores the resultant string String res = ""; for(int i = 0; i < n; i++) { // Decrease the count of // current character cnt[s[i] - 'a']--; // If character is not already // in answer if (vis[s[i] - 'a'] == 0) { // Last character > S[i] // and its count > 0 int size = res.Length; while (size > 0 && res[size - 1] > s[i] && cnt[res[size - 1] - 'a'] > 0) { // Mark letter unvisited vis[res[size - 1] - 'a'] = 0; res = res.Substring(0, size - 1); size--; } // Add s[i] in res and // mark it visited res += s[i]; vis[s[i] - 'a'] = 1; } } // Return the resultant string return res;} // Driver Codepublic static void Main(){ // Given string S string S = "acbc"; // Function Call Console.WriteLine(removeDuplicateLetters(S));}} // This code is contributed by akhilsaini
<script> // Javascript program for the above approach // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringfunction removeDuplicateLetters(s){ // Stores the frequency of characters var cnt = Array(26).fill(0); // Mark visited characters var vis = Array(26).fill(false); var n = s.length; // Stores count of each character for (var i = 0; i < n; i++) cnt[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Stores the resultant string var res = ""; for (var i = 0; i < n; i++) { // Decrease the count of // current character cnt[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; // If character is not already // in answer if (!vis[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]) { // Last character > S[i] // and its count > 0 while (res.length > 0 && res[res.length-1].charCodeAt(0) > s[i].charCodeAt(0) && cnt[res[res.length-1].charCodeAt(0) - 'a'.charCodeAt(0)] > 0) { // Mark letter unvisited vis[res[res.length-1].charCodeAt(0) - 'a'.charCodeAt(0)] = 0; res = res.substring(0, res.length-1); } // Add s[i] in res and // mark it visited res += s[i]; vis[s[i].charCodeAt(0) - 'a'.charCodeAt(0)] = 1; } } // Return the resultant string return res;} // Driver Code// Given string Svar S = "acbc"; // Function Calldocument.write( removeDuplicateLetters(S)); </script>
abc
Time Complexity: O(N)Auxiliary Space: O(1) (as we are using visited and cnt both array of fixed size 26)
mohit kumar 29
akhilsaini
itsok
ajaymakvana
frequency-counting
lexicographic-ordering
Greedy
Hash
Strings
Hash
Strings
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Policemen catch thieves
Fractional Knapsack Problem
What is Hashing | A Complete Tutorial
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Hashing | Set 1 (Introduction)
Internal Working of HashMap in Java
Longest Consecutive Subsequence
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 233,
"s": 54,
"text": "Given a string S consisting of lowercase alphabets, the task is to find the lexicographically smallest string that can be obtained by removing duplicates from the given string S."
},
{
"code": null,
"e": 243,
"s": 233,
"text": "Examples:"
},
{
"code": null,
"e": 487,
"s": 243,
"text": "Input: S = “yzxyz”Output: xyzExplanation: Removing the duplicate characters at indices 0 and 1 in the given string, the remaining string “xyz” consists only of unique alphabets only and is the smallest possible string in lexicographical order."
},
{
"code": null,
"e": 724,
"s": 487,
"text": "Input: S = “acbc”Output: “abc”Explanation: Removing the duplicate characters at index 3 in the given string, the remaining string “abc” consists only of unique alphabets only and is the smallest possible string in lexicographical order."
},
{
"code": null,
"e": 779,
"s": 724,
"text": "Approach: Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 834,
"s": 779,
"text": "Initialize a string res to store the resultant string."
},
{
"code": null,
"e": 920,
"s": 834,
"text": "Store the frequency of each character present in the given string in an array freq[]."
},
{
"code": null,
"e": 1025,
"s": 920,
"text": "Maintain an array vis[] for marking the characters that are already present in the resultant string res."
},
{
"code": null,
"e": 1612,
"s": 1025,
"text": "Traverse the given string S and for each character S[i], perform the following:Decrease the frequency of the current character by 1.If the current character is not marked visited in the array vis[], then perform the following:If the last letter of res is less than S[i], add S[i] to res.If the last letter of res is greater than S[i] and the count of the last letter of res exceeds 0, then remove that character and mark visit[S[i]] as 0 and continue this step till the above condition is satisfied.After breaking out from the above condition, add S[i] to res and mark visit[S[i]] as 1."
},
{
"code": null,
"e": 1666,
"s": 1612,
"text": "Decrease the frequency of the current character by 1."
},
{
"code": null,
"e": 2121,
"s": 1666,
"text": "If the current character is not marked visited in the array vis[], then perform the following:If the last letter of res is less than S[i], add S[i] to res.If the last letter of res is greater than S[i] and the count of the last letter of res exceeds 0, then remove that character and mark visit[S[i]] as 0 and continue this step till the above condition is satisfied.After breaking out from the above condition, add S[i] to res and mark visit[S[i]] as 1."
},
{
"code": null,
"e": 2183,
"s": 2121,
"text": "If the last letter of res is less than S[i], add S[i] to res."
},
{
"code": null,
"e": 2396,
"s": 2183,
"text": "If the last letter of res is greater than S[i] and the count of the last letter of res exceeds 0, then remove that character and mark visit[S[i]] as 0 and continue this step till the above condition is satisfied."
},
{
"code": null,
"e": 2484,
"s": 2396,
"text": "After breaking out from the above condition, add S[i] to res and mark visit[S[i]] as 1."
},
{
"code": null,
"e": 2554,
"s": 2484,
"text": "After completing the above steps, print the string res as the result."
},
{
"code": null,
"e": 2605,
"s": 2554,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2609,
"s": 2605,
"text": "C++"
},
{
"code": null,
"e": 2614,
"s": 2609,
"text": "Java"
},
{
"code": null,
"e": 2622,
"s": 2614,
"text": "Python3"
},
{
"code": null,
"e": 2625,
"s": 2622,
"text": "C#"
},
{
"code": null,
"e": 2636,
"s": 2625,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringstring removeDuplicateLetters(string s){ // Stores the frequency of characters int cnt[26] = { 0 }; // Mark visited characters int vis[26] = { 0 }; int n = s.size(); // Stores count of each character for (int i = 0; i < n; i++) cnt[s[i] - 'a']++; // Stores the resultant string string res = \"\"; for (int i = 0; i < n; i++) { // Decrease the count of // current character cnt[s[i] - 'a']--; // If character is not already // in answer if (!vis[s[i] - 'a']) { // Last character > S[i] // and its count > 0 while (res.size() > 0 && res.back() > s[i] && cnt[res.back() - 'a'] > 0) { // Mark letter unvisited vis[res.back() - 'a'] = 0; res.pop_back(); } // Add s[i] in res and // mark it visited res += s[i]; vis[s[i] - 'a'] = 1; } } // Return the resultant string return res;} // Driver Codeint main(){ // Given string S string S = \"acbc\"; // Function Call cout << removeDuplicateLetters(S); return 0;}",
"e": 4021,
"s": 2636,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringstatic String removeDuplicateLetters(String s){ // Stores the frequency of characters int[] cnt = new int[26]; // Mark visited characters int[] vis = new int[26]; int n = s.length(); // Stores count of each character for(int i = 0; i < n; i++) cnt[s.charAt(i) - 'a']++; // Stores the resultant string String res = \"\"; for(int i = 0; i < n; i++) { // Decrease the count of // current character cnt[s.charAt(i) - 'a']--; // If character is not already // in answer if (vis[s.charAt(i) - 'a'] == 0) { // Last character > S[i] // and its count > 0 int size = res.length(); while (size > 0 && res.charAt(size - 1) > s.charAt(i) && cnt[res.charAt(size - 1) - 'a'] > 0) { // Mark letter unvisited vis[res.charAt(size - 1) - 'a'] = 0; res = res.substring(0, size - 1); size--; } // Add s[i] in res and // mark it visited res += s.charAt(i); vis[s.charAt(i) - 'a'] = 1; } } // Return the resultant string return res;} // Driver Codepublic static void main(String[] args){ // Given string S String S = \"acbc\"; // Function Call System.out.println(removeDuplicateLetters(S));}} // This code is contributed by akhilsaini",
"e": 5705,
"s": 4021,
"text": null
},
{
"code": "# Python3 program for the above approach # Function that finds lexicographically# smallest after removing the# duplicates from the given stringdef removeDuplicateLetters(s): # Stores the frequency of characters cnt = [0] * 26 # Mark visited characters vis = [0] * 26 n = len(s) # Stores count of each character for i in s: cnt[ord(i) - ord('a')] += 1 # Stores the resultant string res = [] for i in range(n): # Decrease the count of # current character cnt[ord(s[i]) - ord('a')] -= 1 # If character is not already # in answer if (not vis[ord(s[i]) - ord('a')]): # Last character > S[i] # and its count > 0 while (len(res) > 0 and res[-1] > s[i] and cnt[ord(res[-1]) - ord('a')] > 0): # Mark letter unvisited vis[ord(res[-1]) - ord('a')] = 0 del res[-1] # Add s[i] in res and # mark it visited res += s[i] vis[ord(s[i]) - ord('a')] = 1 # Return the resultant string return \"\".join(res) # Driver Codeif __name__ == '__main__': # Given S S = \"acbc\" # Function Call print(removeDuplicateLetters(S)) # This code is contributed by mohit kumar 29",
"e": 7052,
"s": 5705,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringstatic string removeDuplicateLetters(string s){ // Stores the frequency of characters int[] cnt = new int[26]; // Mark visited characters int[] vis = new int[26]; int n = s.Length; // Stores count of each character for(int i = 0; i < n; i++) cnt[s[i] - 'a']++; // Stores the resultant string String res = \"\"; for(int i = 0; i < n; i++) { // Decrease the count of // current character cnt[s[i] - 'a']--; // If character is not already // in answer if (vis[s[i] - 'a'] == 0) { // Last character > S[i] // and its count > 0 int size = res.Length; while (size > 0 && res[size - 1] > s[i] && cnt[res[size - 1] - 'a'] > 0) { // Mark letter unvisited vis[res[size - 1] - 'a'] = 0; res = res.Substring(0, size - 1); size--; } // Add s[i] in res and // mark it visited res += s[i]; vis[s[i] - 'a'] = 1; } } // Return the resultant string return res;} // Driver Codepublic static void Main(){ // Given string S string S = \"acbc\"; // Function Call Console.WriteLine(removeDuplicateLetters(S));}} // This code is contributed by akhilsaini",
"e": 8620,
"s": 7052,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function that finds lexicographically// smallest string after removing the// duplicates from the given stringfunction removeDuplicateLetters(s){ // Stores the frequency of characters var cnt = Array(26).fill(0); // Mark visited characters var vis = Array(26).fill(false); var n = s.length; // Stores count of each character for (var i = 0; i < n; i++) cnt[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // Stores the resultant string var res = \"\"; for (var i = 0; i < n; i++) { // Decrease the count of // current character cnt[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]--; // If character is not already // in answer if (!vis[s[i].charCodeAt(0) - 'a'.charCodeAt(0)]) { // Last character > S[i] // and its count > 0 while (res.length > 0 && res[res.length-1].charCodeAt(0) > s[i].charCodeAt(0) && cnt[res[res.length-1].charCodeAt(0) - 'a'.charCodeAt(0)] > 0) { // Mark letter unvisited vis[res[res.length-1].charCodeAt(0) - 'a'.charCodeAt(0)] = 0; res = res.substring(0, res.length-1); } // Add s[i] in res and // mark it visited res += s[i]; vis[s[i].charCodeAt(0) - 'a'.charCodeAt(0)] = 1; } } // Return the resultant string return res;} // Driver Code// Given string Svar S = \"acbc\"; // Function Calldocument.write( removeDuplicateLetters(S)); </script>",
"e": 10253,
"s": 8620,
"text": null
},
{
"code": null,
"e": 10257,
"s": 10253,
"text": "abc"
},
{
"code": null,
"e": 10364,
"s": 10259,
"text": "Time Complexity: O(N)Auxiliary Space: O(1) (as we are using visited and cnt both array of fixed size 26)"
},
{
"code": null,
"e": 10379,
"s": 10364,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 10390,
"s": 10379,
"text": "akhilsaini"
},
{
"code": null,
"e": 10396,
"s": 10390,
"text": "itsok"
},
{
"code": null,
"e": 10408,
"s": 10396,
"text": "ajaymakvana"
},
{
"code": null,
"e": 10427,
"s": 10408,
"text": "frequency-counting"
},
{
"code": null,
"e": 10450,
"s": 10427,
"text": "lexicographic-ordering"
},
{
"code": null,
"e": 10457,
"s": 10450,
"text": "Greedy"
},
{
"code": null,
"e": 10462,
"s": 10457,
"text": "Hash"
},
{
"code": null,
"e": 10470,
"s": 10462,
"text": "Strings"
},
{
"code": null,
"e": 10475,
"s": 10470,
"text": "Hash"
},
{
"code": null,
"e": 10483,
"s": 10475,
"text": "Strings"
},
{
"code": null,
"e": 10490,
"s": 10483,
"text": "Greedy"
},
{
"code": null,
"e": 10588,
"s": 10490,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10619,
"s": 10588,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 10638,
"s": 10619,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 10681,
"s": 10638,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 10705,
"s": 10681,
"text": "Policemen catch thieves"
},
{
"code": null,
"e": 10733,
"s": 10705,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 10771,
"s": 10733,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 10856,
"s": 10771,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 10887,
"s": 10856,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 10923,
"s": 10887,
"text": "Internal Working of HashMap in Java"
}
] |
Recursive program to generate power set
|
Difficulty Level :
Medium
Given a set represented as a string, write a recursive code to print all subsets of it. The subsets can be printed in any order.
Examples:
Input : set = "abc"
Output : "", "a", "b", "c", "ab", "ac", "bc", "abc"
Input : set = "abcd"
Output : "" "a" "ab" "abc" "abcd" "abd" "ac" "acd"
"ad" "b" "bc" "bcd" "bd" "c" "cd" "d"
Method 1: The idea is to fix a prefix, generate all subsets beginning with the current prefix. After all subsets with a prefix are generated, replace the last character with one of the remaining characters.
C++
Java
Python3
C#
Javascript
// CPP program to generate power set#include <bits/stdc++.h>using namespace std; // str : Stores input string// curr : Stores current subset// index : Index in current subset, currvoid powerSet(string str, int index = -1, string curr = ""){ int n = str.length(); // base case if (index == n) return; // First print current subset cout << curr << "\n"; // Try appending remaining characters // to current subset for (int i = index + 1; i < n; i++) { curr += str[i]; powerSet(str, i, curr); // Once all subsets beginning with // initial "curr" are printed, remove // last character to consider a different // prefix of subsets. curr.erase(curr.size() - 1); } return;} // Driver codeint main(){ string str = "abc"; powerSet(str); return 0;}
// Java program to generate power setimport java.util.*; class GFG{ // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr static void powerSet(String str, int index, String curr) { int n = str.length(); // base case if (index == n) { return; } // First print current subset System.out.println(curr); // Try appending remaining characters // to current subset for (int i = index + 1; i < n; i++) { curr += str.charAt(i); powerSet(str, i, curr); // Once all subsets beginning with // initial "curr" are printed, remove // last character to consider a different // prefix of subsets. curr = curr.substring(0, curr.length() - 1); } } // Driver code public static void main(String[] args) { String str = "abc"; int index = -1; String curr = ""; powerSet(str, index, curr); }} // This code is contributed by PrinciRaj1992
# Python3 program to generate power set # str : Stores input string# curr : Stores current subset# index : Index in current subset, currdef powerSet(str1, index, curr): n = len(str1) # base case if (index == n): return # First print current subset print(curr) # Try appending remaining characters # to current subset for i in range(index + 1, n): curr += str1[i] powerSet(str1, i, curr) # Once all subsets beginning with # initial "curr" are printed, remove # last character to consider a different # prefix of subsets. curr = curr.replace(curr[len(curr) - 1], "") return # Driver codeif __name__ == '__main__': str = "abc"; powerSet(str, -1, "") # This code is contributed by# Surendra_Gangwar
// C# program to generate power setusing System; class GFG{ // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr static void powerSet(string str, int index, string curr) { int n = str.Length; // base case if (index == n) { return; } // First print current subset Console.WriteLine(curr); // Try appending remaining characters // to current subset for (int i = index + 1; i < n; i++) { curr += str[i]; powerSet(str, i, curr); // Once all subsets beginning with // initial "curr" are printed, remove // last character to consider a different // prefix of subsets. curr = curr.Substring(0, curr.Length - 1); } } // Driver code public static void Main() { string str = "abc"; int index = -1; string curr = ""; powerSet(str, index, curr); }} // This code is contributed by Ita_c.
<script>// Javascript program to generate power set // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr function powerSet(str,index,curr) { let n = str.length; // base case if (index == n) { return; } // First print current subset document.write(curr+"<br>"); // Try appending remaining characters // to current subset for (let i = index + 1; i < n; i++) { curr += str[i]; powerSet(str, i, curr); // Once all subsets beginning with // initial "curr" are printed, remove // last character to consider a different // prefix of subsets. curr = curr.substring(0, curr.length - 1); } } // Driver code let str = "abc"; let index = -1; let curr = ""; powerSet(str, index, curr); // This code is contributed by rag2127</script>
a
ab
abc
ac
b
bc
c
Method 2: The idea is to consider two cases for every character. (i) Consider current character as part of current subset (ii) Do not consider current character as part of the current subset.
C++
Java
Python3
C#
Javascript
// CPP program to generate power set#include <bits/stdc++.h>using namespace std; // str : Stores input string// curr : Stores current subset// index : Index in current subset, currvoid powerSet(string str, int index = 0, string curr = ""){ int n = str.length(); // base case if (index == n) { cout << curr << endl; return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str[index]); powerSet(str, index + 1, curr);} // Driver codeint main(){ string str = "abc"; powerSet(str); return 0;}
// Java program to generate power setclass GFG { // str : Stores input string// curr : Stores current subset// index : Index in current subset, currstatic void powerSet(String str, int index, String curr) { int n = str.length(); // base case if (index == n) { System.out.println(curr); return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str.charAt(index)); powerSet(str, index + 1, curr); } // Driver codepublic static void main(String[] args){ String str = "abc"; int index = 0; String curr=""; powerSet(str,index,curr); }}// This code is contributed by 29AjayKumar
# Python3 program to generate power setdef powerSet(string , index , curr): # string : Stores input string # curr : Stores current subset # index : Index in current subset, curr if index == len(string): print(curr) return powerSet(string, index + 1, curr + string[index]) powerSet(string, index + 1, curr) # Driver Codeif __name__ == "__main__": s1 = "abc" index = 0 curr = "" powerSet(s1, index , curr) # This code is contributed by Ekta Singh
// C# program to generate power setusing System; class GFG{ // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr static void powerSet(String str, int index, String curr) { int n = str.Length; // base case if (index == n) { Console.WriteLine(curr); return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str[index]); powerSet(str, index + 1, curr); } // Driver code public static void Main() { String str = "abc"; int index = 0; String curr=""; powerSet(str,index,curr); }} //This code is contributed by Rajput-Ji
<script>// Javascript program to generate power set // str : Stores input string// curr : Stores current subset// index : Index in current subset, curr function powerSet(str,index,curr) { let n = str.length; // base case if (index == n) { document.write(curr+"<br>"); return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str[index]); powerSet(str, index + 1, curr); } // Driver code let str = "abc"; let index = 0; let curr=""; powerSet(str,index,curr); // This code is contributed by avanitrachhadiya2155</script>
abc
ab
ac
a
bc
b
c
Method 3: The idea is to pick each element one by one from the input set, then generate a subset for the same, and we follow this process recursively. We’ll use ArrayList for this purpose For ex, f(0) = {a}, {} // {} when we don’t include any element from the set, it is null i.e {}. f(1) = {a}, {}, {b}, {a, b} // We have to copy all the elements from f(0) and then include the very next element from the set i.e b. So f(1) = f(0) + 1; f(2) = {a}, {}, {b}, {a, b}, {a, c}, {c}, {b, c}, {a, b, c}. So f(2) = f(1) +2;The general form becomes f(n) = f(n-1) + n;
Java
// Java Recursive code to print// all subsets of set using ArrayListimport java.util.ArrayList; public class PowerSet { public static void main(String[] args) { String[] set = { "a", "b", "c" }; int index = set.length - 1; ArrayList<ArrayList<String> > result = getSubset(set, index); System.out.println(result); } static ArrayList<ArrayList<String> > getSubset(String[] set, int index) { ArrayList<ArrayList<String> > allSubsets; if (index < 0) { allSubsets = new ArrayList<ArrayList<String> >(); allSubsets.add(new ArrayList<String>()); } else { allSubsets = getSubset(set, index - 1); String item = set[index]; ArrayList<ArrayList<String> > moreSubsets = new ArrayList<ArrayList<String> >(); for (ArrayList<String> subset : allSubsets) { ArrayList<String> newSubset = new ArrayList<String>(); newSubset.addAll(subset); newSubset.add(item); moreSubsets.add(newSubset); } allSubsets.addAll(moreSubsets); } return allSubsets; }}
[[], [a], [b], [a, b], , [a, c], [b, c], [a, b, c]]
Iterative program for power set.
Anurag Vishwa
29AjayKumar
Rajput-Ji
princiraj1992
ukasp
rambabuy
SURENDRA_GANGWAR
ekta1991singh
rag2127
avanitrachhadiya2155
whoibrar
subset
Backtracking
Recursion
Recursion
subset
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 26,
"s": 0,
"text": "Difficulty Level :\nMedium"
},
{
"code": null,
"e": 156,
"s": 26,
"text": "Given a set represented as a string, write a recursive code to print all subsets of it. The subsets can be printed in any order. "
},
{
"code": null,
"e": 168,
"s": 156,
"text": "Examples: "
},
{
"code": null,
"e": 362,
"s": 168,
"text": "Input : set = \"abc\"\nOutput : \"\", \"a\", \"b\", \"c\", \"ab\", \"ac\", \"bc\", \"abc\"\n\nInput : set = \"abcd\"\nOutput : \"\" \"a\" \"ab\" \"abc\" \"abcd\" \"abd\" \"ac\" \"acd\"\n \"ad\" \"b\" \"bc\" \"bcd\" \"bd\" \"c\" \"cd\" \"d\" "
},
{
"code": null,
"e": 571,
"s": 362,
"text": "Method 1: The idea is to fix a prefix, generate all subsets beginning with the current prefix. After all subsets with a prefix are generated, replace the last character with one of the remaining characters. "
},
{
"code": null,
"e": 575,
"s": 571,
"text": "C++"
},
{
"code": null,
"e": 580,
"s": 575,
"text": "Java"
},
{
"code": null,
"e": 588,
"s": 580,
"text": "Python3"
},
{
"code": null,
"e": 591,
"s": 588,
"text": "C#"
},
{
"code": null,
"e": 602,
"s": 591,
"text": "Javascript"
},
{
"code": "// CPP program to generate power set#include <bits/stdc++.h>using namespace std; // str : Stores input string// curr : Stores current subset// index : Index in current subset, currvoid powerSet(string str, int index = -1, string curr = \"\"){ int n = str.length(); // base case if (index == n) return; // First print current subset cout << curr << \"\\n\"; // Try appending remaining characters // to current subset for (int i = index + 1; i < n; i++) { curr += str[i]; powerSet(str, i, curr); // Once all subsets beginning with // initial \"curr\" are printed, remove // last character to consider a different // prefix of subsets. curr.erase(curr.size() - 1); } return;} // Driver codeint main(){ string str = \"abc\"; powerSet(str); return 0;}",
"e": 1453,
"s": 602,
"text": null
},
{
"code": "// Java program to generate power setimport java.util.*; class GFG{ // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr static void powerSet(String str, int index, String curr) { int n = str.length(); // base case if (index == n) { return; } // First print current subset System.out.println(curr); // Try appending remaining characters // to current subset for (int i = index + 1; i < n; i++) { curr += str.charAt(i); powerSet(str, i, curr); // Once all subsets beginning with // initial \"curr\" are printed, remove // last character to consider a different // prefix of subsets. curr = curr.substring(0, curr.length() - 1); } } // Driver code public static void main(String[] args) { String str = \"abc\"; int index = -1; String curr = \"\"; powerSet(str, index, curr); }} // This code is contributed by PrinciRaj1992",
"e": 2580,
"s": 1453,
"text": null
},
{
"code": "# Python3 program to generate power set # str : Stores input string# curr : Stores current subset# index : Index in current subset, currdef powerSet(str1, index, curr): n = len(str1) # base case if (index == n): return # First print current subset print(curr) # Try appending remaining characters # to current subset for i in range(index + 1, n): curr += str1[i] powerSet(str1, i, curr) # Once all subsets beginning with # initial \"curr\" are printed, remove # last character to consider a different # prefix of subsets. curr = curr.replace(curr[len(curr) - 1], \"\") return # Driver codeif __name__ == '__main__': str = \"abc\"; powerSet(str, -1, \"\") # This code is contributed by# Surendra_Gangwar",
"e": 3369,
"s": 2580,
"text": null
},
{
"code": "// C# program to generate power setusing System; class GFG{ // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr static void powerSet(string str, int index, string curr) { int n = str.Length; // base case if (index == n) { return; } // First print current subset Console.WriteLine(curr); // Try appending remaining characters // to current subset for (int i = index + 1; i < n; i++) { curr += str[i]; powerSet(str, i, curr); // Once all subsets beginning with // initial \"curr\" are printed, remove // last character to consider a different // prefix of subsets. curr = curr.Substring(0, curr.Length - 1); } } // Driver code public static void Main() { string str = \"abc\"; int index = -1; string curr = \"\"; powerSet(str, index, curr); }} // This code is contributed by Ita_c.",
"e": 4456,
"s": 3369,
"text": null
},
{
"code": "<script>// Javascript program to generate power set // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr function powerSet(str,index,curr) { let n = str.length; // base case if (index == n) { return; } // First print current subset document.write(curr+\"<br>\"); // Try appending remaining characters // to current subset for (let i = index + 1; i < n; i++) { curr += str[i]; powerSet(str, i, curr); // Once all subsets beginning with // initial \"curr\" are printed, remove // last character to consider a different // prefix of subsets. curr = curr.substring(0, curr.length - 1); } } // Driver code let str = \"abc\"; let index = -1; let curr = \"\"; powerSet(str, index, curr); // This code is contributed by rag2127</script>",
"e": 5466,
"s": 4456,
"text": null
},
{
"code": null,
"e": 5485,
"s": 5466,
"text": "a\nab\nabc\nac\nb\nbc\nc"
},
{
"code": null,
"e": 5681,
"s": 5487,
"text": "Method 2: The idea is to consider two cases for every character. (i) Consider current character as part of current subset (ii) Do not consider current character as part of the current subset. "
},
{
"code": null,
"e": 5685,
"s": 5681,
"text": "C++"
},
{
"code": null,
"e": 5690,
"s": 5685,
"text": "Java"
},
{
"code": null,
"e": 5698,
"s": 5690,
"text": "Python3"
},
{
"code": null,
"e": 5701,
"s": 5698,
"text": "C#"
},
{
"code": null,
"e": 5712,
"s": 5701,
"text": "Javascript"
},
{
"code": "// CPP program to generate power set#include <bits/stdc++.h>using namespace std; // str : Stores input string// curr : Stores current subset// index : Index in current subset, currvoid powerSet(string str, int index = 0, string curr = \"\"){ int n = str.length(); // base case if (index == n) { cout << curr << endl; return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str[index]); powerSet(str, index + 1, curr);} // Driver codeint main(){ string str = \"abc\"; powerSet(str); return 0;}",
"e": 6433,
"s": 5712,
"text": null
},
{
"code": "// Java program to generate power setclass GFG { // str : Stores input string// curr : Stores current subset// index : Index in current subset, currstatic void powerSet(String str, int index, String curr) { int n = str.length(); // base case if (index == n) { System.out.println(curr); return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str.charAt(index)); powerSet(str, index + 1, curr); } // Driver codepublic static void main(String[] args){ String str = \"abc\"; int index = 0; String curr=\"\"; powerSet(str,index,curr); }}// This code is contributed by 29AjayKumar",
"e": 7257,
"s": 6433,
"text": null
},
{
"code": "# Python3 program to generate power setdef powerSet(string , index , curr): # string : Stores input string # curr : Stores current subset # index : Index in current subset, curr if index == len(string): print(curr) return powerSet(string, index + 1, curr + string[index]) powerSet(string, index + 1, curr) # Driver Codeif __name__ == \"__main__\": s1 = \"abc\" index = 0 curr = \"\" powerSet(s1, index , curr) # This code is contributed by Ekta Singh",
"e": 7773,
"s": 7257,
"text": null
},
{
"code": "// C# program to generate power setusing System; class GFG{ // str : Stores input string // curr : Stores current subset // index : Index in current subset, curr static void powerSet(String str, int index, String curr) { int n = str.Length; // base case if (index == n) { Console.WriteLine(curr); return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str[index]); powerSet(str, index + 1, curr); } // Driver code public static void Main() { String str = \"abc\"; int index = 0; String curr=\"\"; powerSet(str,index,curr); }} //This code is contributed by Rajput-Ji",
"e": 8685,
"s": 7773,
"text": null
},
{
"code": "<script>// Javascript program to generate power set // str : Stores input string// curr : Stores current subset// index : Index in current subset, curr function powerSet(str,index,curr) { let n = str.length; // base case if (index == n) { document.write(curr+\"<br>\"); return; } // Two cases for every character // (i) We consider the character // as part of current subset // (ii) We do not consider current // character as part of current // subset powerSet(str, index + 1, curr + str[index]); powerSet(str, index + 1, curr); } // Driver code let str = \"abc\"; let index = 0; let curr=\"\"; powerSet(str,index,curr); // This code is contributed by avanitrachhadiya2155</script>",
"e": 9468,
"s": 8685,
"text": null
},
{
"code": null,
"e": 9487,
"s": 9468,
"text": "abc\nab\nac\na\nbc\nb\nc"
},
{
"code": null,
"e": 10050,
"s": 9489,
"text": "Method 3: The idea is to pick each element one by one from the input set, then generate a subset for the same, and we follow this process recursively. We’ll use ArrayList for this purpose For ex, f(0) = {a}, {} // {} when we don’t include any element from the set, it is null i.e {}. f(1) = {a}, {}, {b}, {a, b} // We have to copy all the elements from f(0) and then include the very next element from the set i.e b. So f(1) = f(0) + 1; f(2) = {a}, {}, {b}, {a, b}, {a, c}, {c}, {b, c}, {a, b, c}. So f(2) = f(1) +2;The general form becomes f(n) = f(n-1) + n; "
},
{
"code": null,
"e": 10055,
"s": 10050,
"text": "Java"
},
{
"code": "// Java Recursive code to print// all subsets of set using ArrayListimport java.util.ArrayList; public class PowerSet { public static void main(String[] args) { String[] set = { \"a\", \"b\", \"c\" }; int index = set.length - 1; ArrayList<ArrayList<String> > result = getSubset(set, index); System.out.println(result); } static ArrayList<ArrayList<String> > getSubset(String[] set, int index) { ArrayList<ArrayList<String> > allSubsets; if (index < 0) { allSubsets = new ArrayList<ArrayList<String> >(); allSubsets.add(new ArrayList<String>()); } else { allSubsets = getSubset(set, index - 1); String item = set[index]; ArrayList<ArrayList<String> > moreSubsets = new ArrayList<ArrayList<String> >(); for (ArrayList<String> subset : allSubsets) { ArrayList<String> newSubset = new ArrayList<String>(); newSubset.addAll(subset); newSubset.add(item); moreSubsets.add(newSubset); } allSubsets.addAll(moreSubsets); } return allSubsets; }}",
"e": 11241,
"s": 10055,
"text": null
},
{
"code": null,
"e": 11293,
"s": 11241,
"text": "[[], [a], [b], [a, b], , [a, c], [b, c], [a, b, c]]"
},
{
"code": null,
"e": 11329,
"s": 11295,
"text": "Iterative program for power set. "
},
{
"code": null,
"e": 11343,
"s": 11329,
"text": "Anurag Vishwa"
},
{
"code": null,
"e": 11355,
"s": 11343,
"text": "29AjayKumar"
},
{
"code": null,
"e": 11365,
"s": 11355,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11379,
"s": 11365,
"text": "princiraj1992"
},
{
"code": null,
"e": 11385,
"s": 11379,
"text": "ukasp"
},
{
"code": null,
"e": 11394,
"s": 11385,
"text": "rambabuy"
},
{
"code": null,
"e": 11411,
"s": 11394,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 11425,
"s": 11411,
"text": "ekta1991singh"
},
{
"code": null,
"e": 11433,
"s": 11425,
"text": "rag2127"
},
{
"code": null,
"e": 11454,
"s": 11433,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 11463,
"s": 11454,
"text": "whoibrar"
},
{
"code": null,
"e": 11470,
"s": 11463,
"text": "subset"
},
{
"code": null,
"e": 11483,
"s": 11470,
"text": "Backtracking"
},
{
"code": null,
"e": 11493,
"s": 11483,
"text": "Recursion"
},
{
"code": null,
"e": 11503,
"s": 11493,
"text": "Recursion"
},
{
"code": null,
"e": 11510,
"s": 11503,
"text": "subset"
},
{
"code": null,
"e": 11523,
"s": 11510,
"text": "Backtracking"
}
] |
Java Program to Calculate Difference Between Two Time Periods
|
11 Dec, 2020
In this article, let’s explore the various methods to find the difference between the Two Time Periods in Java. For simplicity, let’s assume that the Time Period provided to us is in the format HH:MM:SS
Example
Input : 1st Time Period :- 18:00:00
2nd Time Period :- 21:00:00
Output: 3 hours 0 minutes and 0 seconds
Input : 1st Time Period :- 17:00:00
2nd Time Period :- 23:22:00
Output: 6 hours 22 minutes and 0 seconds
Method 1 :- Using SimpleDateFormat class and Date class
SimpleDateFormat class has been added to the java.text package in the 7th JDK version. Parse the Time Period in the format HH:MM:SS by creating a SimpleDateFormat object. SimpleDateFormat object parses the Time period and returns a Date object which can be used to calculate the time elapsed.
Below is the code for the above approach:
Java
// Java Program to Find the difference// between Two Time Periods // Importing the Date Class from the util packageimport java.util.*; // Importing the SimpleDateFormat// Class from the text packageimport java.text.*; public class GFG { public static void main(String[] args) throws Exception { // Dates to be parsed String time1 = "18:00:00"; String time2 = "7:30:50"; // Creating a SimpleDateFormat object // to parse time in the format HH:MM:SS SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss"); // Parsing the Time Period Date date1 = simpleDateFormat.parse(time1); Date date2 = simpleDateFormat.parse(time2); // Calculating the difference in milliseconds long differenceInMilliSeconds = Math.abs(date2.getTime() - date1.getTime()); // Calculating the difference in Hours long differenceInHours = (differenceInMilliSeconds / (60 * 60 * 1000)) % 24; // Calculating the difference in Minutes long differenceInMinutes = (differenceInMilliSeconds / (60 * 1000)) % 60; // Calculating the difference in Seconds long differenceInSeconds = (differenceInMilliSeconds / 1000) % 60; // Printing the answer System.out.println( "Difference is " + differenceInHours + " hours " + differenceInMinutes + " minutes " + differenceInSeconds + " Seconds. "); }}
Difference is 10 hours 29 minutes 10 Seconds.
Time Complexity: O(1)
Method 2 :- Using the LocalTime and ChronoUnit class
Java has brought a ton of features in the 8th JDK version and few of them are the LocalTime and ChronoUnit classes present in the java.time package. LocalTime object parses the date in the format HH:MM:SS and ChronoUnit is used to get the difference in hours, minutes and seconds.
Below is the code for the above approach:
Java
// Java program to get the difference// between Two Time Periods in Java // Importing the LocalTime classimport java.time.*; // Importing the ChronoUnit classimport java.time.temporal.ChronoUnit; class GFG { public static void main(String[] args) { // Parsing Time Period in the format HH:MM:SS LocalTime time1 = LocalTime.of(18, 00, 00); LocalTime time2 = LocalTime.of(21, 22, 00); // Calculating the difference in Hours long hours = ChronoUnit.HOURS.between(time1, time2); // Calculating the difference in Minutes long minutes = ChronoUnit.MINUTES.between(time1, time2) % 60; // Calculating the difference in Seconds long seconds = ChronoUnit.SECONDS.between(time1, time2) % 60; // Printing the difference System.out.println( "Difference is " + hours + " hours " + minutes + " minutes " + seconds + " seconds."); }}
Difference is 3 hours 22 minutes 0 seconds.
Time Complexity: O(1)
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "In this article, let’s explore the various methods to find the difference between the Two Time Periods in Java. For simplicity, let’s assume that the Time Period provided to us is in the format HH:MM:SS"
},
{
"code": null,
"e": 239,
"s": 231,
"text": "Example"
},
{
"code": null,
"e": 462,
"s": 239,
"text": "Input : 1st Time Period :- 18:00:00\n 2nd Time Period :- 21:00:00\nOutput: 3 hours 0 minutes and 0 seconds\n \nInput : 1st Time Period :- 17:00:00\n 2nd Time Period :- 23:22:00\nOutput: 6 hours 22 minutes and 0 seconds"
},
{
"code": null,
"e": 520,
"s": 464,
"text": "Method 1 :- Using SimpleDateFormat class and Date class"
},
{
"code": null,
"e": 813,
"s": 520,
"text": "SimpleDateFormat class has been added to the java.text package in the 7th JDK version. Parse the Time Period in the format HH:MM:SS by creating a SimpleDateFormat object. SimpleDateFormat object parses the Time period and returns a Date object which can be used to calculate the time elapsed."
},
{
"code": null,
"e": 855,
"s": 813,
"text": "Below is the code for the above approach:"
},
{
"code": null,
"e": 860,
"s": 855,
"text": "Java"
},
{
"code": "// Java Program to Find the difference// between Two Time Periods // Importing the Date Class from the util packageimport java.util.*; // Importing the SimpleDateFormat// Class from the text packageimport java.text.*; public class GFG { public static void main(String[] args) throws Exception { // Dates to be parsed String time1 = \"18:00:00\"; String time2 = \"7:30:50\"; // Creating a SimpleDateFormat object // to parse time in the format HH:MM:SS SimpleDateFormat simpleDateFormat = new SimpleDateFormat(\"HH:mm:ss\"); // Parsing the Time Period Date date1 = simpleDateFormat.parse(time1); Date date2 = simpleDateFormat.parse(time2); // Calculating the difference in milliseconds long differenceInMilliSeconds = Math.abs(date2.getTime() - date1.getTime()); // Calculating the difference in Hours long differenceInHours = (differenceInMilliSeconds / (60 * 60 * 1000)) % 24; // Calculating the difference in Minutes long differenceInMinutes = (differenceInMilliSeconds / (60 * 1000)) % 60; // Calculating the difference in Seconds long differenceInSeconds = (differenceInMilliSeconds / 1000) % 60; // Printing the answer System.out.println( \"Difference is \" + differenceInHours + \" hours \" + differenceInMinutes + \" minutes \" + differenceInSeconds + \" Seconds. \"); }}",
"e": 2389,
"s": 860,
"text": null
},
{
"code": null,
"e": 2437,
"s": 2389,
"text": "Difference is 10 hours 29 minutes 10 Seconds. \n"
},
{
"code": null,
"e": 2459,
"s": 2437,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 2514,
"s": 2461,
"text": "Method 2 :- Using the LocalTime and ChronoUnit class"
},
{
"code": null,
"e": 2795,
"s": 2514,
"text": "Java has brought a ton of features in the 8th JDK version and few of them are the LocalTime and ChronoUnit classes present in the java.time package. LocalTime object parses the date in the format HH:MM:SS and ChronoUnit is used to get the difference in hours, minutes and seconds."
},
{
"code": null,
"e": 2837,
"s": 2795,
"text": "Below is the code for the above approach:"
},
{
"code": null,
"e": 2842,
"s": 2837,
"text": "Java"
},
{
"code": "// Java program to get the difference// between Two Time Periods in Java // Importing the LocalTime classimport java.time.*; // Importing the ChronoUnit classimport java.time.temporal.ChronoUnit; class GFG { public static void main(String[] args) { // Parsing Time Period in the format HH:MM:SS LocalTime time1 = LocalTime.of(18, 00, 00); LocalTime time2 = LocalTime.of(21, 22, 00); // Calculating the difference in Hours long hours = ChronoUnit.HOURS.between(time1, time2); // Calculating the difference in Minutes long minutes = ChronoUnit.MINUTES.between(time1, time2) % 60; // Calculating the difference in Seconds long seconds = ChronoUnit.SECONDS.between(time1, time2) % 60; // Printing the difference System.out.println( \"Difference is \" + hours + \" hours \" + minutes + \" minutes \" + seconds + \" seconds.\"); }}",
"e": 3803,
"s": 2842,
"text": null
},
{
"code": null,
"e": 3848,
"s": 3803,
"text": "Difference is 3 hours 22 minutes 0 seconds.\n"
},
{
"code": null,
"e": 3870,
"s": 3848,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 3877,
"s": 3870,
"text": "Picked"
},
{
"code": null,
"e": 3901,
"s": 3877,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3906,
"s": 3901,
"text": "Java"
},
{
"code": null,
"e": 3920,
"s": 3906,
"text": "Java Programs"
},
{
"code": null,
"e": 3939,
"s": 3920,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3944,
"s": 3939,
"text": "Java"
}
] |
How to make browser to go back to previous page using JavaScript ?
|
30 Sep, 2019
There is two popular way to make browsers go back to the previous page by clicking JavaScript event, both methods are described below:
Method 1: Using history.go() method: The go() method of the window.history object is used to load a page from the session history. It can be used to move forward or backward using the value of the delta parameter. A positive delta parameter means that the page would go forward in history. Similarly, a negative delta value would make the page go back to the previous page.This method can be used with ‘-1’ as the delta value to go back one page in history. The onclick event can be specified with the method to go back one page in history.
Syntax:
window.history.go(-1)
Note: If we want to go back more than one step then increase the value of delta from ‘-1’ to as much as you want.
Example:
Page 1
Page 2
<!DOCTYPE html><html> <head> <title> How to make browser to go back to previous page using JavaScript ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 1</h2> <p> Click on the link to get to the second page. </p> <a href="page2.html">Go to Page 2</a></body> </html>
<!DOCTYPE html><html> <head> <title> How to make browser to go back to previous page using JavaScript ? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 2</h2> <p> Click on the button to go back to the previous page. </p> <button onclick="history.go(-1)"> Click here to go back </button></body> </html>
Before clicking on the link:
After clicking on the link:
After clicking on the button:
Method 2: Using the history.back() method: The back() method of the window.history object is used to go back to the previous page in the current session history. In case there is no previous page, this method call does nothing.The onclick event can be specified with this method to go back one page in history.
Syntax:
window.history.back()
Example:
Page 1
Page 2
<!DOCTYPE html><html> <head> <title> Onclick javascript to make browser go back to previous page? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 1</h2> <p> Click on the link to get to the second page. </p> <a href="page2.html">Go to Page 2</a></body> </html>
<!DOCTYPE html><html> <head> <title> Onclick javascript to make browser go back to previous page? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 2</h2> <p> Click on the button to go back to the previous page. </p> <button onclick="history.back()"> Click here to go back </button></body> </html>
Before clicking on the link:
After clicking on the link:
After clicking on the button:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Sep, 2019"
},
{
"code": null,
"e": 188,
"s": 53,
"text": "There is two popular way to make browsers go back to the previous page by clicking JavaScript event, both methods are described below:"
},
{
"code": null,
"e": 729,
"s": 188,
"text": "Method 1: Using history.go() method: The go() method of the window.history object is used to load a page from the session history. It can be used to move forward or backward using the value of the delta parameter. A positive delta parameter means that the page would go forward in history. Similarly, a negative delta value would make the page go back to the previous page.This method can be used with ‘-1’ as the delta value to go back one page in history. The onclick event can be specified with the method to go back one page in history."
},
{
"code": null,
"e": 737,
"s": 729,
"text": "Syntax:"
},
{
"code": null,
"e": 759,
"s": 737,
"text": "window.history.go(-1)"
},
{
"code": null,
"e": 873,
"s": 759,
"text": "Note: If we want to go back more than one step then increase the value of delta from ‘-1’ to as much as you want."
},
{
"code": null,
"e": 882,
"s": 873,
"text": "Example:"
},
{
"code": null,
"e": 889,
"s": 882,
"text": "Page 1"
},
{
"code": null,
"e": 896,
"s": 889,
"text": "Page 2"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to make browser to go back to previous page using JavaScript ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 1</h2> <p> Click on the link to get to the second page. </p> <a href=\"page2.html\">Go to Page 2</a></body> </html>",
"e": 1368,
"s": 896,
"text": null
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to make browser to go back to previous page using JavaScript ? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 2</h2> <p> Click on the button to go back to the previous page. </p> <button onclick=\"history.go(-1)\"> Click here to go back </button></body> </html>",
"e": 1887,
"s": 1368,
"text": null
},
{
"code": null,
"e": 1916,
"s": 1887,
"text": "Before clicking on the link:"
},
{
"code": null,
"e": 1944,
"s": 1916,
"text": "After clicking on the link:"
},
{
"code": null,
"e": 1974,
"s": 1944,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2285,
"s": 1974,
"text": "Method 2: Using the history.back() method: The back() method of the window.history object is used to go back to the previous page in the current session history. In case there is no previous page, this method call does nothing.The onclick event can be specified with this method to go back one page in history."
},
{
"code": null,
"e": 2293,
"s": 2285,
"text": "Syntax:"
},
{
"code": null,
"e": 2315,
"s": 2293,
"text": "window.history.back()"
},
{
"code": null,
"e": 2324,
"s": 2315,
"text": "Example:"
},
{
"code": null,
"e": 2331,
"s": 2324,
"text": "Page 1"
},
{
"code": null,
"e": 2338,
"s": 2331,
"text": "Page 2"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Onclick javascript to make browser go back to previous page? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 1</h2> <p> Click on the link to get to the second page. </p> <a href=\"page2.html\">Go to Page 2</a></body> </html>",
"e": 2806,
"s": 2338,
"text": null
},
{
"code": "<!DOCTYPE html><html> <head> <title> Onclick javascript to make browser go back to previous page? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> Onclick javascript to make browser go back to previous page? </b> <h2>Page 2</h2> <p> Click on the button to go back to the previous page. </p> <button onclick=\"history.back()\"> Click here to go back </button></body> </html>",
"e": 3319,
"s": 2806,
"text": null
},
{
"code": null,
"e": 3348,
"s": 3319,
"text": "Before clicking on the link:"
},
{
"code": null,
"e": 3376,
"s": 3348,
"text": "After clicking on the link:"
},
{
"code": null,
"e": 3406,
"s": 3376,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 3422,
"s": 3406,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3429,
"s": 3422,
"text": "Picked"
},
{
"code": null,
"e": 3440,
"s": 3429,
"text": "JavaScript"
},
{
"code": null,
"e": 3457,
"s": 3440,
"text": "Web Technologies"
},
{
"code": null,
"e": 3484,
"s": 3457,
"text": "Web technologies Questions"
}
] |
K Means Clustering using PySpark on Big Data | by Angel Das | Towards Data Science
|
If you are not familiar with K Means clustering, I recommend going through the article below. This article focuses mostly on data parallelism and clustering, i.e. K Means clustering on Big Data.
towardsdatascience.com
Clustering is an unsupervised learning technique, in short, you are working on data, without having any information about a target attribute or a dependent variable. The general idea of clustering is to find some intrinsic structure in the data, often referred to as groups of similar objects. The algorithm studies the data to identify these patterns or groups such that each member in a group is closer to another member in the group (lower intracluster distance) and farther from another member in a different group (higher inter-cluster distance).
Most of you must be familiar with these examples from real life:
Customer Segmentation — Used widely for targeted marketingImage Segmentation — Identify the change in landscape or intrusionRecommendation Engines
Customer Segmentation — Used widely for targeted marketing
Image Segmentation — Identify the change in landscape or intrusion
Recommendation Engines
K Means clustering, irrespective of the platform uses a similarity measure in the form of Euclidean Distance. Often referred to as Divisive or Partitional Clustering, the basic idea of K Means is to start with every data point a bigger cluster and then divide them into smaller groups based on user input K (or the number of clusters). Each cluster has a center called the centroid. The total number of centroids in a given cluster is always equal to K. The algorithm iteratively looks for data points and assign them to their closest cluster.
Once all data points are assigned to their respective centroids (which represents each cluster here), the centroid values are recalculated and the process repeats until the clusters reach a convergence criterion. Centroids are nothing but new mean for each cluster (e.g. A Cluster Consisting of Customers A, B, C with an average spend of 100, 200, 300 and a basket size of 10, 15, and 20 will have centroids as 200 and 15 respectively). Convergence criterion is a measure of stability or compactness of the cluster, i.e. the intracluster distance between any two iterations doesn’t change beyond a given threshold.
Before we discuss why PySpark and not a Sklearn based algorithm, let’s discuss how the process differs in PySpark. When building any clustering algorithm using PySpark, one needs to perform a few data transformations. Let us dig deep into the data first. The data used for the analysis can be found here.
The dataset consists of 9K active credit cardholders over 6 months and their transaction and account attributes. The idea is to develop a customer segmentation for marketing strategy.
from pyspark.sql import SparkSessionspark = SparkSession.builder.appName(‘Clustering using K-Means’).getOrCreate()data_customer=spark.read.csv('CC General.csv', header=True, inferSchema=True)data_customer.printSchema()
The attributes that are self intuitive can be divided into three broader categories. Customer Information (Primary Key as CUST_ID), account information (balance, balance frequency, purchases, credit limit, tenure, etc.), and transactions (purchase frequency, payments, cash advance, etc.).
data_customer=data_customer.na.drop()
All attributes under consideration are numerical or discrete numeric, hence we need to convert them into features using a Vector Assembler. A vector assembler is a transformer that converts a set of features into a single vector column often referred to as an array of features. Features here are columns. Since customer id is an identifier that won’t be used for clustering, we first extract the required columns using .columns, pass it as an input to Vector Assembler, and then use the transform() to convert the input columns into a single vector column called a feature.
from pyspark.ml.feature import VectorAssemblerdata_customer.columnsassemble=VectorAssembler(inputCols=[ 'BALANCE', 'BALANCE_FREQUENCY', 'PURCHASES', 'ONEOFF_PURCHASES', 'INSTALLMENTS_PURCHASES', 'CASH_ADVANCE', 'PURCHASES_FREQUENCY', 'ONEOFF_PURCHASES_FREQUENCY', 'PURCHASES_INSTALLMENTS_FREQUENCY', 'CASH_ADVANCE_FREQUENCY', 'CASH_ADVANCE_TRX', 'PURCHASES_TRX', 'CREDIT_LIMIT', 'PAYMENTS', 'MINIMUM_PAYMENTS', 'PRC_FULL_PAYMENT', 'TENURE'], outputCol='features')assembled_data=assemble.transform(data_customer)assembled_data.show(2)
Now that all columns are transformed into a single feature vector we need to standardize the data to bring them to a comparable scale. E.g. Balance can have a scale from 10–1000 whereas balance frequency has a scale from 0–1 say. Euclidean distance is always impacted more by variables on a higher scale, hence it’s important to scale the variables out.
from pyspark.ml.feature import StandardScalerscale=StandardScaler(inputCol='features',outputCol='standardized')data_scale=scale.fit(assembled_data)data_scale_output=data_scale.transform(assembled_data)data_scale_output.show(2)
Now that our data is standardized we can develop the K Means algorithm.
K-means is one of the most commonly used clustering algorithms for grouping data into a predefined number of clusters. The spark.mllib includes a parallelized variant of the k-means++ method called kmeans||. The KMeans function from pyspark.ml.clustering includes the following parameters:
k is the number of clusters specified by the user
maxIterations is the maximum number of iterations before the clustering algorithm stops. Note that if the intracluster distance doesn’t change beyond the epsilon value mentioned, the iteration will stop irrespective of max iterations
initializationMode specifies either random initialization of centroids or initialization via k-means|| (similar to K-means ++)
epsilon determines the distance threshold within which k-means is expected to converge
initialModel is an optional set of cluster centroids that the user can provide as an input. If this parameter is used, the algorithm just runs once to allocate points to its nearest centroid
train(k=4, maxIterations=20, minDivisibleClusterSize=1.0, seed=-1888008604) are the default values.
from pyspark.ml.clustering import KMeansfrom pyspark.ml.evaluation import ClusteringEvaluatorsilhouette_score=[]evaluator = ClusteringEvaluator(predictionCol='prediction', featuresCol='standardized', \ metricName='silhouette', distanceMeasure='squaredEuclidean')for i in range(2,10): KMeans_algo=KMeans(featuresCol='standardized', k=i) KMeans_fit=KMeans_algo.fit(data_scale_output) output=KMeans_fit.transform(data_scale_output) score=evaluator.evaluate(output) silhouette_score.append(score) print("Silhouette Score:",score)
Visualizing the silhouette score. Note previous versions of the K Means had computeScore() that calculated the sum of intracluster distance but got deprecated in Spark 3.0.0. Silhouette Score using ClusteringEvaluator() measures how close each point in one cluster is to points in the neighboring clusters thus helping in figuring out clusters that are compact and well-spaced out.
#Visualizing the silhouette scores in a plotimport matplotlib.pyplot as pltfig, ax = plt.subplots(1,1, figsize =(8,6))ax.plot(range(2,10),silhouette_score)ax.set_xlabel(‘k’)ax.set_ylabel(‘cost’)
I prefer going ahead with K=7 where a local maxima of Silhouette Score is observed. Since there is no correct answer for what value of K is good, we can restore to descriptive statistics and plots to check the distribution of customers. This is where SkLearn comes in more handy with documentation and PCA implementation. Most of us are more comfortable studying an elbow plot with SSE on the y axis rather than a Silhouette Score, but PySpark comes with its merit.
PySpark uses the concept of Data Parallelism or Result Parallelism when performing the K Means clustering. Imagine you need to roll out targeted marketing campaigns for the Boxing Day event in Melbourne and you want to reach out to 200K customers with different purchasing attributes. Imagine running multiple iterations of K Means on your local system. For K=5, the number of distance metrics you require to calculate is 5 x 200K = 1Million. 1 Million such metrics need to be calculated for say 30 times before a convergence criterion is met, i.e. 30Million distances (euclidean). You will require a lot of computation power and time to handle a scenario like this.
What data parallelism does is, creates parallelism from the beginning by partitioning the dataset into smaller partitions. On the other hand, result parallelism is based on targeted clusters. Let’s say:
D = Number of Records {X1, X2, ......, Xn}
k = Number of clusters
P = Number of Processors {P1, P2,...Pm}
C = Initial Centroids {C1, C2, .... Ck}
Data D is divided across P processors. Each processor works on a set of records (determined by spark configuration). The initial centroid values, C, are shared across each of these processorsNow every processor has centroid information. The processors compute the distance of their records to these centroids and form local clusters by assigning data points to its closest centroidOnce step 2 is done, the sum and count of records for each of these clusters across P processors are stored by a master process for future referenceOnce one iteration is completed, the information from the processor is exchanged and a master process computes the updated Centroids and shares them across the P processors again, i.e. one point is allocated to K clusters, a master process updates the centroids, and reshare the information back with the processorsThis process keeps iterating till convergence is met. Once a convergence criterion is met, the master process collects local clusters and combines them into a global one
Data D is divided across P processors. Each processor works on a set of records (determined by spark configuration). The initial centroid values, C, are shared across each of these processors
Now every processor has centroid information. The processors compute the distance of their records to these centroids and form local clusters by assigning data points to its closest centroid
Once step 2 is done, the sum and count of records for each of these clusters across P processors are stored by a master process for future reference
Once one iteration is completed, the information from the processor is exchanged and a master process computes the updated Centroids and shares them across the P processors again, i.e. one point is allocated to K clusters, a master process updates the centroids, and reshare the information back with the processors
This process keeps iterating till convergence is met. Once a convergence criterion is met, the master process collects local clusters and combines them into a global one
Imagine 200K records divided across 3 processors each having ~70K records. This is where distributed processing comes into the picture to reduce the volume of data, yet ensuring a complete result.
In result parallelism say:
D = Number of Records {X1, X2, ......, Xn}
k = Number of clusters
P = Number of Processors {P1, P2,...Pm}
C = Initial Centroids {C1, C2, .... Ck}
Data D is divided across P processors and then sorted within each processor. Each processor works on a set of records (determined by spark configuration)The initial centroid values, C, are initialized and divided/shared across each of these processors (i.e., unlike data parallelism where all centroid values are shared across all processors, here, we pass one centroid value to one processorNow every processor has one centroid of information. Compute the distance of these points to these centroids. For data points in a processor which are extremely low or high: If they are closer to the centroid of processor assign them to that cluster, else if they are closer to the centroid belonging to a different processor, move data point to the new processorRepeat till convergence is met. All local clusters from Processor P is returned
Data D is divided across P processors and then sorted within each processor. Each processor works on a set of records (determined by spark configuration)
The initial centroid values, C, are initialized and divided/shared across each of these processors (i.e., unlike data parallelism where all centroid values are shared across all processors, here, we pass one centroid value to one processor
Now every processor has one centroid of information. Compute the distance of these points to these centroids. For data points in a processor which are extremely low or high: If they are closer to the centroid of processor assign them to that cluster, else if they are closer to the centroid belonging to a different processor, move data point to the new processor
Repeat till convergence is met. All local clusters from Processor P is returned
https://spark.apache.org/docs/latest/mllib-clustering.htmlhttps://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.clustering.KMeansModelhttps://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.evaluation.ClusteringEvaluatorhttps://spark.apache.org/docs/latest/api/python/_modules/pyspark/ml/evaluation.html
https://spark.apache.org/docs/latest/mllib-clustering.html
https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.clustering.KMeansModel
https://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.evaluation.ClusteringEvaluator
https://spark.apache.org/docs/latest/api/python/_modules/pyspark/ml/evaluation.html
About the Author: Advanced analytics professional and management consultant helping companies find solutions for diverse problems through a mix of business, technology, and math on organizational data. A Data Science enthusiast, here to share, learn and contribute; You can connect with me on Linked and Twitter;
|
[
{
"code": null,
"e": 367,
"s": 172,
"text": "If you are not familiar with K Means clustering, I recommend going through the article below. This article focuses mostly on data parallelism and clustering, i.e. K Means clustering on Big Data."
},
{
"code": null,
"e": 390,
"s": 367,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 942,
"s": 390,
"text": "Clustering is an unsupervised learning technique, in short, you are working on data, without having any information about a target attribute or a dependent variable. The general idea of clustering is to find some intrinsic structure in the data, often referred to as groups of similar objects. The algorithm studies the data to identify these patterns or groups such that each member in a group is closer to another member in the group (lower intracluster distance) and farther from another member in a different group (higher inter-cluster distance)."
},
{
"code": null,
"e": 1007,
"s": 942,
"text": "Most of you must be familiar with these examples from real life:"
},
{
"code": null,
"e": 1154,
"s": 1007,
"text": "Customer Segmentation — Used widely for targeted marketingImage Segmentation — Identify the change in landscape or intrusionRecommendation Engines"
},
{
"code": null,
"e": 1213,
"s": 1154,
"text": "Customer Segmentation — Used widely for targeted marketing"
},
{
"code": null,
"e": 1280,
"s": 1213,
"text": "Image Segmentation — Identify the change in landscape or intrusion"
},
{
"code": null,
"e": 1303,
"s": 1280,
"text": "Recommendation Engines"
},
{
"code": null,
"e": 1847,
"s": 1303,
"text": "K Means clustering, irrespective of the platform uses a similarity measure in the form of Euclidean Distance. Often referred to as Divisive or Partitional Clustering, the basic idea of K Means is to start with every data point a bigger cluster and then divide them into smaller groups based on user input K (or the number of clusters). Each cluster has a center called the centroid. The total number of centroids in a given cluster is always equal to K. The algorithm iteratively looks for data points and assign them to their closest cluster."
},
{
"code": null,
"e": 2462,
"s": 1847,
"text": "Once all data points are assigned to their respective centroids (which represents each cluster here), the centroid values are recalculated and the process repeats until the clusters reach a convergence criterion. Centroids are nothing but new mean for each cluster (e.g. A Cluster Consisting of Customers A, B, C with an average spend of 100, 200, 300 and a basket size of 10, 15, and 20 will have centroids as 200 and 15 respectively). Convergence criterion is a measure of stability or compactness of the cluster, i.e. the intracluster distance between any two iterations doesn’t change beyond a given threshold."
},
{
"code": null,
"e": 2767,
"s": 2462,
"text": "Before we discuss why PySpark and not a Sklearn based algorithm, let’s discuss how the process differs in PySpark. When building any clustering algorithm using PySpark, one needs to perform a few data transformations. Let us dig deep into the data first. The data used for the analysis can be found here."
},
{
"code": null,
"e": 2951,
"s": 2767,
"text": "The dataset consists of 9K active credit cardholders over 6 months and their transaction and account attributes. The idea is to develop a customer segmentation for marketing strategy."
},
{
"code": null,
"e": 3170,
"s": 2951,
"text": "from pyspark.sql import SparkSessionspark = SparkSession.builder.appName(‘Clustering using K-Means’).getOrCreate()data_customer=spark.read.csv('CC General.csv', header=True, inferSchema=True)data_customer.printSchema()"
},
{
"code": null,
"e": 3460,
"s": 3170,
"text": "The attributes that are self intuitive can be divided into three broader categories. Customer Information (Primary Key as CUST_ID), account information (balance, balance frequency, purchases, credit limit, tenure, etc.), and transactions (purchase frequency, payments, cash advance, etc.)."
},
{
"code": null,
"e": 3498,
"s": 3460,
"text": "data_customer=data_customer.na.drop()"
},
{
"code": null,
"e": 4073,
"s": 3498,
"text": "All attributes under consideration are numerical or discrete numeric, hence we need to convert them into features using a Vector Assembler. A vector assembler is a transformer that converts a set of features into a single vector column often referred to as an array of features. Features here are columns. Since customer id is an identifier that won’t be used for clustering, we first extract the required columns using .columns, pass it as an input to Vector Assembler, and then use the transform() to convert the input columns into a single vector column called a feature."
},
{
"code": null,
"e": 4607,
"s": 4073,
"text": "from pyspark.ml.feature import VectorAssemblerdata_customer.columnsassemble=VectorAssembler(inputCols=[ 'BALANCE', 'BALANCE_FREQUENCY', 'PURCHASES', 'ONEOFF_PURCHASES', 'INSTALLMENTS_PURCHASES', 'CASH_ADVANCE', 'PURCHASES_FREQUENCY', 'ONEOFF_PURCHASES_FREQUENCY', 'PURCHASES_INSTALLMENTS_FREQUENCY', 'CASH_ADVANCE_FREQUENCY', 'CASH_ADVANCE_TRX', 'PURCHASES_TRX', 'CREDIT_LIMIT', 'PAYMENTS', 'MINIMUM_PAYMENTS', 'PRC_FULL_PAYMENT', 'TENURE'], outputCol='features')assembled_data=assemble.transform(data_customer)assembled_data.show(2)"
},
{
"code": null,
"e": 4961,
"s": 4607,
"text": "Now that all columns are transformed into a single feature vector we need to standardize the data to bring them to a comparable scale. E.g. Balance can have a scale from 10–1000 whereas balance frequency has a scale from 0–1 say. Euclidean distance is always impacted more by variables on a higher scale, hence it’s important to scale the variables out."
},
{
"code": null,
"e": 5188,
"s": 4961,
"text": "from pyspark.ml.feature import StandardScalerscale=StandardScaler(inputCol='features',outputCol='standardized')data_scale=scale.fit(assembled_data)data_scale_output=data_scale.transform(assembled_data)data_scale_output.show(2)"
},
{
"code": null,
"e": 5260,
"s": 5188,
"text": "Now that our data is standardized we can develop the K Means algorithm."
},
{
"code": null,
"e": 5550,
"s": 5260,
"text": "K-means is one of the most commonly used clustering algorithms for grouping data into a predefined number of clusters. The spark.mllib includes a parallelized variant of the k-means++ method called kmeans||. The KMeans function from pyspark.ml.clustering includes the following parameters:"
},
{
"code": null,
"e": 5600,
"s": 5550,
"text": "k is the number of clusters specified by the user"
},
{
"code": null,
"e": 5834,
"s": 5600,
"text": "maxIterations is the maximum number of iterations before the clustering algorithm stops. Note that if the intracluster distance doesn’t change beyond the epsilon value mentioned, the iteration will stop irrespective of max iterations"
},
{
"code": null,
"e": 5961,
"s": 5834,
"text": "initializationMode specifies either random initialization of centroids or initialization via k-means|| (similar to K-means ++)"
},
{
"code": null,
"e": 6048,
"s": 5961,
"text": "epsilon determines the distance threshold within which k-means is expected to converge"
},
{
"code": null,
"e": 6239,
"s": 6048,
"text": "initialModel is an optional set of cluster centroids that the user can provide as an input. If this parameter is used, the algorithm just runs once to allocate points to its nearest centroid"
},
{
"code": null,
"e": 6339,
"s": 6239,
"text": "train(k=4, maxIterations=20, minDivisibleClusterSize=1.0, seed=-1888008604) are the default values."
},
{
"code": null,
"e": 6946,
"s": 6339,
"text": "from pyspark.ml.clustering import KMeansfrom pyspark.ml.evaluation import ClusteringEvaluatorsilhouette_score=[]evaluator = ClusteringEvaluator(predictionCol='prediction', featuresCol='standardized', \\ metricName='silhouette', distanceMeasure='squaredEuclidean')for i in range(2,10): KMeans_algo=KMeans(featuresCol='standardized', k=i) KMeans_fit=KMeans_algo.fit(data_scale_output) output=KMeans_fit.transform(data_scale_output) score=evaluator.evaluate(output) silhouette_score.append(score) print(\"Silhouette Score:\",score)"
},
{
"code": null,
"e": 7328,
"s": 6946,
"text": "Visualizing the silhouette score. Note previous versions of the K Means had computeScore() that calculated the sum of intracluster distance but got deprecated in Spark 3.0.0. Silhouette Score using ClusteringEvaluator() measures how close each point in one cluster is to points in the neighboring clusters thus helping in figuring out clusters that are compact and well-spaced out."
},
{
"code": null,
"e": 7523,
"s": 7328,
"text": "#Visualizing the silhouette scores in a plotimport matplotlib.pyplot as pltfig, ax = plt.subplots(1,1, figsize =(8,6))ax.plot(range(2,10),silhouette_score)ax.set_xlabel(‘k’)ax.set_ylabel(‘cost’)"
},
{
"code": null,
"e": 7989,
"s": 7523,
"text": "I prefer going ahead with K=7 where a local maxima of Silhouette Score is observed. Since there is no correct answer for what value of K is good, we can restore to descriptive statistics and plots to check the distribution of customers. This is where SkLearn comes in more handy with documentation and PCA implementation. Most of us are more comfortable studying an elbow plot with SSE on the y axis rather than a Silhouette Score, but PySpark comes with its merit."
},
{
"code": null,
"e": 8656,
"s": 7989,
"text": "PySpark uses the concept of Data Parallelism or Result Parallelism when performing the K Means clustering. Imagine you need to roll out targeted marketing campaigns for the Boxing Day event in Melbourne and you want to reach out to 200K customers with different purchasing attributes. Imagine running multiple iterations of K Means on your local system. For K=5, the number of distance metrics you require to calculate is 5 x 200K = 1Million. 1 Million such metrics need to be calculated for say 30 times before a convergence criterion is met, i.e. 30Million distances (euclidean). You will require a lot of computation power and time to handle a scenario like this."
},
{
"code": null,
"e": 8859,
"s": 8656,
"text": "What data parallelism does is, creates parallelism from the beginning by partitioning the dataset into smaller partitions. On the other hand, result parallelism is based on targeted clusters. Let’s say:"
},
{
"code": null,
"e": 8902,
"s": 8859,
"text": "D = Number of Records {X1, X2, ......, Xn}"
},
{
"code": null,
"e": 8925,
"s": 8902,
"text": "k = Number of clusters"
},
{
"code": null,
"e": 8965,
"s": 8925,
"text": "P = Number of Processors {P1, P2,...Pm}"
},
{
"code": null,
"e": 9005,
"s": 8965,
"text": "C = Initial Centroids {C1, C2, .... Ck}"
},
{
"code": null,
"e": 10019,
"s": 9005,
"text": "Data D is divided across P processors. Each processor works on a set of records (determined by spark configuration). The initial centroid values, C, are shared across each of these processorsNow every processor has centroid information. The processors compute the distance of their records to these centroids and form local clusters by assigning data points to its closest centroidOnce step 2 is done, the sum and count of records for each of these clusters across P processors are stored by a master process for future referenceOnce one iteration is completed, the information from the processor is exchanged and a master process computes the updated Centroids and shares them across the P processors again, i.e. one point is allocated to K clusters, a master process updates the centroids, and reshare the information back with the processorsThis process keeps iterating till convergence is met. Once a convergence criterion is met, the master process collects local clusters and combines them into a global one"
},
{
"code": null,
"e": 10211,
"s": 10019,
"text": "Data D is divided across P processors. Each processor works on a set of records (determined by spark configuration). The initial centroid values, C, are shared across each of these processors"
},
{
"code": null,
"e": 10402,
"s": 10211,
"text": "Now every processor has centroid information. The processors compute the distance of their records to these centroids and form local clusters by assigning data points to its closest centroid"
},
{
"code": null,
"e": 10551,
"s": 10402,
"text": "Once step 2 is done, the sum and count of records for each of these clusters across P processors are stored by a master process for future reference"
},
{
"code": null,
"e": 10867,
"s": 10551,
"text": "Once one iteration is completed, the information from the processor is exchanged and a master process computes the updated Centroids and shares them across the P processors again, i.e. one point is allocated to K clusters, a master process updates the centroids, and reshare the information back with the processors"
},
{
"code": null,
"e": 11037,
"s": 10867,
"text": "This process keeps iterating till convergence is met. Once a convergence criterion is met, the master process collects local clusters and combines them into a global one"
},
{
"code": null,
"e": 11234,
"s": 11037,
"text": "Imagine 200K records divided across 3 processors each having ~70K records. This is where distributed processing comes into the picture to reduce the volume of data, yet ensuring a complete result."
},
{
"code": null,
"e": 11261,
"s": 11234,
"text": "In result parallelism say:"
},
{
"code": null,
"e": 11304,
"s": 11261,
"text": "D = Number of Records {X1, X2, ......, Xn}"
},
{
"code": null,
"e": 11327,
"s": 11304,
"text": "k = Number of clusters"
},
{
"code": null,
"e": 11367,
"s": 11327,
"text": "P = Number of Processors {P1, P2,...Pm}"
},
{
"code": null,
"e": 11407,
"s": 11367,
"text": "C = Initial Centroids {C1, C2, .... Ck}"
},
{
"code": null,
"e": 12242,
"s": 11407,
"text": "Data D is divided across P processors and then sorted within each processor. Each processor works on a set of records (determined by spark configuration)The initial centroid values, C, are initialized and divided/shared across each of these processors (i.e., unlike data parallelism where all centroid values are shared across all processors, here, we pass one centroid value to one processorNow every processor has one centroid of information. Compute the distance of these points to these centroids. For data points in a processor which are extremely low or high: If they are closer to the centroid of processor assign them to that cluster, else if they are closer to the centroid belonging to a different processor, move data point to the new processorRepeat till convergence is met. All local clusters from Processor P is returned"
},
{
"code": null,
"e": 12396,
"s": 12242,
"text": "Data D is divided across P processors and then sorted within each processor. Each processor works on a set of records (determined by spark configuration)"
},
{
"code": null,
"e": 12636,
"s": 12396,
"text": "The initial centroid values, C, are initialized and divided/shared across each of these processors (i.e., unlike data parallelism where all centroid values are shared across all processors, here, we pass one centroid value to one processor"
},
{
"code": null,
"e": 13000,
"s": 12636,
"text": "Now every processor has one centroid of information. Compute the distance of these points to these centroids. For data points in a processor which are extremely low or high: If they are closer to the centroid of processor assign them to that cluster, else if they are closer to the centroid belonging to a different processor, move data point to the new processor"
},
{
"code": null,
"e": 13080,
"s": 13000,
"text": "Repeat till convergence is met. All local clusters from Processor P is returned"
},
{
"code": null,
"e": 13430,
"s": 13080,
"text": "https://spark.apache.org/docs/latest/mllib-clustering.htmlhttps://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.clustering.KMeansModelhttps://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.evaluation.ClusteringEvaluatorhttps://spark.apache.org/docs/latest/api/python/_modules/pyspark/ml/evaluation.html"
},
{
"code": null,
"e": 13489,
"s": 13430,
"text": "https://spark.apache.org/docs/latest/mllib-clustering.html"
},
{
"code": null,
"e": 13593,
"s": 13489,
"text": "https://spark.apache.org/docs/latest/api/python/pyspark.mllib.html#pyspark.mllib.clustering.KMeansModel"
},
{
"code": null,
"e": 13699,
"s": 13593,
"text": "https://spark.apache.org/docs/latest/api/python/pyspark.ml.html#pyspark.ml.evaluation.ClusteringEvaluator"
},
{
"code": null,
"e": 13783,
"s": 13699,
"text": "https://spark.apache.org/docs/latest/api/python/_modules/pyspark/ml/evaluation.html"
}
] |
Getting started with APIs in Python to Gather Data | by Nik Piepenbreier | Towards Data Science
|
APIs, or Application Programming Interfaces, provide easy ways to retrieve (and post) data. They are the interfaces provided by servers that you can use to, among others, retrieve and send data using code. In essence, they streamline complex instructions to provide back a request from a server. They can be compared to a waiter at a restaurant. As a patron, you give the waiter instructions for a meal, who then communicates the request back to the kitchen, where the chefs undertake complex steps to prepare a dish, without you ever knowing all the hard work he or she put into it! You then get back the meal you ordered, without having to figure out the steps it took to get there!
APIs provide many efficiencies over using static data downloads (such as CSV files). These include the ability to work with rapidly changing data or working with data from which you only want a small chunk (say, today’s temperature, compared to downloading a whole trove of weather data).
In the real, abstracted world, you likely use APIs every day, without knowing it. It’s this abstraction that makes APIs so useful — websites may rely on Google Maps’ API to link you to directions or your Twitter client lets you post data directly to your account.
But how do we leverage APIs to collect data?
In this tutorial, we’ll explore gathering data first without requiring authentication, and then another API that requires us to authenticate. We’ll start by finding where the International Space Station (ISS) currently is using the Open Notify API, and then use authentication to Dark Sky’s weather API to collect interesting weather data. We’ll close off the post by exploring how to add data about the Frankfurt Stock Exchange into a Pandas DataFrame!
Similarly to interacting with regular websites, when you want to get data from an API, you need to make a request from the server. To be able to pull data from an API using Python, we’ll need to use the requests library (go figure!). Requests is more or less the standard package for making HTTP requests in Python. It’s immensely simple to use due to its abstractions, especially when working with APIs.
To get started, you may need to install the Requests library, as it’s not part of the standard Python package. This can be accomplished either via pip or conda.
pip install requestsconda install requests
A request is made up of four different pieces:
An endpoint — which looks like the URL to the dataA method — either GET, PUT, POST, or DELETE. We’ll only be exploring GET requests in this post.The headers — which provide information such as authentication keys.The data/body — which isn’t part of a GET request (so, pretend I didn’t mention it for now)
An endpoint — which looks like the URL to the data
A method — either GET, PUT, POST, or DELETE. We’ll only be exploring GET requests in this post.
The headers — which provide information such as authentication keys.
The data/body — which isn’t part of a GET request (so, pretend I didn’t mention it for now)
When we run a request using the requests library, it returns a request object, which includes the data we’re hoping to extract, but also a requests status code. The status code tells us what happened with the request and they are a part of every request that we make. We’ll be working with GET requests and there’s a number of response codes that are relevant for our work. The codes are split into different values in hundreds, depending on the information they’re returning:
1xx: Provide information
2xx: Generally are successful
3xx: Provide information on redirects
4xx: Refer to a client error (our bad)
5xx: Refer to a server error (their bad)
You may be familiar with seeing the (sometimes comical) 404 page when a page can’t be found. This is what that status code is.
Similarly, a status code of 200 lets us know that everything is OK! This is the one we’re going for and will hopefully get!
For the first part of this tutorial, we’ll take a look at the Open Notify API that provides data on the International Space Station. You can find more information on the API by visiting their documentation.
One of the great things about this API is that it doesn’t require authentication, meaning we can dive right into pulling some data without additional set up.
Let’s begin by generating a URL request with the Requests library, and accessing its status code attribute.
We can do this by using the code outlined below. The output is printed under the dashed line for simplicity.
The .get() function requests a request object. Here, we can use the .status_code attribute to discover what the status code returns. In this example, the status_code returned was 200, meaning we are good to move forward!
The data that we get back comes back in what’s known as JSON format. A JSON file is similar to a Python dictionary and ensures that data is easily readable by machines. An easy way to understand JSON files is to think of them as Python dictionaries represented as strings.
To begin working with JSON files, let’s import the JSON library, which is part of the standard package (so we don’t need to install anything). I’ve included the output of the code under the dashed line for ease of reading.
The string that this response returned is quite short and quite easy to read. However, many API responses will be lengthy and may require a bit of parsing to determine where you want to look for your data (if you’re interested in a particular piece). Let’s use the .dumps() function to convert a JSON string into a Python object. We’ll repeat some of the code for continuity.
This is a much easier-to-read format, allowing us to parse out the data much more readily. Say we were only interested in knowing the latitude and longitude, we could parse this out in the same manner that we would parse data out of a dictionary in Python.
An important thing to note here is that we are calling the response.json() object here — not the one that we returned using the .dumps() function.
From here, we can now use this data to easily append data to a data set, using whatever method we want.
Let’s now turn our attention to the Dark Sky API, which requires a bit of set up before we can get started.
To get started, we’ll need to get what’s known as an API secret key. Keys are ways that allow a user to be authenticated without needing to provide a username and password. As such, they should be treated securely and not be shared. To get your own Dark Sky secret key, sign up for a Dark Sky account at https://darksky.net/dev/register. A free tier will be fine for experimenting with.
Once you’re signed up, navigate to the Account Page https://darksky.net/dev/account, which will give you your API Key. Make note of this key, and be sure to keep it secret.
As part of the free tier, you can make up to 1,000 calls per day.
Dark Sky provides a thorough resource for what data is included in their API, which you can access by visiting: https://darksky.net/dev/docs
There are two main types of calls: (1) the Forecast request, and (2) the Time Machine Request. The former provides current weather (up to the next week), and the latter provides data for the past and the future.
Let’s assume that we wanted to pull out the current weather conditions (summary, temperature, and wind speed) for Toronto, Ontario.
Forecast requests take the following format: https://api.darksky.net/forecast/[key]/[latitude],[longitude]
That means we need three things:
Our API key,Our latitude, andOur longitude.
Our API key,
Our latitude, and
Our longitude.
To easily find your latitude and longitude, you can put the address you’re looking for into Google Maps. For example, I searched for Toronto’s CN Tower. The URL returned will include the coordinates: https://www.google.com/maps/place/CN+Tower/@43.6425701,-79.3892455,17z/
Following the @ sign, the longitude comes first (43.6425701), followed by the latitude (-79.3892455).
Let’s write the code out in a verbose, but easy to follow manner. We’ll make use of f-strings to make the code even easier to read. If you’re not familiar with f-strings, check out the Python docs for them.
Based on the documentation, we can see that the generic request pulls more data than we need. While not required, we can trim this down using Dark Sky’s exclude block, which will reduce latency on the request. We’ll only be using the currently block, so we will exclude all the others.
Earlier we mentioned we were going to be interested in the current conditions (specifically, the summary, temperature, and windspeed). By reviewing the structure above, we can see that we can readily pull this data by accessing the key-value pairs for those items.
The Dark Sky API lets you also set units. Right now, our statement isn’t clear as to what units the data we’re extracting is in. Let’s be more explicit. As we’re pulling data for a Canadian location, let’s specify for their locale. The Dark Sky API documentation tells u that we should set units=si.
So far, we’ve learned how to make API calls with and without authentication. Let’s take it one step further by adding this into a Pandas dataframe.
Let’s say we’re working on a project, and we need to generate a data frame with financial data. We can do this easily using built-in functions in Pandas.
For this, we’ll use Quandl’s financial API. In particular, we’ll use the free API for Frankfurt’s Stock Exchange, for which the documentation can be found here.
Let’s explore the data a bit. We’ll load the data following the instructions for generating the URL on the website and print the data using the json.dumps() function described above. We’ll need to import the same libraries as before, as well as Pandas.
The data actually keeps going for a long, long time, but it’s truncated here.
From this, we can see that:
Column names are found in [‘dataset’][‘column_names’]
The data is found in [‘dataset’][‘data’]
Let’s create a dataframe using this knowledge:
In this post, we explored what APIs are, how to use them in Python, both with and without authentication, and how to add data from APIs to pandas dataframes. There’s still a whole lot more to APIs that we didn’t cover here, but hopefully this gives you a good understanding of where to take your learning from here!
|
[
{
"code": null,
"e": 856,
"s": 171,
"text": "APIs, or Application Programming Interfaces, provide easy ways to retrieve (and post) data. They are the interfaces provided by servers that you can use to, among others, retrieve and send data using code. In essence, they streamline complex instructions to provide back a request from a server. They can be compared to a waiter at a restaurant. As a patron, you give the waiter instructions for a meal, who then communicates the request back to the kitchen, where the chefs undertake complex steps to prepare a dish, without you ever knowing all the hard work he or she put into it! You then get back the meal you ordered, without having to figure out the steps it took to get there!"
},
{
"code": null,
"e": 1145,
"s": 856,
"text": "APIs provide many efficiencies over using static data downloads (such as CSV files). These include the ability to work with rapidly changing data or working with data from which you only want a small chunk (say, today’s temperature, compared to downloading a whole trove of weather data)."
},
{
"code": null,
"e": 1409,
"s": 1145,
"text": "In the real, abstracted world, you likely use APIs every day, without knowing it. It’s this abstraction that makes APIs so useful — websites may rely on Google Maps’ API to link you to directions or your Twitter client lets you post data directly to your account."
},
{
"code": null,
"e": 1454,
"s": 1409,
"text": "But how do we leverage APIs to collect data?"
},
{
"code": null,
"e": 1908,
"s": 1454,
"text": "In this tutorial, we’ll explore gathering data first without requiring authentication, and then another API that requires us to authenticate. We’ll start by finding where the International Space Station (ISS) currently is using the Open Notify API, and then use authentication to Dark Sky’s weather API to collect interesting weather data. We’ll close off the post by exploring how to add data about the Frankfurt Stock Exchange into a Pandas DataFrame!"
},
{
"code": null,
"e": 2313,
"s": 1908,
"text": "Similarly to interacting with regular websites, when you want to get data from an API, you need to make a request from the server. To be able to pull data from an API using Python, we’ll need to use the requests library (go figure!). Requests is more or less the standard package for making HTTP requests in Python. It’s immensely simple to use due to its abstractions, especially when working with APIs."
},
{
"code": null,
"e": 2474,
"s": 2313,
"text": "To get started, you may need to install the Requests library, as it’s not part of the standard Python package. This can be accomplished either via pip or conda."
},
{
"code": null,
"e": 2517,
"s": 2474,
"text": "pip install requestsconda install requests"
},
{
"code": null,
"e": 2564,
"s": 2517,
"text": "A request is made up of four different pieces:"
},
{
"code": null,
"e": 2869,
"s": 2564,
"text": "An endpoint — which looks like the URL to the dataA method — either GET, PUT, POST, or DELETE. We’ll only be exploring GET requests in this post.The headers — which provide information such as authentication keys.The data/body — which isn’t part of a GET request (so, pretend I didn’t mention it for now)"
},
{
"code": null,
"e": 2920,
"s": 2869,
"text": "An endpoint — which looks like the URL to the data"
},
{
"code": null,
"e": 3016,
"s": 2920,
"text": "A method — either GET, PUT, POST, or DELETE. We’ll only be exploring GET requests in this post."
},
{
"code": null,
"e": 3085,
"s": 3016,
"text": "The headers — which provide information such as authentication keys."
},
{
"code": null,
"e": 3177,
"s": 3085,
"text": "The data/body — which isn’t part of a GET request (so, pretend I didn’t mention it for now)"
},
{
"code": null,
"e": 3654,
"s": 3177,
"text": "When we run a request using the requests library, it returns a request object, which includes the data we’re hoping to extract, but also a requests status code. The status code tells us what happened with the request and they are a part of every request that we make. We’ll be working with GET requests and there’s a number of response codes that are relevant for our work. The codes are split into different values in hundreds, depending on the information they’re returning:"
},
{
"code": null,
"e": 3679,
"s": 3654,
"text": "1xx: Provide information"
},
{
"code": null,
"e": 3709,
"s": 3679,
"text": "2xx: Generally are successful"
},
{
"code": null,
"e": 3747,
"s": 3709,
"text": "3xx: Provide information on redirects"
},
{
"code": null,
"e": 3786,
"s": 3747,
"text": "4xx: Refer to a client error (our bad)"
},
{
"code": null,
"e": 3827,
"s": 3786,
"text": "5xx: Refer to a server error (their bad)"
},
{
"code": null,
"e": 3954,
"s": 3827,
"text": "You may be familiar with seeing the (sometimes comical) 404 page when a page can’t be found. This is what that status code is."
},
{
"code": null,
"e": 4078,
"s": 3954,
"text": "Similarly, a status code of 200 lets us know that everything is OK! This is the one we’re going for and will hopefully get!"
},
{
"code": null,
"e": 4285,
"s": 4078,
"text": "For the first part of this tutorial, we’ll take a look at the Open Notify API that provides data on the International Space Station. You can find more information on the API by visiting their documentation."
},
{
"code": null,
"e": 4443,
"s": 4285,
"text": "One of the great things about this API is that it doesn’t require authentication, meaning we can dive right into pulling some data without additional set up."
},
{
"code": null,
"e": 4551,
"s": 4443,
"text": "Let’s begin by generating a URL request with the Requests library, and accessing its status code attribute."
},
{
"code": null,
"e": 4660,
"s": 4551,
"text": "We can do this by using the code outlined below. The output is printed under the dashed line for simplicity."
},
{
"code": null,
"e": 4881,
"s": 4660,
"text": "The .get() function requests a request object. Here, we can use the .status_code attribute to discover what the status code returns. In this example, the status_code returned was 200, meaning we are good to move forward!"
},
{
"code": null,
"e": 5154,
"s": 4881,
"text": "The data that we get back comes back in what’s known as JSON format. A JSON file is similar to a Python dictionary and ensures that data is easily readable by machines. An easy way to understand JSON files is to think of them as Python dictionaries represented as strings."
},
{
"code": null,
"e": 5377,
"s": 5154,
"text": "To begin working with JSON files, let’s import the JSON library, which is part of the standard package (so we don’t need to install anything). I’ve included the output of the code under the dashed line for ease of reading."
},
{
"code": null,
"e": 5753,
"s": 5377,
"text": "The string that this response returned is quite short and quite easy to read. However, many API responses will be lengthy and may require a bit of parsing to determine where you want to look for your data (if you’re interested in a particular piece). Let’s use the .dumps() function to convert a JSON string into a Python object. We’ll repeat some of the code for continuity."
},
{
"code": null,
"e": 6010,
"s": 5753,
"text": "This is a much easier-to-read format, allowing us to parse out the data much more readily. Say we were only interested in knowing the latitude and longitude, we could parse this out in the same manner that we would parse data out of a dictionary in Python."
},
{
"code": null,
"e": 6157,
"s": 6010,
"text": "An important thing to note here is that we are calling the response.json() object here — not the one that we returned using the .dumps() function."
},
{
"code": null,
"e": 6261,
"s": 6157,
"text": "From here, we can now use this data to easily append data to a data set, using whatever method we want."
},
{
"code": null,
"e": 6369,
"s": 6261,
"text": "Let’s now turn our attention to the Dark Sky API, which requires a bit of set up before we can get started."
},
{
"code": null,
"e": 6756,
"s": 6369,
"text": "To get started, we’ll need to get what’s known as an API secret key. Keys are ways that allow a user to be authenticated without needing to provide a username and password. As such, they should be treated securely and not be shared. To get your own Dark Sky secret key, sign up for a Dark Sky account at https://darksky.net/dev/register. A free tier will be fine for experimenting with."
},
{
"code": null,
"e": 6929,
"s": 6756,
"text": "Once you’re signed up, navigate to the Account Page https://darksky.net/dev/account, which will give you your API Key. Make note of this key, and be sure to keep it secret."
},
{
"code": null,
"e": 6995,
"s": 6929,
"text": "As part of the free tier, you can make up to 1,000 calls per day."
},
{
"code": null,
"e": 7136,
"s": 6995,
"text": "Dark Sky provides a thorough resource for what data is included in their API, which you can access by visiting: https://darksky.net/dev/docs"
},
{
"code": null,
"e": 7348,
"s": 7136,
"text": "There are two main types of calls: (1) the Forecast request, and (2) the Time Machine Request. The former provides current weather (up to the next week), and the latter provides data for the past and the future."
},
{
"code": null,
"e": 7480,
"s": 7348,
"text": "Let’s assume that we wanted to pull out the current weather conditions (summary, temperature, and wind speed) for Toronto, Ontario."
},
{
"code": null,
"e": 7587,
"s": 7480,
"text": "Forecast requests take the following format: https://api.darksky.net/forecast/[key]/[latitude],[longitude]"
},
{
"code": null,
"e": 7620,
"s": 7587,
"text": "That means we need three things:"
},
{
"code": null,
"e": 7664,
"s": 7620,
"text": "Our API key,Our latitude, andOur longitude."
},
{
"code": null,
"e": 7677,
"s": 7664,
"text": "Our API key,"
},
{
"code": null,
"e": 7695,
"s": 7677,
"text": "Our latitude, and"
},
{
"code": null,
"e": 7710,
"s": 7695,
"text": "Our longitude."
},
{
"code": null,
"e": 7982,
"s": 7710,
"text": "To easily find your latitude and longitude, you can put the address you’re looking for into Google Maps. For example, I searched for Toronto’s CN Tower. The URL returned will include the coordinates: https://www.google.com/maps/place/CN+Tower/@43.6425701,-79.3892455,17z/"
},
{
"code": null,
"e": 8084,
"s": 7982,
"text": "Following the @ sign, the longitude comes first (43.6425701), followed by the latitude (-79.3892455)."
},
{
"code": null,
"e": 8291,
"s": 8084,
"text": "Let’s write the code out in a verbose, but easy to follow manner. We’ll make use of f-strings to make the code even easier to read. If you’re not familiar with f-strings, check out the Python docs for them."
},
{
"code": null,
"e": 8577,
"s": 8291,
"text": "Based on the documentation, we can see that the generic request pulls more data than we need. While not required, we can trim this down using Dark Sky’s exclude block, which will reduce latency on the request. We’ll only be using the currently block, so we will exclude all the others."
},
{
"code": null,
"e": 8842,
"s": 8577,
"text": "Earlier we mentioned we were going to be interested in the current conditions (specifically, the summary, temperature, and windspeed). By reviewing the structure above, we can see that we can readily pull this data by accessing the key-value pairs for those items."
},
{
"code": null,
"e": 9142,
"s": 8842,
"text": "The Dark Sky API lets you also set units. Right now, our statement isn’t clear as to what units the data we’re extracting is in. Let’s be more explicit. As we’re pulling data for a Canadian location, let’s specify for their locale. The Dark Sky API documentation tells u that we should set units=si."
},
{
"code": null,
"e": 9290,
"s": 9142,
"text": "So far, we’ve learned how to make API calls with and without authentication. Let’s take it one step further by adding this into a Pandas dataframe."
},
{
"code": null,
"e": 9444,
"s": 9290,
"text": "Let’s say we’re working on a project, and we need to generate a data frame with financial data. We can do this easily using built-in functions in Pandas."
},
{
"code": null,
"e": 9605,
"s": 9444,
"text": "For this, we’ll use Quandl’s financial API. In particular, we’ll use the free API for Frankfurt’s Stock Exchange, for which the documentation can be found here."
},
{
"code": null,
"e": 9858,
"s": 9605,
"text": "Let’s explore the data a bit. We’ll load the data following the instructions for generating the URL on the website and print the data using the json.dumps() function described above. We’ll need to import the same libraries as before, as well as Pandas."
},
{
"code": null,
"e": 9936,
"s": 9858,
"text": "The data actually keeps going for a long, long time, but it’s truncated here."
},
{
"code": null,
"e": 9964,
"s": 9936,
"text": "From this, we can see that:"
},
{
"code": null,
"e": 10018,
"s": 9964,
"text": "Column names are found in [‘dataset’][‘column_names’]"
},
{
"code": null,
"e": 10059,
"s": 10018,
"text": "The data is found in [‘dataset’][‘data’]"
},
{
"code": null,
"e": 10106,
"s": 10059,
"text": "Let’s create a dataframe using this knowledge:"
}
] |
Stop worrying about configs with Gin | by Alexander Bailey | Towards Data Science
|
We’ve all been there, you’re modelling away and one by one the hyper-parameters start adding up. At first, you ignore the problem and tell yourself that you’ll go back later to sort it out but inevitably don’t. There are loads of bad ways to tackle the problem of project configuration they include but are by no means limited to:
The really silly ways to configure your project:
Creating a list of variables at the top of your script that you change until you find ones that workMaybe you just define defaults for your functions and classes that you change on the fly
Creating a list of variables at the top of your script that you change until you find ones that work
Maybe you just define defaults for your functions and classes that you change on the fly
The less silly ways to configure your project:
Use a TOML or YAML file and pass a dictionary of config variables around with youUse a config script that sets environment variables that get read by your packages
Use a TOML or YAML file and pass a dictionary of config variables around with you
Use a config script that sets environment variables that get read by your packages
The last two aren’t bad options but they come with the overhead of having to carry around a dictionary of parameters that you can pass as **kwargs to a function or class. What if we could abstract that all away and get Python to do all the heavy lifting for us? Well, there’s where Gin comes in. Gin is a lightweight Python library developed by Google to specifically try and tackle this problem. In this article, we’re going to take a look at the basics of how to use the library and then try and work out if it’s actually something you would use.
Consider the following function:
def make_drink(drink_name:str, ingredients:list, ice:bool=False): print(f"New drink called: {drink_name}") print(f"Drink contains: " + ", ".join(ingredients)) if ice is True: print("With ice") else: print("Without ice")
All we need to do to make this Gin configurable is to add a simple decorator to the function @gin.configurable which tells the library to index this function as one that can be configured in a .gin file - if you don’t know what a decorator I've linked an article below explaining how they work.
towardsdatascience.com
So let’s start writing that gin file:
make_drink.drink_name = "G&T"make_drink.ingredients = ["Gin", "Tonic", "Lemon"]make_drink.ice = False
The syntax is pretty simple, the first part is the function or class name, followed by a dot and then the argument name. This syntax support the assignment of all major Python variable types as you might expect, here we have a string, a list and a boolean but equally this could have been a dictionary, an integer or a tuple.
So now our function becomes:
import gingin.parse_config_file("path/to/gin_file.gin")@gin.configurabledef make_drink(drink_name:str, ingredients:list, ice:bool=False): print(f"New drink called: {drink_name}") print(f"Drink contains: " + ", ".join(ingredients)) if ice is True: print("With ice") else: print("Without ice")
And we can call it like this:
>>> make_drink()New drink called: G&TDrink contains:Gin, Tonic, LemonWithout ice
If you’re anything like me this should annoy you. We didn’t define any default values for any of the arguments so, for anyone who’s reading the code, it isn’t clear where the values came from!
The developers of Gin saw this coming though and have provided a gin.REQUIRED value that can be used in the argument’s position to make it clear where the value should be sourced from. This comes with the added benefit of a custom error if you fail to provide that value in the Gin file.
>>> make_drink(gin.REQUIRED, gin.REQUIRED, ice=gin.REQUIRED)New drink called: G&TDrink contains:Gin, Tonic, LemonWithout ice
Now let’s build on our code and create a Drink class...
@gin.configurableclass Drink: def __init__(self, name, ingredients, ice=True): self.name = name self.ingredients = ingredients self.ice = ice@gin.configurabledef make_drink(drink: Drink): print(f"New drink called: {drink.name}") print(f"Drink contains: " + ", ".join(drink.ingredients)) if drink.ice is True: print("With ice") else: print("Without ice") print("\n")
Both the class and the function are configurable. Gin’s pretty cool so we can configure it such that make_drink takes an instance of Drink which itself takes parameter values:
make_drink.drink = @Drink()Drink.name = "Gin Martini"Drink.ingredients = ["Gin", "Vermouth"]Drink.ice = False
And call it...
>>> make_drink(gin.REQUIRED)New drink called: Gin MartiniDrink contains: Gin, VermouthWithout ice
But you know what’s better than one drink... two drinks... Let's consider the following example...
@gin.configurabledef make_two_drinks(drink1: Drink, drink2:Drink): print("Making drink 1") make_drink(drink1) print("Making drink 2") make_drink(drink2)
Both require an instance of Drink and you might try and write something like this.
make_two_drinks.drink1 = @Drink()Drink.name = "Gin Martini"Drink.ingredients = ["Gin", "Vermouth"]Drink.ice = Falsemake_two_drinks.drink2 = @Drink()Drink.name = "Gin Fizz"Drink.ingredients = ["Gin", "Sparkling Water"]Drink.ice = True
But this isn’t going to have the desired effect.
>>> make_two_drinks(gin.REQUIRED, gin.REQUIRED)Making drink 1New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith iceMaking drink 2New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith ice
We just get two Gin Fizzes! Fortunately for us, Gin has a concept of scopes that allow us to define different drinks for the two inputs.
make_two_drinks.drink1 = @drink1/Drink()drink1/Drink.name = "Gin Martini"drink1/Drink.ingredients = ["Gin", "Vermouth"]drink1/Drink.ice = Falsemake_two_drinks.drink2 = @drink2/Drink()drink2/Drink.name = "Gin Fizz"drink2/Drink.ingredients = ["Gin", "Sparkling Water"]drink2/Drink.ice = True
Which now yields exactly what we want.
>>> make_two_drinks(gin.REQUIRED, gin.REQUIRED)Making drink 1New drink called: Gin MartiniDrink contains: Gin, VermouthWithout iceMaking drink 2New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith ice
If a function calls a function and both have been configured in Gin, the uppermost in the tree will take precedence.
make_two_drinks.drink1 = @drink1/Drink()drink1/Drink.name = "Gin Martini"drink1/Drink.ingredients = ["Gin", "Vermouth"]drink1/Drink.ice = Falsemake_two_drinks.drink2 = @drink2/Drink()drink2/Drink.name = "Gin Fizz"drink2/Drink.ingredients = ["Gin", "Sparkling Water"]drink2/Drink.ice = Truemake_drink.drink = @Drink()Drink.name = "French 75"Drink.ingredients = ["Gin", "Champagne"]Drink.ice = False
Will give us...
>>> make_two_drinks(gin.REQUIRED, gin.REQUIRED)Making drink 1New drink called: Gin MartiniDrink contains: Gin, VermouthWithout iceMaking drink 2New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith ice
As we expect and...
>>> make_drink(gin.REQUIRED)New drink called: French 75Drink contains: Gin, ChampagneWithout ice
As we expect.
I’ve given you a flavour for the basic functionality here, Gin contains a whole load of other features such as macros and the ability to programmatically set and retrieve config parameters.
So that’s the basics, next we’ll take a look at how this applies to a real-world example. We’ll build a quick model and a training loop and show how Gin can be used to configure it.
import torch.nn as nnimport torch.nn.functional as F@gin.configurableclass DNN(torch.nn.Module): def __init__(self, input_size, output_size, hidden_size): super(DNN, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, hidden_size) self.fc3 = nn.Linear(hidden_size, output_size) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x@gin.configurabledef train(model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_func: torch.nn.modules.loss, epochs: int, train_dataloader: torch.utils.data.DataLoader, ): opt = optimizer(model.parameters()) for epoch in range(epochs): for i, (inputs, labels) in enumerate(train_dataloader): opt.zero_grad() outputs = model(inputs) loss = loss_func(outputs, labels) loss.backward() opt.step() print('Finished Training')
We might build a Gin file like this...
train.epochs = 10train.model = @DNN()DNN.input_size = 10DNN.output_size = 10DNN.hidden_size = 128
Which is great but what about the optimizer and the loss function? Can we configure them too? Gin allows you to register external functions so that we can!
gin.external_configurable(torch.optim.Adam)gin.external_configurable(torch.nn.CrossEntropyLoss)
Gin has a lot of TensorFlow and PyTorch functions built-in so you don’t need to do this for everything, all you need to do is import gin.tensorflow and/or gin.torch. Our new Gin file looks like this...
train.epochs = 10train.model = @DNN()DNN.input_size = 10DNN.output_size = 10DNN.hidden_size = 128train.optimizer = @AdamAdam.lr = 0.001train.loss_func = @CrossEntropyLoss()
Notice the subtle difference between Adam and CrossEntropyLoss(), Adam needs to be instantiated with the model parameters which happens within the fit function whereasCrossEntropyLoss() is passed as an instantiated class.
The short answer is yes. I think it saves a lot of faff that comes with the task of configuring your project. I think the difficulty which comes with configuration, in general, is knowing that you can overdo it. The more you hide away in config files, the less readable your code tends to be. The Gin developers are also aware of this and say that we should “use Gin responsibly”. The other thing worth adding is there’s a bit of overhead in learning to us Gin and learning the best practices such that your code remains both Pythonic and readable. This is less true of learning to use TOML or YAML. Using these comes with its own learning curve but I just get the feeling there’s less that can go wrong.
I’ll caveat that opinion by adding: to write this article, I spent a few hours playing around with some of the core functionality of the library. In reality, I should probably form a proper opinion after using it in anger on a real-world project. But hey, you shouldn't trust my opinion anyway, try it out for yourself and let me know what you make of it.
GitHub repoGin’s walkthrough
|
[
{
"code": null,
"e": 503,
"s": 172,
"text": "We’ve all been there, you’re modelling away and one by one the hyper-parameters start adding up. At first, you ignore the problem and tell yourself that you’ll go back later to sort it out but inevitably don’t. There are loads of bad ways to tackle the problem of project configuration they include but are by no means limited to:"
},
{
"code": null,
"e": 552,
"s": 503,
"text": "The really silly ways to configure your project:"
},
{
"code": null,
"e": 741,
"s": 552,
"text": "Creating a list of variables at the top of your script that you change until you find ones that workMaybe you just define defaults for your functions and classes that you change on the fly"
},
{
"code": null,
"e": 842,
"s": 741,
"text": "Creating a list of variables at the top of your script that you change until you find ones that work"
},
{
"code": null,
"e": 931,
"s": 842,
"text": "Maybe you just define defaults for your functions and classes that you change on the fly"
},
{
"code": null,
"e": 978,
"s": 931,
"text": "The less silly ways to configure your project:"
},
{
"code": null,
"e": 1142,
"s": 978,
"text": "Use a TOML or YAML file and pass a dictionary of config variables around with youUse a config script that sets environment variables that get read by your packages"
},
{
"code": null,
"e": 1224,
"s": 1142,
"text": "Use a TOML or YAML file and pass a dictionary of config variables around with you"
},
{
"code": null,
"e": 1307,
"s": 1224,
"text": "Use a config script that sets environment variables that get read by your packages"
},
{
"code": null,
"e": 1856,
"s": 1307,
"text": "The last two aren’t bad options but they come with the overhead of having to carry around a dictionary of parameters that you can pass as **kwargs to a function or class. What if we could abstract that all away and get Python to do all the heavy lifting for us? Well, there’s where Gin comes in. Gin is a lightweight Python library developed by Google to specifically try and tackle this problem. In this article, we’re going to take a look at the basics of how to use the library and then try and work out if it’s actually something you would use."
},
{
"code": null,
"e": 1889,
"s": 1856,
"text": "Consider the following function:"
},
{
"code": null,
"e": 2135,
"s": 1889,
"text": "def make_drink(drink_name:str, ingredients:list, ice:bool=False): print(f\"New drink called: {drink_name}\") print(f\"Drink contains: \" + \", \".join(ingredients)) if ice is True: print(\"With ice\") else: print(\"Without ice\")"
},
{
"code": null,
"e": 2430,
"s": 2135,
"text": "All we need to do to make this Gin configurable is to add a simple decorator to the function @gin.configurable which tells the library to index this function as one that can be configured in a .gin file - if you don’t know what a decorator I've linked an article below explaining how they work."
},
{
"code": null,
"e": 2453,
"s": 2430,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2491,
"s": 2453,
"text": "So let’s start writing that gin file:"
},
{
"code": null,
"e": 2593,
"s": 2491,
"text": "make_drink.drink_name = \"G&T\"make_drink.ingredients = [\"Gin\", \"Tonic\", \"Lemon\"]make_drink.ice = False"
},
{
"code": null,
"e": 2919,
"s": 2593,
"text": "The syntax is pretty simple, the first part is the function or class name, followed by a dot and then the argument name. This syntax support the assignment of all major Python variable types as you might expect, here we have a string, a list and a boolean but equally this could have been a dictionary, an integer or a tuple."
},
{
"code": null,
"e": 2948,
"s": 2919,
"text": "So now our function becomes:"
},
{
"code": null,
"e": 3266,
"s": 2948,
"text": "import gingin.parse_config_file(\"path/to/gin_file.gin\")@gin.configurabledef make_drink(drink_name:str, ingredients:list, ice:bool=False): print(f\"New drink called: {drink_name}\") print(f\"Drink contains: \" + \", \".join(ingredients)) if ice is True: print(\"With ice\") else: print(\"Without ice\")"
},
{
"code": null,
"e": 3296,
"s": 3266,
"text": "And we can call it like this:"
},
{
"code": null,
"e": 3377,
"s": 3296,
"text": ">>> make_drink()New drink called: G&TDrink contains:Gin, Tonic, LemonWithout ice"
},
{
"code": null,
"e": 3570,
"s": 3377,
"text": "If you’re anything like me this should annoy you. We didn’t define any default values for any of the arguments so, for anyone who’s reading the code, it isn’t clear where the values came from!"
},
{
"code": null,
"e": 3858,
"s": 3570,
"text": "The developers of Gin saw this coming though and have provided a gin.REQUIRED value that can be used in the argument’s position to make it clear where the value should be sourced from. This comes with the added benefit of a custom error if you fail to provide that value in the Gin file."
},
{
"code": null,
"e": 3983,
"s": 3858,
"text": ">>> make_drink(gin.REQUIRED, gin.REQUIRED, ice=gin.REQUIRED)New drink called: G&TDrink contains:Gin, Tonic, LemonWithout ice"
},
{
"code": null,
"e": 4039,
"s": 3983,
"text": "Now let’s build on our code and create a Drink class..."
},
{
"code": null,
"e": 4458,
"s": 4039,
"text": "@gin.configurableclass Drink: def __init__(self, name, ingredients, ice=True): self.name = name self.ingredients = ingredients self.ice = ice@gin.configurabledef make_drink(drink: Drink): print(f\"New drink called: {drink.name}\") print(f\"Drink contains: \" + \", \".join(drink.ingredients)) if drink.ice is True: print(\"With ice\") else: print(\"Without ice\") print(\"\\n\")"
},
{
"code": null,
"e": 4634,
"s": 4458,
"text": "Both the class and the function are configurable. Gin’s pretty cool so we can configure it such that make_drink takes an instance of Drink which itself takes parameter values:"
},
{
"code": null,
"e": 4744,
"s": 4634,
"text": "make_drink.drink = @Drink()Drink.name = \"Gin Martini\"Drink.ingredients = [\"Gin\", \"Vermouth\"]Drink.ice = False"
},
{
"code": null,
"e": 4759,
"s": 4744,
"text": "And call it..."
},
{
"code": null,
"e": 4857,
"s": 4759,
"text": ">>> make_drink(gin.REQUIRED)New drink called: Gin MartiniDrink contains: Gin, VermouthWithout ice"
},
{
"code": null,
"e": 4956,
"s": 4857,
"text": "But you know what’s better than one drink... two drinks... Let's consider the following example..."
},
{
"code": null,
"e": 5129,
"s": 4956,
"text": "@gin.configurabledef make_two_drinks(drink1: Drink, drink2:Drink): print(\"Making drink 1\") make_drink(drink1) print(\"Making drink 2\") make_drink(drink2)"
},
{
"code": null,
"e": 5212,
"s": 5129,
"text": "Both require an instance of Drink and you might try and write something like this."
},
{
"code": null,
"e": 5446,
"s": 5212,
"text": "make_two_drinks.drink1 = @Drink()Drink.name = \"Gin Martini\"Drink.ingredients = [\"Gin\", \"Vermouth\"]Drink.ice = Falsemake_two_drinks.drink2 = @Drink()Drink.name = \"Gin Fizz\"Drink.ingredients = [\"Gin\", \"Sparkling Water\"]Drink.ice = True"
},
{
"code": null,
"e": 5495,
"s": 5446,
"text": "But this isn’t going to have the desired effect."
},
{
"code": null,
"e": 5711,
"s": 5495,
"text": ">>> make_two_drinks(gin.REQUIRED, gin.REQUIRED)Making drink 1New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith iceMaking drink 2New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith ice"
},
{
"code": null,
"e": 5848,
"s": 5711,
"text": "We just get two Gin Fizzes! Fortunately for us, Gin has a concept of scopes that allow us to define different drinks for the two inputs."
},
{
"code": null,
"e": 6138,
"s": 5848,
"text": "make_two_drinks.drink1 = @drink1/Drink()drink1/Drink.name = \"Gin Martini\"drink1/Drink.ingredients = [\"Gin\", \"Vermouth\"]drink1/Drink.ice = Falsemake_two_drinks.drink2 = @drink2/Drink()drink2/Drink.name = \"Gin Fizz\"drink2/Drink.ingredients = [\"Gin\", \"Sparkling Water\"]drink2/Drink.ice = True"
},
{
"code": null,
"e": 6177,
"s": 6138,
"text": "Which now yields exactly what we want."
},
{
"code": null,
"e": 6392,
"s": 6177,
"text": ">>> make_two_drinks(gin.REQUIRED, gin.REQUIRED)Making drink 1New drink called: Gin MartiniDrink contains: Gin, VermouthWithout iceMaking drink 2New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith ice"
},
{
"code": null,
"e": 6509,
"s": 6392,
"text": "If a function calls a function and both have been configured in Gin, the uppermost in the tree will take precedence."
},
{
"code": null,
"e": 6907,
"s": 6509,
"text": "make_two_drinks.drink1 = @drink1/Drink()drink1/Drink.name = \"Gin Martini\"drink1/Drink.ingredients = [\"Gin\", \"Vermouth\"]drink1/Drink.ice = Falsemake_two_drinks.drink2 = @drink2/Drink()drink2/Drink.name = \"Gin Fizz\"drink2/Drink.ingredients = [\"Gin\", \"Sparkling Water\"]drink2/Drink.ice = Truemake_drink.drink = @Drink()Drink.name = \"French 75\"Drink.ingredients = [\"Gin\", \"Champagne\"]Drink.ice = False"
},
{
"code": null,
"e": 6923,
"s": 6907,
"text": "Will give us..."
},
{
"code": null,
"e": 7138,
"s": 6923,
"text": ">>> make_two_drinks(gin.REQUIRED, gin.REQUIRED)Making drink 1New drink called: Gin MartiniDrink contains: Gin, VermouthWithout iceMaking drink 2New drink called: Gin FizzDrink contains: Gin, Sparkling WaterWith ice"
},
{
"code": null,
"e": 7158,
"s": 7138,
"text": "As we expect and..."
},
{
"code": null,
"e": 7255,
"s": 7158,
"text": ">>> make_drink(gin.REQUIRED)New drink called: French 75Drink contains: Gin, ChampagneWithout ice"
},
{
"code": null,
"e": 7269,
"s": 7255,
"text": "As we expect."
},
{
"code": null,
"e": 7459,
"s": 7269,
"text": "I’ve given you a flavour for the basic functionality here, Gin contains a whole load of other features such as macros and the ability to programmatically set and retrieve config parameters."
},
{
"code": null,
"e": 7641,
"s": 7459,
"text": "So that’s the basics, next we’ll take a look at how this applies to a real-world example. We’ll build a quick model and a training loop and show how Gin can be used to configure it."
},
{
"code": null,
"e": 8675,
"s": 7641,
"text": "import torch.nn as nnimport torch.nn.functional as F@gin.configurableclass DNN(torch.nn.Module): def __init__(self, input_size, output_size, hidden_size): super(DNN, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, hidden_size) self.fc3 = nn.Linear(hidden_size, output_size) def forward(self, x): x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x@gin.configurabledef train(model: torch.nn.Module, optimizer: torch.optim.Optimizer, loss_func: torch.nn.modules.loss, epochs: int, train_dataloader: torch.utils.data.DataLoader, ): opt = optimizer(model.parameters()) for epoch in range(epochs): for i, (inputs, labels) in enumerate(train_dataloader): opt.zero_grad() outputs = model(inputs) loss = loss_func(outputs, labels) loss.backward() opt.step() print('Finished Training')"
},
{
"code": null,
"e": 8714,
"s": 8675,
"text": "We might build a Gin file like this..."
},
{
"code": null,
"e": 8812,
"s": 8714,
"text": "train.epochs = 10train.model = @DNN()DNN.input_size = 10DNN.output_size = 10DNN.hidden_size = 128"
},
{
"code": null,
"e": 8968,
"s": 8812,
"text": "Which is great but what about the optimizer and the loss function? Can we configure them too? Gin allows you to register external functions so that we can!"
},
{
"code": null,
"e": 9064,
"s": 8968,
"text": "gin.external_configurable(torch.optim.Adam)gin.external_configurable(torch.nn.CrossEntropyLoss)"
},
{
"code": null,
"e": 9266,
"s": 9064,
"text": "Gin has a lot of TensorFlow and PyTorch functions built-in so you don’t need to do this for everything, all you need to do is import gin.tensorflow and/or gin.torch. Our new Gin file looks like this..."
},
{
"code": null,
"e": 9439,
"s": 9266,
"text": "train.epochs = 10train.model = @DNN()DNN.input_size = 10DNN.output_size = 10DNN.hidden_size = 128train.optimizer = @AdamAdam.lr = 0.001train.loss_func = @CrossEntropyLoss()"
},
{
"code": null,
"e": 9661,
"s": 9439,
"text": "Notice the subtle difference between Adam and CrossEntropyLoss(), Adam needs to be instantiated with the model parameters which happens within the fit function whereasCrossEntropyLoss() is passed as an instantiated class."
},
{
"code": null,
"e": 10366,
"s": 9661,
"text": "The short answer is yes. I think it saves a lot of faff that comes with the task of configuring your project. I think the difficulty which comes with configuration, in general, is knowing that you can overdo it. The more you hide away in config files, the less readable your code tends to be. The Gin developers are also aware of this and say that we should “use Gin responsibly”. The other thing worth adding is there’s a bit of overhead in learning to us Gin and learning the best practices such that your code remains both Pythonic and readable. This is less true of learning to use TOML or YAML. Using these comes with its own learning curve but I just get the feeling there’s less that can go wrong."
},
{
"code": null,
"e": 10722,
"s": 10366,
"text": "I’ll caveat that opinion by adding: to write this article, I spent a few hours playing around with some of the core functionality of the library. In reality, I should probably form a proper opinion after using it in anger on a real-world project. But hey, you shouldn't trust my opinion anyway, try it out for yourself and let me know what you make of it."
}
] |
Fast I/O in Java in Competitive Programming - GeeksforGeeks
|
14 Apr, 2022
Using Java in competitive programming is not something many people would suggest just because of its slow input and output, and well indeed it is slow.
In this article, we have discussed some ways to get around the difficulty and change the verdict from TLE to (in most cases) AC.
Example:
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
1. Scanner Class (easy, less typing, but not recommended very slow, refer this for reasons of slowness):
In most of the cases, we get TLE while using scanner class. It uses built-in nextInt(), nextLong(), nextDouble methods to read the desired object after initiating scanner object with the input stream(e.g. System.in). The following program many times gets time limit exceeded verdict and therefore not of much use.
Java
// Working program using Scannerimport java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); int count = 0; while (n-- > 0) { int x = s.nextInt(); if (x % k == 0) count++; } System.out.println(count); }}
2. BufferedReader (fast, but not recommended as it requires a lot of typing):
The Java.io.BufferedReader class reads text from a character-input stream, buffering characters to provide for the efficient reading of characters, arrays, and lines. With this method, we will have to parse the value every time for the desired type. Reading multiple words from a single line adds to its complexity because of the use of Stringtokenizer and hence this is not recommended. These get accepted with a running time of approx 0.89 s.but still as you can see it requires a lot of typing altogether and therefore method 3 is recommended.
Java
// Working program using BufferedReaderimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int count = 0; while (n-- > 0) { int x = Integer.parseInt(br.readLine()); if (x % k == 0) count++; } System.out.println(count); }}
3.Userdefined FastReader Class (which uses bufferedReader and StringTokenizer):
This method uses the time advantage of BufferedReader and StringTokenizer and the advantage of user-defined methods for less typing and therefore a faster input altogether. These get accepted with a time of 1.23 s and this method is very much recommended as it is easy to remember and is fast enough to meet the needs of most of the question in competitive coding.
Java
// Working program with FastReaderimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Scanner;import java.util.StringTokenizer; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = ""; try { if(st.hasMoreTokens()){ str = st.nextToken("\n"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s = new FastReader(); int n = s.nextInt(); int k = s.nextInt(); int count = 0; while (n-- > 0) { int x = s.nextInt(); if (x % k == 0) count++; } System.out.println(count); }}
4.Using Reader Class:
There is yet another fast way through the problem, I would say the fastest way but is not recommended since it requires very cumbersome methods in its implementation. It uses inputDataStream to read through the stream of data and uses read() method and nextInt() methods for taking inputs. This is by far the fastest ways of taking input but is difficult to remember and is cumbersome in its approach. Below is the sample program using this method. These get accepted with a surprising time of just 0.28 s. Although this is ultra-fast, it is clearly not an easy method to remember.
Java
// Working program using Reader Classimport java.io.DataInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.Scanner;import java.util.StringTokenizer; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader s = new Reader(); int n = s.nextInt(); int k = s.nextInt(); int count = 0; while (n-- > 0) { int x = s.nextInt(); if (x % k == 0) count++; } System.out.println(count); }}
Suggested Read:
Enormous Input Test designed to check the fast input handling of your language. Timings of all programs are noted from SPOJ.
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
amaannassar123
yogeshiitm
Competitive Programming
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Reduce the string by removing K consecutive identical characters
Use of FLAG in programming
Pairs with same Manhattan and Euclidean distance
Container with Most Water
Breadth First Traversal ( BFS ) on a 2D array
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 24680,
"s": 24652,
"text": "\n14 Apr, 2022"
},
{
"code": null,
"e": 24832,
"s": 24680,
"text": "Using Java in competitive programming is not something many people would suggest just because of its slow input and output, and well indeed it is slow."
},
{
"code": null,
"e": 24961,
"s": 24832,
"text": "In this article, we have discussed some ways to get around the difficulty and change the verdict from TLE to (in most cases) AC."
},
{
"code": null,
"e": 24970,
"s": 24961,
"text": "Example:"
},
{
"code": null,
"e": 25018,
"s": 24970,
"text": "Input:\n7 3\n1\n51\n966369\n7\n9\n999996\n11\nOutput: \n4"
},
{
"code": null,
"e": 25124,
"s": 25018,
"text": "1. Scanner Class (easy, less typing, but not recommended very slow, refer this for reasons of slowness): "
},
{
"code": null,
"e": 25438,
"s": 25124,
"text": "In most of the cases, we get TLE while using scanner class. It uses built-in nextInt(), nextLong(), nextDouble methods to read the desired object after initiating scanner object with the input stream(e.g. System.in). The following program many times gets time limit exceeded verdict and therefore not of much use."
},
{
"code": null,
"e": 25443,
"s": 25438,
"text": "Java"
},
{
"code": "// Working program using Scannerimport java.io.BufferedReader;import java.io.InputStreamReader;import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); int k = s.nextInt(); int count = 0; while (n-- > 0) { int x = s.nextInt(); if (x % k == 0) count++; } System.out.println(count); }}",
"e": 25908,
"s": 25443,
"text": null
},
{
"code": null,
"e": 25989,
"s": 25910,
"text": "2. BufferedReader (fast, but not recommended as it requires a lot of typing): "
},
{
"code": null,
"e": 26537,
"s": 25989,
"text": "The Java.io.BufferedReader class reads text from a character-input stream, buffering characters to provide for the efficient reading of characters, arrays, and lines. With this method, we will have to parse the value every time for the desired type. Reading multiple words from a single line adds to its complexity because of the use of Stringtokenizer and hence this is not recommended. These get accepted with a running time of approx 0.89 s.but still as you can see it requires a lot of typing altogether and therefore method 3 is recommended. "
},
{
"code": null,
"e": 26542,
"s": 26537,
"text": "Java"
},
{
"code": "// Working program using BufferedReaderimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int k = Integer.parseInt(st.nextToken()); int count = 0; while (n-- > 0) { int x = Integer.parseInt(br.readLine()); if (x % k == 0) count++; } System.out.println(count); }}",
"e": 27265,
"s": 26542,
"text": null
},
{
"code": null,
"e": 27348,
"s": 27267,
"text": "3.Userdefined FastReader Class (which uses bufferedReader and StringTokenizer): "
},
{
"code": null,
"e": 27713,
"s": 27348,
"text": "This method uses the time advantage of BufferedReader and StringTokenizer and the advantage of user-defined methods for less typing and therefore a faster input altogether. These get accepted with a time of 1.23 s and this method is very much recommended as it is easy to remember and is fast enough to meet the needs of most of the question in competitive coding."
},
{
"code": null,
"e": 27718,
"s": 27713,
"text": "Java"
},
{
"code": "// Working program with FastReaderimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.util.Scanner;import java.util.StringTokenizer; public class Main { static class FastReader { BufferedReader br; StringTokenizer st; public FastReader() { br = new BufferedReader( new InputStreamReader(System.in)); } String next() { while (st == null || !st.hasMoreElements()) { try { st = new StringTokenizer(br.readLine()); } catch (IOException e) { e.printStackTrace(); } } return st.nextToken(); } int nextInt() { return Integer.parseInt(next()); } long nextLong() { return Long.parseLong(next()); } double nextDouble() { return Double.parseDouble(next()); } String nextLine() { String str = \"\"; try { if(st.hasMoreTokens()){ str = st.nextToken(\"\\n\"); } else{ str = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } return str; } } public static void main(String[] args) { FastReader s = new FastReader(); int n = s.nextInt(); int k = s.nextInt(); int count = 0; while (n-- > 0) { int x = s.nextInt(); if (x % k == 0) count++; } System.out.println(count); }}",
"e": 29399,
"s": 27718,
"text": null
},
{
"code": null,
"e": 29424,
"s": 29401,
"text": "4.Using Reader Class: "
},
{
"code": null,
"e": 30006,
"s": 29424,
"text": "There is yet another fast way through the problem, I would say the fastest way but is not recommended since it requires very cumbersome methods in its implementation. It uses inputDataStream to read through the stream of data and uses read() method and nextInt() methods for taking inputs. This is by far the fastest ways of taking input but is difficult to remember and is cumbersome in its approach. Below is the sample program using this method. These get accepted with a surprising time of just 0.28 s. Although this is ultra-fast, it is clearly not an easy method to remember."
},
{
"code": null,
"e": 30011,
"s": 30006,
"text": "Java"
},
{
"code": "// Working program using Reader Classimport java.io.DataInputStream;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import java.util.Scanner;import java.util.StringTokenizer; public class Main { static class Reader { final private int BUFFER_SIZE = 1 << 16; private DataInputStream din; private byte[] buffer; private int bufferPointer, bytesRead; public Reader() { din = new DataInputStream(System.in); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public Reader(String file_name) throws IOException { din = new DataInputStream( new FileInputStream(file_name)); buffer = new byte[BUFFER_SIZE]; bufferPointer = bytesRead = 0; } public String readLine() throws IOException { byte[] buf = new byte[64]; // line length int cnt = 0, c; while ((c = read()) != -1) { if (c == '\\n') { if (cnt != 0) { break; } else { continue; } } buf[cnt++] = (byte)c; } return new String(buf, 0, cnt); } public int nextInt() throws IOException { int ret = 0; byte c = read(); while (c <= ' ') { c = read(); } boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public long nextLong() throws IOException { long ret = 0; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (neg) return -ret; return ret; } public double nextDouble() throws IOException { double ret = 0, div = 1; byte c = read(); while (c <= ' ') c = read(); boolean neg = (c == '-'); if (neg) c = read(); do { ret = ret * 10 + c - '0'; } while ((c = read()) >= '0' && c <= '9'); if (c == '.') { while ((c = read()) >= '0' && c <= '9') { ret += (c - '0') / (div *= 10); } } if (neg) return -ret; return ret; } private void fillBuffer() throws IOException { bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE); if (bytesRead == -1) buffer[0] = -1; } private byte read() throws IOException { if (bufferPointer == bytesRead) fillBuffer(); return buffer[bufferPointer++]; } public void close() throws IOException { if (din == null) return; din.close(); } } public static void main(String[] args) throws IOException { Reader s = new Reader(); int n = s.nextInt(); int k = s.nextInt(); int count = 0; while (n-- > 0) { int x = s.nextInt(); if (x % k == 0) count++; } System.out.println(count); }}",
"e": 33782,
"s": 30011,
"text": null
},
{
"code": null,
"e": 33801,
"s": 33784,
"text": "Suggested Read: "
},
{
"code": null,
"e": 33928,
"s": 33801,
"text": "Enormous Input Test designed to check the fast input handling of your language. Timings of all programs are noted from SPOJ. "
},
{
"code": null,
"e": 34198,
"s": 33928,
"text": "This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 34322,
"s": 34198,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 34337,
"s": 34322,
"text": "amaannassar123"
},
{
"code": null,
"e": 34348,
"s": 34337,
"text": "yogeshiitm"
},
{
"code": null,
"e": 34372,
"s": 34348,
"text": "Competitive Programming"
},
{
"code": null,
"e": 34377,
"s": 34372,
"text": "Java"
},
{
"code": null,
"e": 34382,
"s": 34377,
"text": "Java"
},
{
"code": null,
"e": 34480,
"s": 34382,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34489,
"s": 34480,
"text": "Comments"
},
{
"code": null,
"e": 34502,
"s": 34489,
"text": "Old Comments"
},
{
"code": null,
"e": 34567,
"s": 34502,
"text": "Reduce the string by removing K consecutive identical characters"
},
{
"code": null,
"e": 34594,
"s": 34567,
"text": "Use of FLAG in programming"
},
{
"code": null,
"e": 34643,
"s": 34594,
"text": "Pairs with same Manhattan and Euclidean distance"
},
{
"code": null,
"e": 34669,
"s": 34643,
"text": "Container with Most Water"
},
{
"code": null,
"e": 34715,
"s": 34669,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 34730,
"s": 34715,
"text": "Arrays in Java"
},
{
"code": null,
"e": 34774,
"s": 34730,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 34796,
"s": 34774,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 34821,
"s": 34796,
"text": "Reverse a string in Java"
}
] |
8086 program to reverse a string - GeeksforGeeks
|
17 Dec, 2021
Problem: Given a string we have to reverse the string and print the reversed string. Examples:
Input: String : "This is a sample string"
Output: gnirts elpmas a si sihT
Input: String : "Geeks for Geeks"
Output: skeeG rof skeeG
Explanation:
Create a stringTraverse through the stringPush the characters in the stackCount the number of charactersLoad the starting address of the stringPOP the top character of the stack until count is not equal to zeroPut the character and reduce the count and increase the addressContinue until the count is greater than zeroLoad the effective address of the string in dx using LEA commandPrint the sting by calling the interrupt with 9H in AHThe string must be terminated by ‘$’ sign
Create a string
Traverse through the string
Push the characters in the stack
Count the number of characters
Load the starting address of the string
POP the top character of the stack until count is not equal to zero
Put the character and reduce the count and increase the address
Continue until the count is greater than zero
Load the effective address of the string in dx using LEA command
Print the sting by calling the interrupt with 9H in AH
The string must be terminated by ‘$’ sign
Program:
CPP
.MODEL SMALL.STACK 100H.DATA ; The string to be printedSTRING DB 'This is a sample string', '$' .CODEMAIN PROC FARMOV AX,@DATAMOV DS,AX ; call reverse functionCALL REVERSE ; load address of the stringLEA DX,STRING ; output the string; loaded in dxMOV AH, 09HINT 21H ; interrupt to exitMOV AH, 4CHINT 21H MAIN ENDPREVERSE PROC ; load the offset of ; the string MOV SI, OFFSET STRING ; count of characters of the; ;string MOV CX, 0H LOOP1: ; compare if this is; ;the last character MOV AX, [SI] CMP AL, '$' JE LABEL1 ; else push it in the; ;stack PUSH [SI] ; increment the pointer; ;and count INC SI INC CX JMP LOOP1 LABEL1: ; again load the starting; ;address of the string MOV SI, OFFSET STRING LOOP2: ;if count not equal to zero CMP CX,0 JE EXIT ; pop the top of stack POP DX ; make dh, 0 XOR DH, DH ; put the character of the; ;reversed string MOV [SI], DX ; increment si and; ;decrement count INC SI DEC CX JMP LOOP2 EXIT: ; add $ to the end of string MOV [SI],'$ ' RET REVERSE ENDPEND MAIN
Output:
gnirts elpmas a si sihT
Note: The program cannot be run on an online editor, please use MASM to run the program and use dos box to run MASM, you might use any 8086 emulator to run the program.
andrew1234
akshaysingh98088
rs1686740
Computer Organization and Architecture
microprocessor
system-programming
Computer Organization & Architecture
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Architecture of 8086
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Addressing modes in 8085 microprocessor
Computer Organization | RISC and CISC
Architecture of 8085 microprocessor
Interrupts
Memory Hierarchy Design and its Characteristics
Computer Organization | Von Neumann architecture
Difference between Von Neumann and Harvard Architecture
|
[
{
"code": null,
"e": 24725,
"s": 24697,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 24822,
"s": 24725,
"text": "Problem: Given a string we have to reverse the string and print the reversed string. Examples: "
},
{
"code": null,
"e": 24956,
"s": 24822,
"text": "Input: String : \"This is a sample string\"\nOutput: gnirts elpmas a si sihT\n\nInput: String : \"Geeks for Geeks\"\nOutput: skeeG rof skeeG "
},
{
"code": null,
"e": 24971,
"s": 24956,
"text": "Explanation: "
},
{
"code": null,
"e": 25449,
"s": 24971,
"text": "Create a stringTraverse through the stringPush the characters in the stackCount the number of charactersLoad the starting address of the stringPOP the top character of the stack until count is not equal to zeroPut the character and reduce the count and increase the addressContinue until the count is greater than zeroLoad the effective address of the string in dx using LEA commandPrint the sting by calling the interrupt with 9H in AHThe string must be terminated by ‘$’ sign"
},
{
"code": null,
"e": 25465,
"s": 25449,
"text": "Create a string"
},
{
"code": null,
"e": 25493,
"s": 25465,
"text": "Traverse through the string"
},
{
"code": null,
"e": 25526,
"s": 25493,
"text": "Push the characters in the stack"
},
{
"code": null,
"e": 25557,
"s": 25526,
"text": "Count the number of characters"
},
{
"code": null,
"e": 25597,
"s": 25557,
"text": "Load the starting address of the string"
},
{
"code": null,
"e": 25665,
"s": 25597,
"text": "POP the top character of the stack until count is not equal to zero"
},
{
"code": null,
"e": 25729,
"s": 25665,
"text": "Put the character and reduce the count and increase the address"
},
{
"code": null,
"e": 25775,
"s": 25729,
"text": "Continue until the count is greater than zero"
},
{
"code": null,
"e": 25840,
"s": 25775,
"text": "Load the effective address of the string in dx using LEA command"
},
{
"code": null,
"e": 25895,
"s": 25840,
"text": "Print the sting by calling the interrupt with 9H in AH"
},
{
"code": null,
"e": 25937,
"s": 25895,
"text": "The string must be terminated by ‘$’ sign"
},
{
"code": null,
"e": 25947,
"s": 25937,
"text": "Program: "
},
{
"code": null,
"e": 25951,
"s": 25947,
"text": "CPP"
},
{
"code": ".MODEL SMALL.STACK 100H.DATA ; The string to be printedSTRING DB 'This is a sample string', '$' .CODEMAIN PROC FARMOV AX,@DATAMOV DS,AX ; call reverse functionCALL REVERSE ; load address of the stringLEA DX,STRING ; output the string; loaded in dxMOV AH, 09HINT 21H ; interrupt to exitMOV AH, 4CHINT 21H MAIN ENDPREVERSE PROC ; load the offset of ; the string MOV SI, OFFSET STRING ; count of characters of the; ;string MOV CX, 0H LOOP1: ; compare if this is; ;the last character MOV AX, [SI] CMP AL, '$' JE LABEL1 ; else push it in the; ;stack PUSH [SI] ; increment the pointer; ;and count INC SI INC CX JMP LOOP1 LABEL1: ; again load the starting; ;address of the string MOV SI, OFFSET STRING LOOP2: ;if count not equal to zero CMP CX,0 JE EXIT ; pop the top of stack POP DX ; make dh, 0 XOR DH, DH ; put the character of the; ;reversed string MOV [SI], DX ; increment si and; ;decrement count INC SI DEC CX JMP LOOP2 EXIT: ; add $ to the end of string MOV [SI],'$ ' RET REVERSE ENDPEND MAIN",
"e": 27179,
"s": 25951,
"text": null
},
{
"code": null,
"e": 27189,
"s": 27179,
"text": "Output: "
},
{
"code": null,
"e": 27213,
"s": 27189,
"text": "gnirts elpmas a si sihT"
},
{
"code": null,
"e": 27383,
"s": 27213,
"text": "Note: The program cannot be run on an online editor, please use MASM to run the program and use dos box to run MASM, you might use any 8086 emulator to run the program. "
},
{
"code": null,
"e": 27394,
"s": 27383,
"text": "andrew1234"
},
{
"code": null,
"e": 27411,
"s": 27394,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 27421,
"s": 27411,
"text": "rs1686740"
},
{
"code": null,
"e": 27460,
"s": 27421,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 27475,
"s": 27460,
"text": "microprocessor"
},
{
"code": null,
"e": 27494,
"s": 27475,
"text": "system-programming"
},
{
"code": null,
"e": 27531,
"s": 27494,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 27546,
"s": 27531,
"text": "microprocessor"
},
{
"code": null,
"e": 27644,
"s": 27546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27653,
"s": 27644,
"text": "Comments"
},
{
"code": null,
"e": 27666,
"s": 27653,
"text": "Old Comments"
},
{
"code": null,
"e": 27687,
"s": 27666,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 27736,
"s": 27687,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 27831,
"s": 27736,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 27871,
"s": 27831,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 27909,
"s": 27871,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 27945,
"s": 27909,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 27956,
"s": 27945,
"text": "Interrupts"
},
{
"code": null,
"e": 28004,
"s": 27956,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 28053,
"s": 28004,
"text": "Computer Organization | Von Neumann architecture"
}
] |
Quickly Compare Multiple Models. How to train and evaluate multiple... | by Cole Brendel | Towards Data Science
|
A question all data scientists must confront when working on any machine learning project is...
Which model architecture is going to best fit my data?
There are several theoretical considerations one should take into account. For example, if your features show strong linear relationships to your dependent variable (target) then a linear model is likely to work best. If the relationships are non-linear, then maybe an SVM or instance-based classifier like K-Nearest Neighbors would be best. If explainability in crucial, a tree based model may be the way to go. Additionally, there are several practical considerations you ought to take into account.
For the purposes of this article, I am going to assume you already know whether you are dealing with a supervised vs. unsupervised problem and whether you need classification or regression.
Unfortunately, there is no clear answer to the question of which model is best. When faced with uncertainty, the scientist in me always resorts to humanity’s most rigorous and sure-fire method for knowledge discovery: the experiment!
In this article, I will show you how to quickly test multiple models on your dataset to find which ones are likely to provide the best performance allowing you to focus your efforts on fine-tuning and optimizing your model.
Before we can start any experimentation, we need a dataset. I am going to assume our problem is a supervised binary classification task. Let’s load in the breast cancer dataset from sklearn to get started.
from sklearn.datasets import load_breast_cancerX, y = data = load_breast_cancer(return_X_y=True)
Next, we need to split the data into a training and test set. I’ve chosen a 75/25 split.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=8675309)
We are now ready to run some experiments!
We are going to quickly test the fit of 6 different models on this dataset. I have chosen to test:
Logistic Regression: basic linear classifier (good to baseline)Random Forest: ensemble bagging classifierK-Nearest Neighbors: instance based classifierSupport Vector Machines: maximum margin classifierGaussian Naive Bayes: probabilistic classifierXGBoost: ensemble (extreme!) boosting classifier
Logistic Regression: basic linear classifier (good to baseline)
Random Forest: ensemble bagging classifier
K-Nearest Neighbors: instance based classifier
Support Vector Machines: maximum margin classifier
Gaussian Naive Bayes: probabilistic classifier
XGBoost: ensemble (extreme!) boosting classifier
To run the initial experiments, I used the default parameters for each model. To get a more accurate representation of the fit for each of these models, the default parameters would need to be adjusted; however, for the purposes of this article, the general idea is made more clear by not tweaking each model.
from sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVCfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.naive_bayes import GaussianNBfrom xgboost import XGBClassifierfrom sklearn import model_selectionfrom sklearn.utils import class_weightfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matriximport numpy as npimport pandas as pddef run_exps(X_train: pd.DataFrame , y_train: pd.DataFrame, X_test: pd.DataFrame, y_test: pd.DataFrame) -> pd.DataFrame: ''' Lightweight script to test many models and find winners:param X_train: training split :param y_train: training target vector :param X_test: test split :param y_test: test target vector :return: DataFrame of predictions ''' dfs = []models = [ ('LogReg', LogisticRegression()), ('RF', RandomForestClassifier()), ('KNN', KNeighborsClassifier()), ('SVM', SVC()), ('GNB', GaussianNB()), ('XGB', XGBClassifier()) ]results = [] names = [] scoring = ['accuracy', 'precision_weighted', 'recall_weighted', 'f1_weighted', 'roc_auc'] target_names = ['malignant', 'benign']for name, model in models: kfold = model_selection.KFold(n_splits=5, shuffle=True, random_state=90210) cv_results = model_selection.cross_validate(model, X_train, y_train, cv=kfold, scoring=scoring) clf = model.fit(X_train, y_train) y_pred = clf.predict(X_test) print(name) print(classification_report(y_test, y_pred, target_names=target_names))results.append(cv_results) names.append(name)this_df = pd.DataFrame(cv_results) this_df['model'] = name dfs.append(this_df)final = pd.concat(dfs, ignore_index=True)return final
There is a lot to unpack in this script. Firstly, we create a variable dfs to hold all of the datasets that will be created from the application of 5-fold cross validation on the training set.
Next, models in a list of tuples holding the name and class for each classifier to be tested. After this, we loop through this list and run 5-fold cross validation. The results of each run are recorded in a pandas dataframe which we append to the dfs list. One must note that the metrics recorded here are weighted mean metrics across both classes. This will not work well for any imbalanced dataset as performance on the majority class will overshadow the minority class. One may wish to tweak the script below to record only the metrics for the classes of interest!
To further aid in evaluation, a classification report on the test set is printed to screen. Finally, we concatenate and return all of our results.
To wrap up our analysis, we are going to analyze the data in the final dataframe returned from the run_exps() script.
To obtain better estimates of the distribution of metrics from each model, I run empirical bootstrapping at 30 samples. Additionally, I partition the data into two sorts: performance metrics and fit-time metrics. The following block of code achieves this.
bootstraps = []for model in list(set(final.model.values)): model_df = final.loc[final.model == model] bootstrap = model_df.sample(n=30, replace=True) bootstraps.append(bootstrap) bootstrap_df = pd.concat(bootstraps, ignore_index=True)results_long = pd.melt(bootstrap_df,id_vars=['model'],var_name='metrics', value_name='values')time_metrics = ['fit_time','score_time'] # fit time metrics## PERFORMANCE METRICSresults_long_nofit = results_long.loc[~results_long['metrics'].isin(time_metrics)] # get df without fit dataresults_long_nofit = results_long_nofit.sort_values(by='values')## TIME METRICSresults_long_fit = results_long.loc[results_long['metrics'].isin(time_metrics)] # df with fit dataresults_long_fit = results_long_fit.sort_values(by='values')
We now have some robust data to plot and analyze. First, let’s plot our performance metrics from the 5-fold cross validation.
import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(20, 12))sns.set(font_scale=2.5)g = sns.boxplot(x="model", y="values", hue="metrics", data=results_long_nofit, palette="Set3")plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)plt.title('Comparison of Model by Classification Metric')plt.savefig('./benchmark_models_performance.png',dpi=300)
It is immediately clear that SVMs fit our data rather poorly across all metrics and that the ensemble decision tree models (Random Forest and XGBoost) fit the data very well.
How about the training and scoring times?
plt.figure(figsize=(20, 12))sns.set(font_scale=2.5)g = sns.boxplot(x="model", y="values", hue="metrics", data=results_long_fit, palette="Set3")plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)plt.title('Comparison of Model by Fit and Score Time')plt.savefig('./benchmark_models_time.png',dpi=300)
Wow, SVM just can’t catch a break! The worst performing model and slow to train/score!
It is interesting to note that XGBoost was far and away the slowest to train; however, it was the best performing. We generally see a trade-off in terms of performance and training time. Consider neural networks which require a massive amount of data and time to train, but which generally perform very well.
RandomForest, while relatively slow compared to KNN, GNB, and LogReg had the second-best performance. If I were to continue refining models, I would likely focus most of my effort on RandomForest because it performed nearly identical to XGBoost (their 95% confidence intervals might overlap!) but trained almost 4 times faster!
Should you wish to do more analysis on these models (e.g., calculate confidence intervals around each metric) you will need to access the means and stds for each metric. You will find this information here.
metrics = list(set(results_long_nofit.metrics.values))bootstrap_df.groupby(['model'])[metrics].agg([np.std, np.mean])
time_metrics = list(set(results_long_fit.metrics.values))bootstrap_df.groupby(['model'])[time_metrics].agg([np.std, np.mean])
You now have the tools to rapidly test many different models on your data and to see which architectures might offer the best fit.
I cannot stress enough that such comparisons are not exhaustive!
The above analysis considered only mean precision, recall, etc. In your actual problems, it is unlikely that you will care much about mean precision across your classes, instead, you may be focussed on precision for one class in particular! Additionally, one must tune the hyperparameters of each model to truly evaluate their fit to the data.
Data structures for statistical computing in python, McKinney, Proceedings of the 9th Python in Science Conference, Volume 445, 2010.
@software{reback2020pandas, author = {The pandas development team}, title = {pandas-dev/pandas: Pandas}, month = feb, year = 2020, publisher = {Zenodo}, version = {latest}, doi = {10.5281/zenodo.3509134}, url = {https://doi.org/10.5281/zenodo.3509134}}
Harris, C.R., Millman, K.J., van der Walt, S.J. et al. Array programming with NumPy. Nature 585, 357–362 (2020). DOI: 10.1038/s41586–020–2649–2.
Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011.
J. D. Hunter, “Matplotlib: A 2D Graphics Environment”, Computing in Science & Engineering, vol. 9, no. 3, pp. 90–95, 2007.
Waskom, M. L., (2021). seaborn: statistical data visualization. Journal of Open Source Software, 6(60), 3021, https://doi.org/10.21105/joss.03021
Chen, T., & Guestrin, C. (2016). XGBoost: A Scalable Tree Boosting System. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (pp. 785–794). New York, NY, USA: ACM. https://doi.org/10.1145/2939672.2939785
|
[
{
"code": null,
"e": 268,
"s": 172,
"text": "A question all data scientists must confront when working on any machine learning project is..."
},
{
"code": null,
"e": 323,
"s": 268,
"text": "Which model architecture is going to best fit my data?"
},
{
"code": null,
"e": 825,
"s": 323,
"text": "There are several theoretical considerations one should take into account. For example, if your features show strong linear relationships to your dependent variable (target) then a linear model is likely to work best. If the relationships are non-linear, then maybe an SVM or instance-based classifier like K-Nearest Neighbors would be best. If explainability in crucial, a tree based model may be the way to go. Additionally, there are several practical considerations you ought to take into account."
},
{
"code": null,
"e": 1015,
"s": 825,
"text": "For the purposes of this article, I am going to assume you already know whether you are dealing with a supervised vs. unsupervised problem and whether you need classification or regression."
},
{
"code": null,
"e": 1249,
"s": 1015,
"text": "Unfortunately, there is no clear answer to the question of which model is best. When faced with uncertainty, the scientist in me always resorts to humanity’s most rigorous and sure-fire method for knowledge discovery: the experiment!"
},
{
"code": null,
"e": 1473,
"s": 1249,
"text": "In this article, I will show you how to quickly test multiple models on your dataset to find which ones are likely to provide the best performance allowing you to focus your efforts on fine-tuning and optimizing your model."
},
{
"code": null,
"e": 1679,
"s": 1473,
"text": "Before we can start any experimentation, we need a dataset. I am going to assume our problem is a supervised binary classification task. Let’s load in the breast cancer dataset from sklearn to get started."
},
{
"code": null,
"e": 1776,
"s": 1679,
"text": "from sklearn.datasets import load_breast_cancerX, y = data = load_breast_cancer(return_X_y=True)"
},
{
"code": null,
"e": 1865,
"s": 1776,
"text": "Next, we need to split the data into a training and test set. I’ve chosen a 75/25 split."
},
{
"code": null,
"e": 2013,
"s": 1865,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=8675309)"
},
{
"code": null,
"e": 2055,
"s": 2013,
"text": "We are now ready to run some experiments!"
},
{
"code": null,
"e": 2154,
"s": 2055,
"text": "We are going to quickly test the fit of 6 different models on this dataset. I have chosen to test:"
},
{
"code": null,
"e": 2450,
"s": 2154,
"text": "Logistic Regression: basic linear classifier (good to baseline)Random Forest: ensemble bagging classifierK-Nearest Neighbors: instance based classifierSupport Vector Machines: maximum margin classifierGaussian Naive Bayes: probabilistic classifierXGBoost: ensemble (extreme!) boosting classifier"
},
{
"code": null,
"e": 2514,
"s": 2450,
"text": "Logistic Regression: basic linear classifier (good to baseline)"
},
{
"code": null,
"e": 2557,
"s": 2514,
"text": "Random Forest: ensemble bagging classifier"
},
{
"code": null,
"e": 2604,
"s": 2557,
"text": "K-Nearest Neighbors: instance based classifier"
},
{
"code": null,
"e": 2655,
"s": 2604,
"text": "Support Vector Machines: maximum margin classifier"
},
{
"code": null,
"e": 2702,
"s": 2655,
"text": "Gaussian Naive Bayes: probabilistic classifier"
},
{
"code": null,
"e": 2751,
"s": 2702,
"text": "XGBoost: ensemble (extreme!) boosting classifier"
},
{
"code": null,
"e": 3061,
"s": 2751,
"text": "To run the initial experiments, I used the default parameters for each model. To get a more accurate representation of the fit for each of these models, the default parameters would need to be adjusted; however, for the purposes of this article, the general idea is made more clear by not tweaking each model."
},
{
"code": null,
"e": 4888,
"s": 3061,
"text": "from sklearn.linear_model import LogisticRegressionfrom sklearn.neighbors import KNeighborsClassifierfrom sklearn.svm import SVCfrom sklearn.ensemble import RandomForestClassifierfrom sklearn.naive_bayes import GaussianNBfrom xgboost import XGBClassifierfrom sklearn import model_selectionfrom sklearn.utils import class_weightfrom sklearn.metrics import classification_reportfrom sklearn.metrics import confusion_matriximport numpy as npimport pandas as pddef run_exps(X_train: pd.DataFrame , y_train: pd.DataFrame, X_test: pd.DataFrame, y_test: pd.DataFrame) -> pd.DataFrame: ''' Lightweight script to test many models and find winners:param X_train: training split :param y_train: training target vector :param X_test: test split :param y_test: test target vector :return: DataFrame of predictions ''' dfs = []models = [ ('LogReg', LogisticRegression()), ('RF', RandomForestClassifier()), ('KNN', KNeighborsClassifier()), ('SVM', SVC()), ('GNB', GaussianNB()), ('XGB', XGBClassifier()) ]results = [] names = [] scoring = ['accuracy', 'precision_weighted', 'recall_weighted', 'f1_weighted', 'roc_auc'] target_names = ['malignant', 'benign']for name, model in models: kfold = model_selection.KFold(n_splits=5, shuffle=True, random_state=90210) cv_results = model_selection.cross_validate(model, X_train, y_train, cv=kfold, scoring=scoring) clf = model.fit(X_train, y_train) y_pred = clf.predict(X_test) print(name) print(classification_report(y_test, y_pred, target_names=target_names))results.append(cv_results) names.append(name)this_df = pd.DataFrame(cv_results) this_df['model'] = name dfs.append(this_df)final = pd.concat(dfs, ignore_index=True)return final"
},
{
"code": null,
"e": 5081,
"s": 4888,
"text": "There is a lot to unpack in this script. Firstly, we create a variable dfs to hold all of the datasets that will be created from the application of 5-fold cross validation on the training set."
},
{
"code": null,
"e": 5649,
"s": 5081,
"text": "Next, models in a list of tuples holding the name and class for each classifier to be tested. After this, we loop through this list and run 5-fold cross validation. The results of each run are recorded in a pandas dataframe which we append to the dfs list. One must note that the metrics recorded here are weighted mean metrics across both classes. This will not work well for any imbalanced dataset as performance on the majority class will overshadow the minority class. One may wish to tweak the script below to record only the metrics for the classes of interest!"
},
{
"code": null,
"e": 5796,
"s": 5649,
"text": "To further aid in evaluation, a classification report on the test set is printed to screen. Finally, we concatenate and return all of our results."
},
{
"code": null,
"e": 5914,
"s": 5796,
"text": "To wrap up our analysis, we are going to analyze the data in the final dataframe returned from the run_exps() script."
},
{
"code": null,
"e": 6170,
"s": 5914,
"text": "To obtain better estimates of the distribution of metrics from each model, I run empirical bootstrapping at 30 samples. Additionally, I partition the data into two sorts: performance metrics and fit-time metrics. The following block of code achieves this."
},
{
"code": null,
"e": 6941,
"s": 6170,
"text": "bootstraps = []for model in list(set(final.model.values)): model_df = final.loc[final.model == model] bootstrap = model_df.sample(n=30, replace=True) bootstraps.append(bootstrap) bootstrap_df = pd.concat(bootstraps, ignore_index=True)results_long = pd.melt(bootstrap_df,id_vars=['model'],var_name='metrics', value_name='values')time_metrics = ['fit_time','score_time'] # fit time metrics## PERFORMANCE METRICSresults_long_nofit = results_long.loc[~results_long['metrics'].isin(time_metrics)] # get df without fit dataresults_long_nofit = results_long_nofit.sort_values(by='values')## TIME METRICSresults_long_fit = results_long.loc[results_long['metrics'].isin(time_metrics)] # df with fit dataresults_long_fit = results_long_fit.sort_values(by='values')"
},
{
"code": null,
"e": 7067,
"s": 6941,
"text": "We now have some robust data to plot and analyze. First, let’s plot our performance metrics from the 5-fold cross validation."
},
{
"code": null,
"e": 7440,
"s": 7067,
"text": "import matplotlib.pyplot as pltimport seaborn as snsplt.figure(figsize=(20, 12))sns.set(font_scale=2.5)g = sns.boxplot(x=\"model\", y=\"values\", hue=\"metrics\", data=results_long_nofit, palette=\"Set3\")plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)plt.title('Comparison of Model by Classification Metric')plt.savefig('./benchmark_models_performance.png',dpi=300)"
},
{
"code": null,
"e": 7615,
"s": 7440,
"text": "It is immediately clear that SVMs fit our data rather poorly across all metrics and that the ensemble decision tree models (Random Forest and XGBoost) fit the data very well."
},
{
"code": null,
"e": 7657,
"s": 7615,
"text": "How about the training and scoring times?"
},
{
"code": null,
"e": 7966,
"s": 7657,
"text": "plt.figure(figsize=(20, 12))sns.set(font_scale=2.5)g = sns.boxplot(x=\"model\", y=\"values\", hue=\"metrics\", data=results_long_fit, palette=\"Set3\")plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)plt.title('Comparison of Model by Fit and Score Time')plt.savefig('./benchmark_models_time.png',dpi=300)"
},
{
"code": null,
"e": 8053,
"s": 7966,
"text": "Wow, SVM just can’t catch a break! The worst performing model and slow to train/score!"
},
{
"code": null,
"e": 8362,
"s": 8053,
"text": "It is interesting to note that XGBoost was far and away the slowest to train; however, it was the best performing. We generally see a trade-off in terms of performance and training time. Consider neural networks which require a massive amount of data and time to train, but which generally perform very well."
},
{
"code": null,
"e": 8690,
"s": 8362,
"text": "RandomForest, while relatively slow compared to KNN, GNB, and LogReg had the second-best performance. If I were to continue refining models, I would likely focus most of my effort on RandomForest because it performed nearly identical to XGBoost (their 95% confidence intervals might overlap!) but trained almost 4 times faster!"
},
{
"code": null,
"e": 8897,
"s": 8690,
"text": "Should you wish to do more analysis on these models (e.g., calculate confidence intervals around each metric) you will need to access the means and stds for each metric. You will find this information here."
},
{
"code": null,
"e": 9015,
"s": 8897,
"text": "metrics = list(set(results_long_nofit.metrics.values))bootstrap_df.groupby(['model'])[metrics].agg([np.std, np.mean])"
},
{
"code": null,
"e": 9141,
"s": 9015,
"text": "time_metrics = list(set(results_long_fit.metrics.values))bootstrap_df.groupby(['model'])[time_metrics].agg([np.std, np.mean])"
},
{
"code": null,
"e": 9272,
"s": 9141,
"text": "You now have the tools to rapidly test many different models on your data and to see which architectures might offer the best fit."
},
{
"code": null,
"e": 9337,
"s": 9272,
"text": "I cannot stress enough that such comparisons are not exhaustive!"
},
{
"code": null,
"e": 9681,
"s": 9337,
"text": "The above analysis considered only mean precision, recall, etc. In your actual problems, it is unlikely that you will care much about mean precision across your classes, instead, you may be focussed on precision for one class in particular! Additionally, one must tune the hyperparameters of each model to truly evaluate their fit to the data."
},
{
"code": null,
"e": 9815,
"s": 9681,
"text": "Data structures for statistical computing in python, McKinney, Proceedings of the 9th Python in Science Conference, Volume 445, 2010."
},
{
"code": null,
"e": 10146,
"s": 9815,
"text": "@software{reback2020pandas, author = {The pandas development team}, title = {pandas-dev/pandas: Pandas}, month = feb, year = 2020, publisher = {Zenodo}, version = {latest}, doi = {10.5281/zenodo.3509134}, url = {https://doi.org/10.5281/zenodo.3509134}}"
},
{
"code": null,
"e": 10291,
"s": 10146,
"text": "Harris, C.R., Millman, K.J., van der Walt, S.J. et al. Array programming with NumPy. Nature 585, 357–362 (2020). DOI: 10.1038/s41586–020–2649–2."
},
{
"code": null,
"e": 10381,
"s": 10291,
"text": "Scikit-learn: Machine Learning in Python, Pedregosa et al., JMLR 12, pp. 2825–2830, 2011."
},
{
"code": null,
"e": 10504,
"s": 10381,
"text": "J. D. Hunter, “Matplotlib: A 2D Graphics Environment”, Computing in Science & Engineering, vol. 9, no. 3, pp. 90–95, 2007."
},
{
"code": null,
"e": 10650,
"s": 10504,
"text": "Waskom, M. L., (2021). seaborn: statistical data visualization. Journal of Open Source Software, 6(60), 3021, https://doi.org/10.21105/joss.03021"
}
] |
Python - IMAP
|
IMAP is an email retrieval protocol which does not download the emails. It just reads them and displays them. This is very useful in low bandwidth condition. Python’s client side library called imaplib is used for accessing emails over imap protocol.
IMAP stands for Internet Mail Access Protocol. It was first proposed in 1986.
Key Points:
IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer.
IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer.
The e-mail is hold and maintained by the remote server.
The e-mail is hold and maintained by the remote server.
It enables us to take any action such as downloading, delete the mail without reading the mail.It enables us to create, manipulate and delete remote message folders called mail boxes.
It enables us to take any action such as downloading, delete the mail without reading the mail.It enables us to create, manipulate and delete remote message folders called mail boxes.
IMAP enables the users to search the e-mails.
IMAP enables the users to search the e-mails.
It allows concurrent access to multiple mailboxes on multiple mail servers.
It allows concurrent access to multiple mailboxes on multiple mail servers.
The following table describes some of the IMAP commands:
In the below example we login to a gmail server with user credentials. Then we choose to display the messages in the inbox. A for loop is used to display the fetched messages one by one and finally the connection is closed.
import imaplib
import pprint
imap_host = 'imap.gmail.com'
imap_user = 'username@gmail.com'
imap_pass = 'password'
# connect to host using SSL
imap = imaplib.IMAP4_SSL(imap_host)
## login to server
imap.login(imap_user, imap_pass)
imap.select('Inbox')
tmp, data = imap.search(None, 'ALL')
for num in data[0].split():
tmp, data = imap.fetch(num, '(RFC822)')
print('Message: {0}\n'.format(num))
pprint.pprint(data[0][1])
break
imap.close()
Depending on the mail box configuration, mail is displayed.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2577,
"s": 2326,
"text": "IMAP is an email retrieval protocol which does not download the emails. It just reads them and displays them. This is very useful in low bandwidth condition. Python’s client side library called imaplib is used for accessing emails over imap protocol."
},
{
"code": null,
"e": 2655,
"s": 2577,
"text": "IMAP stands for Internet Mail Access Protocol. It was first proposed in 1986."
},
{
"code": null,
"e": 2667,
"s": 2655,
"text": "Key Points:"
},
{
"code": null,
"e": 2793,
"s": 2667,
"text": "IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer."
},
{
"code": null,
"e": 2919,
"s": 2793,
"text": "IMAP allows the client program to manipulate the e-mail message on the server without downloading them on the local computer."
},
{
"code": null,
"e": 2975,
"s": 2919,
"text": "The e-mail is hold and maintained by the remote server."
},
{
"code": null,
"e": 3031,
"s": 2975,
"text": "The e-mail is hold and maintained by the remote server."
},
{
"code": null,
"e": 3215,
"s": 3031,
"text": "It enables us to take any action such as downloading, delete the mail without reading the mail.It enables us to create, manipulate and delete remote message folders called mail boxes."
},
{
"code": null,
"e": 3399,
"s": 3215,
"text": "It enables us to take any action such as downloading, delete the mail without reading the mail.It enables us to create, manipulate and delete remote message folders called mail boxes."
},
{
"code": null,
"e": 3445,
"s": 3399,
"text": "IMAP enables the users to search the e-mails."
},
{
"code": null,
"e": 3491,
"s": 3445,
"text": "IMAP enables the users to search the e-mails."
},
{
"code": null,
"e": 3567,
"s": 3491,
"text": "It allows concurrent access to multiple mailboxes on multiple mail servers."
},
{
"code": null,
"e": 3643,
"s": 3567,
"text": "It allows concurrent access to multiple mailboxes on multiple mail servers."
},
{
"code": null,
"e": 3700,
"s": 3643,
"text": "The following table describes some of the IMAP commands:"
},
{
"code": null,
"e": 3926,
"s": 3700,
"text": " In the below example we login to a gmail server with user credentials. Then we choose to display the messages in the inbox. A for loop is used to display the fetched messages one by one and finally the connection is closed. "
},
{
"code": null,
"e": 4372,
"s": 3926,
"text": "import imaplib\nimport pprint\n\nimap_host = 'imap.gmail.com'\nimap_user = 'username@gmail.com'\nimap_pass = 'password'\n\n# connect to host using SSL\nimap = imaplib.IMAP4_SSL(imap_host)\n\n## login to server\nimap.login(imap_user, imap_pass)\n\nimap.select('Inbox')\n\ntmp, data = imap.search(None, 'ALL')\nfor num in data[0].split():\n\ttmp, data = imap.fetch(num, '(RFC822)')\n\tprint('Message: {0}\\n'.format(num))\n\tpprint.pprint(data[0][1])\n\tbreak\nimap.close()"
},
{
"code": null,
"e": 4432,
"s": 4372,
"text": "Depending on the mail box configuration, mail is displayed."
},
{
"code": null,
"e": 4469,
"s": 4432,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4485,
"s": 4469,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4518,
"s": 4485,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4537,
"s": 4518,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4572,
"s": 4537,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4594,
"s": 4572,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4628,
"s": 4594,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4656,
"s": 4628,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4691,
"s": 4656,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4705,
"s": 4691,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4738,
"s": 4705,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4755,
"s": 4738,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4762,
"s": 4755,
"text": " Print"
},
{
"code": null,
"e": 4773,
"s": 4762,
"text": " Add Notes"
}
] |
Advanced Morse Code Decoder in Python | by Kieran Tan Kah Wang | Towards Data Science
|
In one of my previous post, I’ve designed a simple Morse Code Decoder in Python which is capable of accepting user inputs and outputting them in their original alphanumerical form. One of the limitations of the decoder is that it does not allow the user to input sentences. Remember that we have chosen to represent each alphabet or number using a series of ‘0’ and ‘1’, where ‘0’ represents a dot, and ‘1’ represents a dash. Each alphabet or number is then separated by a ‘*’ in our decoder, as shown in the screenshot below.
In this post, we will improve our simple Morse Code Decoder to be able to decipher sentences as well. Furthermore, we can implement checks in the decoder to inform us of the frequencies in which each alphabet/number, word, or sentence type have been decoded.
One major difference between this decoder and the previous one is that we will be using Python class to build our decoder and the respective analysis checks. A simple explanation about Python class is that it defines a set of instance variables (data values to be represented for each object) and a set of methods (operations) that can be applied to the objects.
We will build a class called Decoder and it will contain several methods, with the first being __init__(self). This is the essential method for object creation and it usually initialize the values of the instance variables of each object. Remember that we chose to use a dictionary structure to store our Morse Code representation in Python, where each alphabet or number is represented by a series of ‘0’s and ‘1’s. As we are adding sentences analysis checks too, we have also added three punctuation marks “ . ” , “ , ” and “ ? ”.
class Decoder: def __init__(self): self.the_dict = dict(zip(('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','.',',','?'),('01','1000','1010','100','0','0010','110','0000','00','0111','101','0100','11','10','111','0110','1101','010','000','1','001','0001','011','1001','1011','1100','11111','01111','00111','00011','00001','00000','10000','11000','11100','11110','010101','110011','001100')))
The next essential method in a class creation is returning/printing the output. With just the __init__ (self) method, we cannot display any results if we assign a variable to this class. We will add a __str__ (self) method which works the same way as print(variable), but allows us to customize the way the results will be displayed.
def __str__ (self): dict_str = "" for key,value in self.the_dict.items(): dict_str += "Character: " + str(key) + " ->" + " Code: " + str(value) + "\n" return dict_str
Once we have defined the above two methods, we can try displaying the dictionary structure we have defined earlier by assigning a variable name to the class and printing the result. Notice that my_dict now is an object of class Decoder.
The last method we will define in this class is the decoding of the Morse Code itself called decode (self, morse_code_sequence). Note that in this method, other than defining self, we added another morse_code_sequence. This means that to call this method, we will have to pass a variable through this method (i.e. the Morse Code sequence) which works similarly to calling a function and passing a value through it. We will also include the error checks we have implemented previously in our Simple Morse Code Decoder mainly:
User can only enter 0, 1 and *User can only enter Morse Code Representation that has been pre-defined (e.g. 0000000 is not a valid representation)Morse Code sequences must end with a punctuation mark (i.e. full stop, comma, or question mark)
User can only enter 0, 1 and *
User can only enter Morse Code Representation that has been pre-defined (e.g. 0000000 is not a valid representation)
Morse Code sequences must end with a punctuation mark (i.e. full stop, comma, or question mark)
def decode (self,morse_code_sequence): character = list(self.the_dict.keys()) code = list(self.the_dict.values()) reverse_dict = dict(zip(code,character)) # Error check 1, checking for invalid characters (i.e. other than 0,1,*) i=0 while i!=len(morse_code_sequence): if morse_code_sequence[i]=="0" or morse_code_sequence[i]=="1" or morse_code_sequence[i]=="*": i += 1 else: return "Invalid characters in morse code sequence, it should only consists of 0, 1 and *" break # Proceed for error check 2 once the morse_code_sequence does not contain invalid characters if i == len(morse_code_sequence): splitted_morse_code_sequence = morse_code_sequence.split("***") morse_code_word = [] for j in range(0,len(splitted_morse_code_sequence)): morse_code_word.append(splitted_morse_code_sequence[j].split("*")) #[['001','100','110'], ['90','9','9'], ['abc','17']] morse_code_char=[] # Initialise a result list as the format of morse_code_word result = morse_code_word # split into list containing all character's morse code for k in range(0,len(morse_code_word)): for l in range (0,len(morse_code_word[k])): morse_code_char.append(morse_code_word[k][l]) # Check 2, terminate with punctuation marks i.e 010101, 110011, 001100 if morse_code_char[len(morse_code_char)-1]=="010101" or morse_code_char[len(morse_code_char)-1]=="110011" or morse_code_char[len(morse_code_char)-1]=="001100" : # Check 3, check if character's morse code representation is valid as per the dictionary for k in range(0,len(morse_code_word)): for l in range (0,len(morse_code_word[k])): if morse_code_word[k][l] in reverse_dict.keys(): result[k][l]=reverse_dict[morse_code_word[k][l]] else: return "Invalid morse code representation" else: return "Invalid morse code sequence input, morse code sequence should end with punctuation characters" # Create an empty list to append result in and convert into readable string format output printed_result = [] for i in range(0,len(result)): for j in range(0,len(result[i])): printed_result.append(result[i][j]) printed_result.append(" ") return ''.join(printed_result)
The next class we will build is the Character Analyser class, which will tell the user the frequencies of each character (i.e. alphabet or number) being decoded. Similar to our Decoder class, the two essential methods __init__(self) and __str__(self) will be defined.
The third method analyse_characters (self, decoded_sequence) will be created to analyze the characters, with the decoded sequence being passed through this method. How we will count the characters is that for each character in the decoded sequence, we will add them into an empty dictionary. Looping through each character, we will aggregate the counts of the character and display them as a dictionary structure in the end, which we define in the __str__(self) method.
class CharacterAnalyser: def __init__ (self): self.the_dict_char = {} def __str__ (self): dict_char_str = "" for key,value in self.the_dict_char.items(): dict_char_str += str(key) + " has been decoded " + str(value) + " time(s) " + "\n" return dict_char_str def analyse_characters (self, decoded_sequence): for each in decoded_sequence: if each != "?" and each != "." and each != "," and each != " ": if each not in self.the_dict_char.keys(): self.the_dict_char[each] = 1 else: self.the_dict_char[each] += 1 return self.the_dict_char
In our next class, we will implement the Word Analyser which will count the number of times certain words are being decoded in the Morse Code sequences. After defining the two essential methods __init__(self) and __str__(self), we will define the third method analyse_words (self, decoded_sequence) that will analyze the word frequencies. The concept is similar to Character Analyser Class whereby we will loop through each word in the decoded sequence, and aggregate the counts in a dictionary.
class WordAnalyser: def __init__ (self): self.the_dict_word = {} def __str__ (self): dict_word_str = "" for key,value in self.the_dict_word.items(): dict_word_str += str(key) + " has been decoded " + str(value) + " time(s) " +"\n" return dict_word_str def analyse_words (self, decoded_sequence): decoded_sequence_word=(decoded_sequence.strip()).split(" ") for each in decoded_sequence_word: if each != "?" and each != "." and each != ",": if each not in self.the_dict_word.keys(): self.the_dict_word[each] = 1 else: self.the_dict_word[each] += 1 return self.the_dict_word
The last analyzer class we will build is a Sentence Analyser Class. As we allow the users to key in three punctuation marks of a full stop, comma, and question mark, we can analyze how many times each sentence type is being decoded as per the following:
1. A sentence ending with ‘ ? ’ — Questions
2. A sentence ending with ‘ . ’ — Complete Sentences
3. A sentence ending with ‘ , ’ — Clauses
After defining the essential two classes __init__(self) and __str__(self), the way we will build our third method analyse_sentences (self, decoded_sequence) is that we will split the sequences into individual words/punctuation marks and loop through each of them. If a question mark is found, we will add a count to ‘Questions’ and so forth.
class SentenceAnalyser: def __init__ (self): self.the_dict_sentence = dict(zip(("Clauses","Complete Sentences","Questions"),(0,0,0))) def __str__ (self): dict_sentence_str = "" for key,value in self.the_dict_sentence.items(): dict_sentence_str += str(key) + " has been decoded " + str(value) + " times(s) " + "\n" return dict_sentence_str def analyse_sentences (self, decoded_sequence): decoded_sequence_sentence = decoded_sequence.split(" ") for each in decoded_sequence_sentence: if each == ",": self.the_dict_sentence["Clauses"] += 1 elif each == ".": self.the_dict_sentence["Complete Sentences"] += 1 elif each == "?": self.the_dict_sentence["Questions"] += 1 return self.the_dict_sentence
In this last section, we will put all the above 4 classes together and create a program that provides the user the capability to enter Morse Code sequences and choosing the type of analysis he/she is interested in. The way we put all the classes together is using the main() method which is the starting point of any program. Below is the whole code which I will walk you guys through.
# import all the 4 classesfrom decoder_29442826 import Decoderfrom character_29442826 import CharacterAnalyserfrom word_29442826 import WordAnalyserfrom sentence_29442826 import SentenceAnalyser def main(): # set 4 variables to each of the 4 classes my_dict_1 = Decoder() my_dict_2 = CharacterAnalyser() my_dict_3 = WordAnalyser() my_dict_4 = SentenceAnalyser() # initialise empty list to store user input user_input_list = [] # print the structure of morse code representation for user's reference print(str(my_dict_1)) # asking user to input morse code sequences for decoding while True: user_input_morse = input ("Enter sequences of Morse Code to be decoded based on representation shown, leave blank to stop input: ") # Proceed for error checking of user input if it's not empty if len(user_input_morse)!=0: # Error check 1, checking for invalid characters other than 0, 1, * if my_dict_1.decode(user_input_morse)=="Invalid characters in morse code sequence, it should only consists of 0, 1 and *": print ("Invalid characters in morse code sequence, it should only consists of 0, 1 and *" + "\n") # Error check 2, checking for minimum requirement of one set of *** elif "***" not in user_input_morse: print ("Error input, the Morse Code sequence should have at least one set of ***" + "\n") # Error check 3, checking for punctuation at the end of user input, i.e. 010101, 110011, 001100 elif my_dict_1.decode(user_input_morse)=="Invalid morse code sequence input, morse code sequence should end with punctuation characters": print("Invalid morse code sequence input, morse code sequence should end with punctuation characters" + "\n") # Error check 4, checking for invalid morse code representation as per the pre-defined morse code dictionary elif my_dict_1.decode(user_input_morse)=="Invalid morse code representation": print("Invalid morse code representation" + "\n") # add user input into list for decoding if no errors found else: user_input_list.append(user_input_morse) # Stop asking for input once user leaved blank else: print("You have chosen to stop inputting morse code sequences" + "\n") break # empty string to store decoded sequences overall_decoded_sequence="" # decoding the morse code sequences in user_input_list for each in user_input_list: overall_decoded_sequence += my_dict_1.decode(each) # character analysis of all the decoded morse code sequence my_dict_2.analyse_characters(overall_decoded_sequence) # word analysis of all the decoded morse code sequence my_dict_3.analyse_words(overall_decoded_sequence) # sentence analysis of all the decoded morse code sequence my_dict_4.analyse_sentences(overall_decoded_sequence) if len(overall_decoded_sequence)!=0: # asking user to choose level of analysis from character, word, sentence or all while True: user_input_level = input ("Please choose the level of analysis from character, word, sentence or all, leave blank to quit:") # if character analysis chosen, return result of character analysis only if user_input_level == "character": print("Decoded Morse Code Sequence(s):") for each in user_input_list: print(str(each) + " has been decoded to: " + my_dict_1.decode(each)) print("\n" + "Characters Analysis:" + "\n" + str(my_dict_2)) # if word analysis chosen, return result of word analysis only elif user_input_level == "word": print("Decoded Morse Code Sequence(s):") for each in user_input_list: print(str(each) + " has been decoded to: " + my_dict_1.decode(each)) print("\n" + "Words Analysis:" + "\n" + str(my_dict_3)) # if sentence analysis chosen, return result of sentence analysis only elif user_input_level == "sentence": print("Decoded Morse Code Sequence(s):") for each in user_input_list: print(str(each) + " has been decoded to: " + my_dict_1.decode(each)) print("\n" + "Sentence Analysis:" + "\n" + str(my_dict_4)) # if all has been chose, return result of character, word and sentence analysis elif user_input_level == "all": print("Decoded Morse Code Sequence(s):") for each in user_input_list: print(str(each) + " has been decoded to: " + my_dict_1.decode(each)) print("\n" + "Characters Analysis:" + "\n" + str(my_dict_2)) print("Words Analysis:" + "\n" + str(my_dict_3)) print("Sentence Analysis:" + "\n" + str(my_dict_4)) # if user leaved blank, terminate the whole program elif user_input_level == "": print("You have chosen to terminate the whole program") break # prompt the user for level of analysis again if invalid input has been found else: print("Invalid input, choose the level of analysis from character, word, sentence or all, leave blank to quit") else: print("No morse code sequences were entered")if __name__ == "__main__": main()
The way this program will work is that once the user runs this program, the Morse Code representation will first be displayed (using the first Decoder class). Users will be prompted to enter a Morse Code sequence and can continue inputting for decoding till they decided to stop inputting by leaving a blank.
If the user chose to quit inputting Morse Code Sequences and did not input any Morse Code Sequence or all Morse Code Sequences that were entered were invalid, the program will terminate with the message “No morse code sequences were entered”.
Once the user has entered a Morse Code sequence or a series of them and keyed in a blank to indicate he/she wants to stop inputting, the program will then prompt the user to choose the level of analysis (i.e. Character, Word, Sentence or All).
Character Analysis will call upon the character_analyser class and return the characters found in the sequences entered by users along with their decoded frequencies.
Word Analysis will call upon word_analyser class and return the words found in the sequences entered by users along with their decoded frequencies.
Sentence Analysis will call upon sentence_analyser and return the counts of the number of times Questions, Clauses & Complete Sentences have been decoded based on ‘ ? ’, ‘ , ’ and ‘ . ’ respectively.
Users can also choose “all” and all three analyses will be displayed at once.
Once the user is done with the analysis, he/she can terminate the program by inputting a blank input and the program will exit itself.
This article has described the process of building a more advanced Morse Code Decoder compared to the previous one which was only capable of accepting user inputs and outputting them in their original alphanumerical form. The new decoder allows the users to decode sentences and getting aggregated analysis of character/word/sentence being decoded. I hope you guys enjoy this article and this is more advanced in terms of coding proficiency as we were defining our Python classes in this decoder. Nonetheless, have fun improving your Morse Code Decoder!
|
[
{
"code": null,
"e": 699,
"s": 172,
"text": "In one of my previous post, I’ve designed a simple Morse Code Decoder in Python which is capable of accepting user inputs and outputting them in their original alphanumerical form. One of the limitations of the decoder is that it does not allow the user to input sentences. Remember that we have chosen to represent each alphabet or number using a series of ‘0’ and ‘1’, where ‘0’ represents a dot, and ‘1’ represents a dash. Each alphabet or number is then separated by a ‘*’ in our decoder, as shown in the screenshot below."
},
{
"code": null,
"e": 958,
"s": 699,
"text": "In this post, we will improve our simple Morse Code Decoder to be able to decipher sentences as well. Furthermore, we can implement checks in the decoder to inform us of the frequencies in which each alphabet/number, word, or sentence type have been decoded."
},
{
"code": null,
"e": 1321,
"s": 958,
"text": "One major difference between this decoder and the previous one is that we will be using Python class to build our decoder and the respective analysis checks. A simple explanation about Python class is that it defines a set of instance variables (data values to be represented for each object) and a set of methods (operations) that can be applied to the objects."
},
{
"code": null,
"e": 1854,
"s": 1321,
"text": "We will build a class called Decoder and it will contain several methods, with the first being __init__(self). This is the essential method for object creation and it usually initialize the values of the instance variables of each object. Remember that we chose to use a dictionary structure to store our Morse Code representation in Python, where each alphabet or number is represented by a series of ‘0’s and ‘1’s. As we are adding sentences analysis checks too, we have also added three punctuation marks “ . ” , “ , ” and “ ? ”."
},
{
"code": null,
"e": 2361,
"s": 1854,
"text": "class Decoder: def __init__(self): self.the_dict = dict(zip(('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9','.',',','?'),('01','1000','1010','100','0','0010','110','0000','00','0111','101','0100','11','10','111','0110','1101','010','000','1','001','0001','011','1001','1011','1100','11111','01111','00111','00011','00001','00000','10000','11000','11100','11110','010101','110011','001100'))) "
},
{
"code": null,
"e": 2695,
"s": 2361,
"text": "The next essential method in a class creation is returning/printing the output. With just the __init__ (self) method, we cannot display any results if we assign a variable to this class. We will add a __str__ (self) method which works the same way as print(variable), but allows us to customize the way the results will be displayed."
},
{
"code": null,
"e": 2894,
"s": 2695,
"text": "def __str__ (self): dict_str = \"\" for key,value in self.the_dict.items(): dict_str += \"Character: \" + str(key) + \" ->\" + \" Code: \" + str(value) + \"\\n\" return dict_str"
},
{
"code": null,
"e": 3131,
"s": 2894,
"text": "Once we have defined the above two methods, we can try displaying the dictionary structure we have defined earlier by assigning a variable name to the class and printing the result. Notice that my_dict now is an object of class Decoder."
},
{
"code": null,
"e": 3656,
"s": 3131,
"text": "The last method we will define in this class is the decoding of the Morse Code itself called decode (self, morse_code_sequence). Note that in this method, other than defining self, we added another morse_code_sequence. This means that to call this method, we will have to pass a variable through this method (i.e. the Morse Code sequence) which works similarly to calling a function and passing a value through it. We will also include the error checks we have implemented previously in our Simple Morse Code Decoder mainly:"
},
{
"code": null,
"e": 3898,
"s": 3656,
"text": "User can only enter 0, 1 and *User can only enter Morse Code Representation that has been pre-defined (e.g. 0000000 is not a valid representation)Morse Code sequences must end with a punctuation mark (i.e. full stop, comma, or question mark)"
},
{
"code": null,
"e": 3929,
"s": 3898,
"text": "User can only enter 0, 1 and *"
},
{
"code": null,
"e": 4046,
"s": 3929,
"text": "User can only enter Morse Code Representation that has been pre-defined (e.g. 0000000 is not a valid representation)"
},
{
"code": null,
"e": 4142,
"s": 4046,
"text": "Morse Code sequences must end with a punctuation mark (i.e. full stop, comma, or question mark)"
},
{
"code": null,
"e": 6800,
"s": 4142,
"text": "def decode (self,morse_code_sequence): character = list(self.the_dict.keys()) code = list(self.the_dict.values()) reverse_dict = dict(zip(code,character)) # Error check 1, checking for invalid characters (i.e. other than 0,1,*) i=0 while i!=len(morse_code_sequence): if morse_code_sequence[i]==\"0\" or morse_code_sequence[i]==\"1\" or morse_code_sequence[i]==\"*\": i += 1 else: return \"Invalid characters in morse code sequence, it should only consists of 0, 1 and *\" break # Proceed for error check 2 once the morse_code_sequence does not contain invalid characters if i == len(morse_code_sequence): splitted_morse_code_sequence = morse_code_sequence.split(\"***\") morse_code_word = [] for j in range(0,len(splitted_morse_code_sequence)): morse_code_word.append(splitted_morse_code_sequence[j].split(\"*\")) #[['001','100','110'], ['90','9','9'], ['abc','17']] morse_code_char=[] # Initialise a result list as the format of morse_code_word result = morse_code_word # split into list containing all character's morse code for k in range(0,len(morse_code_word)): for l in range (0,len(morse_code_word[k])): morse_code_char.append(morse_code_word[k][l]) # Check 2, terminate with punctuation marks i.e 010101, 110011, 001100 if morse_code_char[len(morse_code_char)-1]==\"010101\" or morse_code_char[len(morse_code_char)-1]==\"110011\" or morse_code_char[len(morse_code_char)-1]==\"001100\" : # Check 3, check if character's morse code representation is valid as per the dictionary for k in range(0,len(morse_code_word)): for l in range (0,len(morse_code_word[k])): if morse_code_word[k][l] in reverse_dict.keys(): result[k][l]=reverse_dict[morse_code_word[k][l]] else: return \"Invalid morse code representation\" else: return \"Invalid morse code sequence input, morse code sequence should end with punctuation characters\" # Create an empty list to append result in and convert into readable string format output printed_result = [] for i in range(0,len(result)): for j in range(0,len(result[i])): printed_result.append(result[i][j]) printed_result.append(\" \") return ''.join(printed_result)"
},
{
"code": null,
"e": 7068,
"s": 6800,
"text": "The next class we will build is the Character Analyser class, which will tell the user the frequencies of each character (i.e. alphabet or number) being decoded. Similar to our Decoder class, the two essential methods __init__(self) and __str__(self) will be defined."
},
{
"code": null,
"e": 7538,
"s": 7068,
"text": "The third method analyse_characters (self, decoded_sequence) will be created to analyze the characters, with the decoded sequence being passed through this method. How we will count the characters is that for each character in the decoded sequence, we will add them into an empty dictionary. Looping through each character, we will aggregate the counts of the character and display them as a dictionary structure in the end, which we define in the __str__(self) method."
},
{
"code": null,
"e": 8243,
"s": 7538,
"text": "class CharacterAnalyser: def __init__ (self): self.the_dict_char = {} def __str__ (self): dict_char_str = \"\" for key,value in self.the_dict_char.items(): dict_char_str += str(key) + \" has been decoded \" + str(value) + \" time(s) \" + \"\\n\" return dict_char_str def analyse_characters (self, decoded_sequence): for each in decoded_sequence: if each != \"?\" and each != \".\" and each != \",\" and each != \" \": if each not in self.the_dict_char.keys(): self.the_dict_char[each] = 1 else: self.the_dict_char[each] += 1 return self.the_dict_char"
},
{
"code": null,
"e": 8739,
"s": 8243,
"text": "In our next class, we will implement the Word Analyser which will count the number of times certain words are being decoded in the Morse Code sequences. After defining the two essential methods __init__(self) and __str__(self), we will define the third method analyse_words (self, decoded_sequence) that will analyze the word frequencies. The concept is similar to Character Analyser Class whereby we will loop through each word in the decoded sequence, and aggregate the counts in a dictionary."
},
{
"code": null,
"e": 9480,
"s": 8739,
"text": "class WordAnalyser: def __init__ (self): self.the_dict_word = {} def __str__ (self): dict_word_str = \"\" for key,value in self.the_dict_word.items(): dict_word_str += str(key) + \" has been decoded \" + str(value) + \" time(s) \" +\"\\n\" return dict_word_str def analyse_words (self, decoded_sequence): decoded_sequence_word=(decoded_sequence.strip()).split(\" \") for each in decoded_sequence_word: if each != \"?\" and each != \".\" and each != \",\": if each not in self.the_dict_word.keys(): self.the_dict_word[each] = 1 else: self.the_dict_word[each] += 1 return self.the_dict_word"
},
{
"code": null,
"e": 9734,
"s": 9480,
"text": "The last analyzer class we will build is a Sentence Analyser Class. As we allow the users to key in three punctuation marks of a full stop, comma, and question mark, we can analyze how many times each sentence type is being decoded as per the following:"
},
{
"code": null,
"e": 9778,
"s": 9734,
"text": "1. A sentence ending with ‘ ? ’ — Questions"
},
{
"code": null,
"e": 9831,
"s": 9778,
"text": "2. A sentence ending with ‘ . ’ — Complete Sentences"
},
{
"code": null,
"e": 9873,
"s": 9831,
"text": "3. A sentence ending with ‘ , ’ — Clauses"
},
{
"code": null,
"e": 10215,
"s": 9873,
"text": "After defining the essential two classes __init__(self) and __str__(self), the way we will build our third method analyse_sentences (self, decoded_sequence) is that we will split the sequences into individual words/punctuation marks and loop through each of them. If a question mark is found, we will add a count to ‘Questions’ and so forth."
},
{
"code": null,
"e": 11082,
"s": 10215,
"text": "class SentenceAnalyser: def __init__ (self): self.the_dict_sentence = dict(zip((\"Clauses\",\"Complete Sentences\",\"Questions\"),(0,0,0))) def __str__ (self): dict_sentence_str = \"\" for key,value in self.the_dict_sentence.items(): dict_sentence_str += str(key) + \" has been decoded \" + str(value) + \" times(s) \" + \"\\n\" return dict_sentence_str def analyse_sentences (self, decoded_sequence): decoded_sequence_sentence = decoded_sequence.split(\" \") for each in decoded_sequence_sentence: if each == \",\": self.the_dict_sentence[\"Clauses\"] += 1 elif each == \".\": self.the_dict_sentence[\"Complete Sentences\"] += 1 elif each == \"?\": self.the_dict_sentence[\"Questions\"] += 1 return self.the_dict_sentence"
},
{
"code": null,
"e": 11468,
"s": 11082,
"text": "In this last section, we will put all the above 4 classes together and create a program that provides the user the capability to enter Morse Code sequences and choosing the type of analysis he/she is interested in. The way we put all the classes together is using the main() method which is the starting point of any program. Below is the whole code which I will walk you guys through."
},
{
"code": null,
"e": 16949,
"s": 11468,
"text": "# import all the 4 classesfrom decoder_29442826 import Decoderfrom character_29442826 import CharacterAnalyserfrom word_29442826 import WordAnalyserfrom sentence_29442826 import SentenceAnalyser def main(): # set 4 variables to each of the 4 classes my_dict_1 = Decoder() my_dict_2 = CharacterAnalyser() my_dict_3 = WordAnalyser() my_dict_4 = SentenceAnalyser() # initialise empty list to store user input user_input_list = [] # print the structure of morse code representation for user's reference print(str(my_dict_1)) # asking user to input morse code sequences for decoding while True: user_input_morse = input (\"Enter sequences of Morse Code to be decoded based on representation shown, leave blank to stop input: \") # Proceed for error checking of user input if it's not empty if len(user_input_morse)!=0: # Error check 1, checking for invalid characters other than 0, 1, * if my_dict_1.decode(user_input_morse)==\"Invalid characters in morse code sequence, it should only consists of 0, 1 and *\": print (\"Invalid characters in morse code sequence, it should only consists of 0, 1 and *\" + \"\\n\") # Error check 2, checking for minimum requirement of one set of *** elif \"***\" not in user_input_morse: print (\"Error input, the Morse Code sequence should have at least one set of ***\" + \"\\n\") # Error check 3, checking for punctuation at the end of user input, i.e. 010101, 110011, 001100 elif my_dict_1.decode(user_input_morse)==\"Invalid morse code sequence input, morse code sequence should end with punctuation characters\": print(\"Invalid morse code sequence input, morse code sequence should end with punctuation characters\" + \"\\n\") # Error check 4, checking for invalid morse code representation as per the pre-defined morse code dictionary elif my_dict_1.decode(user_input_morse)==\"Invalid morse code representation\": print(\"Invalid morse code representation\" + \"\\n\") # add user input into list for decoding if no errors found else: user_input_list.append(user_input_morse) # Stop asking for input once user leaved blank else: print(\"You have chosen to stop inputting morse code sequences\" + \"\\n\") break # empty string to store decoded sequences overall_decoded_sequence=\"\" # decoding the morse code sequences in user_input_list for each in user_input_list: overall_decoded_sequence += my_dict_1.decode(each) # character analysis of all the decoded morse code sequence my_dict_2.analyse_characters(overall_decoded_sequence) # word analysis of all the decoded morse code sequence my_dict_3.analyse_words(overall_decoded_sequence) # sentence analysis of all the decoded morse code sequence my_dict_4.analyse_sentences(overall_decoded_sequence) if len(overall_decoded_sequence)!=0: # asking user to choose level of analysis from character, word, sentence or all while True: user_input_level = input (\"Please choose the level of analysis from character, word, sentence or all, leave blank to quit:\") # if character analysis chosen, return result of character analysis only if user_input_level == \"character\": print(\"Decoded Morse Code Sequence(s):\") for each in user_input_list: print(str(each) + \" has been decoded to: \" + my_dict_1.decode(each)) print(\"\\n\" + \"Characters Analysis:\" + \"\\n\" + str(my_dict_2)) # if word analysis chosen, return result of word analysis only elif user_input_level == \"word\": print(\"Decoded Morse Code Sequence(s):\") for each in user_input_list: print(str(each) + \" has been decoded to: \" + my_dict_1.decode(each)) print(\"\\n\" + \"Words Analysis:\" + \"\\n\" + str(my_dict_3)) # if sentence analysis chosen, return result of sentence analysis only elif user_input_level == \"sentence\": print(\"Decoded Morse Code Sequence(s):\") for each in user_input_list: print(str(each) + \" has been decoded to: \" + my_dict_1.decode(each)) print(\"\\n\" + \"Sentence Analysis:\" + \"\\n\" + str(my_dict_4)) # if all has been chose, return result of character, word and sentence analysis elif user_input_level == \"all\": print(\"Decoded Morse Code Sequence(s):\") for each in user_input_list: print(str(each) + \" has been decoded to: \" + my_dict_1.decode(each)) print(\"\\n\" + \"Characters Analysis:\" + \"\\n\" + str(my_dict_2)) print(\"Words Analysis:\" + \"\\n\" + str(my_dict_3)) print(\"Sentence Analysis:\" + \"\\n\" + str(my_dict_4)) # if user leaved blank, terminate the whole program elif user_input_level == \"\": print(\"You have chosen to terminate the whole program\") break # prompt the user for level of analysis again if invalid input has been found else: print(\"Invalid input, choose the level of analysis from character, word, sentence or all, leave blank to quit\") else: print(\"No morse code sequences were entered\")if __name__ == \"__main__\": main()"
},
{
"code": null,
"e": 17258,
"s": 16949,
"text": "The way this program will work is that once the user runs this program, the Morse Code representation will first be displayed (using the first Decoder class). Users will be prompted to enter a Morse Code sequence and can continue inputting for decoding till they decided to stop inputting by leaving a blank."
},
{
"code": null,
"e": 17501,
"s": 17258,
"text": "If the user chose to quit inputting Morse Code Sequences and did not input any Morse Code Sequence or all Morse Code Sequences that were entered were invalid, the program will terminate with the message “No morse code sequences were entered”."
},
{
"code": null,
"e": 17745,
"s": 17501,
"text": "Once the user has entered a Morse Code sequence or a series of them and keyed in a blank to indicate he/she wants to stop inputting, the program will then prompt the user to choose the level of analysis (i.e. Character, Word, Sentence or All)."
},
{
"code": null,
"e": 17912,
"s": 17745,
"text": "Character Analysis will call upon the character_analyser class and return the characters found in the sequences entered by users along with their decoded frequencies."
},
{
"code": null,
"e": 18060,
"s": 17912,
"text": "Word Analysis will call upon word_analyser class and return the words found in the sequences entered by users along with their decoded frequencies."
},
{
"code": null,
"e": 18260,
"s": 18060,
"text": "Sentence Analysis will call upon sentence_analyser and return the counts of the number of times Questions, Clauses & Complete Sentences have been decoded based on ‘ ? ’, ‘ , ’ and ‘ . ’ respectively."
},
{
"code": null,
"e": 18338,
"s": 18260,
"text": "Users can also choose “all” and all three analyses will be displayed at once."
},
{
"code": null,
"e": 18473,
"s": 18338,
"text": "Once the user is done with the analysis, he/she can terminate the program by inputting a blank input and the program will exit itself."
}
] |
Graham Scan Algorithm
|
The convex hull is the minimum closed area which can cover all given data points.
Graham’s Scan algorithm will find the corner points of the convex hull. In this algorithm, at first, the lowest point is chosen. That point is the starting point of the convex hull. Remaining n-1 vertices are sorted based on the anti-clockwise direction from the start point. If two or more points are forming the same angle, then remove all points of the same angle except the farthest point from start.
From the remaining points, push them into the stack. And remove items from stack one by one, when orientation is not anti-clockwise for stack top point, second top point and newly selected point points[i], after checking, insert points[i] into the stack.
Input:
Set of points: {(-7,8), (-4,6), (2,6), (6,4), (8,6), (7,-2), (4,-6), (8,-7),(0,0), (3,-2),(6,-10),(0,-6),(-9,-5),(-8,-2),(-8,0),(-10,3),(-2,2),(-10,4)}
Output:
Boundary points of convex hull are:
(-9, -5) (-10, 3) (-10, 4) (-7, 8) (8, 6) (8, -7) (6, -10)
findConvexHull(points, n)
Input − The set of points, number of points.
Output − The boundary points of the convex hull.
Begin
minY := points[0].y
min := 0
for i := 1 to n-1 do
y := points[i].y
if y < minY or minY = y and points[i].x < points[min].x, then
minY := points[i].y
min := i
done
swap points[0] and points[min]
p0 := points[0]
sort points from points[1] to end
arrSize := 1
for i := 1 to n, do
when i < n-1 and (p0, points[i], points[i+1]) are collinear, do
i := i + 1
done
points[arrSize] := points[i]
arrSize := arrSize + 1
done
if arrSize < 3, then
return cHullPoints
push points[0] into stack
push points[1] into stack
push points[2] into stack
for i := 3 to arrSize, do
while top of stack, item below the top and points[i] is not in
anticlockwise rotation, do
delete top element from stack
done
push points[i] into stack
done
while stack is not empty, do
item stack top element into cHullPoints
pop from stack
done
End
#include<iostream>
#include<stack>
#include<algorithm>
#include<vector>
using namespace std;
struct point { //define points for 2d plane
int x, y;
};
point p0; //used to another two points
point secondTop(stack<point>&stk) {
point tempPoint = stk.top(); stk.pop();
point res = stk.top(); //get the second top element
stk.push(tempPoint); //push previous top again
return res;
}
int squaredDist(point p1, point p2) {
return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}
int direction(point a, point b, point c) {
int val = (b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y);
if (val == 0)
return 0; //colinear
else if(val < 0)
return 2; //anti-clockwise direction
return 1; //clockwise direction
}
int comp(const void *point1, const void*point2) {
point *p1 = (point*)point1;
point *p2 = (point*)point2;
int dir = direction(p0, *p1, *p2);
if(dir == 0)
return (squaredDist(p0, *p2) >= squaredDist(p0, *p1))?-1 : 1;
return (dir==2)? -1 : 1;
}
vector<point>findConvexHull(point points[], int n) {
vector<point> convexHullPoints;
int minY = points[0].y, min = 0;
for(int i = 1; i<n; i++) {
int y = points[i].y;
//find bottom most or left most point
if((y < minY) || (minY == y) && points[i].x < points[min].x) {
minY = points[i].y;
min = i;
}
}
swap(points[0], points[min]); //swap min point to 0th location
p0 = points[0];
qsort(&points[1], n-1, sizeof(point), comp); //sort points from 1 place to end
int arrSize = 1; //used to locate items in modified array
for(int i = 1; i<n; i++) {
//when the angle of ith and (i+1)th elements are same, remove points
while(i < n-1 && direction(p0, points[i], points[i+1]) == 0)
i++;
points[arrSize] = points[i];
arrSize++;
}
if(arrSize < 3)
return convexHullPoints; //there must be at least 3 points, return empty list.
//create a stack and add first three points in the stack
stack<point> stk;
stk.push(points[0]); stk.push(points[1]); stk.push(points[2]);
for(int i = 3; i<arrSize; i++) { //for remaining vertices
while(direction(secondTop(stk), stk.top(), points[i]) != 2)
stk.pop(); //when top, second top and ith point are not making left turn, remove point
stk.push(points[i]);
}
while(!stk.empty()) {
convexHullPoints.push_back(stk.top()); //add points from stack
stk.pop();
}
}
int main() {
point points[] = {{-7,8},{-4,6},{2,6},{6,4},{8,6},{7,-2},{4,-6},{8,-7},{0,0},
{3,-2},{6,-10},{0,-6},{-9,-5},{-8,-2},{-8,0},{-10,3},{-2,2},{-10,4}};
int n = 18;
vector<point> result;
result = findConvexHull(points, n);
cout << "Boundary points of convex hull are: "<<endl;
vector<point>::iterator it;
for(it = result.begin(); it!=result.end(); it++)
cout << "(" << it->x << ", " <<it->y <<") ";
}
Boundary points of convex hull are:
(-9, -5) (-10, 3) (-10, 4) (-7, 8) (8, 6) (8, -7) (6, -10)
|
[
{
"code": null,
"e": 1144,
"s": 1062,
"text": "The convex hull is the minimum closed area which can cover all given data points."
},
{
"code": null,
"e": 1549,
"s": 1144,
"text": "Graham’s Scan algorithm will find the corner points of the convex hull. In this algorithm, at first, the lowest point is chosen. That point is the starting point of the convex hull. Remaining n-1 vertices are sorted based on the anti-clockwise direction from the start point. If two or more points are forming the same angle, then remove all points of the same angle except the farthest point from start."
},
{
"code": null,
"e": 1804,
"s": 1549,
"text": "From the remaining points, push them into the stack. And remove items from stack one by one, when orientation is not anti-clockwise for stack top point, second top point and newly selected point points[i], after checking, insert points[i] into the stack."
},
{
"code": null,
"e": 2066,
"s": 1804,
"text": "Input:\nSet of points: {(-7,8), (-4,6), (2,6), (6,4), (8,6), (7,-2), (4,-6), (8,-7),(0,0), (3,-2),(6,-10),(0,-6),(-9,-5),(-8,-2),(-8,0),(-10,3),(-2,2),(-10,4)}\nOutput:\nBoundary points of convex hull are:\n(-9, -5) (-10, 3) (-10, 4) (-7, 8) (8, 6) (8, -7) (6, -10)"
},
{
"code": null,
"e": 2092,
"s": 2066,
"text": "findConvexHull(points, n)"
},
{
"code": null,
"e": 2137,
"s": 2092,
"text": "Input − The set of points, number of points."
},
{
"code": null,
"e": 2186,
"s": 2137,
"text": "Output − The boundary points of the convex hull."
},
{
"code": null,
"e": 3176,
"s": 2186,
"text": "Begin\n minY := points[0].y\n min := 0\n\n for i := 1 to n-1 do\n y := points[i].y\n if y < minY or minY = y and points[i].x < points[min].x, then\n minY := points[i].y\n min := i\n done\n\n swap points[0] and points[min]\n p0 := points[0]\n sort points from points[1] to end\n arrSize := 1\n\n for i := 1 to n, do\n when i < n-1 and (p0, points[i], points[i+1]) are collinear, do\n i := i + 1\n done\n points[arrSize] := points[i]\n arrSize := arrSize + 1\n done\n\n if arrSize < 3, then\n return cHullPoints\n push points[0] into stack\n push points[1] into stack\n push points[2] into stack\n\n for i := 3 to arrSize, do\n while top of stack, item below the top and points[i] is not in\n anticlockwise rotation, do\n delete top element from stack\n done\n push points[i] into stack\n done\n\n while stack is not empty, do\n item stack top element into cHullPoints\n pop from stack\n done\nEnd"
},
{
"code": null,
"e": 6202,
"s": 3176,
"text": "#include<iostream>\n#include<stack>\n#include<algorithm>\n#include<vector>\nusing namespace std;\n\nstruct point { //define points for 2d plane\n int x, y;\n};\n\npoint p0; //used to another two points\n\npoint secondTop(stack<point>&stk) {\n point tempPoint = stk.top(); stk.pop();\n point res = stk.top(); //get the second top element\n stk.push(tempPoint); //push previous top again\n return res;\n}\n\nint squaredDist(point p1, point p2) {\n return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));\n}\n\nint direction(point a, point b, point c) {\n int val = (b.y-a.y)*(c.x-b.x)-(b.x-a.x)*(c.y-b.y);\n if (val == 0)\n return 0; //colinear\n else if(val < 0)\n return 2; //anti-clockwise direction\n return 1; //clockwise direction\n}\n\nint comp(const void *point1, const void*point2) {\n point *p1 = (point*)point1;\n point *p2 = (point*)point2;\n int dir = direction(p0, *p1, *p2);\n\n if(dir == 0)\n return (squaredDist(p0, *p2) >= squaredDist(p0, *p1))?-1 : 1;\n return (dir==2)? -1 : 1; \n}\n\nvector<point>findConvexHull(point points[], int n) {\n vector<point> convexHullPoints;\n int minY = points[0].y, min = 0;\n\n for(int i = 1; i<n; i++) {\n int y = points[i].y;\n //find bottom most or left most point\n if((y < minY) || (minY == y) && points[i].x < points[min].x) {\n minY = points[i].y;\n min = i; \n }\n }\n\n swap(points[0], points[min]); //swap min point to 0th location\n p0 = points[0];\n qsort(&points[1], n-1, sizeof(point), comp); //sort points from 1 place to end\n \n int arrSize = 1; //used to locate items in modified array\n for(int i = 1; i<n; i++) {\n\n //when the angle of ith and (i+1)th elements are same, remove points\n while(i < n-1 && direction(p0, points[i], points[i+1]) == 0)\n i++;\n points[arrSize] = points[i];\n arrSize++;\n }\n\n if(arrSize < 3)\n return convexHullPoints; //there must be at least 3 points, return empty list.\n \n //create a stack and add first three points in the stack\n stack<point> stk;\n stk.push(points[0]); stk.push(points[1]); stk.push(points[2]);\n \n for(int i = 3; i<arrSize; i++) { //for remaining vertices\n while(direction(secondTop(stk), stk.top(), points[i]) != 2)\n stk.pop(); //when top, second top and ith point are not making left turn, remove point\n stk.push(points[i]);\n }\n\n while(!stk.empty()) {\n convexHullPoints.push_back(stk.top()); //add points from stack\n stk.pop();\n }\n}\n\nint main() {\n point points[] = {{-7,8},{-4,6},{2,6},{6,4},{8,6},{7,-2},{4,-6},{8,-7},{0,0},\n {3,-2},{6,-10},{0,-6},{-9,-5},{-8,-2},{-8,0},{-10,3},{-2,2},{-10,4}};\n int n = 18;\n vector<point> result;\n result = findConvexHull(points, n);\n cout << \"Boundary points of convex hull are: \"<<endl;\n vector<point>::iterator it;\n\n for(it = result.begin(); it!=result.end(); it++)\n cout << \"(\" << it->x << \", \" <<it->y <<\") \";\n}"
},
{
"code": null,
"e": 6297,
"s": 6202,
"text": "Boundary points of convex hull are:\n(-9, -5) (-10, 3) (-10, 4) (-7, 8) (8, 6) (8, -7) (6, -10)"
}
] |
How to check whether a year or a vector of years is leap year or not in R?
|
Almost everyone knows that a leap has 366 instead of 365 days and it occurs once in four years. If we want to check whether a particular year is a leap year or in a range of years which years correspond to leap year then we can use leap_year function of leap year. The length function can be used with the year value and if the output is 1 then it will be a leap year otherwise the output will be 0 which refers to the non-leap year.
Loading lubridate package −
library("lubridate")
year1<-2000
length(year1[leap_year(year1)])
[1] 1
year2<-2001
length(year2[leap_year(year2)])
[1] 0
year3<-2004
length(year3[leap_year(year3)])
[1] 1
year4<-0001:0010
length(year4[leap_year(year4)])
[1] 2
year5<-0001:0050
length(year5[leap_year(year5)])
[1] 12
year6<-0001:0100
length(year6[leap_year(year6)])
[1] 24
year7<-0001:1000
length(year7[leap_year(year7)])
[1] 242
We can also find the years that were leap years during year 1 to year 1000 by just removing the length command as shown below −
year7[leap_year(year7)]
[1] 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72
[19] 76 80 84 88 92 96 104 108 112 116 120 124 128 132 136 140 144 148
[37] 152 156 160 164 168 172 176 180 184 188 192 196 204 208 212 216 220 224
[55] 228 232 236 240 244 248 252 256 260 264 268 272 276 280 284 288 292 296
[73] 304 308 312 316 320 324 328 332 336 340 344 348 352 356 360 364 368 372
[91] 376 380 384 388 392 396 400 404 408 412 416 420 424 428 432 436 440 444
[109] 448 452 456 460 464 468 472 476 480 484 488 492 496 504 508 512 516 520
[127] 524 528 532 536 540 544 548 552 556 560 564 568 572 576 580 584 588 592
[145] 596 604 608 612 616 620 624 628 632 636 640 644 648 652 656 660 664 668
[163] 672 676 680 684 688 692 696 704 708 712 716 720 724 728 732 736 740 744
[181] 748 752 756 760 764 768 772 776 780 784 788 792 796 800 804 808 812 816
[199] 820 824 828 832 836 840 844 848 852 856 860 864 868 872 876 880 884 888
[217] 892 896 904 908 912 916 920 924 928 932 936 940 944 948 952 956 960 964
[235] 968 972 976 980 984 988 992 996
year8<-1001:1200
year8[leap_year(year8)]
[1] 1004 1008 1012 1016 1020 1024 1028 1032 1036 1040 1044 1048 1052 1056 1060
[16] 1064 1068 1072 1076 1080 1084 1088 1092 1096 1104 1108 1112 1116 1120 1124
[31] 1128 1132 1136 1140 1144 1148 1152 1156 1160 1164 1168 1172 1176 1180 1184
[46] 1188 1192 1196 1200
length(year8[leap_year(year8)])
[1] 49
year9<-1001:2000 year9[leap_year(year9)]
[1] 1004 1008 1012 1016 1020 1024 1028 1032 1036 1040 1044 1048 1052 1056 1060
[16] 1064 1068 1072 1076 1080 1084 1088 1092 1096 1104 1108 1112 1116 1120 1124
[31] 1128 1132 1136 1140 1144 1148 1152 1156 1160 1164 1168 1172 1176 1180 1184
[46] 1188 1192 1196 1200 1204 1208 1212 1216 1220 1224 1228 1232 1236 1240 1244
[61] 1248 1252 1256 1260 1264 1268 1272 1276 1280 1284 1288 1292 1296 1304 1308
[76] 1312 1316 1320 1324 1328 1332 1336 1340 1344 1348 1352 1356 1360 1364 1368
[91] 1372 1376 1380 1384 1388 1392 1396 1404 1408 1412 1416 1420 1424 1428 1432
[106] 1436 1440 1444 1448 1452 1456 1460 1464 1468 1472 1476 1480 1484 1488 1492
[121] 1496 1504 1508 1512 1516 1520 1524 1528 1532 1536 1540 1544 1548 1552 1556
[136] 1560 1564 1568 1572 1576 1580 1584 1588 1592 1596 1600 1604 1608 1612 1616
[151] 1620 1624 1628 1632 1636 1640 1644 1648 1652 1656 1660 1664 1668 1672 1676
[166] 1680 1684 1688 1692 1696 1704 1708 1712 1716 1720 1724 1728 1732 1736 1740
[181] 1744 1748 1752 1756 1760 1764 1768 1772 1776 1780 1784 1788 1792 1796 1804
[196] 1808 1812 1816 1820 1824 1828 1832 1836 1840 1844 1848 1852 1856 1860 1864
[211] 1868 1872 1876 1880 1884 1888 1892 1896 1904 1908 1912 1916 1920 1924 1928
[226] 1932 1936 1940 1944 1948 1952 1956 1960 1964 1968 1972 1976 1980 1984 1988
[241] 1992 1996 2000
length(year9[leap_year(year9)])
[1] 243
year10<-0001:2020
length(year10[leap_year(year10)])
[1] 490
|
[
{
"code": null,
"e": 1496,
"s": 1062,
"text": "Almost everyone knows that a leap has 366 instead of 365 days and it occurs once in four years. If we want to check whether a particular year is a leap year or in a range of years which years correspond to leap year then we can use leap_year function of leap year. The length function can be used with the year value and if the output is 1 then it will be a leap year otherwise the output will be 0 which refers to the non-leap year."
},
{
"code": null,
"e": 1524,
"s": 1496,
"text": "Loading lubridate package −"
},
{
"code": null,
"e": 1589,
"s": 1524,
"text": "library(\"lubridate\")\nyear1<-2000\nlength(year1[leap_year(year1)])"
},
{
"code": null,
"e": 1595,
"s": 1589,
"text": "[1] 1"
},
{
"code": null,
"e": 1639,
"s": 1595,
"text": "year2<-2001\nlength(year2[leap_year(year2)])"
},
{
"code": null,
"e": 1645,
"s": 1639,
"text": "[1] 0"
},
{
"code": null,
"e": 1689,
"s": 1645,
"text": "year3<-2004\nlength(year3[leap_year(year3)])"
},
{
"code": null,
"e": 1695,
"s": 1689,
"text": "[1] 1"
},
{
"code": null,
"e": 1744,
"s": 1695,
"text": "year4<-0001:0010\nlength(year4[leap_year(year4)])"
},
{
"code": null,
"e": 1750,
"s": 1744,
"text": "[1] 2"
},
{
"code": null,
"e": 1799,
"s": 1750,
"text": "year5<-0001:0050\nlength(year5[leap_year(year5)])"
},
{
"code": null,
"e": 1806,
"s": 1799,
"text": "[1] 12"
},
{
"code": null,
"e": 1855,
"s": 1806,
"text": "year6<-0001:0100\nlength(year6[leap_year(year6)])"
},
{
"code": null,
"e": 1862,
"s": 1855,
"text": "[1] 24"
},
{
"code": null,
"e": 1911,
"s": 1862,
"text": "year7<-0001:1000\nlength(year7[leap_year(year7)])"
},
{
"code": null,
"e": 1919,
"s": 1911,
"text": "[1] 242"
},
{
"code": null,
"e": 2047,
"s": 1919,
"text": "We can also find the years that were leap years during year 1 to year 1000 by just removing the length command as shown below −"
},
{
"code": null,
"e": 2071,
"s": 2047,
"text": "year7[leap_year(year7)]"
},
{
"code": null,
"e": 3092,
"s": 2071,
"text": "[1] 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 64 68 72\n [19] 76 80 84 88 92 96 104 108 112 116 120 124 128 132 136 140 144 148\n[37] 152 156 160 164 168 172 176 180 184 188 192 196 204 208 212 216 220 224\n[55] 228 232 236 240 244 248 252 256 260 264 268 272 276 280 284 288 292 296\n[73] 304 308 312 316 320 324 328 332 336 340 344 348 352 356 360 364 368 372\n[91] 376 380 384 388 392 396 400 404 408 412 416 420 424 428 432 436 440 444\n[109] 448 452 456 460 464 468 472 476 480 484 488 492 496 504 508 512 516 520\n[127] 524 528 532 536 540 544 548 552 556 560 564 568 572 576 580 584 588 592\n[145] 596 604 608 612 616 620 624 628 632 636 640 644 648 652 656 660 664 668\n[163] 672 676 680 684 688 692 696 704 708 712 716 720 724 728 732 736 740 744\n [181] 748 752 756 760 764 768 772 776 780 784 788 792 796 800 804 808 812 816\n[199] 820 824 828 832 836 840 844 848 852 856 860 864 868 872 876 880 884 888\n[217] 892 896 904 908 912 916 920 924 928 932 936 940 944 948 952 956 960 964\n[235] 968 972 976 980 984 988 992 996"
},
{
"code": null,
"e": 3133,
"s": 3092,
"text": "year8<-1001:1200\nyear8[leap_year(year8)]"
},
{
"code": null,
"e": 3397,
"s": 3133,
"text": "[1] 1004 1008 1012 1016 1020 1024 1028 1032 1036 1040 1044 1048 1052 1056 1060\n[16] 1064 1068 1072 1076 1080 1084 1088 1092 1096 1104 1108 1112 1116 1120 1124\n[31] 1128 1132 1136 1140 1144 1148 1152 1156 1160 1164 1168 1172 1176 1180 1184\n[46] 1188 1192 1196 1200"
},
{
"code": null,
"e": 3429,
"s": 3397,
"text": "length(year8[leap_year(year8)])"
},
{
"code": null,
"e": 3437,
"s": 3429,
"text": "[1] 49\n"
},
{
"code": null,
"e": 3478,
"s": 3437,
"text": "year9<-1001:2000 year9[leap_year(year9)]"
},
{
"code": null,
"e": 4790,
"s": 3478,
"text": "[1] 1004 1008 1012 1016 1020 1024 1028 1032 1036 1040 1044 1048 1052 1056 1060\n[16] 1064 1068 1072 1076 1080 1084 1088 1092 1096 1104 1108 1112 1116 1120 1124\n [31] 1128 1132 1136 1140 1144 1148 1152 1156 1160 1164 1168 1172 1176 1180 1184\n [46] 1188 1192 1196 1200 1204 1208 1212 1216 1220 1224 1228 1232 1236 1240 1244\n[61] 1248 1252 1256 1260 1264 1268 1272 1276 1280 1284 1288 1292 1296 1304 1308\n[76] 1312 1316 1320 1324 1328 1332 1336 1340 1344 1348 1352 1356 1360 1364 1368\n[91] 1372 1376 1380 1384 1388 1392 1396 1404 1408 1412 1416 1420 1424 1428 1432\n[106] 1436 1440 1444 1448 1452 1456 1460 1464 1468 1472 1476 1480 1484 1488 1492\n[121] 1496 1504 1508 1512 1516 1520 1524 1528 1532 1536 1540 1544 1548 1552 1556\n[136] 1560 1564 1568 1572 1576 1580 1584 1588 1592 1596 1600 1604 1608 1612 1616\n[151] 1620 1624 1628 1632 1636 1640 1644 1648 1652 1656 1660 1664 1668 1672 1676\n[166] 1680 1684 1688 1692 1696 1704 1708 1712 1716 1720 1724 1728 1732 1736 1740\n [181] 1744 1748 1752 1756 1760 1764 1768 1772 1776 1780 1784 1788 1792 1796 1804\n[196] 1808 1812 1816 1820 1824 1828 1832 1836 1840 1844 1848 1852 1856 1860 1864\n[211] 1868 1872 1876 1880 1884 1888 1892 1896 1904 1908 1912 1916 1920 1924 1928\n[226] 1932 1936 1940 1944 1948 1952 1956 1960 1964 1968 1972 1976 1980 1984 1988\n[241] 1992 1996 2000"
},
{
"code": null,
"e": 4822,
"s": 4790,
"text": "length(year9[leap_year(year9)])"
},
{
"code": null,
"e": 4831,
"s": 4822,
"text": "[1] 243\n"
},
{
"code": null,
"e": 4883,
"s": 4831,
"text": "year10<-0001:2020\nlength(year10[leap_year(year10)])"
},
{
"code": null,
"e": 4891,
"s": 4883,
"text": "[1] 490"
}
] |
Tryit Editor v3.6 - Show Node.js
|
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
//Return the url part of the request object:
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "var http = require('http');"
},
{
"code": null,
"e": 30,
"s": 28,
"text": ""
},
{
"code": null,
"e": 70,
"s": 30,
"text": "http.createServer(function (req, res) {"
},
{
"code": null,
"e": 123,
"s": 70,
"text": " res.writeHead(200, {'Content-Type': 'text/html'});"
}
] |
Work with $push in MongoDB
|
Let us create a collection with documents −
> db.demo738.insertOne({Subjects:["C","C++"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ead696557bb72a10bcf0661")
}
> db.demo738.insertOne({Subjects:["MySQL","PL/SQL"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ead696657bb72a10bcf0662")
}
Display all documents from a collection with the help of find() method −
> db.demo738.find();
This will produce the following output −
{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] }
{ "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL" ] }
Following is the query to push −
>db.demo738.update({_id:ObjectId("5ead696657bb72a10bcf0662")},{$push:{"Subjects":"MongoDB"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Display all documents from a collection with the help of find() method −
> db.demo738.find();
This will produce the following output −
{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] }
{ "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL", "MongoDB" ] }
|
[
{
"code": null,
"e": 1106,
"s": 1062,
"text": "Let us create a collection with documents −"
},
{
"code": null,
"e": 1379,
"s": 1106,
"text": "> db.demo738.insertOne({Subjects:[\"C\",\"C++\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ead696557bb72a10bcf0661\")\n}\n> db.demo738.insertOne({Subjects:[\"MySQL\",\"PL/SQL\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ead696657bb72a10bcf0662\")\n}"
},
{
"code": null,
"e": 1452,
"s": 1379,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1473,
"s": 1452,
"text": "> db.demo738.find();"
},
{
"code": null,
"e": 1514,
"s": 1473,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1677,
"s": 1514,
"text": "{ \"_id\" : ObjectId(\"5ead696557bb72a10bcf0661\"), \"Subjects\" : [ \"C\", \"C++\" ] }\n{ \"_id\" : ObjectId(\"5ead696657bb72a10bcf0662\"), \"Subjects\" : [ \"MySQL\", \"PL/SQL\" ] }"
},
{
"code": null,
"e": 1710,
"s": 1677,
"text": "Following is the query to push −"
},
{
"code": null,
"e": 1871,
"s": 1710,
"text": ">db.demo738.update({_id:ObjectId(\"5ead696657bb72a10bcf0662\")},{$push:{\"Subjects\":\"MongoDB\"}});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })"
},
{
"code": null,
"e": 1944,
"s": 1871,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1965,
"s": 1944,
"text": "> db.demo738.find();"
},
{
"code": null,
"e": 2006,
"s": 1965,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2180,
"s": 2006,
"text": "{ \"_id\" : ObjectId(\"5ead696557bb72a10bcf0661\"), \"Subjects\" : [ \"C\", \"C++\" ] }\n{ \"_id\" : ObjectId(\"5ead696657bb72a10bcf0662\"), \"Subjects\" : [ \"MySQL\", \"PL/SQL\", \"MongoDB\" ] }"
}
] |
How can we set the shortcut key to a JButton in Java?
|
A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can also set the short cut keys for a JButton using the setMnemonic() method.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonTest extends JFrame {
private JButton button;
public JButtonTest() {
setTitle("JButtonTest");
button = new JButton("Click or press ALT-C");
button.setMnemonic('C');
add(button, BorderLayout.CENTER);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JOptionPane.showMessageDialog(null, ("Button clicked or pressed"));
}
});
setSize(475, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) throws Exception {
new JButtonTest();
}
}
In the above program, if we click or apply short cut key (Alt+C from the keyboard) on JButton, a new popup window can be generated below
|
[
{
"code": null,
"e": 1429,
"s": 1062,
"text": "A JButton is a subclass of AbstractButton and it can be used for adding platform-independent buttons to a Java Swing application. A JButon can generate an ActionListener interface when the button is pressed or clicked, it can also generate the MouseListener and KeyListener interfaces. We can also set the short cut keys for a JButton using the setMnemonic() method."
},
{
"code": null,
"e": 2191,
"s": 1429,
"text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JButtonTest extends JFrame {\n private JButton button;\n public JButtonTest() {\n setTitle(\"JButtonTest\");\n button = new JButton(\"Click or press ALT-C\");\n button.setMnemonic('C');\n add(button, BorderLayout.CENTER);\n button.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent evt) {\n JOptionPane.showMessageDialog(null, (\"Button clicked or pressed\"));\n }\n });\n setSize(475, 250);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public static void main(String args[]) throws Exception {\n new JButtonTest();\n }\n}"
},
{
"code": null,
"e": 2328,
"s": 2191,
"text": "In the above program, if we click or apply short cut key (Alt+C from the keyboard) on JButton, a new popup window can be generated below"
}
] |
Tryit Editor v3.7
|
CSS Style Images
Tryit: Create rounded image
|
[
{
"code": null,
"e": 26,
"s": 9,
"text": "CSS Style Images"
}
] |
C++ Arrays
|
C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows −
type arrayName [ arraySize ];
This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double,
use this statement −
double balance[10];
You can initialize C++ array elements either one by one or using a single statement as follows −
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −
If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −
double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};
You will create exactly the same array as you did in the previous example.
balance[4] = 50.0;
The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representaion of the same array we discussed above −
An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −
double salary = balance[9];
The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −
#include <iostream>
using namespace std;
#include <iomanip>
using std::setw;
int main () {
int n[ 10 ]; // n is an array of 10 integers
// initialize elements of array n to 0
for ( int i = 0; i < 10; i++ ) {
n[ i ] = i + 100; // set element at location i to i + 100
}
cout << "Element" << setw( 13 ) << "Value" << endl;
// output each array element's value
for ( int j = 0; j < 10; j++ ) {
cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;
}
return 0;
}
This program makes use of setw() function to format the output. When the above code is compiled and executed, it produces the following result −
Element Value
0 100
1 101
2 102
3 103
4 104
5 105
6 106
7 107
8 108
9 109
Arrays are important to C++ and should need lots of more detail. There are following few important concepts, which should be clear to a C++ programmer −
C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
You can generate a pointer to the first element of an array by simply specifying the array name, without any index.
You can pass to the function a pointer to an array by specifying the array's name without an index.
C++ allows a function to return an array.
154 Lectures
11.5 hours
Arnab Chakraborty
14 Lectures
57 mins
Kaushik Roy Chowdhury
30 Lectures
12.5 hours
Frahaan Hussain
54 Lectures
3.5 hours
Frahaan Hussain
77 Lectures
5.5 hours
Frahaan Hussain
12 Lectures
3.5 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2582,
"s": 2318,
"text": "C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type."
},
{
"code": null,
"e": 2862,
"s": 2582,
"text": "Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. "
},
{
"code": null,
"e": 3010,
"s": 2862,
"text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element."
},
{
"code": null,
"e": 3149,
"s": 3010,
"text": "To declare an array in C++, the programmer specifies the type of the elements and the number of elements required by an array as follows −"
},
{
"code": null,
"e": 3180,
"s": 3149,
"text": "type arrayName [ arraySize ];\n"
},
{
"code": null,
"e": 3417,
"s": 3180,
"text": "This is called a single-dimension array. The arraySize must be an integer constant greater than zero and type can be any valid C++ data type. For example, to declare a 10-element array called balance of type double,\nuse this statement −"
},
{
"code": null,
"e": 3438,
"s": 3417,
"text": "double balance[10];\n"
},
{
"code": null,
"e": 3535,
"s": 3438,
"text": "You can initialize C++ array elements either one by one or using a single statement as follows −"
},
{
"code": null,
"e": 3588,
"s": 3535,
"text": "double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};\n"
},
{
"code": null,
"e": 3799,
"s": 3588,
"text": "The number of values between braces { } can not be larger than the number of elements that we declare for the array between square brackets [ ]. Following is an example to assign a single element of the array −"
},
{
"code": null,
"e": 3925,
"s": 3799,
"text": "If you omit the size of the array, an array just big enough to hold the initialization is created. Therefore, if you write −"
},
{
"code": null,
"e": 3977,
"s": 3925,
"text": "double balance[] = {1000.0, 2.0, 3.4, 17.0, 50.0};\n"
},
{
"code": null,
"e": 4052,
"s": 3977,
"text": "You will create exactly the same array as you did in the previous example."
},
{
"code": null,
"e": 4072,
"s": 4052,
"text": "balance[4] = 50.0;\n"
},
{
"code": null,
"e": 4377,
"s": 4072,
"text": "The above statement assigns element number 5th in the array a value of 50.0. Array with 4th index will be 5th, i.e., last element because all arrays have 0 as the index of their first element which is also called base index. Following is the pictorial representaion of the same array we discussed above −"
},
{
"code": null,
"e": 4543,
"s": 4377,
"text": "An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example −"
},
{
"code": null,
"e": 4572,
"s": 4543,
"text": "double salary = balance[9];\n"
},
{
"code": null,
"e": 4802,
"s": 4572,
"text": "The above statement will take 10th element from the array and assign the value to salary variable. Following is an example, which will use all the above-mentioned three concepts viz. declaration, assignment and accessing arrays −"
},
{
"code": null,
"e": 5343,
"s": 4802,
"text": "#include <iostream>\nusing namespace std;\n \n#include <iomanip>\nusing std::setw;\n \nint main () {\n\n int n[ 10 ]; // n is an array of 10 integers\n \n // initialize elements of array n to 0 \n for ( int i = 0; i < 10; i++ ) {\n n[ i ] = i + 100; // set element at location i to i + 100\n }\n cout << \"Element\" << setw( 13 ) << \"Value\" << endl;\n \n // output each array element's value \n for ( int j = 0; j < 10; j++ ) {\n cout << setw( 7 )<< j << setw( 13 ) << n[ j ] << endl;\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 5488,
"s": 5343,
"text": "This program makes use of setw() function to format the output. When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5720,
"s": 5488,
"text": "Element Value\n 0 100\n 1 101\n 2 102\n 3 103\n 4 104\n 5 105\n 6 106\n 7 107\n 8 108\n 9 109\n"
},
{
"code": null,
"e": 5873,
"s": 5720,
"text": "Arrays are important to C++ and should need lots of more detail. There are following few important concepts, which should be clear to a C++ programmer −"
},
{
"code": null,
"e": 5989,
"s": 5873,
"text": "C++ supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array."
},
{
"code": null,
"e": 6105,
"s": 5989,
"text": "You can generate a pointer to the first element of an array by simply specifying the array name, without any index."
},
{
"code": null,
"e": 6205,
"s": 6105,
"text": "You can pass to the function a pointer to an array by specifying the array's name without an index."
},
{
"code": null,
"e": 6247,
"s": 6205,
"text": "C++ allows a function to return an array."
},
{
"code": null,
"e": 6284,
"s": 6247,
"text": "\n 154 Lectures \n 11.5 hours \n"
},
{
"code": null,
"e": 6303,
"s": 6284,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6335,
"s": 6303,
"text": "\n 14 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 6358,
"s": 6335,
"text": " Kaushik Roy Chowdhury"
},
{
"code": null,
"e": 6394,
"s": 6358,
"text": "\n 30 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 6411,
"s": 6394,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6446,
"s": 6411,
"text": "\n 54 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6463,
"s": 6446,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6498,
"s": 6463,
"text": "\n 77 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6515,
"s": 6498,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6550,
"s": 6515,
"text": "\n 12 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6567,
"s": 6550,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6574,
"s": 6567,
"text": " Print"
},
{
"code": null,
"e": 6585,
"s": 6574,
"text": " Add Notes"
}
] |
How to extract strings that contains a particular substring in an R vector?
|
Suppose we have a vector that contains multiple string elements and we want to find out which string element has a particular substring. This can be done with the help of grep function. For example, if we have a vector called x that contains five string elements each of varying length then finding which of the elements has a substring say programming then it can be done by using the command grep("programming",x,fixed=TRUE)
Live Demo
x1<-c("R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team","R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac","This programming language was named R, based on the first letter of first name of the two R authors (Robert Gentleman and Ross Ihaka), and partly a play on the name of the Bell Labs Language S")
x1
[1] "R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team"
[2] "R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac"
[3] "This programming language was named R, based on the first letter of first name of the two R authors (Robert Gentleman and Ross Ihaka), and partly a play on the name of the Bell Labs Language S"
grep("programming",x1,fixed=TRUE)
[1] 1 3
Live Demo
x2<-c("A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions","In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions","The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects","Function Name − This is the actual name of the function. It is stored in R environment as an object with this name","Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values","Function Body − The function body contains a collection of statements that defines what the function does","Return Value − The return value of a function is the last expression in the function body to be evaluated","R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions")
x2
[1] "A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions"
[2] "In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions"
[3] "The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects"
[4] "Function Name − This is the actual name of the function. It is stored in R environment as an object with this name"
[5] "Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values"
[6] "Function Body − The function body contains a collection of statements that defines what the function does"
[7] "Return Value − The return value of a function is the last expression in the function body to be evaluated"
[8] "R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions"
grep("R",x2,fixed=TRUE)
[1] 1 2 4 7 8
Live Demo
x3<-c("Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations","A Matrix is created using the matrix() function","data is the input vector
which becomes the data elements of the matrix","nrow is the number of rows to be created","ncol is the number of columns to be created","byrow is a logical clue. If TRUE then the input vector elements are arranged by row","dimname is the names assigned to the rows and columns")
x3
[1] "Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations"
[2] "A Matrix is created using the matrix() function"
[3] "data is the input vector which becomes the data elements of the matrix"
[4] "nrow is the number of rows to be created"
[5] "ncol is the number of columns to be created"
[6] "byrow is a logical clue. If TRUE then the input vector elements are arranged by row"
[7] "dimname is the names assigned to the rows and columns"
grep("matrix",x3,fixed=TRUE)
[1] 1 2 3
grep("Matrix",x3,fixed=TRUE)
[1] 2
|
[
{
"code": null,
"e": 1489,
"s": 1062,
"text": "Suppose we have a vector that contains multiple string elements and we want to find out which string element has a particular substring. This can be done with the help of grep function. For example, if we have a vector called x that contains five string elements each of varying length then finding which of the elements has a substring say programming then it can be done by using the command grep(\"programming\",x,fixed=TRUE)"
},
{
"code": null,
"e": 1500,
"s": 1489,
"text": " Live Demo"
},
{
"code": null,
"e": 2142,
"s": 1500,
"text": "x1<-c(\"R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team\",\"R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac\",\"This programming language was named R, based on the first letter of first name of the two R authors (Robert Gentleman and Ross Ihaka), and partly a play on the name of the Bell Labs Language S\")\nx1"
},
{
"code": null,
"e": 2786,
"s": 2142,
"text": "[1] \"R is a programming language and software environment for statistical analysis, graphics representation and reporting. R was created by Ross Ihaka and Robert Gentleman at the University of Auckland, New Zealand, and is currently developed by the R Development Core Team\"\n[2] \"R is freely available under the GNU General Public License, and pre-compiled binary versions are provided for various operating systems like Linux, Windows and Mac\"\n[3] \"This programming language was named R, based on the first letter of first name of the two R authors (Robert Gentleman and Ross Ihaka), and partly a play on the name of the Bell Labs Language S\""
},
{
"code": null,
"e": 2820,
"s": 2786,
"text": "grep(\"programming\",x1,fixed=TRUE)"
},
{
"code": null,
"e": 2828,
"s": 2820,
"text": "[1] 1 3"
},
{
"code": null,
"e": 2839,
"s": 2828,
"text": " Live Demo"
},
{
"code": null,
"e": 4071,
"s": 2839,
"text": "x2<-c(\"A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions\",\"In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions\",\"The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects\",\"Function Name − This is the actual name of the function. It is stored in R environment as an object with this name\",\"Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values\",\"Function Body − The function body contains a collection of statements that defines what the function does\",\"Return Value − The return value of a function is the last expression in the function body to be evaluated\",\"R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions\")\nx2"
},
{
"code": null,
"e": 5325,
"s": 4071,
"text": "[1] \"A function is a set of statements organized together to perform a specific task. R has a large number of in-built functions and the user can create their own functions\"\n[2] \"In R, a function is an object so the R interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions\"\n[3] \"The function in turn performs its task and returns control to the interpreter as well as any result which may be stored in other objects\"\n[4] \"Function Name − This is the actual name of the function. It is stored in R environment as an object with this name\"\n[5] \"Arguments − An argument is a placeholder. When a function is invoked, you pass a value to the argument. Arguments are optional; that is, a function may contain no arguments. Also arguments can have default values\"\n[6] \"Function Body − The function body contains a collection of statements that defines what the function does\"\n[7] \"Return Value − The return value of a function is the last expression in the function body to be evaluated\"\n[8] \"R has many in-built functions which can be directly called in the program without defining them first. We can also create and use our own functions referred as user defined functions\""
},
{
"code": null,
"e": 5349,
"s": 5325,
"text": "grep(\"R\",x2,fixed=TRUE)"
},
{
"code": null,
"e": 5363,
"s": 5349,
"text": "[1] 1 2 4 7 8"
},
{
"code": null,
"e": 5374,
"s": 5363,
"text": " Live Demo"
},
{
"code": null,
"e": 6082,
"s": 5374,
"text": "x3<-c(\"Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations\",\"A Matrix is created using the matrix() function\",\"data is the input vector\nwhich becomes the data elements of the matrix\",\"nrow is the number of rows to be created\",\"ncol is the number of columns to be created\",\"byrow is a logical clue. If TRUE then the input vector elements are arranged by row\",\"dimname is the names assigned to the rows and columns\")\nx3"
},
{
"code": null,
"e": 6808,
"s": 6082,
"text": "[1] \"Matrices are the R objects in which the elements are arranged in a two-dimensional rectangular layout. They contain elements of the same atomic types. Though we can create a matrix containing only characters or only logical values, they are not of much use. We use matrices containing numeric elements to be used in mathematical calculations\"\n[2] \"A Matrix is created using the matrix() function\"\n[3] \"data is the input vector which becomes the data elements of the matrix\"\n[4] \"nrow is the number of rows to be created\"\n[5] \"ncol is the number of columns to be created\"\n[6] \"byrow is a logical clue. If TRUE then the input vector elements are arranged by row\"\n[7] \"dimname is the names assigned to the rows and columns\""
},
{
"code": null,
"e": 6837,
"s": 6808,
"text": "grep(\"matrix\",x3,fixed=TRUE)"
},
{
"code": null,
"e": 6847,
"s": 6837,
"text": "[1] 1 2 3"
},
{
"code": null,
"e": 6876,
"s": 6847,
"text": "grep(\"Matrix\",x3,fixed=TRUE)"
},
{
"code": null,
"e": 6882,
"s": 6876,
"text": "[1] 2"
}
] |
How to create a Java HashMap of user defined class type? - GeeksforGeeks
|
04 Mar, 2019
Pre-requisite: Internal working of HashMap, HashMapIf we wish to create a HashMap of our own class, we need to ensure that the hashcode() of the key of HashMap doesn’t change as if it happens then it is impossible to get object value of the key from HashMap.
On runtime, JVM processes hash code for each object and give it on interest. When we alter an objects’ state, JVM calculates its hash code again which may result in memory leak. To make things work what we have to do is make sure that state change for a key object does not change the hash code of object i.e. the key must have properly overridden equals() and hashcode() methods for it to work correctly.
One of the ways of doing this is by making key objects IMMUTABLE. Immutability allows you to get same hashcode every time, for a key object. This is the primary motivation behind why Immutable classes like String, Integer or other wrapper classes are a decent key object applicant. Learn more about this here- How to make class Immutable?
// Java example to create a Java HashMap// of user-defined class type import java.util.*;import java.io.*; // User defined classpublic class CustomKeyObject { public static class Student { private int rollno; private String name; // Constructor public Student(int rollno, String name) { this.rollno = rollno; this.name = name; } public String getname() { return this.name; } public int getmarks() { return this.rollno; } public void setname(String name) { this.name = name; } public void setmarks(int rollno) { this.rollno = rollno; } // Overriding the hashcode() function @Override public int hashCode() { // uses roll no to verify the uniqueness // of the object of Student class final int temp = 14; int ans = 1; ans = temp * ans + rollno; return ans; } // Equal objects must produce the same // hash code as long as they are equal @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Student other = (Student)o; if (this.rollno != other.rollno) { return false; } return true; } } // main method public static void main(String[] args) throws NumberFormatException, IOException { HashMap<Student, String> map = new HashMap<>(); Student one = new Student(1, "Geeks1"); // key1 Student two = new Student(2, "Geeks2"); // key2 // put keys in map map.put(one, one.getname()); map.put(two, two.getname()); // changing key state so that // hashcode() should be calculated again one.setname("Not Geeks1"); two.setname("Not Geeks2"); // still prints Geeks1 System.out.println(map.get(one)); // still prints Geeks1 System.out.println(map.get(two)); // try with newly created key with same Rollno Student three = new Student(1, "Geeks3"); // we get Geeks1 System.out.println(map.get(three)); } // This code is contributed by Subhesh}
Geeks1
Geeks2
Geeks1
Java-HashMap
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java
|
[
{
"code": null,
"e": 25251,
"s": 25223,
"text": "\n04 Mar, 2019"
},
{
"code": null,
"e": 25510,
"s": 25251,
"text": "Pre-requisite: Internal working of HashMap, HashMapIf we wish to create a HashMap of our own class, we need to ensure that the hashcode() of the key of HashMap doesn’t change as if it happens then it is impossible to get object value of the key from HashMap."
},
{
"code": null,
"e": 25916,
"s": 25510,
"text": "On runtime, JVM processes hash code for each object and give it on interest. When we alter an objects’ state, JVM calculates its hash code again which may result in memory leak. To make things work what we have to do is make sure that state change for a key object does not change the hash code of object i.e. the key must have properly overridden equals() and hashcode() methods for it to work correctly."
},
{
"code": null,
"e": 26255,
"s": 25916,
"text": "One of the ways of doing this is by making key objects IMMUTABLE. Immutability allows you to get same hashcode every time, for a key object. This is the primary motivation behind why Immutable classes like String, Integer or other wrapper classes are a decent key object applicant. Learn more about this here- How to make class Immutable?"
},
{
"code": "// Java example to create a Java HashMap// of user-defined class type import java.util.*;import java.io.*; // User defined classpublic class CustomKeyObject { public static class Student { private int rollno; private String name; // Constructor public Student(int rollno, String name) { this.rollno = rollno; this.name = name; } public String getname() { return this.name; } public int getmarks() { return this.rollno; } public void setname(String name) { this.name = name; } public void setmarks(int rollno) { this.rollno = rollno; } // Overriding the hashcode() function @Override public int hashCode() { // uses roll no to verify the uniqueness // of the object of Student class final int temp = 14; int ans = 1; ans = temp * ans + rollno; return ans; } // Equal objects must produce the same // hash code as long as they are equal @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null) { return false; } if (this.getClass() != o.getClass()) { return false; } Student other = (Student)o; if (this.rollno != other.rollno) { return false; } return true; } } // main method public static void main(String[] args) throws NumberFormatException, IOException { HashMap<Student, String> map = new HashMap<>(); Student one = new Student(1, \"Geeks1\"); // key1 Student two = new Student(2, \"Geeks2\"); // key2 // put keys in map map.put(one, one.getname()); map.put(two, two.getname()); // changing key state so that // hashcode() should be calculated again one.setname(\"Not Geeks1\"); two.setname(\"Not Geeks2\"); // still prints Geeks1 System.out.println(map.get(one)); // still prints Geeks1 System.out.println(map.get(two)); // try with newly created key with same Rollno Student three = new Student(1, \"Geeks3\"); // we get Geeks1 System.out.println(map.get(three)); } // This code is contributed by Subhesh}",
"e": 28809,
"s": 26255,
"text": null
},
{
"code": null,
"e": 28831,
"s": 28809,
"text": "Geeks1\nGeeks2\nGeeks1\n"
},
{
"code": null,
"e": 28844,
"s": 28831,
"text": "Java-HashMap"
},
{
"code": null,
"e": 28851,
"s": 28844,
"text": "Picked"
},
{
"code": null,
"e": 28856,
"s": 28851,
"text": "Java"
},
{
"code": null,
"e": 28861,
"s": 28856,
"text": "Java"
},
{
"code": null,
"e": 28959,
"s": 28861,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28974,
"s": 28959,
"text": "Stream In Java"
},
{
"code": null,
"e": 28995,
"s": 28974,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29014,
"s": 28995,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29044,
"s": 29014,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29090,
"s": 29044,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29107,
"s": 29090,
"text": "Generics in Java"
},
{
"code": null,
"e": 29128,
"s": 29107,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29171,
"s": 29128,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29207,
"s": 29171,
"text": "Internal Working of HashMap in Java"
}
] |
Divide cuboid into cubes such that sum of volumes is maximum - GeeksforGeeks
|
13 Apr, 2021
Given the length, breadth, height of a cuboid. The task is to divide the given cuboid in minimum number of cubes such that size of all cubes is same and sum of volumes of cubes is maximum. Examples:
Input : l = 2, b = 4, h = 6
Output : 2 6
A cuboid of length 2, breadth 4 and
height 6 can be divided into 6 cube
of side equal to 2.
Volume of cubes = 6*(2*2*2) = 6*8 = 48.
Volume of cuboid = 2*4*6 = 48.
Input : 1 2 3
Output : 1 6
First of all, we are not allowed to waste volume of cuboid as we meed maximum volume sum. So, each side should be completely divide among all cubes. And since each of three side of cubes are equal, so each side of the cuboid need to be divisible by same number, say x, which will going to be the side of the cube. So, we have to maximize this x, which will divide given length, breadth and height. This x will be maximum only if it is greatest common divisor of given length, breadth and height. So, the length of the cube will be GCD of length, breadth and height.Now, to compute number of cubes, we know total volume of cuboid and can find volume of one cube (since side is already calculated). So, total number of cubes is equal to (volume of cuboid)/(volume of cube) i.e (l * b * h)/(x * x * x). Below is implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find optimal way to break// cuboid into cubes.#include <bits/stdc++.h>using namespace std; // Print the maximum side and no of cube.void maximizecube(int l, int b, int h){ // GCD to find side. int side = __gcd(l, __gcd(b, h)); // dividing to find number of cubes. int num = l / side; num = (num * b / side); num = (num * h / side); cout << side << " " << num << endl;} // Driver codeint main(){ int l = 2, b = 4, h = 6; maximizecube(l, b, h); return 0;}
// JAVA Code for Divide cuboid into cubes// such that sum of volumes is maximumimport java.util.*; class GFG { static int gcd(int m, int n) { if(n == 0) return m; else if(n > m) return gcd(n,m); else return gcd(n, m % n); } // Print the maximum side and no // of cube. static void maximizecube(int l, int b, int h) { // GCD to find side. int side = gcd(l, gcd(b, h)); // dividing to find number of cubes. int num = l / side; num = (num * b / side); num = (num * h / side); System.out.println( side + " " + num); } /* Driver program */ public static void main(String[] args) { int l = 2, b = 4, h = 6; maximizecube(l, b, h); }} // This code is contributed by Arnav Kr. Mandal.
# Python3 code to find optimal way to break# cuboid into cubes.from fractions import gcd # Print the maximum side and no of cube.def maximizecube( l , b , h ): # GCD to find side. side = gcd(l, gcd(b, h)) # dividing to find number of cubes. num = int(l / side) num = int(num * b / side) num = int(num * h / side) print(side, num) # Driver codel = 2b = 4h = 6 maximizecube(l, b, h) # This code is contributed by "Sharad_Bhardwaj".
// C# Code for Divide cuboid into cubes// such that sum of volumes is maximumusing System; class GFG { static int gcd(int m, int n) { if(n == 0) return m; else if(n > m) return gcd(n,m); else return gcd(n, m % n); } // Print the maximum side and no // of cube. static void maximizecube(int l, int b, int h) { // GCD to find side. int side = gcd(l, gcd(b, h)); // dividing to find number of cubes. int num = l / side; num = (num * b / side); num = (num * h / side); Console.WriteLine( side + " " + num); } /* Driver program */ public static void Main() { int l = 2, b = 4, h = 6; maximizecube(l, b, h); }} // This code is contributed by vt_m.
<?php// PHP program to find optimal way// to break cuboid into cubes. // Recursive function to// return gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if($a == 0 or $b == 0) return 0 ; // base case if($a == $b) return $a ; // a is greater if($a > $b) return __gcd($a - $b , $b ) ; return __gcd($a , $b - $a) ;} // Print the maximum side and no of cube.function maximizecube($l, $b, $h){ // GCD to find side. $side = __gcd($l, __gcd($b, $h)); // dividing to find number of cubes. $num = $l / $side; $num = ($num * $b / $side); $num = ($num * $h / $side); echo $side , " " , $num ;} // Driver code $l = 2; $b = 4; $h = 6; maximizecube($l, $b, $h); // This code is contributed by anuj_67.?>
<script> // JavaScript program for Divide cuboid into cubes// such that sum of volumes is maximum function gcd(m, n) { if(n == 0) return m; else if(n > m) return gcd(n,m); else return gcd(n, m % n); } // Print the maximum side and no // of cube. function maximizecube(l, b, h) { // GCD to find side. let side = gcd(l, gcd(b, h)); // dividing to find number of cubes. let num = l / side; num = (num * b / side); num = (num * h / side); document.write( side + " " + num); } // Driver code let l = 2, b = 4, h = 6; maximizecube(l, b, h); // This code is contributed by sanjoy_62.</script>
Output:
2 6
vt_m
sanjoy_62
area-volume-programs
Geometric
Greedy
Greedy
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Convex Hull | Set 2 (Graham Scan)
Optimum location of point to minimize total distance
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Program for array rotation
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 26275,
"s": 26247,
"text": "\n13 Apr, 2021"
},
{
"code": null,
"e": 26476,
"s": 26275,
"text": "Given the length, breadth, height of a cuboid. The task is to divide the given cuboid in minimum number of cubes such that size of all cubes is same and sum of volumes of cubes is maximum. Examples: "
},
{
"code": null,
"e": 26710,
"s": 26476,
"text": "Input : l = 2, b = 4, h = 6\nOutput : 2 6\nA cuboid of length 2, breadth 4 and \nheight 6 can be divided into 6 cube \nof side equal to 2.\nVolume of cubes = 6*(2*2*2) = 6*8 = 48.\nVolume of cuboid = 2*4*6 = 48.\n\nInput : 1 2 3\nOutput : 1 6"
},
{
"code": null,
"e": 27556,
"s": 26712,
"text": "First of all, we are not allowed to waste volume of cuboid as we meed maximum volume sum. So, each side should be completely divide among all cubes. And since each of three side of cubes are equal, so each side of the cuboid need to be divisible by same number, say x, which will going to be the side of the cube. So, we have to maximize this x, which will divide given length, breadth and height. This x will be maximum only if it is greatest common divisor of given length, breadth and height. So, the length of the cube will be GCD of length, breadth and height.Now, to compute number of cubes, we know total volume of cuboid and can find volume of one cube (since side is already calculated). So, total number of cubes is equal to (volume of cuboid)/(volume of cube) i.e (l * b * h)/(x * x * x). Below is implementation of this approach: "
},
{
"code": null,
"e": 27560,
"s": 27556,
"text": "C++"
},
{
"code": null,
"e": 27565,
"s": 27560,
"text": "Java"
},
{
"code": null,
"e": 27573,
"s": 27565,
"text": "Python3"
},
{
"code": null,
"e": 27576,
"s": 27573,
"text": "C#"
},
{
"code": null,
"e": 27580,
"s": 27576,
"text": "PHP"
},
{
"code": null,
"e": 27591,
"s": 27580,
"text": "Javascript"
},
{
"code": "// CPP program to find optimal way to break// cuboid into cubes.#include <bits/stdc++.h>using namespace std; // Print the maximum side and no of cube.void maximizecube(int l, int b, int h){ // GCD to find side. int side = __gcd(l, __gcd(b, h)); // dividing to find number of cubes. int num = l / side; num = (num * b / side); num = (num * h / side); cout << side << \" \" << num << endl;} // Driver codeint main(){ int l = 2, b = 4, h = 6; maximizecube(l, b, h); return 0;}",
"e": 28096,
"s": 27591,
"text": null
},
{
"code": "// JAVA Code for Divide cuboid into cubes// such that sum of volumes is maximumimport java.util.*; class GFG { static int gcd(int m, int n) { if(n == 0) return m; else if(n > m) return gcd(n,m); else return gcd(n, m % n); } // Print the maximum side and no // of cube. static void maximizecube(int l, int b, int h) { // GCD to find side. int side = gcd(l, gcd(b, h)); // dividing to find number of cubes. int num = l / side; num = (num * b / side); num = (num * h / side); System.out.println( side + \" \" + num); } /* Driver program */ public static void main(String[] args) { int l = 2, b = 4, h = 6; maximizecube(l, b, h); }} // This code is contributed by Arnav Kr. Mandal.",
"e": 28993,
"s": 28096,
"text": null
},
{
"code": "# Python3 code to find optimal way to break# cuboid into cubes.from fractions import gcd # Print the maximum side and no of cube.def maximizecube( l , b , h ): # GCD to find side. side = gcd(l, gcd(b, h)) # dividing to find number of cubes. num = int(l / side) num = int(num * b / side) num = int(num * h / side) print(side, num) # Driver codel = 2b = 4h = 6 maximizecube(l, b, h) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 29455,
"s": 28993,
"text": null
},
{
"code": "// C# Code for Divide cuboid into cubes// such that sum of volumes is maximumusing System; class GFG { static int gcd(int m, int n) { if(n == 0) return m; else if(n > m) return gcd(n,m); else return gcd(n, m % n); } // Print the maximum side and no // of cube. static void maximizecube(int l, int b, int h) { // GCD to find side. int side = gcd(l, gcd(b, h)); // dividing to find number of cubes. int num = l / side; num = (num * b / side); num = (num * h / side); Console.WriteLine( side + \" \" + num); } /* Driver program */ public static void Main() { int l = 2, b = 4, h = 6; maximizecube(l, b, h); }} // This code is contributed by vt_m.",
"e": 30306,
"s": 29455,
"text": null
},
{
"code": "<?php// PHP program to find optimal way// to break cuboid into cubes. // Recursive function to// return gcd of a and bfunction __gcd($a, $b){ // Everything divides 0 if($a == 0 or $b == 0) return 0 ; // base case if($a == $b) return $a ; // a is greater if($a > $b) return __gcd($a - $b , $b ) ; return __gcd($a , $b - $a) ;} // Print the maximum side and no of cube.function maximizecube($l, $b, $h){ // GCD to find side. $side = __gcd($l, __gcd($b, $h)); // dividing to find number of cubes. $num = $l / $side; $num = ($num * $b / $side); $num = ($num * $h / $side); echo $side , \" \" , $num ;} // Driver code $l = 2; $b = 4; $h = 6; maximizecube($l, $b, $h); // This code is contributed by anuj_67.?>",
"e": 31112,
"s": 30306,
"text": null
},
{
"code": "<script> // JavaScript program for Divide cuboid into cubes// such that sum of volumes is maximum function gcd(m, n) { if(n == 0) return m; else if(n > m) return gcd(n,m); else return gcd(n, m % n); } // Print the maximum side and no // of cube. function maximizecube(l, b, h) { // GCD to find side. let side = gcd(l, gcd(b, h)); // dividing to find number of cubes. let num = l / side; num = (num * b / side); num = (num * h / side); document.write( side + \" \" + num); } // Driver code let l = 2, b = 4, h = 6; maximizecube(l, b, h); // This code is contributed by sanjoy_62.</script>",
"e": 31896,
"s": 31112,
"text": null
},
{
"code": null,
"e": 31906,
"s": 31896,
"text": "Output: "
},
{
"code": null,
"e": 31910,
"s": 31906,
"text": "2 6"
},
{
"code": null,
"e": 31917,
"s": 31912,
"text": "vt_m"
},
{
"code": null,
"e": 31927,
"s": 31917,
"text": "sanjoy_62"
},
{
"code": null,
"e": 31948,
"s": 31927,
"text": "area-volume-programs"
},
{
"code": null,
"e": 31958,
"s": 31948,
"text": "Geometric"
},
{
"code": null,
"e": 31965,
"s": 31958,
"text": "Greedy"
},
{
"code": null,
"e": 31972,
"s": 31965,
"text": "Greedy"
},
{
"code": null,
"e": 31982,
"s": 31972,
"text": "Geometric"
},
{
"code": null,
"e": 32080,
"s": 31982,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32129,
"s": 32080,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 32182,
"s": 32129,
"text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)"
},
{
"code": null,
"e": 32233,
"s": 32182,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 32267,
"s": 32233,
"text": "Convex Hull | Set 2 (Graham Scan)"
},
{
"code": null,
"e": 32320,
"s": 32267,
"text": "Optimum location of point to minimize total distance"
},
{
"code": null,
"e": 32371,
"s": 32320,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 32422,
"s": 32371,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 32480,
"s": 32422,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 32507,
"s": 32480,
"text": "Program for array rotation"
}
] |
Node.js fs.appendFile() Function - GeeksforGeeks
|
08 Oct, 2021
The fs.appendFile() method is used to asynchronously append the given data to a file. A new file is created if it does not exist. The options parameter can be used to modify the behavior of the operation.
Syntax:
fs.appendFile( path, data[, options], callback )
Parameters: This method accepts four parameters as mentioned above and described below:
path: It is a String, Buffer, URL or number that denotes the source filename or file descriptor that will be appended to.
data: It is a String or Buffer that denotes the data that has to be appended.
options: It is an string or an object that can be used to specify optional parameters that will affect the output. It has three optional parameters:encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer which specifies the file mode. The default value is ‘0o666’.flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’.
encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.
mode: It is an integer which specifies the file mode. The default value is ‘0o666’.
flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’.
callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails.
err: It is an error that would be thrown if the method fails.
Below examples illustrate the fs.appendFile() method in Node.js:
Example 1: This example shows the appending of the given text to a file.
// Node.js program to demonstrate the// fs.appendFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log("\nFile Contents of file before append:", fs.readFileSync("example_file.txt", "utf8")); fs.appendFile("example_file.txt", "World", (err) => { if (err) { console.log(err); } else { // Get the file contents after the append operation console.log("\nFile Contents of file after append:", fs.readFileSync("example_file.txt", "utf8")); }});
Output:
File Contents of file before append: Hello
File Contents of file after append: HelloWorld
Example 2: This example shows the usage of the optional parameters to change the file encoding, mode, and flag of the operation.
// Node.js program to demonstrate the// fs.appendFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log("\nFile Contents of file before append:", fs.readFileSync("example_file.txt", "utf8")); fs.appendFile("example_file.txt", " - GeeksForGeeks", { encoding: "latin1", mode: 0o666, flag: "a" }, (err) => { if (err) { console.log(err); } else { // Get the file contents after the append operation console.log("\nFile Contents of file after append:", fs.readFileSync("example_file.txt", "utf8")); } });
Output:
File Contents of file before append: This is a test file
File Contents of file after append: This is a test file - GeeksForGeeks
Reference: https://nodejs.org/api/fs.html#fs_fs_appendfile_path_data_options_callback
Node.js-fs-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
How to use an ES6 import in Node.js?
How to read and write Excel file in Node.js ?
Express.js res.render() Function
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25869,
"s": 25841,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 26074,
"s": 25869,
"text": "The fs.appendFile() method is used to asynchronously append the given data to a file. A new file is created if it does not exist. The options parameter can be used to modify the behavior of the operation."
},
{
"code": null,
"e": 26082,
"s": 26074,
"text": "Syntax:"
},
{
"code": null,
"e": 26131,
"s": 26082,
"text": "fs.appendFile( path, data[, options], callback )"
},
{
"code": null,
"e": 26219,
"s": 26131,
"text": "Parameters: This method accepts four parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26341,
"s": 26219,
"text": "path: It is a String, Buffer, URL or number that denotes the source filename or file descriptor that will be appended to."
},
{
"code": null,
"e": 26419,
"s": 26341,
"text": "data: It is a String or Buffer that denotes the data that has to be appended."
},
{
"code": null,
"e": 26851,
"s": 26419,
"text": "options: It is an string or an object that can be used to specify optional parameters that will affect the output. It has three optional parameters:encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer which specifies the file mode. The default value is ‘0o666’.flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’."
},
{
"code": null,
"e": 26947,
"s": 26851,
"text": "encoding: It is a string which specifies the encoding of the file. The default value is ‘utf8’."
},
{
"code": null,
"e": 27031,
"s": 26947,
"text": "mode: It is an integer which specifies the file mode. The default value is ‘0o666’."
},
{
"code": null,
"e": 27137,
"s": 27031,
"text": "flag: It is a string which specifies the flag used while appending to the file. The default value is ‘a’."
},
{
"code": null,
"e": 27275,
"s": 27137,
"text": "callback: It is a function that would be called when the method is executed.err: It is an error that would be thrown if the method fails."
},
{
"code": null,
"e": 27337,
"s": 27275,
"text": "err: It is an error that would be thrown if the method fails."
},
{
"code": null,
"e": 27402,
"s": 27337,
"text": "Below examples illustrate the fs.appendFile() method in Node.js:"
},
{
"code": null,
"e": 27475,
"s": 27402,
"text": "Example 1: This example shows the appending of the given text to a file."
},
{
"code": "// Node.js program to demonstrate the// fs.appendFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log(\"\\nFile Contents of file before append:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); fs.appendFile(\"example_file.txt\", \"World\", (err) => { if (err) { console.log(err); } else { // Get the file contents after the append operation console.log(\"\\nFile Contents of file after append:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); }});",
"e": 28017,
"s": 27475,
"text": null
},
{
"code": null,
"e": 28025,
"s": 28017,
"text": "Output:"
},
{
"code": null,
"e": 28117,
"s": 28025,
"text": "File Contents of file before append: Hello\n\nFile Contents of file after append: HelloWorld\n"
},
{
"code": null,
"e": 28246,
"s": 28117,
"text": "Example 2: This example shows the usage of the optional parameters to change the file encoding, mode, and flag of the operation."
},
{
"code": "// Node.js program to demonstrate the// fs.appendFile() method // Import the filesystem moduleconst fs = require('fs'); // Get the file contents before the append operationconsole.log(\"\\nFile Contents of file before append:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); fs.appendFile(\"example_file.txt\", \" - GeeksForGeeks\", { encoding: \"latin1\", mode: 0o666, flag: \"a\" }, (err) => { if (err) { console.log(err); } else { // Get the file contents after the append operation console.log(\"\\nFile Contents of file after append:\", fs.readFileSync(\"example_file.txt\", \"utf8\")); } });",
"e": 28869,
"s": 28246,
"text": null
},
{
"code": null,
"e": 28877,
"s": 28869,
"text": "Output:"
},
{
"code": null,
"e": 29008,
"s": 28877,
"text": "File Contents of file before append: This is a test file\n\nFile Contents of file after append: This is a test file - GeeksForGeeks\n"
},
{
"code": null,
"e": 29094,
"s": 29008,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_appendfile_path_data_options_callback"
},
{
"code": null,
"e": 29112,
"s": 29094,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 29120,
"s": 29112,
"text": "Node.js"
},
{
"code": null,
"e": 29137,
"s": 29120,
"text": "Web Technologies"
},
{
"code": null,
"e": 29235,
"s": 29137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29292,
"s": 29235,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 29346,
"s": 29292,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 29383,
"s": 29346,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 29429,
"s": 29383,
"text": "How to read and write Excel file in Node.js ?"
},
{
"code": null,
"e": 29462,
"s": 29429,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 29502,
"s": 29462,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29547,
"s": 29502,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29590,
"s": 29547,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29640,
"s": 29590,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to annotate a plot in ggplot2 in R ? - GeeksforGeeks
|
29 Jun, 2021
In this article, we will discuss how to annotate plots in ggplot2 in R Programming Language.
An annotation can help the readability of a plot. It allows adding text to a plot or highlight a specific portion of the curve. The most common form of annotation is text. Let us first plot a regular plot without any annotation so that the difference is apparent.
This allows annotating only text to a plot. This function along with the required parameters is added to the plot.
Syntax:
geom_text(data, x, y, label)
Parameter:
data: dataframe in consideration
x: x coordinate of text
y: y coordinate of text
label: text
To annotate using this function, first, a dataframe of the values is created and then the values to geom_title() are passed with reference to the dataframe so created.
Example:
R
library("ggplot2") x<-c(1, 2, 3, 4, 5)y<-c(10, 30, 20, 40, 35) df<-data.frame(x, y) ann_text<-data.frame( x = 4, y = 20, label = "geeks for geeks") ggplot(df, aes(x,y))+geom_line()+geom_text(data = ann_text, aes( x=x, y=y, label=label), color="green", size=5)
Output:
This function is used to add labels i.e. text is framed in the plot, but since it does the job of adding an annotation this can be considered as one alternative.
Syntax:
geom_text(data, x, y, label)
Parameter:
data: dataframe in consideration
x: x coordinate of text
y: y coordinate of text
label: text
This method is similar to the above one, except the output produced for this will be treated as a label instead of a regular text, and will have a boundary around it.
Example:
R
library("ggplot2") x<-c(1, 2, 3, 4, 5)y<-c(10, 30, 20, 40, 35) df<-data.frame(x, y) ann_text<-data.frame( x = 4, y = 20, label="geeks for geeks") ggplot(df,aes(x,y))+geom_line()+geom_label(data = ann_text, aes( x = x, y = y, label=label), color="green", size=5)
Output:
annotate() function is most the commonly used function to add annotations to a plot. This not only allows text but also shapes to be displayed on the plot.
Syntax:
annotate(type, x, y,)
Parameter:
type: type of annotation
x: x coordinate
y: y coordinate
To annotate a text to the plot pass the “text” as type and in the label argument, pass the text to be annotated.
Example:
R
library("ggplot2") x<-c(1, 2, 3, 4, 5)y<-c(10, 30, 20, 40, 35) df<-data.frame(x,y) ggplot(df,aes(x,y))+geom_line()+annotate( "text", x=3.5, y=20, label="geeks for geeks", color="green", size=5)
Output:
To annotate a shape to the plot, the type argument is passed with the required type and then coordinates are set accordingly.
Example:
R
library("ggplot2") x<-c(1,2,3,4,5)y<-c(10,30,20,40,35) df<-data.frame(x,y) ggplot(df,aes(x,y))+geom_line()+annotate( "segment", x=2, xend=4.5, y=10,yend=25, color="green", arrow=arrow())
Output:
Picked
R-ggplot
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
R - if statement
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n29 Jun, 2021"
},
{
"code": null,
"e": 26581,
"s": 26487,
"text": "In this article, we will discuss how to annotate plots in ggplot2 in R Programming Language. "
},
{
"code": null,
"e": 26845,
"s": 26581,
"text": "An annotation can help the readability of a plot. It allows adding text to a plot or highlight a specific portion of the curve. The most common form of annotation is text. Let us first plot a regular plot without any annotation so that the difference is apparent."
},
{
"code": null,
"e": 26960,
"s": 26845,
"text": "This allows annotating only text to a plot. This function along with the required parameters is added to the plot."
},
{
"code": null,
"e": 26968,
"s": 26960,
"text": "Syntax:"
},
{
"code": null,
"e": 26997,
"s": 26968,
"text": "geom_text(data, x, y, label)"
},
{
"code": null,
"e": 27008,
"s": 26997,
"text": "Parameter:"
},
{
"code": null,
"e": 27041,
"s": 27008,
"text": "data: dataframe in consideration"
},
{
"code": null,
"e": 27065,
"s": 27041,
"text": "x: x coordinate of text"
},
{
"code": null,
"e": 27089,
"s": 27065,
"text": "y: y coordinate of text"
},
{
"code": null,
"e": 27101,
"s": 27089,
"text": "label: text"
},
{
"code": null,
"e": 27269,
"s": 27101,
"text": "To annotate using this function, first, a dataframe of the values is created and then the values to geom_title() are passed with reference to the dataframe so created."
},
{
"code": null,
"e": 27278,
"s": 27269,
"text": "Example:"
},
{
"code": null,
"e": 27280,
"s": 27278,
"text": "R"
},
{
"code": "library(\"ggplot2\") x<-c(1, 2, 3, 4, 5)y<-c(10, 30, 20, 40, 35) df<-data.frame(x, y) ann_text<-data.frame( x = 4, y = 20, label = \"geeks for geeks\") ggplot(df, aes(x,y))+geom_line()+geom_text(data = ann_text, aes( x=x, y=y, label=label), color=\"green\", size=5)",
"e": 27569,
"s": 27280,
"text": null
},
{
"code": null,
"e": 27577,
"s": 27569,
"text": "Output:"
},
{
"code": null,
"e": 27739,
"s": 27577,
"text": "This function is used to add labels i.e. text is framed in the plot, but since it does the job of adding an annotation this can be considered as one alternative."
},
{
"code": null,
"e": 27747,
"s": 27739,
"text": "Syntax:"
},
{
"code": null,
"e": 27776,
"s": 27747,
"text": "geom_text(data, x, y, label)"
},
{
"code": null,
"e": 27787,
"s": 27776,
"text": "Parameter:"
},
{
"code": null,
"e": 27820,
"s": 27787,
"text": "data: dataframe in consideration"
},
{
"code": null,
"e": 27844,
"s": 27820,
"text": "x: x coordinate of text"
},
{
"code": null,
"e": 27868,
"s": 27844,
"text": "y: y coordinate of text"
},
{
"code": null,
"e": 27880,
"s": 27868,
"text": "label: text"
},
{
"code": null,
"e": 28047,
"s": 27880,
"text": "This method is similar to the above one, except the output produced for this will be treated as a label instead of a regular text, and will have a boundary around it."
},
{
"code": null,
"e": 28056,
"s": 28047,
"text": "Example:"
},
{
"code": null,
"e": 28058,
"s": 28056,
"text": "R"
},
{
"code": "library(\"ggplot2\") x<-c(1, 2, 3, 4, 5)y<-c(10, 30, 20, 40, 35) df<-data.frame(x, y) ann_text<-data.frame( x = 4, y = 20, label=\"geeks for geeks\") ggplot(df,aes(x,y))+geom_line()+geom_label(data = ann_text, aes( x = x, y = y, label=label), color=\"green\", size=5)",
"e": 28350,
"s": 28058,
"text": null
},
{
"code": null,
"e": 28358,
"s": 28350,
"text": "Output:"
},
{
"code": null,
"e": 28514,
"s": 28358,
"text": "annotate() function is most the commonly used function to add annotations to a plot. This not only allows text but also shapes to be displayed on the plot."
},
{
"code": null,
"e": 28522,
"s": 28514,
"text": "Syntax:"
},
{
"code": null,
"e": 28544,
"s": 28522,
"text": "annotate(type, x, y,)"
},
{
"code": null,
"e": 28555,
"s": 28544,
"text": "Parameter:"
},
{
"code": null,
"e": 28580,
"s": 28555,
"text": "type: type of annotation"
},
{
"code": null,
"e": 28596,
"s": 28580,
"text": "x: x coordinate"
},
{
"code": null,
"e": 28612,
"s": 28596,
"text": "y: y coordinate"
},
{
"code": null,
"e": 28725,
"s": 28612,
"text": "To annotate a text to the plot pass the “text” as type and in the label argument, pass the text to be annotated."
},
{
"code": null,
"e": 28734,
"s": 28725,
"text": "Example:"
},
{
"code": null,
"e": 28736,
"s": 28734,
"text": "R"
},
{
"code": "library(\"ggplot2\") x<-c(1, 2, 3, 4, 5)y<-c(10, 30, 20, 40, 35) df<-data.frame(x,y) ggplot(df,aes(x,y))+geom_line()+annotate( \"text\", x=3.5, y=20, label=\"geeks for geeks\", color=\"green\", size=5)",
"e": 28937,
"s": 28736,
"text": null
},
{
"code": null,
"e": 28945,
"s": 28937,
"text": "Output:"
},
{
"code": null,
"e": 29071,
"s": 28945,
"text": "To annotate a shape to the plot, the type argument is passed with the required type and then coordinates are set accordingly."
},
{
"code": null,
"e": 29080,
"s": 29071,
"text": "Example:"
},
{
"code": null,
"e": 29082,
"s": 29080,
"text": "R"
},
{
"code": "library(\"ggplot2\") x<-c(1,2,3,4,5)y<-c(10,30,20,40,35) df<-data.frame(x,y) ggplot(df,aes(x,y))+geom_line()+annotate( \"segment\", x=2, xend=4.5, y=10,yend=25, color=\"green\", arrow=arrow())",
"e": 29277,
"s": 29082,
"text": null
},
{
"code": null,
"e": 29285,
"s": 29277,
"text": "Output:"
},
{
"code": null,
"e": 29292,
"s": 29285,
"text": "Picked"
},
{
"code": null,
"e": 29301,
"s": 29292,
"text": "R-ggplot"
},
{
"code": null,
"e": 29312,
"s": 29301,
"text": "R Language"
},
{
"code": null,
"e": 29410,
"s": 29312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29462,
"s": 29410,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29497,
"s": 29462,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 29535,
"s": 29497,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 29593,
"s": 29535,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 29636,
"s": 29593,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 29685,
"s": 29636,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 29722,
"s": 29685,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 29748,
"s": 29722,
"text": "Time Series Analysis in R"
},
{
"code": null,
"e": 29765,
"s": 29748,
"text": "R - if statement"
}
] |
count_if() in C++ STL - GeeksforGeeks
|
31 May, 2021
count_if() function returns the number of elements in a range that satisfy the condition.
Syntax:
template <class InputT, class UnaryPredicate>
typename iterator_traits <InputT> :: difference_type
count_if(InputT first, InputT last, UnaryPredicate p);
Examples:
Input: 0 1 2 3 4 5 6 7 8 9
Output: Total no of even numbers is: 5
Input: 2 3 4 5 6 7 8 9 10 11 12 13
Output: Total no of even numbers is: 6
The count_if function takes three parameters, the first two of which are the first and the last position of the sequence of the elements (where the last position is not included in the range) while the third parameter is an unary predicate ( takes single argument to check the condition and returns true or false ) that takes the element of given sequence one by one as a parameter and returns a boolean value on the basis of condition specified in that function. One thing we should keep in mind is that type of the predicate should be same as the type of the container.
Then, count_if() returns the number of elements in the given sequence for which the comparator function (third parameter) returns true.
CPP
// C++ program to show the working// of count_if()#include <bits/stdc++.h>using namespace std; // Function to check the// number is even or oddbool isEven(int i){ if (i % 2 == 0) return true; else return false;} // Drivers codeint main(){ vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } int noEven = count_if(v.begin(), v.end(), isEven); cout << "Total no of even numbers is: " << noEven; return 0;}
Total no of even numbers is: 5
sohamdas8697
CPP-Functions
STL
C++
C++ Programs
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Inheritance in C++
Map in C++ Standard Template Library (STL)
Bitwise Operators in C/C++
C++ Classes and Objects
Virtual Function in C++
Header files in C/C++ and its uses
Program to print ASCII Value of a character
C++ Program for QuickSort
Sorting a Map by value in C++ STL
Shallow Copy and Deep Copy in C++
|
[
{
"code": null,
"e": 25873,
"s": 25845,
"text": "\n31 May, 2021"
},
{
"code": null,
"e": 25963,
"s": 25873,
"text": "count_if() function returns the number of elements in a range that satisfy the condition."
},
{
"code": null,
"e": 25972,
"s": 25963,
"text": "Syntax: "
},
{
"code": null,
"e": 26130,
"s": 25972,
"text": "template <class InputT, class UnaryPredicate>\ntypename iterator_traits <InputT> :: difference_type\n count_if(InputT first, InputT last, UnaryPredicate p);"
},
{
"code": null,
"e": 26142,
"s": 26130,
"text": "Examples: "
},
{
"code": null,
"e": 26283,
"s": 26142,
"text": "Input: 0 1 2 3 4 5 6 7 8 9\nOutput: Total no of even numbers is: 5\n\nInput: 2 3 4 5 6 7 8 9 10 11 12 13\nOutput: Total no of even numbers is: 6"
},
{
"code": null,
"e": 26857,
"s": 26283,
"text": "The count_if function takes three parameters, the first two of which are the first and the last position of the sequence of the elements (where the last position is not included in the range) while the third parameter is an unary predicate ( takes single argument to check the condition and returns true or false ) that takes the element of given sequence one by one as a parameter and returns a boolean value on the basis of condition specified in that function. One thing we should keep in mind is that type of the predicate should be same as the type of the container. "
},
{
"code": null,
"e": 26994,
"s": 26857,
"text": "Then, count_if() returns the number of elements in the given sequence for which the comparator function (third parameter) returns true. "
},
{
"code": null,
"e": 26998,
"s": 26994,
"text": "CPP"
},
{
"code": "// C++ program to show the working// of count_if()#include <bits/stdc++.h>using namespace std; // Function to check the// number is even or oddbool isEven(int i){ if (i % 2 == 0) return true; else return false;} // Drivers codeint main(){ vector<int> v; for (int i = 0; i < 10; i++) { v.push_back(i); } int noEven = count_if(v.begin(), v.end(), isEven); cout << \"Total no of even numbers is: \" << noEven; return 0;}",
"e": 27505,
"s": 26998,
"text": null
},
{
"code": null,
"e": 27536,
"s": 27505,
"text": "Total no of even numbers is: 5"
},
{
"code": null,
"e": 27551,
"s": 27538,
"text": "sohamdas8697"
},
{
"code": null,
"e": 27565,
"s": 27551,
"text": "CPP-Functions"
},
{
"code": null,
"e": 27569,
"s": 27565,
"text": "STL"
},
{
"code": null,
"e": 27573,
"s": 27569,
"text": "C++"
},
{
"code": null,
"e": 27586,
"s": 27573,
"text": "C++ Programs"
},
{
"code": null,
"e": 27590,
"s": 27586,
"text": "STL"
},
{
"code": null,
"e": 27594,
"s": 27590,
"text": "CPP"
},
{
"code": null,
"e": 27692,
"s": 27594,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27711,
"s": 27692,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 27754,
"s": 27711,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 27781,
"s": 27754,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 27805,
"s": 27781,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27829,
"s": 27805,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 27864,
"s": 27829,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 27908,
"s": 27864,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 27934,
"s": 27908,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 27968,
"s": 27934,
"text": "Sorting a Map by value in C++ STL"
}
] |
Python | FloatLayout in Kivy using .kv file - GeeksforGeeks
|
07 Jul, 2020
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
Kivy Tutorial – Learn Kivy with Examples.
Floatlayout provides us the flexibility to arrange the elements like button relatively i.e it allows us to place the elements using something called relative position. This means rather than defining the specific position or the coordinates we will place everything using the percentage w.r.t the size of window i.e we can dynamically arrange the position of the elements.
The first thing we need to do import FloatLayout –
from kivy.uix.floatlayout import FloatLayout
We have 2 properties to create the dynamic placement –
1) pos_hint: provide hint of positionWe can define upto 6 keys i.e. it takes arguments in form of dictionary.pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, “top”:1, “bottom”:1}
2) size_hint: provide hint of sizeContains two arguments i.e. width and height
Note:
You can only use values between 0-1 for both size_hint and pos_hint. Where 0 = 0% and 1 = 100%.
The coordinate system in kivy works from the bottom left! This will be important when placing our objects. (i.e (0, 0) is the bottom left).
Basic Approach:
1) import kivy
2) import kivyApp
3) import Floatlayout
4) Set minimum version(optional)
5) create Layout class
6) create App class
7) Set up .kv file
8) return Layout/widget/Class(according to requirement)
9) Run an instance of the class
Implementation of the approach –
## Sample Python application demonstrating the## working of FloatLayout in Kivy using .kv file #################################################### import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # module consist the floatlayout# to work with FloatLayout first# you have to import itfrom kivy.uix.floatlayout import FloatLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # creating the root widget used in .kv file class FloatLayout(FloatLayout): pass # creating the App class in which name#.kv file is to be named Float_Layout.kvclass Float_LayoutApp(App): # defining build() def build(self): # returning the instance of root class return FloatLayout() # run the appif __name__ == "__main__": Float_LayoutApp().run()
This file includes the dynamic placements of button i.e as the screen size changes the button adjust themselves relatively this is the benefit of the FloatLayout.
.kv file implementation of approach –
#.kv file implementation of FloatLayout # creating button feature<Button>: font_size: 40 # creating button # a button 30 % of the width and 50 % # of the height of the layout size_hint: 0.3, 0.3 <FloatLayout>: Button: text: "Helooo !!!!! " background_color: 0.1, 0.5, 0.6, 1 # positioned at 0 % right and 100 % up / top # from bottom left, i.e x, top = 0, 100 from bottom left: pos_hint: {"x":0, "top":1} Button: text:"Rajnish:)" background_color: 1, 0, 0, 1 pos_hint: {"x":0.35, "y":0.3} Button: text:"Ravi:)" background_color: 0.4, 0.5, 0.6, 1 pos_hint: {"x":.7, "bottom":0} Button: text:"Sanjeev:)" background_color: 0, 0, 1, 1 pos_hint: {"x":.7, "top":1} Button: text:"Suraj:)" background_color: 0.8, 0.9, 0.2, 1 pos_hint: {"x":0, "bottom":1}
Output:
Video Output:
shubham_singh
nidhi_biet
Python-gui
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n07 Jul, 2020"
},
{
"code": null,
"e": 25773,
"s": 25537,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux and Windows etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."
},
{
"code": null,
"e": 25816,
"s": 25773,
"text": " Kivy Tutorial – Learn Kivy with Examples."
},
{
"code": null,
"e": 26189,
"s": 25816,
"text": "Floatlayout provides us the flexibility to arrange the elements like button relatively i.e it allows us to place the elements using something called relative position. This means rather than defining the specific position or the coordinates we will place everything using the percentage w.r.t the size of window i.e we can dynamically arrange the position of the elements."
},
{
"code": null,
"e": 26240,
"s": 26189,
"text": "The first thing we need to do import FloatLayout –"
},
{
"code": null,
"e": 26285,
"s": 26240,
"text": "from kivy.uix.floatlayout import FloatLayout"
},
{
"code": null,
"e": 26340,
"s": 26285,
"text": "We have 2 properties to create the dynamic placement –"
},
{
"code": null,
"e": 26517,
"s": 26340,
"text": "1) pos_hint: provide hint of positionWe can define upto 6 keys i.e. it takes arguments in form of dictionary.pos_hint = {“x”:1, “y”:1, “left”:1, “right”:1, “top”:1, “bottom”:1}"
},
{
"code": null,
"e": 26596,
"s": 26517,
"text": "2) size_hint: provide hint of sizeContains two arguments i.e. width and height"
},
{
"code": null,
"e": 26602,
"s": 26596,
"text": "Note:"
},
{
"code": null,
"e": 26698,
"s": 26602,
"text": "You can only use values between 0-1 for both size_hint and pos_hint. Where 0 = 0% and 1 = 100%."
},
{
"code": null,
"e": 26838,
"s": 26698,
"text": "The coordinate system in kivy works from the bottom left! This will be important when placing our objects. (i.e (0, 0) is the bottom left)."
},
{
"code": null,
"e": 27093,
"s": 26838,
"text": "Basic Approach:\n\n1) import kivy\n2) import kivyApp\n3) import Floatlayout\n4) Set minimum version(optional)\n5) create Layout class\n6) create App class\n7) Set up .kv file\n8) return Layout/widget/Class(according to requirement)\n9) Run an instance of the class"
},
{
"code": null,
"e": 27127,
"s": 27093,
"text": " Implementation of the approach –"
},
{
"code": "## Sample Python application demonstrating the## working of FloatLayout in Kivy using .kv file #################################################### import modules import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # module consist the floatlayout# to work with FloatLayout first# you have to import itfrom kivy.uix.floatlayout import FloatLayout # To change the kivy default settings # we use this module config from kivy.config import Config # 0 being off 1 being on as in true / false # you can use 0 or 1 && True or False Config.set('graphics', 'resizable', True) # creating the root widget used in .kv file class FloatLayout(FloatLayout): pass # creating the App class in which name#.kv file is to be named Float_Layout.kvclass Float_LayoutApp(App): # defining build() def build(self): # returning the instance of root class return FloatLayout() # run the appif __name__ == \"__main__\": Float_LayoutApp().run()",
"e": 28179,
"s": 27127,
"text": null
},
{
"code": null,
"e": 28342,
"s": 28179,
"text": "This file includes the dynamic placements of button i.e as the screen size changes the button adjust themselves relatively this is the benefit of the FloatLayout."
},
{
"code": null,
"e": 28380,
"s": 28342,
"text": ".kv file implementation of approach –"
},
{
"code": "#.kv file implementation of FloatLayout # creating button feature<Button>: font_size: 40 # creating button # a button 30 % of the width and 50 % # of the height of the layout size_hint: 0.3, 0.3 <FloatLayout>: Button: text: \"Helooo !!!!! \" background_color: 0.1, 0.5, 0.6, 1 # positioned at 0 % right and 100 % up / top # from bottom left, i.e x, top = 0, 100 from bottom left: pos_hint: {\"x\":0, \"top\":1} Button: text:\"Rajnish:)\" background_color: 1, 0, 0, 1 pos_hint: {\"x\":0.35, \"y\":0.3} Button: text:\"Ravi:)\" background_color: 0.4, 0.5, 0.6, 1 pos_hint: {\"x\":.7, \"bottom\":0} Button: text:\"Sanjeev:)\" background_color: 0, 0, 1, 1 pos_hint: {\"x\":.7, \"top\":1} Button: text:\"Suraj:)\" background_color: 0.8, 0.9, 0.2, 1 pos_hint: {\"x\":0, \"bottom\":1}",
"e": 29311,
"s": 28380,
"text": null
},
{
"code": null,
"e": 29319,
"s": 29311,
"text": "Output:"
},
{
"code": null,
"e": 29333,
"s": 29319,
"text": "Video Output:"
},
{
"code": null,
"e": 29347,
"s": 29333,
"text": "shubham_singh"
},
{
"code": null,
"e": 29358,
"s": 29347,
"text": "nidhi_biet"
},
{
"code": null,
"e": 29369,
"s": 29358,
"text": "Python-gui"
},
{
"code": null,
"e": 29381,
"s": 29369,
"text": "Python-kivy"
},
{
"code": null,
"e": 29388,
"s": 29381,
"text": "Python"
},
{
"code": null,
"e": 29486,
"s": 29388,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29518,
"s": 29486,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29560,
"s": 29518,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29602,
"s": 29560,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29629,
"s": 29602,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29685,
"s": 29629,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29707,
"s": 29685,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 29746,
"s": 29707,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 29777,
"s": 29746,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29806,
"s": 29777,
"text": "Create a directory in Python"
}
] |
Python MySQL - Select Query - GeeksforGeeks
|
06 Mar, 2020
Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To connect with MySQL database server from Python, we need to import the mysql.connector module.
Below is a program to connect with MySQL database geeks.
# importing required library import mysql.connector # connecting to the database dataBase = mysql.connector.connect( host = "localhost", user = "user", passwd = "pswrd", database = "geeks" ) # preparing a cursor object cursorObject = dataBase.cursor() # disconnecting from serverdataBase.close()
The above program illustrates the connection with the MySQL database geeks in which host-name is localhost, the username is user and password is pswrd.
After connecting with the database in MySQL we can select queries from the tables in it.
Syntax:
In order to select particular attribute columns from a table, we write the attribute names.SELECT attr1, attr2 FROM table_name
SELECT attr1, attr2 FROM table_name
In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol.SELECT * FROM table_name
SELECT * FROM table_name
Example 1: Let’s consider the table looks like this –
Below is a program to select a query from the table in the database.
# importing required library import mysql.connector # connecting to the database dataBase = mysql.connector.connect( host = "localhost", user = "user", passwd = "pswrd", database = "geeks" ) # preparing a cursor object cursorObject = dataBase.cursor() print("Displaying NAME and ROLL columns from the STUDENT table:") # selecting queryquery = "SELECT NAME, ROLL FROM STUDENT"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()
Output:
Example 2: Let us look at another example for selecting queries in a table.
# importing required library import mysql.connector # connecting to the database dataBase = mysql.connector.connect( host = "localhost", user = "user", passwd = "pswrd", database = "geeks" ) # preparing a cursor object cursorObject = dataBase.cursor() print("Displaying NAME and ROLL columns from the STUDENT table:") # selecting queryquery = "SELECT * FROM STUDENT"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()
Output:
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
|
[
{
"code": null,
"e": 42651,
"s": 42623,
"text": "\n06 Mar, 2020"
},
{
"code": null,
"e": 43090,
"s": 42651,
"text": "Python Database API ( Application Program Interface ) is the Database interface for the standard Python. This standard is adhered to by most Python Database interfaces. There are various Database servers supported by Python Database such as MySQL, GadFly, mSQL, PostgreSQL, Microsoft SQL Server 2000, Informix, Interbase, Oracle, Sybase etc. To connect with MySQL database server from Python, we need to import the mysql.connector module."
},
{
"code": null,
"e": 43147,
"s": 43090,
"text": "Below is a program to connect with MySQL database geeks."
},
{
"code": "# importing required library import mysql.connector # connecting to the database dataBase = mysql.connector.connect( host = \"localhost\", user = \"user\", passwd = \"pswrd\", database = \"geeks\" ) # preparing a cursor object cursorObject = dataBase.cursor() # disconnecting from serverdataBase.close() ",
"e": 43529,
"s": 43147,
"text": null
},
{
"code": null,
"e": 43681,
"s": 43529,
"text": "The above program illustrates the connection with the MySQL database geeks in which host-name is localhost, the username is user and password is pswrd."
},
{
"code": null,
"e": 43770,
"s": 43681,
"text": "After connecting with the database in MySQL we can select queries from the tables in it."
},
{
"code": null,
"e": 43778,
"s": 43770,
"text": "Syntax:"
},
{
"code": null,
"e": 43905,
"s": 43778,
"text": "In order to select particular attribute columns from a table, we write the attribute names.SELECT attr1, attr2 FROM table_name"
},
{
"code": null,
"e": 43941,
"s": 43905,
"text": "SELECT attr1, attr2 FROM table_name"
},
{
"code": null,
"e": 44056,
"s": 43941,
"text": "In order to select all the attribute columns from a table, we use the asterisk ‘*’ symbol.SELECT * FROM table_name"
},
{
"code": null,
"e": 44081,
"s": 44056,
"text": "SELECT * FROM table_name"
},
{
"code": null,
"e": 44135,
"s": 44081,
"text": "Example 1: Let’s consider the table looks like this –"
},
{
"code": null,
"e": 44204,
"s": 44135,
"text": "Below is a program to select a query from the table in the database."
},
{
"code": "# importing required library import mysql.connector # connecting to the database dataBase = mysql.connector.connect( host = \"localhost\", user = \"user\", passwd = \"pswrd\", database = \"geeks\" ) # preparing a cursor object cursorObject = dataBase.cursor() print(\"Displaying NAME and ROLL columns from the STUDENT table:\") # selecting queryquery = \"SELECT NAME, ROLL FROM STUDENT\"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()",
"e": 44812,
"s": 44204,
"text": null
},
{
"code": null,
"e": 44820,
"s": 44812,
"text": "Output:"
},
{
"code": null,
"e": 44896,
"s": 44820,
"text": "Example 2: Let us look at another example for selecting queries in a table."
},
{
"code": "# importing required library import mysql.connector # connecting to the database dataBase = mysql.connector.connect( host = \"localhost\", user = \"user\", passwd = \"pswrd\", database = \"geeks\" ) # preparing a cursor object cursorObject = dataBase.cursor() print(\"Displaying NAME and ROLL columns from the STUDENT table:\") # selecting queryquery = \"SELECT * FROM STUDENT\"cursorObject.execute(query) myresult = cursorObject.fetchall() for x in myresult: print(x) # disconnecting from serverdataBase.close()",
"e": 45496,
"s": 44896,
"text": null
},
{
"code": null,
"e": 45504,
"s": 45496,
"text": "Output:"
},
{
"code": null,
"e": 45517,
"s": 45504,
"text": "Python-mySQL"
},
{
"code": null,
"e": 45524,
"s": 45517,
"text": "Python"
},
{
"code": null,
"e": 45622,
"s": 45524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45650,
"s": 45622,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 45700,
"s": 45650,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 45722,
"s": 45700,
"text": "Python map() function"
},
{
"code": null,
"e": 45766,
"s": 45722,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 45801,
"s": 45766,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 45833,
"s": 45801,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 45855,
"s": 45833,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 45897,
"s": 45855,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 45927,
"s": 45897,
"text": "Iterate over a list in Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.