title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Python Program for Column to Row Transpose using Pandas
|
20 Jan, 2022
Given an Input File, having columns Dept and Name, perform an operation to convert the column values to rows. Name contains pipe separated values that belong to a particular department identified by the column Dept.
Attached Dataset: emp_data
Examples:
Input:
dept, name
10, Vivek|John
20, Ritika|Shubham|Nitin
30, Vishakha|Ankit
Output:
dept, name
10, Vivek
10, John
20, Ritika
20, Shubham
20, Nitin
30, Vishakha
30, Ankit
Method 1: Pythonic Way
Python
# Reading Data From the text# filedata = pd.read_csv(r'GFG.txt') # create new data frame with # split value columns separates# data into three columns as per# separator mentionednew = data["name"].str.split("|",expand = True) # making separate first name column# from new data frame assign columnn# values to dataframe new columns# named as name*data["Name1"] = new[0]data["Name2"] = new[1]data["Name3"] = new[2] # Dropping old Name columns data.drop(columns =["name"], inplace = True) # create separate dataframes with two# columns id,named_name1 = data[['dept','Name1']]d_name2 = data[['dept','Name2']]d_name3 = data[['dept','Name3']] # perform concat/unions operation for# vertical merging of dataframesunion_df=pd.concat([d_name1,d_name2,d_name3],ignore_index=True)union_df.fillna('',inplace=True) # concatenate values of series into one# series "name"union_df['name'] = union_df['Name1'].astype(str)+union_df['Name2'].astype(str)+union_df['Name3'].astype(str) # drop column namesunion_df.drop(['Name1','Name2','Name3'],axis=1,inplace=True) # drop rows having empty valuesfinal_df=union_df[union_df['name']!=''] # sort the dataframe data by dept valuesfinal_df.sort_values('dept')
Output:
Note: Shortcoming of above method is when there are more than 3 names separated by |
Method 2: Exploring Pandas
Python
emp_df = pd.read_csv(r'GFG.txt') # split column data on basis of separator# convert it into list using to_list# stack method performs transpose operation# to the dataemp_df1 = pd.DataFrame(emp_df.name.str.split('|').to_list(), index = emp_df.dept).stack() emp_df1 = emp_df1.reset_index([0, 'dept'])emp_df1.columns =['Dept', 'Name'] emp_df1
Method 3: The Pandas way: explode()
Python
df = pd.read_csv(r'GFG.txt') # separate values using split()# transpose is performed by explode # function explode function overcomes # the method1 shortcomings incase we# have many columns we explode will do# the task in no time and with no hassledf1 = df.assign(name = df['name'].str.split('|')).explode('name')df1
Output:
sweetyty
simmytarika5
Python pandas-dataFrame
Python
Python Programs
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
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python Program for Fibonacci numbers
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jan, 2022"
},
{
"code": null,
"e": 244,
"s": 28,
"text": "Given an Input File, having columns Dept and Name, perform an operation to convert the column values to rows. Name contains pipe separated values that belong to a particular department identified by the column Dept."
},
{
"code": null,
"e": 271,
"s": 244,
"text": "Attached Dataset: emp_data"
},
{
"code": null,
"e": 281,
"s": 271,
"text": "Examples:"
},
{
"code": null,
"e": 454,
"s": 281,
"text": "Input:\ndept, name\n10, Vivek|John\n20, Ritika|Shubham|Nitin\n30, Vishakha|Ankit\n\nOutput:\ndept, name\n10, Vivek\n10, John\n20, Ritika\n20, Shubham\n20, Nitin\n30, Vishakha\n30, Ankit\n"
},
{
"code": null,
"e": 477,
"s": 454,
"text": "Method 1: Pythonic Way"
},
{
"code": null,
"e": 484,
"s": 477,
"text": "Python"
},
{
"code": "# Reading Data From the text# filedata = pd.read_csv(r'GFG.txt') # create new data frame with # split value columns separates# data into three columns as per# separator mentionednew = data[\"name\"].str.split(\"|\",expand = True) # making separate first name column# from new data frame assign columnn# values to dataframe new columns# named as name*data[\"Name1\"] = new[0]data[\"Name2\"] = new[1]data[\"Name3\"] = new[2] # Dropping old Name columns data.drop(columns =[\"name\"], inplace = True) # create separate dataframes with two# columns id,named_name1 = data[['dept','Name1']]d_name2 = data[['dept','Name2']]d_name3 = data[['dept','Name3']] # perform concat/unions operation for# vertical merging of dataframesunion_df=pd.concat([d_name1,d_name2,d_name3],ignore_index=True)union_df.fillna('',inplace=True) # concatenate values of series into one# series \"name\"union_df['name'] = union_df['Name1'].astype(str)+union_df['Name2'].astype(str)+union_df['Name3'].astype(str) # drop column namesunion_df.drop(['Name1','Name2','Name3'],axis=1,inplace=True) # drop rows having empty valuesfinal_df=union_df[union_df['name']!=''] # sort the dataframe data by dept valuesfinal_df.sort_values('dept')",
"e": 1685,
"s": 484,
"text": null
},
{
"code": null,
"e": 1693,
"s": 1685,
"text": "Output:"
},
{
"code": null,
"e": 1778,
"s": 1693,
"text": "Note: Shortcoming of above method is when there are more than 3 names separated by |"
},
{
"code": null,
"e": 1805,
"s": 1778,
"text": "Method 2: Exploring Pandas"
},
{
"code": null,
"e": 1812,
"s": 1805,
"text": "Python"
},
{
"code": "emp_df = pd.read_csv(r'GFG.txt') # split column data on basis of separator# convert it into list using to_list# stack method performs transpose operation# to the dataemp_df1 = pd.DataFrame(emp_df.name.str.split('|').to_list(), index = emp_df.dept).stack() emp_df1 = emp_df1.reset_index([0, 'dept'])emp_df1.columns =['Dept', 'Name'] emp_df1",
"e": 2177,
"s": 1812,
"text": null
},
{
"code": null,
"e": 2213,
"s": 2177,
"text": "Method 3: The Pandas way: explode()"
},
{
"code": null,
"e": 2220,
"s": 2213,
"text": "Python"
},
{
"code": "df = pd.read_csv(r'GFG.txt') # separate values using split()# transpose is performed by explode # function explode function overcomes # the method1 shortcomings incase we# have many columns we explode will do# the task in no time and with no hassledf1 = df.assign(name = df['name'].str.split('|')).explode('name')df1",
"e": 2538,
"s": 2220,
"text": null
},
{
"code": null,
"e": 2546,
"s": 2538,
"text": "Output:"
},
{
"code": null,
"e": 2555,
"s": 2546,
"text": "sweetyty"
},
{
"code": null,
"e": 2568,
"s": 2555,
"text": "simmytarika5"
},
{
"code": null,
"e": 2592,
"s": 2568,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2599,
"s": 2592,
"text": "Python"
},
{
"code": null,
"e": 2615,
"s": 2599,
"text": "Python Programs"
},
{
"code": null,
"e": 2713,
"s": 2615,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2745,
"s": 2713,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2772,
"s": 2745,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2793,
"s": 2772,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2816,
"s": 2793,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2872,
"s": 2816,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2894,
"s": 2872,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2933,
"s": 2894,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2971,
"s": 2933,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3008,
"s": 2971,
"text": "Python Program for Fibonacci numbers"
}
] |
Python β Append List every Nth index
|
11 Oct, 2020
Given 2 list, append list to the original list every nth index.
Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = [βGβ, βFβ, βGβ], N = 3 Output : [βGβ, βFβ, βGβ, 3, 7, 8, βGβ, βFβ, βGβ, 2, 1, 5, βGβ, βFβ, βGβ, 8] Explanation : List is added after every 3rd element.Input : test_list = [3, 7, 8, 2, 1, 5, 8, 9], app_list = [βGβ, βFβ, βGβ], N = 4 Output : [βGβ, βFβ, βGβ, 3, 7, 8, 2, βGβ, βFβ, βGβ, 1, 5, 8, 9 βGβ, βFβ, βGβ] Explanation : List is added after every 4th element.
Method #1 : Using loop
This is brute way to solve this problem, in this, every nth index, inner loop is used to append all other list elements.
Python3
# Python3 code to demonstrate working of # Append List every Nth index# Using loop # initializing listtest_list = [3, 7, 8, 2, 1, 5, 8, 9, 3] # printing original listprint("The original list is : " + str(test_list)) # initializing Append list app_list = ['G', 'F', 'G'] # initializing N N = 3 res = []for idx, ele in enumerate(test_list): # if index multiple of N if idx % N == 0: for ele_in in app_list: res.append(ele_in) res.append(ele) # printing result print("The appended list : " + str(res))
Output:
The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]The appended list : [βGβ, βFβ, βGβ, 3, 7, 8, βGβ, βFβ, βGβ, 2, 1, 5, βGβ, βFβ, βGβ, 8, 9, 3]
Method #2 : Using extend()
Another way to solve this problem. In this, we use extend to get all the elements in every Nth index, rather than inner list.
Python3
# Python3 code to demonstrate working of # Append List every Nth index# Using extend() # initializing listtest_list = [3, 7, 8, 2, 1, 5, 8, 9, 3] # printing original listprint("The original list is : " + str(test_list)) # initializing Append list app_list = ['G', 'F', 'G'] # initializing N N = 3 res = []for idx, ele in enumerate(test_list): # if index multiple of N if idx % N == 0: # extend to append all elements res.extend(app_list) res.append(ele) # printing result print("The appended list : " + str(res))
Output:
The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]The appended list : [βGβ, βFβ, βGβ, 3, 7, 8, βGβ, βFβ, βGβ, 2, 1, 5, βGβ, βFβ, βGβ, 8, 9, 3]
Python list-programs
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": 92,
"s": 28,
"text": "Given 2 list, append list to the original list every nth index."
},
{
"code": null,
"e": 510,
"s": 92,
"text": "Input : test_list = [3, 7, 8, 2, 1, 5, 8], app_list = [βGβ, βFβ, βGβ], N = 3 Output : [βGβ, βFβ, βGβ, 3, 7, 8, βGβ, βFβ, βGβ, 2, 1, 5, βGβ, βFβ, βGβ, 8] Explanation : List is added after every 3rd element.Input : test_list = [3, 7, 8, 2, 1, 5, 8, 9], app_list = [βGβ, βFβ, βGβ], N = 4 Output : [βGβ, βFβ, βGβ, 3, 7, 8, 2, βGβ, βFβ, βGβ, 1, 5, 8, 9 βGβ, βFβ, βGβ] Explanation : List is added after every 4th element. "
},
{
"code": null,
"e": 533,
"s": 510,
"text": "Method #1 : Using loop"
},
{
"code": null,
"e": 654,
"s": 533,
"text": "This is brute way to solve this problem, in this, every nth index, inner loop is used to append all other list elements."
},
{
"code": null,
"e": 662,
"s": 654,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Append List every Nth index# Using loop # initializing listtest_list = [3, 7, 8, 2, 1, 5, 8, 9, 3] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing Append list app_list = ['G', 'F', 'G'] # initializing N N = 3 res = []for idx, ele in enumerate(test_list): # if index multiple of N if idx % N == 0: for ele_in in app_list: res.append(ele_in) res.append(ele) # printing result print(\"The appended list : \" + str(res))",
"e": 1200,
"s": 662,
"text": null
},
{
"code": null,
"e": 1208,
"s": 1200,
"text": "Output:"
},
{
"code": null,
"e": 1351,
"s": 1208,
"text": "The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]The appended list : [βGβ, βFβ, βGβ, 3, 7, 8, βGβ, βFβ, βGβ, 2, 1, 5, βGβ, βFβ, βGβ, 8, 9, 3]"
},
{
"code": null,
"e": 1378,
"s": 1351,
"text": "Method #2 : Using extend()"
},
{
"code": null,
"e": 1504,
"s": 1378,
"text": "Another way to solve this problem. In this, we use extend to get all the elements in every Nth index, rather than inner list."
},
{
"code": null,
"e": 1512,
"s": 1504,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Append List every Nth index# Using extend() # initializing listtest_list = [3, 7, 8, 2, 1, 5, 8, 9, 3] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing Append list app_list = ['G', 'F', 'G'] # initializing N N = 3 res = []for idx, ele in enumerate(test_list): # if index multiple of N if idx % N == 0: # extend to append all elements res.extend(app_list) res.append(ele) # printing result print(\"The appended list : \" + str(res))",
"e": 2080,
"s": 1512,
"text": null
},
{
"code": null,
"e": 2088,
"s": 2080,
"text": "Output:"
},
{
"code": null,
"e": 2231,
"s": 2088,
"text": "The original list is : [3, 7, 8, 2, 1, 5, 8, 9, 3]The appended list : [βGβ, βFβ, βGβ, 3, 7, 8, βGβ, βFβ, βGβ, 2, 1, 5, βGβ, βFβ, βGβ, 8, 9, 3]"
},
{
"code": null,
"e": 2252,
"s": 2231,
"text": "Python list-programs"
},
{
"code": null,
"e": 2259,
"s": 2252,
"text": "Python"
}
] |
Python program to count occurrences of a word in a string
|
In this tutorial, we are going to write a program that counts the number of times a word occurs in the string. You are given the word and a string, we have to calculate the frequency of the word in the string.
Suppose we have a string I am a programmer. I am a student. And the word is. The program that we are going to write will return a number 2 as the word occurs two times in the string.
Let's follow the below steps to achieve our goal.
1. Initialize the string and the word as two variables.
2. Split the string at spaces using the split() method. We will get a list of words.
3. Initialize a variable count to zero.
4. Iterate over the list.
4.1. Check whether the word in the list is equal to the given the word or not.
4.1.1. Increment the count if the two words are matched.
5. Print the count.
Try to write the code for the program on your own first. Let's see the code.
## initializing the string and the word
string = "I am programmer. I am student."
word = "am"
## splitting the string at space
words = string.split()
## initializing count variable to 0
count = 0
## iterating over the list
for w in words:
## checking the match of the words
if w == word:
## incrementint count on match
count += 1
## printing the count
print(count)
If you run the above program, you will get the following results.
2
If you have any doubts regarding the program, ask them in the comment section.
|
[
{
"code": null,
"e": 1397,
"s": 1187,
"text": "In this tutorial, we are going to write a program that counts the number of times a word occurs in the string. You are given the word and a string, we have to calculate the frequency of the word in the string."
},
{
"code": null,
"e": 1580,
"s": 1397,
"text": "Suppose we have a string I am a programmer. I am a student. And the word is. The program that we are going to write will return a number 2 as the word occurs two times in the string."
},
{
"code": null,
"e": 1630,
"s": 1580,
"text": "Let's follow the below steps to achieve our goal."
},
{
"code": null,
"e": 1993,
"s": 1630,
"text": "1. Initialize the string and the word as two variables.\n2. Split the string at spaces using the split() method. We will get a list of words.\n3. Initialize a variable count to zero.\n4. Iterate over the list.\n4.1. Check whether the word in the list is equal to the given the word or not.\n4.1.1. Increment the count if the two words are matched.\n5. Print the count."
},
{
"code": null,
"e": 2070,
"s": 1993,
"text": "Try to write the code for the program on your own first. Let's see the code."
},
{
"code": null,
"e": 2453,
"s": 2070,
"text": "## initializing the string and the word\nstring = \"I am programmer. I am student.\"\nword = \"am\"\n## splitting the string at space\nwords = string.split()\n## initializing count variable to 0\ncount = 0\n## iterating over the list\nfor w in words:\n ## checking the match of the words\n if w == word:\n ## incrementint count on match\n count += 1\n## printing the count\nprint(count)"
},
{
"code": null,
"e": 2519,
"s": 2453,
"text": "If you run the above program, you will get the following results."
},
{
"code": null,
"e": 2521,
"s": 2519,
"text": "2"
},
{
"code": null,
"e": 2600,
"s": 2521,
"text": "If you have any doubts regarding the program, ask them in the comment section."
}
] |
Lottie Animation in Android Jetpack Compose
|
17 Aug, 2021
Lottie is a great library to add animated files into your app. Two days ago Jetpack compose went stable and also Lottie supports Compose. In this article, we are going to see how to add Lottie animations in compose app.
We will build a simple app showing Lottie animation with a pause/play and an increase/decrease speed button. A sample GIF is given below to get an idea about what we are going to do in this article.
Prerequisites:
Knowledge of Android.
Good knowledge of Jetpack compose.
Step 1: Create a New Project (Or use it in the existing Compose project)
Open Android Studio( Must be of the latest version (>=2020.3.1).
Click on New Project > Empty Compose Activity.
Then write the Application name and package name according to your choice and click finish. Wait for Gradle build to finish.
Step 2: Adding Dependencies
Open build.gradle(app) and add the following dependency.
implementation βcom.airbnb.android:lottie-compose:4.0.0β
Step 3: Downloading the Lottie file and placing it in the project
Right-click on the res > new > Android resource Directory.
Type raw to create a raw folder
Now head over to Lottie to download your favorite animation or use this articleβs one (download it from here). After downloading drag and drop it to the raw folder.
Step 4: Working with Lottie Animation
Create a composable function LottieExample().
Kotlin
@Composablefun LottieExample() { // codes to be added here}
We need to create Lottieβs composition and progress state. Add the following code in the same composable, refer to the comments for explanation.
Note: Make sure to (if Android Studio doesnβt do it automatically) import androidx.compose.runtime.*
Create a state to hold speed and play/pause state. Add the following code in the function
Kotlin
// to keep track if the animation is playing// and play pause accordinglyvar isPlaying by remember { mutableStateOf(true) } // for speedvar speed by remember { mutableStateOf(1f) }
Kotlin
// remember lottie composition, which// accepts the lottie composition resultval composition by rememberLottieComposition( LottieCompositionSpec // here `code` is the file name of lottie file // use it accordingly .RawRes(R.raw.code) ) // to control the animation val progress by animateLottieCompositionAsState( // pass the composition created above composition, // Iterates Forever iterations = LottieConstants.IterateForever, // pass isPlaying we created above, // changing isPlaying will recompose // Lottie and pause/play isPlaying = isPlaying, // pass speed we created above, // changing speed will increase Lottie speed = speed, // this makes animation to restart // when paused and play // pass false to continue the animation // at which is was paused restartOnPlay = false )
Now we need to create Buttons and lay down the Lottie composable. Add the following code in the same composable function. These are basic Columns, Rows, Buttons, and text composable. Refer to this for more information.
Kotlin
// Column ComposableColumn( Modifier .background(Color.White) .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // Heading Text( text = "Lottie", color = Color.Gray, fontSize = 70.sp, fontWeight = FontWeight.SemiBold, fontStyle = FontStyle.Italic, modifier = Modifier.padding(10.dp) ) // LottieAnimation // Pass the composition // and the progress state LottieAnimation( composition, progress, modifier = Modifier.size(400.dp) ) // Buttons to control the animation Row( horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { // Button to decrease speed Button( onClick = { // check to prevent speed going negative speed = max(speed - 0.25f, 0f) }, // Button background color colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = "-", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp, ) } // Button to Increase speed Text( text = "Speed ( $speed ) ", color = Color.Black, fontWeight = FontWeight.Bold, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp) ) Button( onClick = { // Increase the speed by 0.25 speed += 0.25f }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = "+", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp ) } } // Button to pause and play Button( onClick = { // change isPlaying state to pause/play isPlaying = !isPlaying }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( // display text according to state text = if (isPlaying) "Pause" else "Play", color = Color.White ) } } }
And finally, call this composable from setcontent from MainActivity class.
Kotlin
class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LottieExample() } }}
Below is the complete code for the MainActivity.kt file.
Kotlin
import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.*import androidx.compose.material.Buttonimport androidx.compose.material.ButtonDefaultsimport androidx.compose.material.Textimport androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.text.font.FontStyleimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport com.airbnb.lottie.compose.*import kotlin.math.max class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LottieExample() } }} @Composablefun LottieExample() { // to keep track if the animation is playing // and play pause accordingly var isPlaying by remember { mutableStateOf(true) } // for speed var speed by remember { mutableStateOf(1f) } // remember lottie composition ,which // accepts the lottie composition result val composition by rememberLottieComposition( LottieCompositionSpec .RawRes(R.raw.code) ) // to control the animation val progress by animateLottieCompositionAsState( // pass the composition created above composition, // Iterates Forever iterations = LottieConstants.IterateForever, // pass isPlaying we created above, // changing isPlaying will recompose // Lottie and pause/play isPlaying = isPlaying, // pass speed we created above, // changing speed will increase Lottie speed = speed, // this makes animation to restart when paused and play // pass false to continue the animation at which is was paused restartOnPlay = false ) // Column Composable Column( Modifier .background(Color.White) .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // Heading Text( text = "Lottie", color = Color.Gray, fontSize = 70.sp, fontWeight = FontWeight.SemiBold, fontStyle = FontStyle.Italic, modifier = Modifier.padding(10.dp) ) // LottieAnimation // Pass the composition and the progress state LottieAnimation( composition, progress, modifier = Modifier.size(400.dp) ) // Buttons to control the animation Row( horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { // Button to decrease speed Button( onClick = { // check to prevent speed going negative speed = max(speed - 0.25f, 0f) }, // Button background color colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = "-", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp, ) } // Button to Increase speed Text( text = "Speed ( $speed ) ", color = Color.Black, fontWeight = FontWeight.Bold, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp) ) Button( onClick = { // Increase the speed by 0.25 speed += 0.25f }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = "+", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp ) } } // Button to pause and play Button( onClick = { // change isPlaying state to pause/play isPlaying = !isPlaying }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( // display text according to state text = if (isPlaying) "Pause" else "Play", color = Color.White ) } } }}
Run the app and see the animation on the screen.
Output:
If having any issues, refer to the Project.
Android-Jetpack
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
Flutter - Custom Bottom Navigation Bar
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
Kotlin Array
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 248,
"s": 28,
"text": "Lottie is a great library to add animated files into your app. Two days ago Jetpack compose went stable and also Lottie supports Compose. In this article, we are going to see how to add Lottie animations in compose app."
},
{
"code": null,
"e": 448,
"s": 248,
"text": "We will build a simple app showing Lottie animation with a pause/play and an increase/decrease speed button. A sample GIF is given below to get an idea about what we are going to do in this article. "
},
{
"code": null,
"e": 463,
"s": 448,
"text": "Prerequisites:"
},
{
"code": null,
"e": 485,
"s": 463,
"text": "Knowledge of Android."
},
{
"code": null,
"e": 520,
"s": 485,
"text": "Good knowledge of Jetpack compose."
},
{
"code": null,
"e": 593,
"s": 520,
"text": "Step 1: Create a New Project (Or use it in the existing Compose project)"
},
{
"code": null,
"e": 658,
"s": 593,
"text": "Open Android Studio( Must be of the latest version (>=2020.3.1)."
},
{
"code": null,
"e": 706,
"s": 658,
"text": "Click on New Project > Empty Compose Activity. "
},
{
"code": null,
"e": 831,
"s": 706,
"text": "Then write the Application name and package name according to your choice and click finish. Wait for Gradle build to finish."
},
{
"code": null,
"e": 859,
"s": 831,
"text": "Step 2: Adding Dependencies"
},
{
"code": null,
"e": 916,
"s": 859,
"text": "Open build.gradle(app) and add the following dependency."
},
{
"code": null,
"e": 973,
"s": 916,
"text": "implementation βcom.airbnb.android:lottie-compose:4.0.0β"
},
{
"code": null,
"e": 1039,
"s": 973,
"text": "Step 3: Downloading the Lottie file and placing it in the project"
},
{
"code": null,
"e": 1098,
"s": 1039,
"text": "Right-click on the res > new > Android resource Directory."
},
{
"code": null,
"e": 1130,
"s": 1098,
"text": "Type raw to create a raw folder"
},
{
"code": null,
"e": 1295,
"s": 1130,
"text": "Now head over to Lottie to download your favorite animation or use this articleβs one (download it from here). After downloading drag and drop it to the raw folder."
},
{
"code": null,
"e": 1333,
"s": 1295,
"text": "Step 4: Working with Lottie Animation"
},
{
"code": null,
"e": 1379,
"s": 1333,
"text": "Create a composable function LottieExample()."
},
{
"code": null,
"e": 1386,
"s": 1379,
"text": "Kotlin"
},
{
"code": "@Composablefun LottieExample() { // codes to be added here}",
"e": 1447,
"s": 1386,
"text": null
},
{
"code": null,
"e": 1592,
"s": 1447,
"text": "We need to create Lottieβs composition and progress state. Add the following code in the same composable, refer to the comments for explanation."
},
{
"code": null,
"e": 1695,
"s": 1592,
"text": "Note: Make sure to (if Android Studio doesnβt do it automatically) import androidx.compose.runtime.* "
},
{
"code": null,
"e": 1785,
"s": 1695,
"text": "Create a state to hold speed and play/pause state. Add the following code in the function"
},
{
"code": null,
"e": 1792,
"s": 1785,
"text": "Kotlin"
},
{
"code": "// to keep track if the animation is playing// and play pause accordinglyvar isPlaying by remember { mutableStateOf(true) } // for speedvar speed by remember { mutableStateOf(1f) }",
"e": 1982,
"s": 1792,
"text": null
},
{
"code": null,
"e": 1989,
"s": 1982,
"text": "Kotlin"
},
{
"code": "// remember lottie composition, which// accepts the lottie composition resultval composition by rememberLottieComposition( LottieCompositionSpec // here `code` is the file name of lottie file // use it accordingly .RawRes(R.raw.code) ) // to control the animation val progress by animateLottieCompositionAsState( // pass the composition created above composition, // Iterates Forever iterations = LottieConstants.IterateForever, // pass isPlaying we created above, // changing isPlaying will recompose // Lottie and pause/play isPlaying = isPlaying, // pass speed we created above, // changing speed will increase Lottie speed = speed, // this makes animation to restart // when paused and play // pass false to continue the animation // at which is was paused restartOnPlay = false )",
"e": 2959,
"s": 1989,
"text": null
},
{
"code": null,
"e": 3178,
"s": 2959,
"text": "Now we need to create Buttons and lay down the Lottie composable. Add the following code in the same composable function. These are basic Columns, Rows, Buttons, and text composable. Refer to this for more information."
},
{
"code": null,
"e": 3185,
"s": 3178,
"text": "Kotlin"
},
{
"code": "// Column ComposableColumn( Modifier .background(Color.White) .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // Heading Text( text = \"Lottie\", color = Color.Gray, fontSize = 70.sp, fontWeight = FontWeight.SemiBold, fontStyle = FontStyle.Italic, modifier = Modifier.padding(10.dp) ) // LottieAnimation // Pass the composition // and the progress state LottieAnimation( composition, progress, modifier = Modifier.size(400.dp) ) // Buttons to control the animation Row( horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { // Button to decrease speed Button( onClick = { // check to prevent speed going negative speed = max(speed - 0.25f, 0f) }, // Button background color colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = \"-\", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp, ) } // Button to Increase speed Text( text = \"Speed ( $speed ) \", color = Color.Black, fontWeight = FontWeight.Bold, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp) ) Button( onClick = { // Increase the speed by 0.25 speed += 0.25f }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = \"+\", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp ) } } // Button to pause and play Button( onClick = { // change isPlaying state to pause/play isPlaying = !isPlaying }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( // display text according to state text = if (isPlaying) \"Pause\" else \"Play\", color = Color.White ) } } }",
"e": 6403,
"s": 3185,
"text": null
},
{
"code": null,
"e": 6478,
"s": 6403,
"text": "And finally, call this composable from setcontent from MainActivity class."
},
{
"code": null,
"e": 6485,
"s": 6478,
"text": "Kotlin"
},
{
"code": "class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LottieExample() } }}",
"e": 6686,
"s": 6485,
"text": null
},
{
"code": null,
"e": 6743,
"s": 6686,
"text": "Below is the complete code for the MainActivity.kt file."
},
{
"code": null,
"e": 6750,
"s": 6743,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.*import androidx.compose.material.Buttonimport androidx.compose.material.ButtonDefaultsimport androidx.compose.material.Textimport androidx.compose.runtime.*import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.text.font.FontStyleimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport com.airbnb.lottie.compose.*import kotlin.math.max class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LottieExample() } }} @Composablefun LottieExample() { // to keep track if the animation is playing // and play pause accordingly var isPlaying by remember { mutableStateOf(true) } // for speed var speed by remember { mutableStateOf(1f) } // remember lottie composition ,which // accepts the lottie composition result val composition by rememberLottieComposition( LottieCompositionSpec .RawRes(R.raw.code) ) // to control the animation val progress by animateLottieCompositionAsState( // pass the composition created above composition, // Iterates Forever iterations = LottieConstants.IterateForever, // pass isPlaying we created above, // changing isPlaying will recompose // Lottie and pause/play isPlaying = isPlaying, // pass speed we created above, // changing speed will increase Lottie speed = speed, // this makes animation to restart when paused and play // pass false to continue the animation at which is was paused restartOnPlay = false ) // Column Composable Column( Modifier .background(Color.White) .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { // Heading Text( text = \"Lottie\", color = Color.Gray, fontSize = 70.sp, fontWeight = FontWeight.SemiBold, fontStyle = FontStyle.Italic, modifier = Modifier.padding(10.dp) ) // LottieAnimation // Pass the composition and the progress state LottieAnimation( composition, progress, modifier = Modifier.size(400.dp) ) // Buttons to control the animation Row( horizontalArrangement = Arrangement.SpaceAround, modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { // Button to decrease speed Button( onClick = { // check to prevent speed going negative speed = max(speed - 0.25f, 0f) }, // Button background color colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = \"-\", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp, ) } // Button to Increase speed Text( text = \"Speed ( $speed ) \", color = Color.Black, fontWeight = FontWeight.Bold, fontSize = 15.sp, modifier = Modifier.padding(horizontal = 10.dp) ) Button( onClick = { // Increase the speed by 0.25 speed += 0.25f }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( text = \"+\", color = Color.White, fontWeight = FontWeight.Bold, fontSize = 20.sp ) } } // Button to pause and play Button( onClick = { // change isPlaying state to pause/play isPlaying = !isPlaying }, colors = ButtonDefaults.buttonColors( backgroundColor = Color(0xFF0F9D58) ) ) { Text( // display text according to state text = if (isPlaying) \"Pause\" else \"Play\", color = Color.White ) } } }}",
"e": 11980,
"s": 6750,
"text": null
},
{
"code": null,
"e": 12029,
"s": 11980,
"text": "Run the app and see the animation on the screen."
},
{
"code": null,
"e": 12037,
"s": 12029,
"text": "Output:"
},
{
"code": null,
"e": 12081,
"s": 12037,
"text": "If having any issues, refer to the Project."
},
{
"code": null,
"e": 12097,
"s": 12081,
"text": "Android-Jetpack"
},
{
"code": null,
"e": 12105,
"s": 12097,
"text": "Android"
},
{
"code": null,
"e": 12112,
"s": 12105,
"text": "Kotlin"
},
{
"code": null,
"e": 12120,
"s": 12112,
"text": "Android"
},
{
"code": null,
"e": 12218,
"s": 12120,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 12287,
"s": 12218,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 12319,
"s": 12287,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 12358,
"s": 12319,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 12407,
"s": 12358,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 12449,
"s": 12407,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 12518,
"s": 12449,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 12537,
"s": 12518,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 12550,
"s": 12537,
"text": "Kotlin Array"
},
{
"code": null,
"e": 12599,
"s": 12550,
"text": "How to Communicate Between Fragments in Android?"
}
] |
PrintStream print(char) method in Java with Examples
|
31 Jan, 2019
The print(char) method of PrintStream Class in Java is used to print the specified char value on the stream. This char value is taken as a parameter.
Syntax:
public void print(char charValue)
Parameters: This method accepts a mandatory parameter charValue which is the char value to be written on the stream.
Return Value: This method do not returns any value.
Below methods illustrates the working of print(char) method:
Program 1:
// Java program to demonstrate// PrintStream print(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintStream instance PrintStream printr = new PrintStream(System.out); // Print the char value 'A' // to this stream using print() method // This will put the charValue in the // stream till it is printed on the console printr.print('A'); printr.flush(); } catch (Exception e) { System.out.println(e); } }}
A
Program 2:
// Java program to demonstrate// PrintStream print(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintStream instance PrintStream printr = new PrintStream(System.out); // Print the char value 'G' // to this stream using print() method // This will put the charValue in the // stream till it is printed on the console printr.print('G'); printr.flush(); } catch (Exception e) { System.out.println(e); } }}
G
Java-Functions
Java-IO package
Java-PrintStream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jan, 2019"
},
{
"code": null,
"e": 178,
"s": 28,
"text": "The print(char) method of PrintStream Class in Java is used to print the specified char value on the stream. This char value is taken as a parameter."
},
{
"code": null,
"e": 186,
"s": 178,
"text": "Syntax:"
},
{
"code": null,
"e": 220,
"s": 186,
"text": "public void print(char charValue)"
},
{
"code": null,
"e": 337,
"s": 220,
"text": "Parameters: This method accepts a mandatory parameter charValue which is the char value to be written on the stream."
},
{
"code": null,
"e": 389,
"s": 337,
"text": "Return Value: This method do not returns any value."
},
{
"code": null,
"e": 450,
"s": 389,
"text": "Below methods illustrates the working of print(char) method:"
},
{
"code": null,
"e": 461,
"s": 450,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// PrintStream print(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintStream instance PrintStream printr = new PrintStream(System.out); // Print the char value 'A' // to this stream using print() method // This will put the charValue in the // stream till it is printed on the console printr.print('A'); printr.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1082,
"s": 461,
"text": null
},
{
"code": null,
"e": 1085,
"s": 1082,
"text": "A\n"
},
{
"code": null,
"e": 1096,
"s": 1085,
"text": "Program 2:"
},
{
"code": "// Java program to demonstrate// PrintStream print(char) method import java.io.*; class GFG { public static void main(String[] args) { try { // Create a PrintStream instance PrintStream printr = new PrintStream(System.out); // Print the char value 'G' // to this stream using print() method // This will put the charValue in the // stream till it is printed on the console printr.print('G'); printr.flush(); } catch (Exception e) { System.out.println(e); } }}",
"e": 1717,
"s": 1096,
"text": null
},
{
"code": null,
"e": 1720,
"s": 1717,
"text": "G\n"
},
{
"code": null,
"e": 1735,
"s": 1720,
"text": "Java-Functions"
},
{
"code": null,
"e": 1751,
"s": 1735,
"text": "Java-IO package"
},
{
"code": null,
"e": 1768,
"s": 1751,
"text": "Java-PrintStream"
},
{
"code": null,
"e": 1773,
"s": 1768,
"text": "Java"
},
{
"code": null,
"e": 1778,
"s": 1773,
"text": "Java"
}
] |
Difference between Primary and Candidate Key
|
22 Mar, 2021
Prerequisite β DBMS | Keys in Relational Model Both Primary Key and Candidate Key are the attributes that are used to access tuples from a table. These(Primary key and Candidate key) are also can be used to create a relationship between two tables.
Primary Key: Primary Key is a set of attributes (or attribute) which uniquely identify the tuples in relation or table. The primary key is a minimal super key, so there is one and only one primary key in any relationship. For example,
Student{ID, F_name, M_name, L_name, Age}
Here only ID can be primary key because the name, age and address can be same, but ID canβt be same.
Candidate Key: A candidate key is a set of attributes (or attribute) which uniquely identify the tuples in relation or table. As we know that Primary key is a minimal super key, so there is one and only one primary key in any relationship but there is more than one candidate key can take place. Candidate keyβs attributes can contain a NULL value which opposes to the primary key. For example,
Student{ID, First_name, Last_name, Age}
Here we can see the two candidate keys ID and {First_name, Last_name, DOB}. So here, there are present more than one candidate keys, which can uniquely identify a tuple in a relation.
Difference between Primary and Candidate Key:
shriwastavaraj52
DBMS
Difference Between
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Functional dependencies in DBMS
MySQL | Regular expressions (Regexp)
Difference between OLAP and OLTP in DBMS
OLAP Guidelines (Codd's Rule)
What is Temporary Table in SQL?
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 303,
"s": 53,
"text": "Prerequisite β DBMS | Keys in Relational Model Both Primary Key and Candidate Key are the attributes that are used to access tuples from a table. These(Primary key and Candidate key) are also can be used to create a relationship between two tables. "
},
{
"code": null,
"e": 540,
"s": 303,
"text": "Primary Key: Primary Key is a set of attributes (or attribute) which uniquely identify the tuples in relation or table. The primary key is a minimal super key, so there is one and only one primary key in any relationship. For example, "
},
{
"code": null,
"e": 582,
"s": 540,
"text": "Student{ID, F_name, M_name, L_name, Age} "
},
{
"code": null,
"e": 684,
"s": 582,
"text": "Here only ID can be primary key because the name, age and address can be same, but ID canβt be same. "
},
{
"code": null,
"e": 1081,
"s": 684,
"text": "Candidate Key: A candidate key is a set of attributes (or attribute) which uniquely identify the tuples in relation or table. As we know that Primary key is a minimal super key, so there is one and only one primary key in any relationship but there is more than one candidate key can take place. Candidate keyβs attributes can contain a NULL value which opposes to the primary key. For example, "
},
{
"code": null,
"e": 1122,
"s": 1081,
"text": "Student{ID, First_name, Last_name, Age} "
},
{
"code": null,
"e": 1307,
"s": 1122,
"text": "Here we can see the two candidate keys ID and {First_name, Last_name, DOB}. So here, there are present more than one candidate keys, which can uniquely identify a tuple in a relation. "
},
{
"code": null,
"e": 1355,
"s": 1307,
"text": "Difference between Primary and Candidate Key: "
},
{
"code": null,
"e": 1372,
"s": 1355,
"text": "shriwastavaraj52"
},
{
"code": null,
"e": 1377,
"s": 1372,
"text": "DBMS"
},
{
"code": null,
"e": 1396,
"s": 1377,
"text": "Difference Between"
},
{
"code": null,
"e": 1404,
"s": 1396,
"text": "GATE CS"
},
{
"code": null,
"e": 1409,
"s": 1404,
"text": "DBMS"
},
{
"code": null,
"e": 1507,
"s": 1409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1548,
"s": 1507,
"text": "Types of Functional dependencies in DBMS"
},
{
"code": null,
"e": 1585,
"s": 1548,
"text": "MySQL | Regular expressions (Regexp)"
},
{
"code": null,
"e": 1626,
"s": 1585,
"text": "Difference between OLAP and OLTP in DBMS"
},
{
"code": null,
"e": 1656,
"s": 1626,
"text": "OLAP Guidelines (Codd's Rule)"
},
{
"code": null,
"e": 1688,
"s": 1656,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 1728,
"s": 1688,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 1759,
"s": 1728,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 1820,
"s": 1759,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1888,
"s": 1820,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
How to fill up the rest of screen height using Tailwind CSS ?
|
26 May, 2021
In this article, we will learn how to fill up the rest of the screen height using Tailwind CSS.
Approach: To solve the above problem weβll be using the Flex Class and Height Class of Tailwind CSS.
The classes that weβll be using to solve this are as follows.
flex: It is used to set the length of flexible items. The flex class is much responsive and mobile-friendly.
flex-col: It is used to position flex items vertically.
h-screen: This class is used to make an element span the entire height of the viewport.
Example:
HTML
<!DOCTYPE html><html> <head> <link href="https://unpkg.com/tailwindcss@1.8.12/dist/tailwind.min.css" rel="stylesheet" /></head> <body> <div class="flex flex-col h-screen"> <div class="bg-yellow-500 py-8 hidden sm:block "> <div class="flex space-x-4"> <a href="#" class="bg-gray-900 text-white px-3 py-2 rounded-md text-sm font-medium" aria-current="page"> GeeksForGeeks Dashboard </a> <a href="#" class="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium"> Team </a> <a href="#" class="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium"> Projects </a> <a href="#" class="text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium"> Calendar </a> </div> </div> <div class="bg-green-500 flex flex-grow"> This is the other content on screen </div> </div></body> </html>
Output:
Picked
Tailwind CSS-Questions
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
Form validation using jQuery
How to Change the Position of Scrollbar using CSS ?
Build a Survey Form using HTML and CSS
Installation of Node.js on Linux
How to set the default value for an HTML <select> element ?
How do you run JavaScript script through the Terminal?
Node.js fs.readFileSync() Method
How to set space between the flexbox ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "In this article, we will learn how to fill up the rest of the screen height using Tailwind CSS."
},
{
"code": null,
"e": 226,
"s": 124,
"text": "Approach: To solve the above problem weβll be using the Flex Class and Height Class of Tailwind CSS. "
},
{
"code": null,
"e": 288,
"s": 226,
"text": "The classes that weβll be using to solve this are as follows."
},
{
"code": null,
"e": 397,
"s": 288,
"text": "flex: It is used to set the length of flexible items. The flex class is much responsive and mobile-friendly."
},
{
"code": null,
"e": 453,
"s": 397,
"text": "flex-col: It is used to position flex items vertically."
},
{
"code": null,
"e": 541,
"s": 453,
"text": "h-screen: This class is used to make an element span the entire height of the viewport."
},
{
"code": null,
"e": 550,
"s": 541,
"text": "Example:"
},
{
"code": null,
"e": 555,
"s": 550,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <link href=\"https://unpkg.com/tailwindcss@1.8.12/dist/tailwind.min.css\" rel=\"stylesheet\" /></head> <body> <div class=\"flex flex-col h-screen\"> <div class=\"bg-yellow-500 py-8 hidden sm:block \"> <div class=\"flex space-x-4\"> <a href=\"#\" class=\"bg-gray-900 text-white px-3 py-2 rounded-md text-sm font-medium\" aria-current=\"page\"> GeeksForGeeks Dashboard </a> <a href=\"#\" class=\"text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium\"> Team </a> <a href=\"#\" class=\"text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium\"> Projects </a> <a href=\"#\" class=\"text-gray-300 hover:bg-gray-700 hover:text-white px-3 py-2 rounded-md text-sm font-medium\"> Calendar </a> </div> </div> <div class=\"bg-green-500 flex flex-grow\"> This is the other content on screen </div> </div></body> </html>",
"e": 2035,
"s": 555,
"text": null
},
{
"code": null,
"e": 2043,
"s": 2035,
"text": "Output:"
},
{
"code": null,
"e": 2050,
"s": 2043,
"text": "Picked"
},
{
"code": null,
"e": 2073,
"s": 2050,
"text": "Tailwind CSS-Questions"
},
{
"code": null,
"e": 2077,
"s": 2073,
"text": "CSS"
},
{
"code": null,
"e": 2094,
"s": 2077,
"text": "Web Technologies"
},
{
"code": null,
"e": 2192,
"s": 2094,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2231,
"s": 2192,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2270,
"s": 2231,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2299,
"s": 2270,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2351,
"s": 2299,
"text": "How to Change the Position of Scrollbar using CSS ?"
},
{
"code": null,
"e": 2390,
"s": 2351,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2423,
"s": 2390,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2483,
"s": 2423,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2538,
"s": 2483,
"text": "How do you run JavaScript script through the Terminal?"
},
{
"code": null,
"e": 2571,
"s": 2538,
"text": "Node.js fs.readFileSync() Method"
}
] |
Python Continue Statement
|
27 Aug, 2021
In this article, we will discuss continue statements in Python for altering the flow of loops.
Loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Continue is a type of loop control statement that can alter the flow of the loop.
Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the rest of the code inside the loop for the current iteration only i.e. when the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped for the current iteration and the next iteration of the loop will begin.
Syntax:
continue
Consider the situation when you need to write a program which prints the number from 1 to 10 and but not 6. It is specified that you have to do this using loop and only one loop is allowed to use. Here comes the usage of continue statement. What we can do here is we can run a loop from 1 to 10 and every time we have to compare the value of the iterator with 6. If it is equal to 6 we will use the continue statement to continue to the next iteration without printing anything otherwise we will print the value.
Below is the implementation of the above idea:
Python3
# Python program to# demonstrate continue# statement # loop from 1 to 10for i in range(1, 11): # If i is equals to 6, # continue to next iteration # without printing if i == 6: continue else: # otherwise print the value # of i print(i, end=" ")
Output:
1 2 3 4 5 7 8 9 10
Note: The continue statement can be used with any other loop also like while loop in a similar way as it is used with for loop above.
Exercise Problem:
Given a number n, print triangular pattern. We are allowed to use only one loop.
Input: 7
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
Solution: Print the pattern by using one loop | Set 2 (Using Continue Statement)
nikhilaggarwal3
kapoorsagar226
Python-OOP
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
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 147,
"s": 52,
"text": "In this article, we will discuss continue statements in Python for altering the flow of loops."
},
{
"code": null,
"e": 479,
"s": 147,
"text": "Loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Continue is a type of loop control statement that can alter the flow of the loop. "
},
{
"code": null,
"e": 868,
"s": 479,
"text": "Continue statement is a loop control statement that forces to execute the next iteration of the loop while skipping the rest of the code inside the loop for the current iteration only i.e. when the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped for the current iteration and the next iteration of the loop will begin."
},
{
"code": null,
"e": 877,
"s": 868,
"text": "Syntax: "
},
{
"code": null,
"e": 886,
"s": 877,
"text": "continue"
},
{
"code": null,
"e": 1399,
"s": 886,
"text": "Consider the situation when you need to write a program which prints the number from 1 to 10 and but not 6. It is specified that you have to do this using loop and only one loop is allowed to use. Here comes the usage of continue statement. What we can do here is we can run a loop from 1 to 10 and every time we have to compare the value of the iterator with 6. If it is equal to 6 we will use the continue statement to continue to the next iteration without printing anything otherwise we will print the value."
},
{
"code": null,
"e": 1446,
"s": 1399,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 1454,
"s": 1446,
"text": "Python3"
},
{
"code": "# Python program to# demonstrate continue# statement # loop from 1 to 10for i in range(1, 11): # If i is equals to 6, # continue to next iteration # without printing if i == 6: continue else: # otherwise print the value # of i print(i, end=\" \")",
"e": 1743,
"s": 1454,
"text": null
},
{
"code": null,
"e": 1752,
"s": 1743,
"text": "Output: "
},
{
"code": null,
"e": 1772,
"s": 1752,
"text": "1 2 3 4 5 7 8 9 10 "
},
{
"code": null,
"e": 1906,
"s": 1772,
"text": "Note: The continue statement can be used with any other loop also like while loop in a similar way as it is used with for loop above."
},
{
"code": null,
"e": 1925,
"s": 1906,
"text": "Exercise Problem: "
},
{
"code": null,
"e": 2006,
"s": 1925,
"text": "Given a number n, print triangular pattern. We are allowed to use only one loop."
},
{
"code": null,
"e": 2080,
"s": 2006,
"text": "Input: 7\nOutput:\n*\n* * \n* * *\n* * * *\n* * * * *\n* * * * * *\n* * * * * * *"
},
{
"code": null,
"e": 2161,
"s": 2080,
"text": "Solution: Print the pattern by using one loop | Set 2 (Using Continue Statement)"
},
{
"code": null,
"e": 2177,
"s": 2161,
"text": "nikhilaggarwal3"
},
{
"code": null,
"e": 2192,
"s": 2177,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 2203,
"s": 2192,
"text": "Python-OOP"
},
{
"code": null,
"e": 2210,
"s": 2203,
"text": "Python"
},
{
"code": null,
"e": 2308,
"s": 2210,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2336,
"s": 2308,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 2386,
"s": 2336,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 2408,
"s": 2386,
"text": "Python map() function"
},
{
"code": null,
"e": 2452,
"s": 2408,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 2494,
"s": 2452,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2516,
"s": 2494,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2551,
"s": 2516,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2577,
"s": 2551,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2609,
"s": 2577,
"text": "How to Install PIP on Windows ?"
}
] |
Count common characters in two strings
|
25 Nov, 2021
Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.Example
Input: s1 = βabcdβ, s2 = βaadβ Output: 2 (s1[0], s2[0]) and (s1[3], s2[2]) are the only valid pairs. (s1[0], s2[1]) is not includes because s1[0] has already been paired with s2[0]Input: s1 = βgeeksforgeeksβ, s2 = βplatformforgeeksβ Output: 8
Approach: Count the frequencies of all the characters from both strings. Now, for every character if the frequency of this character in string s1 is freq1 and in string s2 is freq2 then total valid pairs with this character will be min(freq1, freq2). The sum of this value for all the characters is the required answer.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// valid indices pairsint countPairs(string s1, int n1, string s2, int n2){ // To store the frequencies of characters // of string s1 and s2 int freq1[26] = { 0 }; int freq2[26] = { 0 }; // To store the count of valid pairs int i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1[i] - 'a']++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2[i] - 'a']++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (min(freq1[i], freq2[i])); return count;} // Driver codeint main(){ string s1 = "geeksforgeeks", s2 = "platformforgeeks"; int n1 = s1.length(), n2 = s2.length(); cout << countPairs(s1, n1, s2, n2); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of// valid indices pairsstatic int countPairs(String s1, int n1, String s2, int n2){ // To store the frequencies of characters // of string s1 and s2 int []freq1 = new int[26]; int []freq2 = new int[26]; Arrays.fill(freq1, 0); Arrays.fill(freq2, 0); // To store the count of valid pairs int i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1.charAt(i) - 'a']++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2.charAt(i) - 'a']++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (Math.min(freq1[i], freq2[i])); return count;} // Driver codepublic static void main(String args[]){ String s1 = "geeksforgeeks", s2 = "platformforgeeks"; int n1 = s1.length(), n2 = s2.length(); System.out.println(countPairs(s1, n1, s2, n2));}} // This code is contributed by// Surendra_Gangwar
# Python3 implementation of the approach # Function to return the count of# valid indices pairsdef countPairs(s1, n1, s2, n2) : # To store the frequencies of characters # of string s1 and s2 freq1 = [0] * 26; freq2 = [0] * 26; # To store the count of valid pairs count = 0; # Update the frequencies of # the characters of string s1 for i in range(n1) : freq1[ord(s1[i]) - ord('a')] += 1; # Update the frequencies of # the characters of string s2 for i in range(n2) : freq2[ord(s2[i]) - ord('a')] += 1; # Find the count of valid pairs for i in range(26) : count += min(freq1[i], freq2[i]); return count; # Driver codeif __name__ == "__main__" : s1 = "geeksforgeeks"; s2 = "platformforgeeks"; n1 = len(s1) ; n2 = len(s2); print(countPairs(s1, n1, s2, n2)); # This code is contributed by Ryuga
// C# implementation of the approachusing System; class GFG{ // Function to return the count of// valid indices pairsstatic int countPairs(string s1, int n1, string s2, int n2){ // To store the frequencies of // characters of string s1 and s2 int []freq1 = new int[26]; int []freq2 = new int[26]; Array.Fill(freq1, 0); Array.Fill(freq2, 0); // To store the count of valid pairs int i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1[i] - 'a']++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2[i] - 'a']++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (Math.Min(freq1[i], freq2[i])); return count;} // Driver codepublic static void Main(){ string s1 = "geeksforgeeks", s2 = "platformforgeeks"; int n1 = s1.Length, n2 = s2.Length; Console.WriteLine(countPairs(s1, n1, s2, n2));}} // This code is contributed by// Akanksha Rai
<script> // JavaScript implementation of the approach // Function to return the count of // valid indices pairs function countPairs(s1, n1, s2, n2) { // To store the frequencies of // characters of string s1 and s2 let freq1 = new Array(26); let freq2 = new Array(26); freq1.fill(0); freq2.fill(0); // To store the count of valid pairs let i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1[i].charCodeAt() - 'a'.charCodeAt()]++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2[i].charCodeAt() - 'a'.charCodeAt()]++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (Math.min(freq1[i], freq2[i])); return count; } let s1 = "geeksforgeeks", s2 = "platformforgeeks"; let n1 = s1.length, n2 = s2.length; document.write(countPairs(s1, n1, s2, n2)); </script>
8
Time Complexity: O(max(n1, n2))Auxiliary Space: O(1)
ankthon
SURENDRA_GANGWAR
Akanksha_Rai
suresh07
pankajsharmagfg
ashutoshsinghgeeksforgeeks
frequency-counting
Algorithms
Competitive Programming
Searching
Strings
Searching
Strings
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Understanding Time Complexity with Simple Examples
CPU Scheduling in Operating Systems
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 372,
"s": 52,
"text": "Given two strings s1 and s2 consisting of lowercase English alphabets, the task is to count all the pairs of indices (i, j) from the given strings such that s1[i] = s2[j] and all the indices are distinct i.e. if s1[i] pairs with some s2[j] then these two characters will not be paired with any other character.Example "
},
{
"code": null,
"e": 617,
"s": 372,
"text": "Input: s1 = βabcdβ, s2 = βaadβ Output: 2 (s1[0], s2[0]) and (s1[3], s2[2]) are the only valid pairs. (s1[0], s2[1]) is not includes because s1[0] has already been paired with s2[0]Input: s1 = βgeeksforgeeksβ, s2 = βplatformforgeeksβ Output: 8 "
},
{
"code": null,
"e": 991,
"s": 619,
"text": "Approach: Count the frequencies of all the characters from both strings. Now, for every character if the frequency of this character in string s1 is freq1 and in string s2 is freq2 then total valid pairs with this character will be min(freq1, freq2). The sum of this value for all the characters is the required answer.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 995,
"s": 991,
"text": "C++"
},
{
"code": null,
"e": 1000,
"s": 995,
"text": "Java"
},
{
"code": null,
"e": 1008,
"s": 1000,
"text": "Python3"
},
{
"code": null,
"e": 1011,
"s": 1008,
"text": "C#"
},
{
"code": null,
"e": 1022,
"s": 1011,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of// valid indices pairsint countPairs(string s1, int n1, string s2, int n2){ // To store the frequencies of characters // of string s1 and s2 int freq1[26] = { 0 }; int freq2[26] = { 0 }; // To store the count of valid pairs int i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1[i] - 'a']++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2[i] - 'a']++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (min(freq1[i], freq2[i])); return count;} // Driver codeint main(){ string s1 = \"geeksforgeeks\", s2 = \"platformforgeeks\"; int n1 = s1.length(), n2 = s2.length(); cout << countPairs(s1, n1, s2, n2); return 0;}",
"e": 1955,
"s": 1022,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the count of// valid indices pairsstatic int countPairs(String s1, int n1, String s2, int n2){ // To store the frequencies of characters // of string s1 and s2 int []freq1 = new int[26]; int []freq2 = new int[26]; Arrays.fill(freq1, 0); Arrays.fill(freq2, 0); // To store the count of valid pairs int i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1.charAt(i) - 'a']++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2.charAt(i) - 'a']++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (Math.min(freq1[i], freq2[i])); return count;} // Driver codepublic static void main(String args[]){ String s1 = \"geeksforgeeks\", s2 = \"platformforgeeks\"; int n1 = s1.length(), n2 = s2.length(); System.out.println(countPairs(s1, n1, s2, n2));}} // This code is contributed by// Surendra_Gangwar",
"e": 3061,
"s": 1955,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the count of# valid indices pairsdef countPairs(s1, n1, s2, n2) : # To store the frequencies of characters # of string s1 and s2 freq1 = [0] * 26; freq2 = [0] * 26; # To store the count of valid pairs count = 0; # Update the frequencies of # the characters of string s1 for i in range(n1) : freq1[ord(s1[i]) - ord('a')] += 1; # Update the frequencies of # the characters of string s2 for i in range(n2) : freq2[ord(s2[i]) - ord('a')] += 1; # Find the count of valid pairs for i in range(26) : count += min(freq1[i], freq2[i]); return count; # Driver codeif __name__ == \"__main__\" : s1 = \"geeksforgeeks\"; s2 = \"platformforgeeks\"; n1 = len(s1) ; n2 = len(s2); print(countPairs(s1, n1, s2, n2)); # This code is contributed by Ryuga",
"e": 3950,
"s": 3061,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the count of// valid indices pairsstatic int countPairs(string s1, int n1, string s2, int n2){ // To store the frequencies of // characters of string s1 and s2 int []freq1 = new int[26]; int []freq2 = new int[26]; Array.Fill(freq1, 0); Array.Fill(freq2, 0); // To store the count of valid pairs int i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1[i] - 'a']++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2[i] - 'a']++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (Math.Min(freq1[i], freq2[i])); return count;} // Driver codepublic static void Main(){ string s1 = \"geeksforgeeks\", s2 = \"platformforgeeks\"; int n1 = s1.Length, n2 = s2.Length; Console.WriteLine(countPairs(s1, n1, s2, n2));}} // This code is contributed by// Akanksha Rai",
"e": 5044,
"s": 3950,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the count of // valid indices pairs function countPairs(s1, n1, s2, n2) { // To store the frequencies of // characters of string s1 and s2 let freq1 = new Array(26); let freq2 = new Array(26); freq1.fill(0); freq2.fill(0); // To store the count of valid pairs let i, count = 0; // Update the frequencies of // the characters of string s1 for (i = 0; i < n1; i++) freq1[s1[i].charCodeAt() - 'a'.charCodeAt()]++; // Update the frequencies of // the characters of string s2 for (i = 0; i < n2; i++) freq2[s2[i].charCodeAt() - 'a'.charCodeAt()]++; // Find the count of valid pairs for (i = 0; i < 26; i++) count += (Math.min(freq1[i], freq2[i])); return count; } let s1 = \"geeksforgeeks\", s2 = \"platformforgeeks\"; let n1 = s1.length, n2 = s2.length; document.write(countPairs(s1, n1, s2, n2)); </script>",
"e": 6120,
"s": 5044,
"text": null
},
{
"code": null,
"e": 6122,
"s": 6120,
"text": "8"
},
{
"code": null,
"e": 6177,
"s": 6124,
"text": "Time Complexity: O(max(n1, n2))Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6185,
"s": 6177,
"text": "ankthon"
},
{
"code": null,
"e": 6202,
"s": 6185,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 6215,
"s": 6202,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 6224,
"s": 6215,
"text": "suresh07"
},
{
"code": null,
"e": 6240,
"s": 6224,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 6267,
"s": 6240,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 6286,
"s": 6267,
"text": "frequency-counting"
},
{
"code": null,
"e": 6297,
"s": 6286,
"text": "Algorithms"
},
{
"code": null,
"e": 6321,
"s": 6297,
"text": "Competitive Programming"
},
{
"code": null,
"e": 6331,
"s": 6321,
"text": "Searching"
},
{
"code": null,
"e": 6339,
"s": 6331,
"text": "Strings"
},
{
"code": null,
"e": 6349,
"s": 6339,
"text": "Searching"
},
{
"code": null,
"e": 6357,
"s": 6349,
"text": "Strings"
},
{
"code": null,
"e": 6368,
"s": 6357,
"text": "Algorithms"
},
{
"code": null,
"e": 6466,
"s": 6368,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6491,
"s": 6466,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 6540,
"s": 6491,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 6578,
"s": 6540,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 6629,
"s": 6578,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 6665,
"s": 6629,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 6708,
"s": 6665,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 6751,
"s": 6708,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 6792,
"s": 6751,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 6819,
"s": 6792,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
How to create line chart using react bootstrap ?
|
21 Jun, 2021
Line charts are used to represent the relation between two data X and Y on a different axis. One of the axes of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.npx create-react-app foldername
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save mdbreact react-chartjs-2
Step 3: After creating the ReactJS application, Install the required modules using the following command.
npm install --save mdbreact react-chartjs-2
Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.import '@fortawesome/fontawesome-free/css/all.min.css';
import 'bootstrap-css-only/css/bootstrap.min.css';
import 'mdbreact/dist/css/mdb.css';
Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.
import '@fortawesome/fontawesome-free/css/all.min.css';
import 'bootstrap-css-only/css/bootstrap.min.css';
import 'mdbreact/dist/css/mdb.css';
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import { MDBContainer } from "mdbreact";import { Line } from "react-chartjs-2"; const App = () => { // Sample data const data = { labels: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], datasets: [ { label: "Hours Studied in Geeksforgeeks", data: [2, 5, 7, 9, 7, 6, 4], fill: true, backgroundColor: "rgba(6, 156,51, .3)", borderColor: "#02b844", } ] } return ( <MDBContainer> <Line data={data} /> </MDBContainer> );} export default App;
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Picked
React-Bootstrap
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 313,
"s": 54,
"text": "Line charts are used to represent the relation between two data X and Y on a different axis. One of the axes of the plot represents the specific categories being compared, while the other axis represents the measured values corresponding to those categories."
},
{
"code": null,
"e": 363,
"s": 313,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 458,
"s": 363,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername"
},
{
"code": null,
"e": 522,
"s": 458,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 554,
"s": 522,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 667,
"s": 554,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 767,
"s": 667,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 781,
"s": 767,
"text": "cd foldername"
},
{
"code": null,
"e": 932,
"s": 783,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command.npm install --save mdbreact react-chartjs-2"
},
{
"code": null,
"e": 1038,
"s": 932,
"text": "Step 3: After creating the ReactJS application, Install the required modules using the following command."
},
{
"code": null,
"e": 1082,
"s": 1038,
"text": "npm install --save mdbreact react-chartjs-2"
},
{
"code": null,
"e": 1287,
"s": 1082,
"text": "Step 4: Add Bootstrap CSS and fontawesome CSS to index.js.import '@fortawesome/fontawesome-free/css/all.min.css'; \nimport 'bootstrap-css-only/css/bootstrap.min.css'; \nimport 'mdbreact/dist/css/mdb.css';"
},
{
"code": null,
"e": 1346,
"s": 1287,
"text": "Step 4: Add Bootstrap CSS and fontawesome CSS to index.js."
},
{
"code": null,
"e": 1493,
"s": 1346,
"text": "import '@fortawesome/fontawesome-free/css/all.min.css'; \nimport 'bootstrap-css-only/css/bootstrap.min.css'; \nimport 'mdbreact/dist/css/mdb.css';"
},
{
"code": null,
"e": 1545,
"s": 1493,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1563,
"s": 1545,
"text": "Project Structure"
},
{
"code": null,
"e": 1693,
"s": 1563,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 1700,
"s": 1693,
"text": "App.js"
},
{
"code": "import React from \"react\";import { MDBContainer } from \"mdbreact\";import { Line } from \"react-chartjs-2\"; const App = () => { // Sample data const data = { labels: [\"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\"], datasets: [ { label: \"Hours Studied in Geeksforgeeks\", data: [2, 5, 7, 9, 7, 6, 4], fill: true, backgroundColor: \"rgba(6, 156,51, .3)\", borderColor: \"#02b844\", } ] } return ( <MDBContainer> <Line data={data} /> </MDBContainer> );} export default App;",
"e": 2276,
"s": 1700,
"text": null
},
{
"code": null,
"e": 2389,
"s": 2276,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2399,
"s": 2389,
"text": "npm start"
},
{
"code": null,
"e": 2498,
"s": 2399,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2505,
"s": 2498,
"text": "Picked"
},
{
"code": null,
"e": 2521,
"s": 2505,
"text": "React-Bootstrap"
},
{
"code": null,
"e": 2529,
"s": 2521,
"text": "ReactJS"
},
{
"code": null,
"e": 2546,
"s": 2529,
"text": "Web Technologies"
}
] |
How to create a GitHub repository
|
A GitHub account is a pre-requisite for creating a GitHub repository. Follow the below steps after registering with GitHub.
Step 1 β Login to the GitHub account. Once you login to your account you will see a β+β button on the right. Click on the button and select "New repository" option to create a new repository.
Configure the following in the create a new repository page.
Repository name: GitHub will validate the repository name that you have entered.
Repository name: GitHub will validate the repository name that you have entered.
Type of the repository: GitHub lets you create the following types of repositories βPrivate repository β Private Repository is the one that can be accessed only by the repository owner and individuals with whom the repository has been shared. Anyone who is not explicitly granted access to the repository cannot view the source code. Private repositories can be used for programs that are proprietary for you at the moment and you don't want to share.Public repository β Public Repository is the one which is open and available for everyone. Public Repositories can be used for open-source projects.
Type of the repository: GitHub lets you create the following types of repositories β
Private repository β Private Repository is the one that can be accessed only by the repository owner and individuals with whom the repository has been shared. Anyone who is not explicitly granted access to the repository cannot view the source code. Private repositories can be used for programs that are proprietary for you at the moment and you don't want to share.
Private repository β Private Repository is the one that can be accessed only by the repository owner and individuals with whom the repository has been shared. Anyone who is not explicitly granted access to the repository cannot view the source code. Private repositories can be used for programs that are proprietary for you at the moment and you don't want to share.
Public repository β Public Repository is the one which is open and available for everyone. Public Repositories can be used for open-source projects.
Public repository β Public Repository is the one which is open and available for everyone. Public Repositories can be used for open-source projects.
We will create a public repository for the purpose of demonstration. You can keep the default settings. We have selected the option to add a README.txt. This file is used to provide repo description.
You will find the URL of your first project in the format shown below. In the below URL sample_repo is the name of the repository and author_name will be your GitHub account name.
https://github.com/{author_name}/sample_repo
Once you refresh the URL, you will be able to see the sample README.md file and all commits as shown below.
|
[
{
"code": null,
"e": 1311,
"s": 1187,
"text": "A GitHub account is a pre-requisite for creating a GitHub repository. Follow the below steps after registering with GitHub."
},
{
"code": null,
"e": 1503,
"s": 1311,
"text": "Step 1 β Login to the GitHub account. Once you login to your account you will see a β+β button on the right. Click on the button and select \"New repository\" option to create a new repository."
},
{
"code": null,
"e": 1564,
"s": 1503,
"text": "Configure the following in the create a new repository page."
},
{
"code": null,
"e": 1645,
"s": 1564,
"text": "Repository name: GitHub will validate the repository name that you have entered."
},
{
"code": null,
"e": 1726,
"s": 1645,
"text": "Repository name: GitHub will validate the repository name that you have entered."
},
{
"code": null,
"e": 2326,
"s": 1726,
"text": "Type of the repository: GitHub lets you create the following types of repositories βPrivate repository β Private Repository is the one that can be accessed only by the repository owner and individuals with whom the repository has been shared. Anyone who is not explicitly granted access to the repository cannot view the source code. Private repositories can be used for programs that are proprietary for you at the moment and you don't want to share.Public repository β Public Repository is the one which is open and available for everyone. Public Repositories can be used for open-source projects."
},
{
"code": null,
"e": 2411,
"s": 2326,
"text": "Type of the repository: GitHub lets you create the following types of repositories β"
},
{
"code": null,
"e": 2779,
"s": 2411,
"text": "Private repository β Private Repository is the one that can be accessed only by the repository owner and individuals with whom the repository has been shared. Anyone who is not explicitly granted access to the repository cannot view the source code. Private repositories can be used for programs that are proprietary for you at the moment and you don't want to share."
},
{
"code": null,
"e": 3147,
"s": 2779,
"text": "Private repository β Private Repository is the one that can be accessed only by the repository owner and individuals with whom the repository has been shared. Anyone who is not explicitly granted access to the repository cannot view the source code. Private repositories can be used for programs that are proprietary for you at the moment and you don't want to share."
},
{
"code": null,
"e": 3296,
"s": 3147,
"text": "Public repository β Public Repository is the one which is open and available for everyone. Public Repositories can be used for open-source projects."
},
{
"code": null,
"e": 3445,
"s": 3296,
"text": "Public repository β Public Repository is the one which is open and available for everyone. Public Repositories can be used for open-source projects."
},
{
"code": null,
"e": 3645,
"s": 3445,
"text": "We will create a public repository for the purpose of demonstration. You can keep the default settings. We have selected the option to add a README.txt. This file is used to provide repo description."
},
{
"code": null,
"e": 3825,
"s": 3645,
"text": "You will find the URL of your first project in the format shown below. In the below URL sample_repo is the name of the repository and author_name will be your GitHub account name."
},
{
"code": null,
"e": 3870,
"s": 3825,
"text": "https://github.com/{author_name}/sample_repo"
},
{
"code": null,
"e": 3978,
"s": 3870,
"text": "Once you refresh the URL, you will be able to see the sample README.md file and all commits as shown below."
}
] |
VB.Net - Label Control
|
The Label control represents a standard Windows label. It is generally used to display some informative text on the GUI which is not changed during runtime.
Let's create a label by dragging a Label control from the Toolbox and dropping it on the form.
The following are some of the commonly used properties of the Label control β
Autosize
Gets or sets a value specifying if the control should be automatically resized to display all its contents.
BorderStyle
Gets or sets the border style for the control.
FlatStyle
Gets or sets the flat style appearance of the Label control
Font
Gets or sets the font of the text displayed by the control.
FontHeight
Gets or sets the height of the font of the control.
ForeColor
Gets or sets the foreground color of the control.
PreferredHeight
Gets the preferred height of the control.
PreferredWidth
Gets the preferred width of the control.
TabStop
Gets or sets a value indicating whether the user can tab to the Label. This property is not used by this class.
Text
Gets or sets the text associated with this control.
TextAlign
Gets or sets the alignment of text in the label.
The following are some of the commonly used methods of the Label control β
GetPreferredSize
Retrieves the size of a rectangular area into which a control can be fitted.
Refresh
Forces the control to invalidate its client area and immediately redraw itself and any child controls.
Select
Activates the control.
Show
Displays the control to the user.
ToString
Returns a String that contains the name of the control.
The following are some of the commonly used events of the Label control β
AutoSizeChanged
Occurs when the value of the AutoSize property changes.
Click
Occurs when the control is clicked.
DoubleClick
Occurs when the control is double-clicked.
GotFocus
Occurs when the control receives focus.
Leave
Occurs when the input focus leaves the control.
LostFocus
Occurs when the control loses focus.
TabIndexChanged
Occurs when the TabIndex property value changes.
TabStopChanged
Occurs when the TabStop property changes.
TextChanged
Occurs when the Text property value changes.
Consult Microsoft documentation for detailed list of properties, methods and events of the Label control.
Following is an example, which shows how we can create two labels. Let us create the first label from the designer view tab and set its properties from the properties window. We will use the Click and the DoubleClick events of the label to move the first label and change its text and create the second label and add it to the form, respectively.
Take the following steps β
Drag and drop a Label control on the form.
Drag and drop a Label control on the form.
Set the Text property to provide the caption "This is a Label Control".
Set the Text property to provide the caption "This is a Label Control".
Set the Font property from the properties window.
Set the Font property from the properties window.
Click the label to add the Click event in the code window and add the following codes.
Click the label to add the Click event in the code window and add the following codes.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
' Create two buttons to use as the accept and cancel buttons.
' Set window width and height
Me.Height = 300
Me.Width = 560
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
' Display a help button on the form.
Me.HelpButton = True
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) _
Handles Label1.Click
Label1.Location = New Point(50, 50)
Label1.Text = "You have just moved the label"
End Sub
Private Sub Label1_DoubleClick(sender As Object, e As EventArgs)
Handles Label1.DoubleClick
Dim Label2 As New Label
Label2.Text = "New Label"
Label2.Location = New Point(Label1.Left, Label1.Height + _
Label1.Top + 25)
Me.Controls.Add(Label2)
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window β
Clicking and double clicking the label would produce the following effect β
|
[
{
"code": null,
"e": 2591,
"s": 2434,
"text": "The Label control represents a standard Windows label. It is generally used to display some informative text on the GUI which is not changed during runtime."
},
{
"code": null,
"e": 2686,
"s": 2591,
"text": "Let's create a label by dragging a Label control from the Toolbox and dropping it on the form."
},
{
"code": null,
"e": 2764,
"s": 2686,
"text": "The following are some of the commonly used properties of the Label control β"
},
{
"code": null,
"e": 2773,
"s": 2764,
"text": "Autosize"
},
{
"code": null,
"e": 2881,
"s": 2773,
"text": "Gets or sets a value specifying if the control should be automatically resized to display all its contents."
},
{
"code": null,
"e": 2893,
"s": 2881,
"text": "BorderStyle"
},
{
"code": null,
"e": 2940,
"s": 2893,
"text": "Gets or sets the border style for the control."
},
{
"code": null,
"e": 2950,
"s": 2940,
"text": "FlatStyle"
},
{
"code": null,
"e": 3010,
"s": 2950,
"text": "Gets or sets the flat style appearance of the Label control"
},
{
"code": null,
"e": 3015,
"s": 3010,
"text": "Font"
},
{
"code": null,
"e": 3075,
"s": 3015,
"text": "Gets or sets the font of the text displayed by the control."
},
{
"code": null,
"e": 3086,
"s": 3075,
"text": "FontHeight"
},
{
"code": null,
"e": 3138,
"s": 3086,
"text": "Gets or sets the height of the font of the control."
},
{
"code": null,
"e": 3148,
"s": 3138,
"text": "ForeColor"
},
{
"code": null,
"e": 3198,
"s": 3148,
"text": "Gets or sets the foreground color of the control."
},
{
"code": null,
"e": 3214,
"s": 3198,
"text": "PreferredHeight"
},
{
"code": null,
"e": 3256,
"s": 3214,
"text": "Gets the preferred height of the control."
},
{
"code": null,
"e": 3271,
"s": 3256,
"text": "PreferredWidth"
},
{
"code": null,
"e": 3312,
"s": 3271,
"text": "Gets the preferred width of the control."
},
{
"code": null,
"e": 3320,
"s": 3312,
"text": "TabStop"
},
{
"code": null,
"e": 3432,
"s": 3320,
"text": "Gets or sets a value indicating whether the user can tab to the Label. This property is not used by this class."
},
{
"code": null,
"e": 3437,
"s": 3432,
"text": "Text"
},
{
"code": null,
"e": 3489,
"s": 3437,
"text": "Gets or sets the text associated with this control."
},
{
"code": null,
"e": 3499,
"s": 3489,
"text": "TextAlign"
},
{
"code": null,
"e": 3548,
"s": 3499,
"text": "Gets or sets the alignment of text in the label."
},
{
"code": null,
"e": 3623,
"s": 3548,
"text": "The following are some of the commonly used methods of the Label control β"
},
{
"code": null,
"e": 3640,
"s": 3623,
"text": "GetPreferredSize"
},
{
"code": null,
"e": 3717,
"s": 3640,
"text": "Retrieves the size of a rectangular area into which a control can be fitted."
},
{
"code": null,
"e": 3725,
"s": 3717,
"text": "Refresh"
},
{
"code": null,
"e": 3828,
"s": 3725,
"text": "Forces the control to invalidate its client area and immediately redraw itself and any child controls."
},
{
"code": null,
"e": 3835,
"s": 3828,
"text": "Select"
},
{
"code": null,
"e": 3858,
"s": 3835,
"text": "Activates the control."
},
{
"code": null,
"e": 3863,
"s": 3858,
"text": "Show"
},
{
"code": null,
"e": 3897,
"s": 3863,
"text": "Displays the control to the user."
},
{
"code": null,
"e": 3906,
"s": 3897,
"text": "ToString"
},
{
"code": null,
"e": 3962,
"s": 3906,
"text": "Returns a String that contains the name of the control."
},
{
"code": null,
"e": 4036,
"s": 3962,
"text": "The following are some of the commonly used events of the Label control β"
},
{
"code": null,
"e": 4052,
"s": 4036,
"text": "AutoSizeChanged"
},
{
"code": null,
"e": 4108,
"s": 4052,
"text": "Occurs when the value of the AutoSize property changes."
},
{
"code": null,
"e": 4114,
"s": 4108,
"text": "Click"
},
{
"code": null,
"e": 4150,
"s": 4114,
"text": "Occurs when the control is clicked."
},
{
"code": null,
"e": 4162,
"s": 4150,
"text": "DoubleClick"
},
{
"code": null,
"e": 4205,
"s": 4162,
"text": "Occurs when the control is double-clicked."
},
{
"code": null,
"e": 4214,
"s": 4205,
"text": "GotFocus"
},
{
"code": null,
"e": 4254,
"s": 4214,
"text": "Occurs when the control receives focus."
},
{
"code": null,
"e": 4260,
"s": 4254,
"text": "Leave"
},
{
"code": null,
"e": 4308,
"s": 4260,
"text": "Occurs when the input focus leaves the control."
},
{
"code": null,
"e": 4318,
"s": 4308,
"text": "LostFocus"
},
{
"code": null,
"e": 4355,
"s": 4318,
"text": "Occurs when the control loses focus."
},
{
"code": null,
"e": 4371,
"s": 4355,
"text": "TabIndexChanged"
},
{
"code": null,
"e": 4420,
"s": 4371,
"text": "Occurs when the TabIndex property value changes."
},
{
"code": null,
"e": 4435,
"s": 4420,
"text": "TabStopChanged"
},
{
"code": null,
"e": 4477,
"s": 4435,
"text": "Occurs when the TabStop property changes."
},
{
"code": null,
"e": 4489,
"s": 4477,
"text": "TextChanged"
},
{
"code": null,
"e": 4534,
"s": 4489,
"text": "Occurs when the Text property value changes."
},
{
"code": null,
"e": 4640,
"s": 4534,
"text": "Consult Microsoft documentation for detailed list of properties, methods and events of the Label control."
},
{
"code": null,
"e": 4987,
"s": 4640,
"text": "Following is an example, which shows how we can create two labels. Let us create the first label from the designer view tab and set its properties from the properties window. We will use the Click and the DoubleClick events of the label to move the first label and change its text and create the second label and add it to the form, respectively."
},
{
"code": null,
"e": 5014,
"s": 4987,
"text": "Take the following steps β"
},
{
"code": null,
"e": 5057,
"s": 5014,
"text": "Drag and drop a Label control on the form."
},
{
"code": null,
"e": 5100,
"s": 5057,
"text": "Drag and drop a Label control on the form."
},
{
"code": null,
"e": 5172,
"s": 5100,
"text": "Set the Text property to provide the caption \"This is a Label Control\"."
},
{
"code": null,
"e": 5244,
"s": 5172,
"text": "Set the Text property to provide the caption \"This is a Label Control\"."
},
{
"code": null,
"e": 5294,
"s": 5244,
"text": "Set the Font property from the properties window."
},
{
"code": null,
"e": 5344,
"s": 5294,
"text": "Set the Font property from the properties window."
},
{
"code": null,
"e": 5431,
"s": 5344,
"text": "Click the label to add the Click event in the code window and add the following codes."
},
{
"code": null,
"e": 5518,
"s": 5431,
"text": "Click the label to add the Click event in the code window and add the following codes."
},
{
"code": null,
"e": 6445,
"s": 5518,
"text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) _\n Handles MyBase.Load\n \n ' Create two buttons to use as the accept and cancel buttons. \n ' Set window width and height\n Me.Height = 300\n Me.Width = 560\n\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspont.com\"\n ' Display a help button on the form.\n Me.HelpButton = True\n End Sub\n\n Private Sub Label1_Click(sender As Object, e As EventArgs) _\n Handles Label1.Click\n Label1.Location = New Point(50, 50)\n Label1.Text = \"You have just moved the label\"\n End Sub\n Private Sub Label1_DoubleClick(sender As Object, e As EventArgs) \n Handles Label1.DoubleClick\n Dim Label2 As New Label\n Label2.Text = \"New Label\"\n Label2.Location = New Point(Label1.Left, Label1.Height + _ \n\t Label1.Top + 25)\n Me.Controls.Add(Label2)\n End Sub\nEnd Class"
},
{
"code": null,
"e": 6591,
"s": 6445,
"text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window β"
}
] |
TreeMap values() Method in Java with Examples
|
18 Nov, 2021
In Java, the values() method of the TreeMap class is present inside java.util package which is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the TreeMap.
--> java.util package
--> TreeMap class
--> values() Method
Syntax:
Tree_Map.values()
Return Type: A collection view containing all the values of the map.
Now we will be proposing different sets to illustrate values() method as listed:
Mapping string values to integer keysMapping integer values to string keys
Mapping string values to integer keys
Mapping integer values to string keys
Example 1: Mapping String Values to Integer Keys
Java
// Java Program to illustrate values() Method// of TreeMap class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of integer, string pairs TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys // using put() method tree_map.put(10, "Geeks"); tree_map.put(15, "4"); tree_map.put(20, "Geeks"); tree_map.put(25, "Welcomes"); tree_map.put(30, "You"); // Printing the elements of TreeMap System.out.println("Initial Mappings are: " + tree_map); // Getting the set view of values // using values() method System.out.println("The collection is: " + tree_map.values()); }}
Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The collection is: [Geeks, 4, Geeks, Welcomes, You]
Example 2: Mapping Integer Values to String Keys.
Java
// Java Program to Illustrate values() method// of TreeMap class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of string, integer pairs TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys // using put() method tree_map.put("Geeks", 10); tree_map.put("4", 15); tree_map.put("Geeks", 20); tree_map.put("Welcomes", 25); tree_map.put("You", 30); // Printing the elements of TreeMap System.out.println("Initial Mappings are: " + tree_map); // Getting the set view of values // using values() method System.out.println("The collection is: " + tree_map.values()); }}
Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}
The collection is: [15, 20, 25, 30]
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
solankimayank
anikakapoor
Java-Collections
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 250,
"s": 28,
"text": "In Java, the values() method of the TreeMap class is present inside java.util package which is used to create a collection out of the values of the map. It basically returns a Collection view of the values in the TreeMap."
},
{
"code": null,
"e": 324,
"s": 250,
"text": "--> java.util package\n --> TreeMap class\n --> values() Method "
},
{
"code": null,
"e": 333,
"s": 324,
"text": "Syntax: "
},
{
"code": null,
"e": 351,
"s": 333,
"text": "Tree_Map.values()"
},
{
"code": null,
"e": 420,
"s": 351,
"text": "Return Type: A collection view containing all the values of the map."
},
{
"code": null,
"e": 501,
"s": 420,
"text": "Now we will be proposing different sets to illustrate values() method as listed:"
},
{
"code": null,
"e": 576,
"s": 501,
"text": "Mapping string values to integer keysMapping integer values to string keys"
},
{
"code": null,
"e": 614,
"s": 576,
"text": "Mapping string values to integer keys"
},
{
"code": null,
"e": 652,
"s": 614,
"text": "Mapping integer values to string keys"
},
{
"code": null,
"e": 701,
"s": 652,
"text": "Example 1: Mapping String Values to Integer Keys"
},
{
"code": null,
"e": 706,
"s": 701,
"text": "Java"
},
{
"code": "// Java Program to illustrate values() Method// of TreeMap class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of integer, string pairs TreeMap<Integer, String> tree_map = new TreeMap<Integer, String>(); // Mapping string values to int keys // using put() method tree_map.put(10, \"Geeks\"); tree_map.put(15, \"4\"); tree_map.put(20, \"Geeks\"); tree_map.put(25, \"Welcomes\"); tree_map.put(30, \"You\"); // Printing the elements of TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Getting the set view of values // using values() method System.out.println(\"The collection is: \" + tree_map.values()); }}",
"e": 1653,
"s": 706,
"text": null
},
{
"code": null,
"e": 1775,
"s": 1653,
"text": "Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}\nThe collection is: [Geeks, 4, Geeks, Welcomes, You]"
},
{
"code": null,
"e": 1828,
"s": 1777,
"text": "Example 2: Mapping Integer Values to String Keys. "
},
{
"code": null,
"e": 1833,
"s": 1828,
"text": "Java"
},
{
"code": "// Java Program to Illustrate values() method// of TreeMap class // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty TreeMap by // declaring object of string, integer pairs TreeMap<String, Integer> tree_map = new TreeMap<String, Integer>(); // Mapping int values to string keys // using put() method tree_map.put(\"Geeks\", 10); tree_map.put(\"4\", 15); tree_map.put(\"Geeks\", 20); tree_map.put(\"Welcomes\", 25); tree_map.put(\"You\", 30); // Printing the elements of TreeMap System.out.println(\"Initial Mappings are: \" + tree_map); // Getting the set view of values // using values() method System.out.println(\"The collection is: \" + tree_map.values()); }}",
"e": 2780,
"s": 1833,
"text": null
},
{
"code": null,
"e": 2876,
"s": 2780,
"text": "Initial Mappings are: {4=15, Geeks=20, Welcomes=25, You=30}\nThe collection is: [15, 20, 25, 30]"
},
{
"code": null,
"e": 3002,
"s": 2878,
"text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types."
},
{
"code": null,
"e": 3016,
"s": 3002,
"text": "solankimayank"
},
{
"code": null,
"e": 3028,
"s": 3016,
"text": "anikakapoor"
},
{
"code": null,
"e": 3045,
"s": 3028,
"text": "Java-Collections"
},
{
"code": null,
"e": 3058,
"s": 3045,
"text": "java-TreeMap"
},
{
"code": null,
"e": 3063,
"s": 3058,
"text": "Java"
},
{
"code": null,
"e": 3068,
"s": 3063,
"text": "Java"
},
{
"code": null,
"e": 3085,
"s": 3068,
"text": "Java-Collections"
}
] |
Select the next row after skipping every 2 rows in MySQL
|
To skip rows, you can use OFFSET. Let us first create a table β
mysql> create table DemoTable617(Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,FirstName varchar(100));
Query OK, 0 rows affected (1.70 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable617(FirstName) values('John');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable617(FirstName) values('Sam');
Query OK, 1 row affected (0.39 sec)
mysql> insert into DemoTable617(FirstName) values('Carol');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable617(FirstName) values('Mike');
Query OK, 1 row affected (0.34 sec)
mysql> insert into DemoTable617(FirstName) values('David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable617(FirstName) values('Bob');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable617(FirstName) values('Robert');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable617(FirstName) values('Chris');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable617(FirstName) values('Mike');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable617(FirstName) values('Adam');
Query OK, 1 row affected (0.49 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable617;
This will produce the following output β
+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John |
| 2 | Sam |
| 3 | Carol |
| 4 | Mike |
| 5 | David |
| 6 | Bob |
| 7 | Robert |
| 8 | Chris |
| 9 | Mike |
| 10| Adam |
+----+-----------+
10 rows in set (0.00 sec)
Following is the query to select rows. At first order by DESC. After that, it will skip two rows and display 5 rows using LIMIT 5 β
mysql> select tbl.* from (select *from DemoTable617 order by FirstName DESC LIMIT 5 OFFSET 2) AS tbl ORDER BY tbl.Id
;
This will produce the following output β
+----+-----------+
| Id | FirstName |
+----+-----------+
| 1 | John |
| 4 | Mike |
| 5 | David |
| 8 | Chris |
| 9 | Mike |
+----+-----------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To skip rows, you can use OFFSET. Let us first create a table β"
},
{
"code": null,
"e": 1264,
"s": 1126,
"text": "mysql> create table DemoTable617(Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,FirstName varchar(100));\nQuery OK, 0 rows affected (1.70 sec)"
},
{
"code": null,
"e": 1320,
"s": 1264,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 2273,
"s": 1320,
"text": "mysql> insert into DemoTable617(FirstName) values('John');\nQuery OK, 1 row affected (0.39 sec)\nmysql> insert into DemoTable617(FirstName) values('Sam');\nQuery OK, 1 row affected (0.39 sec)\nmysql> insert into DemoTable617(FirstName) values('Carol');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable617(FirstName) values('Mike');\nQuery OK, 1 row affected (0.34 sec)\nmysql> insert into DemoTable617(FirstName) values('David');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable617(FirstName) values('Bob');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable617(FirstName) values('Robert');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable617(FirstName) values('Chris');\nQuery OK, 1 row affected (0.27 sec)\nmysql> insert into DemoTable617(FirstName) values('Mike');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable617(FirstName) values('Adam');\nQuery OK, 1 row affected (0.49 sec)"
},
{
"code": null,
"e": 2333,
"s": 2273,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 2367,
"s": 2333,
"text": "mysql> select *from DemoTable617;"
},
{
"code": null,
"e": 2408,
"s": 2367,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2699,
"s": 2408,
"text": "+----+-----------+\n| Id | FirstName |\n+----+-----------+\n| 1 | John |\n| 2 | Sam |\n| 3 | Carol |\n| 4 | Mike |\n| 5 | David |\n| 6 | Bob |\n| 7 | Robert |\n| 8 | Chris |\n| 9 | Mike |\n| 10| Adam |\n+----+-----------+\n10 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2831,
"s": 2699,
"text": "Following is the query to select rows. At first order by DESC. After that, it will skip two rows and display 5 rows using LIMIT 5 β"
},
{
"code": null,
"e": 2950,
"s": 2831,
"text": "mysql> select tbl.* from (select *from DemoTable617 order by FirstName DESC LIMIT 5 OFFSET 2) AS tbl ORDER BY tbl.Id\n;"
},
{
"code": null,
"e": 2991,
"s": 2950,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 3187,
"s": 2991,
"text": "+----+-----------+\n| Id | FirstName |\n+----+-----------+\n| 1 | John |\n| 4 | Mike |\n| 5 | David |\n| 8 | Chris |\n| 9 | Mike |\n+----+-----------+\n5 rows in set (0.00 sec)"
}
] |
Delete a directory or file using Python - GeeksforGeeks
|
29 Dec, 2020
Python provides different methods and functions for removing files and directories. One can remove the file according to their need. Various methods provided by Python are β
Using os.remove()
Using os.rmdir()
Using shutil.rmtree()
OS module in Python provides functions for interacting with the operating system. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system.
os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.
Syntax: os.remove(path, *, dir_fd = None)
Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored.
Note: The β*β in parameter list indicates that all following parameters (Here in our case βdir_fdβ) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method does not return any value.
Example 1: Suppose the file contained in the folder are:
We want to delete the file1 from the above folder. Below is the implementation.
# Python program to explain os.remove() method # importing os module import os # File name file = 'file1.txt' # File location location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/" # Path path = os.path.join(location, file) # Remove the file # 'file.txt' os.remove(path)
Output:
Example 2: If the specified path is a directory.
# Python program to explain os.remove() method # importing os module import os # Directory namedir = "Nikhil" # Path location = "D:/Pycharm projects/GeeksforGeeks/Authors/"path = os.path.join(location, dir) # Remove the specified # file path os.remove(path) print("% s has been removed successfully" % dir) # if the specified path # is a directory then # 'IsADirectoryError' error # will raised # Similarly if the specified # file path does not exists or # is invalid then corresponding # OSError will be raised
Output:
Traceback (most recent call last):
File "osremove.py", line 11, in
os.remove(path)
IsADirectoryError: [Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'
Example 3: Handling error while using os.remove() method.
# Python program to explain os.remove() method # importing os module import os # path path = 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil' # Remove the specified # file path try: os.remove(path) print("% s removed successfully" % path) except OSError as error: print(error) print("File path can not be removed")
Output:
[Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'
File path can not be removed
Note: To know more about os.remove() click here.
os.rmdir() method in Python is used to remove or delete a empty directory. OSError will be raised if the specified path is not an empty directory.
Syntax: os.rmdir(path, *, dir_fd = None)
Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored.
Note: The β*β in parameter list indicates that all following parameters (Here in our case βdir_fdβ) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method does not return any value.
Example 1: Suppose the directories are β
We want to remove the directory Geeks. Below is the implementation.
# Python program to explain os.rmdir() method # importing os module import os # Directory name directory = "Geeks" # Parent Directory parent = "D:/Pycharm projects/" # Path path = os.path.join(parent, directory) # Remove the Directory # "Geeks" os.rmdir(path)
Output:
Example 2: Handling errors while using os.rmdir() method,
# Python program to explain os.rmdir() method # importing os module import os # Directory name directory = "GeeksforGeeks" # Parent Directory parent = "D:/Pycharm projects/" # Path path = os.path.join(parent, directory) # Remove the Directory# "GeeksforGeeks"try: os.rmdir(path) print("Directory '% s' has been removed successfully" % directory)except OSError as error: print(error) print("Directory '% s' can not be removed" % directory) # if the specified path# is not an empty directory # then permission error will # be raised # similarly if specified path # is invalid or is not a # directory then corresponding # OSError will be raised
Output:
[WinError 145] The directory is not empty: 'D:/Pycharm projects/GeeksforGeeks'
Directory 'GeeksforGeeks' can not be removed
Note: To know more about os.rmdir() click here.
shutil.rmtree() is used to delete an entire directory tree, path must point to a directory (but not a symbolic link to a directory).
Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
Parameters:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.
Example 1: Suppose the directory and sub-directories are as follow.
# Parent directory:
# Directory inside parent directory:
# File inside the sub-directory:
We want to remove the directory Authors. Below is the implementation.
# Python program to demonstrate# shutil.rmtree() import shutilimport os # locationlocation = "D:/Pycharm projects/GeeksforGeeks/" # directorydir = "Authors" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path)
Output:
Example 2: By passing ignore_errors = True.
# Python program to demonstrate# shutil.rmtree() import shutilimport os # locationlocation = "D:/Pycharm projects/GeeksforGeeks/" # directorydir = "Authors" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path, ignore_errors = False) # making ignore_errors = True will not raise # a FileNotFoundError
Output:
Traceback (most recent call last):File βD:/Pycharm projects/gfg/gfg.pyβ, line 16, in shutil.rmtree(path, ignore_errors=False)File βC:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.pyβ, line 730, in rmtreereturn _rmtree_unsafe(path, onerror)File βC:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.pyβ, line 589, in _rmtree_unsafeonerror(os.scandir, path, sys.exc_info())File βC:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.pyβ, line 586, in _rmtree_unsafewith os.scandir(path) as scandir_it:FileNotFoundError: [WinError 3] The system cannot find the path specified: βD:/Pycharm projects/GeeksforGeeks/Authorsβ
Example 3: By passing onerrorIn onerror a function should be passed which must contain three parameters.
function β function which raised the exception.
path β path name passed which raised the exception while removal
excinfo β exception info raised by sys.exc_info()
Below is the implementation
# Python program to demonstrate# shutil.rmtree() import shutilimport os # exception handlerdef handler(func, path, exc_info): print("Inside handler") print(exc_info) # locationlocation = "D:/Pycharm projects/GeeksforGeeks/" # directorydir = "Authors" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path, onerror = handler)
Output:
Inside handler(, FileNotFoundError(2, βThe system cannot find the path specifiedβ), )Inside handler(, FileNotFoundError(2, βThe system cannot find the file specifiedβ), )
Python file-handling-programs
Python OS-path-module
python-file-handling
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Check if element exists in list in Python
Selecting rows in pandas DataFrame based on conditions
Defaultdict in Python
Python | Split string into list of characters
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python program to check whether a number is Prime or not
|
[
{
"code": null,
"e": 24318,
"s": 24290,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 24492,
"s": 24318,
"text": "Python provides different methods and functions for removing files and directories. One can remove the file according to their need. Various methods provided by Python are β"
},
{
"code": null,
"e": 24510,
"s": 24492,
"text": "Using os.remove()"
},
{
"code": null,
"e": 24527,
"s": 24510,
"text": "Using os.rmdir()"
},
{
"code": null,
"e": 24549,
"s": 24527,
"text": "Using shutil.rmtree()"
},
{
"code": null,
"e": 24826,
"s": 24549,
"text": "OS module in Python provides functions for interacting with the operating system. All functions in os module raise OSError in the case of invalid or inaccessible file names and paths, or other arguments that have the correct type, but are not accepted by the operating system."
},
{
"code": null,
"e": 25026,
"s": 24826,
"text": "os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method."
},
{
"code": null,
"e": 25068,
"s": 25026,
"text": "Syntax: os.remove(path, *, dir_fd = None)"
},
{
"code": null,
"e": 25368,
"s": 25068,
"text": "Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored."
},
{
"code": null,
"e": 25568,
"s": 25368,
"text": "Note: The β*β in parameter list indicates that all following parameters (Here in our case βdir_fdβ) are keyword-only parameters and they can be provided using their name, not as positional parameter."
},
{
"code": null,
"e": 25620,
"s": 25568,
"text": "Return Type: This method does not return any value."
},
{
"code": null,
"e": 25677,
"s": 25620,
"text": "Example 1: Suppose the file contained in the folder are:"
},
{
"code": null,
"e": 25757,
"s": 25677,
"text": "We want to delete the file1 from the above folder. Below is the implementation."
},
{
"code": "# Python program to explain os.remove() method # importing os module import os # File name file = 'file1.txt' # File location location = \"D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/\" # Path path = os.path.join(location, file) # Remove the file # 'file.txt' os.remove(path) ",
"e": 26059,
"s": 25757,
"text": null
},
{
"code": null,
"e": 26067,
"s": 26059,
"text": "Output:"
},
{
"code": null,
"e": 26116,
"s": 26067,
"text": "Example 2: If the specified path is a directory."
},
{
"code": "# Python program to explain os.remove() method # importing os module import os # Directory namedir = \"Nikhil\" # Path location = \"D:/Pycharm projects/GeeksforGeeks/Authors/\"path = os.path.join(location, dir) # Remove the specified # file path os.remove(path) print(\"% s has been removed successfully\" % dir) # if the specified path # is a directory then # 'IsADirectoryError' error # will raised # Similarly if the specified # file path does not exists or # is invalid then corresponding # OSError will be raised ",
"e": 26658,
"s": 26116,
"text": null
},
{
"code": null,
"e": 26666,
"s": 26658,
"text": "Output:"
},
{
"code": null,
"e": 26854,
"s": 26666,
"text": "Traceback (most recent call last):\n File \"osremove.py\", line 11, in \n os.remove(path)\nIsADirectoryError: [Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'\n"
},
{
"code": null,
"e": 26912,
"s": 26854,
"text": "Example 3: Handling error while using os.remove() method."
},
{
"code": "# Python program to explain os.remove() method # importing os module import os # path path = 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil' # Remove the specified # file path try: os.remove(path) print(\"% s removed successfully\" % path) except OSError as error: print(error) print(\"File path can not be removed\") ",
"e": 27262,
"s": 26912,
"text": null
},
{
"code": null,
"e": 27270,
"s": 27262,
"text": "Output:"
},
{
"code": null,
"e": 27378,
"s": 27270,
"text": "[Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'\nFile path can not be removed\n"
},
{
"code": null,
"e": 27427,
"s": 27378,
"text": "Note: To know more about os.remove() click here."
},
{
"code": null,
"e": 27574,
"s": 27427,
"text": "os.rmdir() method in Python is used to remove or delete a empty directory. OSError will be raised if the specified path is not an empty directory."
},
{
"code": null,
"e": 27615,
"s": 27574,
"text": "Syntax: os.rmdir(path, *, dir_fd = None)"
},
{
"code": null,
"e": 27915,
"s": 27615,
"text": "Parameter:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.If the specified path is absolute then dir_fd is ignored."
},
{
"code": null,
"e": 28115,
"s": 27915,
"text": "Note: The β*β in parameter list indicates that all following parameters (Here in our case βdir_fdβ) are keyword-only parameters and they can be provided using their name, not as positional parameter."
},
{
"code": null,
"e": 28167,
"s": 28115,
"text": "Return Type: This method does not return any value."
},
{
"code": null,
"e": 28208,
"s": 28167,
"text": "Example 1: Suppose the directories are β"
},
{
"code": null,
"e": 28276,
"s": 28208,
"text": "We want to remove the directory Geeks. Below is the implementation."
},
{
"code": "# Python program to explain os.rmdir() method # importing os module import os # Directory name directory = \"Geeks\" # Parent Directory parent = \"D:/Pycharm projects/\" # Path path = os.path.join(parent, directory) # Remove the Directory # \"Geeks\" os.rmdir(path) ",
"e": 28559,
"s": 28276,
"text": null
},
{
"code": null,
"e": 28567,
"s": 28559,
"text": "Output:"
},
{
"code": null,
"e": 28625,
"s": 28567,
"text": "Example 2: Handling errors while using os.rmdir() method,"
},
{
"code": "# Python program to explain os.rmdir() method # importing os module import os # Directory name directory = \"GeeksforGeeks\" # Parent Directory parent = \"D:/Pycharm projects/\" # Path path = os.path.join(parent, directory) # Remove the Directory# \"GeeksforGeeks\"try: os.rmdir(path) print(\"Directory '% s' has been removed successfully\" % directory)except OSError as error: print(error) print(\"Directory '% s' can not be removed\" % directory) # if the specified path# is not an empty directory # then permission error will # be raised # similarly if specified path # is invalid or is not a # directory then corresponding # OSError will be raised ",
"e": 29290,
"s": 28625,
"text": null
},
{
"code": null,
"e": 29298,
"s": 29290,
"text": "Output:"
},
{
"code": null,
"e": 29423,
"s": 29298,
"text": "[WinError 145] The directory is not empty: 'D:/Pycharm projects/GeeksforGeeks'\nDirectory 'GeeksforGeeks' can not be removed\n"
},
{
"code": null,
"e": 29471,
"s": 29423,
"text": "Note: To know more about os.rmdir() click here."
},
{
"code": null,
"e": 29604,
"s": 29471,
"text": "shutil.rmtree() is used to delete an entire directory tree, path must point to a directory (but not a symbolic link to a directory)."
},
{
"code": null,
"e": 29667,
"s": 29604,
"text": "Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)"
},
{
"code": null,
"e": 30013,
"s": 29667,
"text": "Parameters:path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror."
},
{
"code": null,
"e": 30081,
"s": 30013,
"text": "Example 1: Suppose the directory and sub-directories are as follow."
},
{
"code": null,
"e": 30101,
"s": 30081,
"text": "# Parent directory:"
},
{
"code": null,
"e": 30138,
"s": 30101,
"text": "# Directory inside parent directory:"
},
{
"code": null,
"e": 30171,
"s": 30138,
"text": "# File inside the sub-directory:"
},
{
"code": null,
"e": 30241,
"s": 30171,
"text": "We want to remove the directory Authors. Below is the implementation."
},
{
"code": "# Python program to demonstrate# shutil.rmtree() import shutilimport os # locationlocation = \"D:/Pycharm projects/GeeksforGeeks/\" # directorydir = \"Authors\" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path)",
"e": 30484,
"s": 30241,
"text": null
},
{
"code": null,
"e": 30492,
"s": 30484,
"text": "Output:"
},
{
"code": null,
"e": 30536,
"s": 30492,
"text": "Example 2: By passing ignore_errors = True."
},
{
"code": "# Python program to demonstrate# shutil.rmtree() import shutilimport os # locationlocation = \"D:/Pycharm projects/GeeksforGeeks/\" # directorydir = \"Authors\" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path, ignore_errors = False) # making ignore_errors = True will not raise # a FileNotFoundError",
"e": 30870,
"s": 30536,
"text": null
},
{
"code": null,
"e": 30878,
"s": 30870,
"text": "Output:"
},
{
"code": null,
"e": 31575,
"s": 30878,
"text": "Traceback (most recent call last):File βD:/Pycharm projects/gfg/gfg.pyβ, line 16, in shutil.rmtree(path, ignore_errors=False)File βC:\\Users\\Nikhil Aggarwal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\shutil.pyβ, line 730, in rmtreereturn _rmtree_unsafe(path, onerror)File βC:\\Users\\Nikhil Aggarwal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\shutil.pyβ, line 589, in _rmtree_unsafeonerror(os.scandir, path, sys.exc_info())File βC:\\Users\\Nikhil Aggarwal\\AppData\\Local\\Programs\\Python\\Python38-32\\lib\\shutil.pyβ, line 586, in _rmtree_unsafewith os.scandir(path) as scandir_it:FileNotFoundError: [WinError 3] The system cannot find the path specified: βD:/Pycharm projects/GeeksforGeeks/Authorsβ"
},
{
"code": null,
"e": 31680,
"s": 31575,
"text": "Example 3: By passing onerrorIn onerror a function should be passed which must contain three parameters."
},
{
"code": null,
"e": 31728,
"s": 31680,
"text": "function β function which raised the exception."
},
{
"code": null,
"e": 31793,
"s": 31728,
"text": "path β path name passed which raised the exception while removal"
},
{
"code": null,
"e": 31843,
"s": 31793,
"text": "excinfo β exception info raised by sys.exc_info()"
},
{
"code": null,
"e": 31871,
"s": 31843,
"text": "Below is the implementation"
},
{
"code": "# Python program to demonstrate# shutil.rmtree() import shutilimport os # exception handlerdef handler(func, path, exc_info): print(\"Inside handler\") print(exc_info) # locationlocation = \"D:/Pycharm projects/GeeksforGeeks/\" # directorydir = \"Authors\" # pathpath = os.path.join(location, dir) # removing directoryshutil.rmtree(path, onerror = handler)",
"e": 32238,
"s": 31871,
"text": null
},
{
"code": null,
"e": 32246,
"s": 32238,
"text": "Output:"
},
{
"code": null,
"e": 32417,
"s": 32246,
"text": "Inside handler(, FileNotFoundError(2, βThe system cannot find the path specifiedβ), )Inside handler(, FileNotFoundError(2, βThe system cannot find the file specifiedβ), )"
},
{
"code": null,
"e": 32447,
"s": 32417,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 32469,
"s": 32447,
"text": "Python OS-path-module"
},
{
"code": null,
"e": 32490,
"s": 32469,
"text": "python-file-handling"
},
{
"code": null,
"e": 32497,
"s": 32490,
"text": "Python"
},
{
"code": null,
"e": 32513,
"s": 32497,
"text": "Python Programs"
},
{
"code": null,
"e": 32611,
"s": 32513,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32643,
"s": 32611,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 32685,
"s": 32643,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 32741,
"s": 32685,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 32783,
"s": 32741,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 32838,
"s": 32783,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 32860,
"s": 32838,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 32906,
"s": 32860,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 32945,
"s": 32906,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 32983,
"s": 32945,
"text": "Python | Convert a list to dictionary"
}
] |
How to use select list in selenium?
|
We can select an option from the dropdown list with Selenium webdriver. The Select class is used to handle static dropdown. A dropdown is identified with the <select> tag in an html code.
Let us consider the below html code for <select> tag.
We have to import org.openqa.selenium.support.ui.Select to work with methods under Select class in our code. Let us see some of the Select methodsβ
selectByVisibleText(arg) β An option is selected if the text visible on the dropdown is the same as the parameter arg passed as an argument to the method.Syntaxsel = Select (driver.findElement(By.id ("option")));sel.selectByVisibleText ("Selenium");
selectByVisibleText(arg) β An option is selected if the text visible on the dropdown is the same as the parameter arg passed as an argument to the method.
sel = Select (driver.findElement(By.id ("option")));
sel.selectByVisibleText ("Selenium");
selectByValue(arg) β An option is selected if the value on the dropdown which is the same as the parameter arg passed as an argument to the method.Syntaxsel = Select (driver.findElement(By.id("option")));sel.selectByValue ("val");
selectByValue(arg) β An option is selected if the value on the dropdown which is the same as the parameter arg passed as an argument to the method.
sel = Select (driver.findElement(By.id("option")));
sel.selectByValue ("val");
selectByIndex(arg) β An option is selected if the index on the dropdown which is the same as the parameter arg passed as an argument to the method. The index starts from 0.Syntaxsel = Select (driver.findElement(By.id("option")));sel.selectByIndex(3);
selectByIndex(arg) β An option is selected if the index on the dropdown which is the same as the parameter arg passed as an argument to the method. The index starts from 0.
sel = Select (driver.findElement(By.id("option")));
sel.selectByIndex(3);
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;
import org.openqa.selenium.support.ui.Select
public class SelectItem{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"
driver.get(url);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// identify element
WebElement p=driver.findElement(By.xpath("//[@name='continents']"));
//Select class
Select sel= new Select(p);
// select with text visible
sel.selectByVisibleText("Africa");
// select with index
sel.selectByIndex(5);
driver.quit();
}
}
|
[
{
"code": null,
"e": 1250,
"s": 1062,
"text": "We can select an option from the dropdown list with Selenium webdriver. The Select class is used to handle static dropdown. A dropdown is identified with the <select> tag in an html code."
},
{
"code": null,
"e": 1304,
"s": 1250,
"text": "Let us consider the below html code for <select> tag."
},
{
"code": null,
"e": 1452,
"s": 1304,
"text": "We have to import org.openqa.selenium.support.ui.Select to work with methods under Select class in our code. Let us see some of the Select methodsβ"
},
{
"code": null,
"e": 1702,
"s": 1452,
"text": "selectByVisibleText(arg) β An option is selected if the text visible on the dropdown is the same as the parameter arg passed as an argument to the method.Syntaxsel = Select (driver.findElement(By.id (\"option\")));sel.selectByVisibleText (\"Selenium\");"
},
{
"code": null,
"e": 1857,
"s": 1702,
"text": "selectByVisibleText(arg) β An option is selected if the text visible on the dropdown is the same as the parameter arg passed as an argument to the method."
},
{
"code": null,
"e": 1910,
"s": 1857,
"text": "sel = Select (driver.findElement(By.id (\"option\")));"
},
{
"code": null,
"e": 1948,
"s": 1910,
"text": "sel.selectByVisibleText (\"Selenium\");"
},
{
"code": null,
"e": 2179,
"s": 1948,
"text": "selectByValue(arg) β An option is selected if the value on the dropdown which is the same as the parameter arg passed as an argument to the method.Syntaxsel = Select (driver.findElement(By.id(\"option\")));sel.selectByValue (\"val\");"
},
{
"code": null,
"e": 2327,
"s": 2179,
"text": "selectByValue(arg) β An option is selected if the value on the dropdown which is the same as the parameter arg passed as an argument to the method."
},
{
"code": null,
"e": 2379,
"s": 2327,
"text": "sel = Select (driver.findElement(By.id(\"option\")));"
},
{
"code": null,
"e": 2406,
"s": 2379,
"text": "sel.selectByValue (\"val\");"
},
{
"code": null,
"e": 2657,
"s": 2406,
"text": "selectByIndex(arg) β An option is selected if the index on the dropdown which is the same as the parameter arg passed as an argument to the method. The index starts from 0.Syntaxsel = Select (driver.findElement(By.id(\"option\")));sel.selectByIndex(3);"
},
{
"code": null,
"e": 2830,
"s": 2657,
"text": "selectByIndex(arg) β An option is selected if the index on the dropdown which is the same as the parameter arg passed as an argument to the method. The index starts from 0."
},
{
"code": null,
"e": 2882,
"s": 2830,
"text": "sel = Select (driver.findElement(By.id(\"option\")));"
},
{
"code": null,
"e": 2904,
"s": 2882,
"text": "sel.selectByIndex(3);"
},
{
"code": null,
"e": 3858,
"s": 2904,
"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;\nimport org.openqa.selenium.support.ui.Select\n\npublic class SelectItem{\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 url =\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\"\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n // identify element\n WebElement p=driver.findElement(By.xpath(\"//[@name='continents']\"));\n //Select class\n Select sel= new Select(p);\n // select with text visible\n sel.selectByVisibleText(\"Africa\");\n // select with index\n sel.selectByIndex(5);\n driver.quit();\n }\n}"
}
] |
Granting _SYS_REPO with SELECT to user schema in SAP HANA
|
In SAP HANA system _SYS_REPO user is required to create run time objects that are saved in HANA database under _SYS_BIC schema. When you activate modeling views in HANA, SYS REPO provides the read access to users on these modeling views. That is why it is required to grant _SYS_REPO with SELECT with GRANT privilege to user schemas.
GRANT SELECT ON SCHEMA "SCHEMA_NAME" TO _SYS_REPO WITH GRANT OPTION
This is required when you use objects of a table/view of a schema to build HANA Modeling Views. You need to grant _SYS_REPO the SELECT WITH GRANT privilege on this schema.
|
[
{
"code": null,
"e": 1396,
"s": 1062,
"text": "In SAP HANA system _SYS_REPO user is required to create run time objects that are saved in HANA database under _SYS_BIC schema. When you activate modeling views in HANA, SYS REPO provides the read access to users on these modeling views. That is why it is required to grant _SYS_REPO with SELECT with GRANT privilege to user schemas."
},
{
"code": null,
"e": 1464,
"s": 1396,
"text": "GRANT SELECT ON SCHEMA \"SCHEMA_NAME\" TO _SYS_REPO WITH GRANT OPTION"
},
{
"code": null,
"e": 1636,
"s": 1464,
"text": "This is required when you use objects of a table/view of a schema to build HANA Modeling Views. You need to grant _SYS_REPO the SELECT WITH GRANT privilege on this schema."
}
] |
Overloading in PHP
|
15 Jun, 2022
What is function overloading? Function overloading is the ability to create multiple functions of the same name with different implementations. Function overloading in PHP? Function overloading in PHP is used to dynamically create properties and methods. These dynamic entities are processed by magic methods which can be used in a class for various action types. Function overloading contains same function name and that function performs different task according to number of arguments. For example, find the area of certain shapes where radius are given then it should return area of circle if height and width are given then it should give area of rectangle and others. Like other OOP languages function overloading can not be done by native approach. In PHP function overloading is done with the help of magic function __call(). This function takes function name and arguments.
Property and Rules of overloading in PHP:
All overloading methods must be defined as Public.
After creating the object for a class, we can access a set of entities that are properties or methods not defined within the scope of the class.
Such entities are said to be overloaded properties or methods, and the process is called as overloading.
For working with these overloaded properties or functions, PHP magic methods are used.
Most of the magic methods will be triggered in object context except __callStatic() method which is used in a static context.
Types of Overloading in PHP: There are two types of overloading in PHP.
Property Overloading
Method Overloading
Property Overloading: PHP property overloading is used to create dynamic properties in the object context. For creating these properties no separate line of code is needed. A property associated with a class instance, and if it is not declared within the scope of the class, it is considered as overloaded property. Following operations are performed with overloaded properties in PHP.
Setting and getting overloaded properties.
Evaluating overloaded properties setting.
Undo such properties setting.
Before performing the operations, we should define appropriate magic methods. which are,
__set(): triggered while initializing overloaded properties.
__get(): triggered while using overloaded properties with PHP print statements.
__isset(): This magic method is invoked when we check overloaded properties with isset() function
__unset(): Similarly, this function will be invoked on using PHP unset() for overloaded properties.
Example:
PHP
<?php //class GFG { // Location of overloading data private $data = array(); // Overloading not used here public $declared = 1; // Overloading used when accessed // outside the class private $hidden = 2; // Function definition public function __set($name, $value) { echo "Setting '$name' to '$value'\n"; $this->data[$name] = $value; } // Function definition public function __get($name) { echo "Getting '$name: "; if (array_key_exists($name, $this->data)) { return $this->data[$name]; } $trace = debug_backtrace(); return null; } // Function definition public function __isset($name) { echo "Is '$name' set?\n"; return isset($this->data[$name]); } // Definition of __unset function public function __unset($name) { echo "Unsetting '$name'\n"; unset($this->data[$name]); } // getHidden function definition public function getHidden() { return $this->hidden; }} // Create an object$obj = new GFG; // Set value 1 to the object variable$obj->a = 1;echo $obj->a . "\n"; // Use isset function to check// 'a' is set or notvar_dump(isset($obj->a)); // Unset 'a'unset($obj->a); var_dump(isset($obj->a)); echo $obj->declared . "\n\n"; echo "Private property are visible inside the class ";echo $obj->getHidden() . "\n\n"; echo "Private property are not visible outside of class\n";echo $obj->hidden . "\n"; ?>
Setting 'a' to '1'
Getting 'a: 1
Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)
1
Private property are visible inside the class 2
Private property are not visible outside of class
Getting 'hidden:
Method Overloading: It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic methods dedicated to the appropriate purpose. Unlike property overloading, PHP method overloading allows function call on both object and static context. The related magic functions are,
__call() β triggered while invoking overloaded methods in the object context.
__callStatic() β triggered while invoking overloaded methods in static context.
Example:
PHP
<?phpclass GFG { public function __call($name, $arguments) { echo "Calling object method '$name' " . implode(', ', $arguments). "\n"; } public static function __callStatic($name, $arguments) { echo "Calling static method '$name' " . implode(', ', $arguments). "\n"; }} // Create new object$obj = new GFG; $obj->runTest('in object context'); GFG::runTest('in static context'); ?>
Calling object method 'runTest' in object context
Calling static method 'runTest' in static context
anikaseth98
kashishsoda
sagartomar9927
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 936,
"s": 52,
"text": "What is function overloading? Function overloading is the ability to create multiple functions of the same name with different implementations. Function overloading in PHP? Function overloading in PHP is used to dynamically create properties and methods. These dynamic entities are processed by magic methods which can be used in a class for various action types. Function overloading contains same function name and that function performs different task according to number of arguments. For example, find the area of certain shapes where radius are given then it should return area of circle if height and width are given then it should give area of rectangle and others. Like other OOP languages function overloading can not be done by native approach. In PHP function overloading is done with the help of magic function __call(). This function takes function name and arguments. "
},
{
"code": null,
"e": 978,
"s": 936,
"text": "Property and Rules of overloading in PHP:"
},
{
"code": null,
"e": 1029,
"s": 978,
"text": "All overloading methods must be defined as Public."
},
{
"code": null,
"e": 1174,
"s": 1029,
"text": "After creating the object for a class, we can access a set of entities that are properties or methods not defined within the scope of the class."
},
{
"code": null,
"e": 1279,
"s": 1174,
"text": "Such entities are said to be overloaded properties or methods, and the process is called as overloading."
},
{
"code": null,
"e": 1366,
"s": 1279,
"text": "For working with these overloaded properties or functions, PHP magic methods are used."
},
{
"code": null,
"e": 1492,
"s": 1366,
"text": "Most of the magic methods will be triggered in object context except __callStatic() method which is used in a static context."
},
{
"code": null,
"e": 1564,
"s": 1492,
"text": "Types of Overloading in PHP: There are two types of overloading in PHP."
},
{
"code": null,
"e": 1585,
"s": 1564,
"text": "Property Overloading"
},
{
"code": null,
"e": 1604,
"s": 1585,
"text": "Method Overloading"
},
{
"code": null,
"e": 1990,
"s": 1604,
"text": "Property Overloading: PHP property overloading is used to create dynamic properties in the object context. For creating these properties no separate line of code is needed. A property associated with a class instance, and if it is not declared within the scope of the class, it is considered as overloaded property. Following operations are performed with overloaded properties in PHP."
},
{
"code": null,
"e": 2033,
"s": 1990,
"text": "Setting and getting overloaded properties."
},
{
"code": null,
"e": 2075,
"s": 2033,
"text": "Evaluating overloaded properties setting."
},
{
"code": null,
"e": 2105,
"s": 2075,
"text": "Undo such properties setting."
},
{
"code": null,
"e": 2194,
"s": 2105,
"text": "Before performing the operations, we should define appropriate magic methods. which are,"
},
{
"code": null,
"e": 2255,
"s": 2194,
"text": "__set(): triggered while initializing overloaded properties."
},
{
"code": null,
"e": 2335,
"s": 2255,
"text": "__get(): triggered while using overloaded properties with PHP print statements."
},
{
"code": null,
"e": 2433,
"s": 2335,
"text": "__isset(): This magic method is invoked when we check overloaded properties with isset() function"
},
{
"code": null,
"e": 2533,
"s": 2433,
"text": "__unset(): Similarly, this function will be invoked on using PHP unset() for overloaded properties."
},
{
"code": null,
"e": 2543,
"s": 2533,
"text": "Example: "
},
{
"code": null,
"e": 2547,
"s": 2543,
"text": "PHP"
},
{
"code": "<?php //class GFG { // Location of overloading data private $data = array(); // Overloading not used here public $declared = 1; // Overloading used when accessed // outside the class private $hidden = 2; // Function definition public function __set($name, $value) { echo \"Setting '$name' to '$value'\\n\"; $this->data[$name] = $value; } // Function definition public function __get($name) { echo \"Getting '$name: \"; if (array_key_exists($name, $this->data)) { return $this->data[$name]; } $trace = debug_backtrace(); return null; } // Function definition public function __isset($name) { echo \"Is '$name' set?\\n\"; return isset($this->data[$name]); } // Definition of __unset function public function __unset($name) { echo \"Unsetting '$name'\\n\"; unset($this->data[$name]); } // getHidden function definition public function getHidden() { return $this->hidden; }} // Create an object$obj = new GFG; // Set value 1 to the object variable$obj->a = 1;echo $obj->a . \"\\n\"; // Use isset function to check// 'a' is set or notvar_dump(isset($obj->a)); // Unset 'a'unset($obj->a); var_dump(isset($obj->a)); echo $obj->declared . \"\\n\\n\"; echo \"Private property are visible inside the class \";echo $obj->getHidden() . \"\\n\\n\"; echo \"Private property are not visible outside of class\\n\";echo $obj->hidden . \"\\n\"; ?>",
"e": 4038,
"s": 2547,
"text": null
},
{
"code": null,
"e": 4251,
"s": 4038,
"text": "Setting 'a' to '1'\nGetting 'a: 1\nIs 'a' set?\nbool(true)\nUnsetting 'a'\nIs 'a' set?\nbool(false)\n1\n\nPrivate property are visible inside the class 2\n\nPrivate property are not visible outside of class\nGetting 'hidden:"
},
{
"code": null,
"e": 4604,
"s": 4251,
"text": "Method Overloading: It is a type of overloading for creating dynamic methods that are not declared within the class scope. PHP method overloading also triggers magic methods dedicated to the appropriate purpose. Unlike property overloading, PHP method overloading allows function call on both object and static context. The related magic functions are,"
},
{
"code": null,
"e": 4682,
"s": 4604,
"text": "__call() β triggered while invoking overloaded methods in the object context."
},
{
"code": null,
"e": 4762,
"s": 4682,
"text": "__callStatic() β triggered while invoking overloaded methods in static context."
},
{
"code": null,
"e": 4772,
"s": 4762,
"text": "Example: "
},
{
"code": null,
"e": 4776,
"s": 4772,
"text": "PHP"
},
{
"code": "<?phpclass GFG { public function __call($name, $arguments) { echo \"Calling object method '$name' \" . implode(', ', $arguments). \"\\n\"; } public static function __callStatic($name, $arguments) { echo \"Calling static method '$name' \" . implode(', ', $arguments). \"\\n\"; }} // Create new object$obj = new GFG; $obj->runTest('in object context'); GFG::runTest('in static context'); ?>",
"e": 5237,
"s": 4776,
"text": null
},
{
"code": null,
"e": 5337,
"s": 5237,
"text": "Calling object method 'runTest' in object context\nCalling static method 'runTest' in static context"
},
{
"code": null,
"e": 5349,
"s": 5337,
"text": "anikaseth98"
},
{
"code": null,
"e": 5361,
"s": 5349,
"text": "kashishsoda"
},
{
"code": null,
"e": 5376,
"s": 5361,
"text": "sagartomar9927"
},
{
"code": null,
"e": 5383,
"s": 5376,
"text": "Picked"
},
{
"code": null,
"e": 5387,
"s": 5383,
"text": "PHP"
},
{
"code": null,
"e": 5400,
"s": 5387,
"text": "PHP Programs"
},
{
"code": null,
"e": 5417,
"s": 5400,
"text": "Web Technologies"
},
{
"code": null,
"e": 5421,
"s": 5417,
"text": "PHP"
}
] |
Use of :even and :odd pseudo-classes with list items in CSS
|
16 Dec, 2021
The:nth-child() selector in CSS is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child. The: even and: odd pseudo-class is used with the list of items such as paragraph, article items which is basically a list content.
odd: The use of odd pseudo-class in any list item that will affect only the odd index number list. Syntax:
li:nth-child( odd ) {
// CSS Property
}
Example:
HTML
<!DOCTYPE html><html> <head> <title> CSS :nth-child(odd) Selector </title> <!-- Style to uses :nth-child(odd) Selector --> <style> li:nth-child(odd) { background: green; font-size: 24px; color:white; } </style></head> <body> <li>GeeksforGeeks</li> <li>A Computer Science portal</li> <li>Welcome to GeeksforGeeks</li></body> </html>
Output:
even: The use of even pseudo-class in any list item that will effect only the even index number list. Syntax:
li:nth-child( even ) {
// CSS Property
}
Example:
HTML
<!DOCTYPE html><html> <head> <title> CSS :nth-child(even) Selector </title> <!-- Style to uses :nth-child(odd) Selector --> <style> li:nth-child(even) { background: green; font-size: 24px; color:white; } </style></head> <body> <li>GeeksforGeeks</li> <li>A Computer Science portal</li> <li>Welcome to GeeksforGeeks</li></body> </html>
Output:
Example: This example uses both :even and :odd pseudo-class selector.
HTML
<!DOCTYPE html><html> <head> <style> li:nth-child(odd) { background: green; font-size: 36px; color:white; } li:nth-child(even) { background: Blue; font-size: 36px; color:yellow; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>:even and :odd pseudo-class</h2> <li>Data Structure</li> <li>Operating System</li> <li>Computer Networks</li> <li>C Programming</li></body> </html>
Output:
Supported Browsers:
Google Chrome 4.0
Internet Explorer 9.0
Firefox 3.5
Opera 9.6
Safari 3.2
ysachin2314
sagar0719kumar
CSS-Selectors
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Create a Responsive Navbar using ReactJS
How to auto-resize an image to fit a div container using CSS?
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": 52,
"s": 24,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 342,
"s": 52,
"text": "The:nth-child() selector in CSS is used to match the elements based on their position in a group of siblings. It matches every element that is the nth-child. The: even and: odd pseudo-class is used with the list of items such as paragraph, article items which is basically a list content. "
},
{
"code": null,
"e": 449,
"s": 342,
"text": "odd: The use of odd pseudo-class in any list item that will affect only the odd index number list. Syntax:"
},
{
"code": null,
"e": 496,
"s": 449,
"text": "li:nth-child( odd ) {\n // CSS Property \n}"
},
{
"code": null,
"e": 505,
"s": 496,
"text": "Example:"
},
{
"code": null,
"e": 510,
"s": 505,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS :nth-child(odd) Selector </title> <!-- Style to uses :nth-child(odd) Selector --> <style> li:nth-child(odd) { background: green; font-size: 24px; color:white; } </style></head> <body> <li>GeeksforGeeks</li> <li>A Computer Science portal</li> <li>Welcome to GeeksforGeeks</li></body> </html> ",
"e": 971,
"s": 510,
"text": null
},
{
"code": null,
"e": 981,
"s": 971,
"text": "Output: "
},
{
"code": null,
"e": 1091,
"s": 981,
"text": "even: The use of even pseudo-class in any list item that will effect only the even index number list. Syntax:"
},
{
"code": null,
"e": 1136,
"s": 1091,
"text": "li:nth-child( even ) {\n // CSS Property\n}"
},
{
"code": null,
"e": 1145,
"s": 1136,
"text": "Example:"
},
{
"code": null,
"e": 1150,
"s": 1145,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> CSS :nth-child(even) Selector </title> <!-- Style to uses :nth-child(odd) Selector --> <style> li:nth-child(even) { background: green; font-size: 24px; color:white; } </style></head> <body> <li>GeeksforGeeks</li> <li>A Computer Science portal</li> <li>Welcome to GeeksforGeeks</li></body> </html> ",
"e": 1616,
"s": 1150,
"text": null
},
{
"code": null,
"e": 1626,
"s": 1616,
"text": "Output: "
},
{
"code": null,
"e": 1696,
"s": 1626,
"text": "Example: This example uses both :even and :odd pseudo-class selector."
},
{
"code": null,
"e": 1701,
"s": 1696,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> li:nth-child(odd) { background: green; font-size: 36px; color:white; } li:nth-child(even) { background: Blue; font-size: 36px; color:yellow; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2>:even and :odd pseudo-class</h2> <li>Data Structure</li> <li>Operating System</li> <li>Computer Networks</li> <li>C Programming</li></body> </html> ",
"e": 2235,
"s": 1701,
"text": null
},
{
"code": null,
"e": 2243,
"s": 2235,
"text": "Output:"
},
{
"code": null,
"e": 2263,
"s": 2243,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 2281,
"s": 2263,
"text": "Google Chrome 4.0"
},
{
"code": null,
"e": 2303,
"s": 2281,
"text": "Internet Explorer 9.0"
},
{
"code": null,
"e": 2315,
"s": 2303,
"text": "Firefox 3.5"
},
{
"code": null,
"e": 2325,
"s": 2315,
"text": "Opera 9.6"
},
{
"code": null,
"e": 2336,
"s": 2325,
"text": "Safari 3.2"
},
{
"code": null,
"e": 2348,
"s": 2336,
"text": "ysachin2314"
},
{
"code": null,
"e": 2363,
"s": 2348,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2377,
"s": 2363,
"text": "CSS-Selectors"
},
{
"code": null,
"e": 2384,
"s": 2377,
"text": "Picked"
},
{
"code": null,
"e": 2388,
"s": 2384,
"text": "CSS"
},
{
"code": null,
"e": 2405,
"s": 2388,
"text": "Web Technologies"
},
{
"code": null,
"e": 2432,
"s": 2405,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2530,
"s": 2432,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2569,
"s": 2530,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2608,
"s": 2569,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2647,
"s": 2608,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2688,
"s": 2647,
"text": "Create a Responsive Navbar using ReactJS"
},
{
"code": null,
"e": 2750,
"s": 2688,
"text": "How to auto-resize an image to fit a div container using CSS?"
},
{
"code": null,
"e": 2783,
"s": 2750,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2844,
"s": 2783,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2887,
"s": 2844,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2959,
"s": 2887,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Header Linked List in C
|
29 Jan, 2020
Prerequisite: Linked List, Circular Linked List
A header node is a special node that is found at the beginning of the list. A list that contains this type of node, is called the header-linked list. This type of list is useful when information other than that found in each node is needed.For example, suppose there is an application in which the number of items in a list is often calculated. Usually, a list is always traversed to find the length of the list. However, if the current length is maintained in an additional header node that information can be easily obtained.
Types of Header Linked List
Grounded Header Linked ListIt is a list whose last node contains the NULL pointer. In the header linked list the start pointer always points to the header node. start -> next = NULL indicates that the grounded header linked list is empty. The operations that are possible on this type of linked list are Insertion, Deletion, and Traversing.Circular Header Linked ListA list in which last node points back to the header node is called circular linked list. The chains do not indicate first or last nodes. In this case, external pointers provide a frame of reference because last node of a circular linked list does not contain the NULL pointer. The possible operations on this type of linked list are Insertion, Deletion and Traversing.
Grounded Header Linked ListIt is a list whose last node contains the NULL pointer. In the header linked list the start pointer always points to the header node. start -> next = NULL indicates that the grounded header linked list is empty. The operations that are possible on this type of linked list are Insertion, Deletion, and Traversing.
Circular Header Linked ListA list in which last node points back to the header node is called circular linked list. The chains do not indicate first or last nodes. In this case, external pointers provide a frame of reference because last node of a circular linked list does not contain the NULL pointer. The possible operations on this type of linked list are Insertion, Deletion and Traversing.
// C program for a Header Linked List#include <malloc.h>#include <stdio.h> // Structure of the liststruct link { int info; struct link* next;}; // Empty Liststruct link* start = NULL; // Function to create a header linked liststruct link* create_header_list(int data){ // Create a new node struct link *new_node, *node; new_node = (struct link*) malloc(sizeof(struct link)); new_node->info = data; new_node->next = NULL; // If it is the first node if (start == NULL) { // Initialize the start start = (struct link*) malloc(sizeof(struct link)); start->next = new_node; } else { // Insert the node in the end node = start; while (node->next != NULL) { node = node->next; } node->next = new_node; } return start;} // Function to display the// header linked liststruct link* display(){ struct link* node; node = start; node = node->next; while (node != NULL) { printf("%d ", node->info); node = node->next; } printf("\n"); return start;} // Driver codeint main(){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list display(); create_header_list(14); create_header_list(15); // Print the list display(); return 0;}
11 12 13
11 12 13 14 15
Applications of Header Linked ListPolynomials
The header linked lists are frequently used to maintain the polynomials in memory. The header node is used to represent the zero polynomial.
Suppose we haveF(x) = 5x5 β 3x3 + 2x2 + x1 +10x0
From the polynomial represented by F(x) it is clear that this polynomial has two parts, coefficient and exponent, where, x is formal parameter. Hence, we can say that a polynomial is sum of terms, each of which consists of a coefficient and an exponent.
The computer implementation requires implementing polynomials as a list of pair of coefficient and exponent. Each of these pairs will constitute a structure, so a polynomial will be represented as a list of structures.
If one wants to represent F(x) with help of linked list then the list will contain 5 nodes. When we link each node we get a linked list structure that represents polynomial F(x).
Addition of polynomials
To add two polynomials, we need to scan them once.If we find terms with the same exponent in the two polynomials, then we add the coefficients, otherwise, we copy the term of larger exponent into the sum and go on.When we reach at the end of one of the polynomial, then remaining part of the other is copied into the sum.Suppose we have two polynomials as illustrated and we have to perform addition of these polynomials.When we scan first node of the two polynomials, we find that exponential power of first node in the second polynomial is greater than that of first node of the first polynomial.Here the exponent of the first node of the second polynomial is greater hence we have to copy first node of the second polynomial into the sum.Then we consider the first node of the first polynomial and once again first node value of first polynomial is compared with the second node value of the second polynomial.Here the first node exponent value of the first polynomial is greater than the second node exponent value of the second polynomial. We copy the first node of the first polynomial into the sum.Now consider the second node of the first polynomial and compare it with the second node of the second polynomial.Here the exponent value of the second node of the second polynomial is greater than the second node of the first polynomial, hence we copy the second node of the second list into the sum.Now we consider the third node exponent of the second polynomial and compare it with second node exponent value of the first polynomial. We find that both are equal, hence perform addition of their coefficient and copy in to the sum.This process continues till all the nodes of both the polynomial are exhausted. For example after adding the above two polynomials, we get the following resultant polynomial as shown.
To add two polynomials, we need to scan them once.
If we find terms with the same exponent in the two polynomials, then we add the coefficients, otherwise, we copy the term of larger exponent into the sum and go on.
When we reach at the end of one of the polynomial, then remaining part of the other is copied into the sum.
Suppose we have two polynomials as illustrated and we have to perform addition of these polynomials.
When we scan first node of the two polynomials, we find that exponential power of first node in the second polynomial is greater than that of first node of the first polynomial.
Here the exponent of the first node of the second polynomial is greater hence we have to copy first node of the second polynomial into the sum.
Then we consider the first node of the first polynomial and once again first node value of first polynomial is compared with the second node value of the second polynomial.
Here the first node exponent value of the first polynomial is greater than the second node exponent value of the second polynomial. We copy the first node of the first polynomial into the sum.
Now consider the second node of the first polynomial and compare it with the second node of the second polynomial.
Here the exponent value of the second node of the second polynomial is greater than the second node of the first polynomial, hence we copy the second node of the second list into the sum.
Now we consider the third node exponent of the second polynomial and compare it with second node exponent value of the first polynomial. We find that both are equal, hence perform addition of their coefficient and copy in to the sum.
This process continues till all the nodes of both the polynomial are exhausted. For example after adding the above two polynomials, we get the following resultant polynomial as shown.
Further reference: Adding Two Polynomials
andrew1234
Data Structures
Linked List
Data Structures
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Jan, 2020"
},
{
"code": null,
"e": 100,
"s": 52,
"text": "Prerequisite: Linked List, Circular Linked List"
},
{
"code": null,
"e": 628,
"s": 100,
"text": "A header node is a special node that is found at the beginning of the list. A list that contains this type of node, is called the header-linked list. This type of list is useful when information other than that found in each node is needed.For example, suppose there is an application in which the number of items in a list is often calculated. Usually, a list is always traversed to find the length of the list. However, if the current length is maintained in an additional header node that information can be easily obtained."
},
{
"code": null,
"e": 656,
"s": 628,
"text": "Types of Header Linked List"
},
{
"code": null,
"e": 1392,
"s": 656,
"text": "Grounded Header Linked ListIt is a list whose last node contains the NULL pointer. In the header linked list the start pointer always points to the header node. start -> next = NULL indicates that the grounded header linked list is empty. The operations that are possible on this type of linked list are Insertion, Deletion, and Traversing.Circular Header Linked ListA list in which last node points back to the header node is called circular linked list. The chains do not indicate first or last nodes. In this case, external pointers provide a frame of reference because last node of a circular linked list does not contain the NULL pointer. The possible operations on this type of linked list are Insertion, Deletion and Traversing."
},
{
"code": null,
"e": 1733,
"s": 1392,
"text": "Grounded Header Linked ListIt is a list whose last node contains the NULL pointer. In the header linked list the start pointer always points to the header node. start -> next = NULL indicates that the grounded header linked list is empty. The operations that are possible on this type of linked list are Insertion, Deletion, and Traversing."
},
{
"code": null,
"e": 2129,
"s": 1733,
"text": "Circular Header Linked ListA list in which last node points back to the header node is called circular linked list. The chains do not indicate first or last nodes. In this case, external pointers provide a frame of reference because last node of a circular linked list does not contain the NULL pointer. The possible operations on this type of linked list are Insertion, Deletion and Traversing."
},
{
"code": "// C program for a Header Linked List#include <malloc.h>#include <stdio.h> // Structure of the liststruct link { int info; struct link* next;}; // Empty Liststruct link* start = NULL; // Function to create a header linked liststruct link* create_header_list(int data){ // Create a new node struct link *new_node, *node; new_node = (struct link*) malloc(sizeof(struct link)); new_node->info = data; new_node->next = NULL; // If it is the first node if (start == NULL) { // Initialize the start start = (struct link*) malloc(sizeof(struct link)); start->next = new_node; } else { // Insert the node in the end node = start; while (node->next != NULL) { node = node->next; } node->next = new_node; } return start;} // Function to display the// header linked liststruct link* display(){ struct link* node; node = start; node = node->next; while (node != NULL) { printf(\"%d \", node->info); node = node->next; } printf(\"\\n\"); return start;} // Driver codeint main(){ // Create the list create_header_list(11); create_header_list(12); create_header_list(13); // Print the list display(); create_header_list(14); create_header_list(15); // Print the list display(); return 0;}",
"e": 3511,
"s": 2129,
"text": null
},
{
"code": null,
"e": 3537,
"s": 3511,
"text": "11 12 13 \n11 12 13 14 15\n"
},
{
"code": null,
"e": 3583,
"s": 3537,
"text": "Applications of Header Linked ListPolynomials"
},
{
"code": null,
"e": 3724,
"s": 3583,
"text": "The header linked lists are frequently used to maintain the polynomials in memory. The header node is used to represent the zero polynomial."
},
{
"code": null,
"e": 3773,
"s": 3724,
"text": "Suppose we haveF(x) = 5x5 β 3x3 + 2x2 + x1 +10x0"
},
{
"code": null,
"e": 4027,
"s": 3773,
"text": "From the polynomial represented by F(x) it is clear that this polynomial has two parts, coefficient and exponent, where, x is formal parameter. Hence, we can say that a polynomial is sum of terms, each of which consists of a coefficient and an exponent."
},
{
"code": null,
"e": 4246,
"s": 4027,
"text": "The computer implementation requires implementing polynomials as a list of pair of coefficient and exponent. Each of these pairs will constitute a structure, so a polynomial will be represented as a list of structures."
},
{
"code": null,
"e": 4425,
"s": 4246,
"text": "If one wants to represent F(x) with help of linked list then the list will contain 5 nodes. When we link each node we get a linked list structure that represents polynomial F(x)."
},
{
"code": null,
"e": 4449,
"s": 4425,
"text": "Addition of polynomials"
},
{
"code": null,
"e": 6272,
"s": 4449,
"text": "To add two polynomials, we need to scan them once.If we find terms with the same exponent in the two polynomials, then we add the coefficients, otherwise, we copy the term of larger exponent into the sum and go on.When we reach at the end of one of the polynomial, then remaining part of the other is copied into the sum.Suppose we have two polynomials as illustrated and we have to perform addition of these polynomials.When we scan first node of the two polynomials, we find that exponential power of first node in the second polynomial is greater than that of first node of the first polynomial.Here the exponent of the first node of the second polynomial is greater hence we have to copy first node of the second polynomial into the sum.Then we consider the first node of the first polynomial and once again first node value of first polynomial is compared with the second node value of the second polynomial.Here the first node exponent value of the first polynomial is greater than the second node exponent value of the second polynomial. We copy the first node of the first polynomial into the sum.Now consider the second node of the first polynomial and compare it with the second node of the second polynomial.Here the exponent value of the second node of the second polynomial is greater than the second node of the first polynomial, hence we copy the second node of the second list into the sum.Now we consider the third node exponent of the second polynomial and compare it with second node exponent value of the first polynomial. We find that both are equal, hence perform addition of their coefficient and copy in to the sum.This process continues till all the nodes of both the polynomial are exhausted. For example after adding the above two polynomials, we get the following resultant polynomial as shown."
},
{
"code": null,
"e": 6323,
"s": 6272,
"text": "To add two polynomials, we need to scan them once."
},
{
"code": null,
"e": 6488,
"s": 6323,
"text": "If we find terms with the same exponent in the two polynomials, then we add the coefficients, otherwise, we copy the term of larger exponent into the sum and go on."
},
{
"code": null,
"e": 6596,
"s": 6488,
"text": "When we reach at the end of one of the polynomial, then remaining part of the other is copied into the sum."
},
{
"code": null,
"e": 6697,
"s": 6596,
"text": "Suppose we have two polynomials as illustrated and we have to perform addition of these polynomials."
},
{
"code": null,
"e": 6875,
"s": 6697,
"text": "When we scan first node of the two polynomials, we find that exponential power of first node in the second polynomial is greater than that of first node of the first polynomial."
},
{
"code": null,
"e": 7019,
"s": 6875,
"text": "Here the exponent of the first node of the second polynomial is greater hence we have to copy first node of the second polynomial into the sum."
},
{
"code": null,
"e": 7192,
"s": 7019,
"text": "Then we consider the first node of the first polynomial and once again first node value of first polynomial is compared with the second node value of the second polynomial."
},
{
"code": null,
"e": 7385,
"s": 7192,
"text": "Here the first node exponent value of the first polynomial is greater than the second node exponent value of the second polynomial. We copy the first node of the first polynomial into the sum."
},
{
"code": null,
"e": 7500,
"s": 7385,
"text": "Now consider the second node of the first polynomial and compare it with the second node of the second polynomial."
},
{
"code": null,
"e": 7688,
"s": 7500,
"text": "Here the exponent value of the second node of the second polynomial is greater than the second node of the first polynomial, hence we copy the second node of the second list into the sum."
},
{
"code": null,
"e": 7922,
"s": 7688,
"text": "Now we consider the third node exponent of the second polynomial and compare it with second node exponent value of the first polynomial. We find that both are equal, hence perform addition of their coefficient and copy in to the sum."
},
{
"code": null,
"e": 8106,
"s": 7922,
"text": "This process continues till all the nodes of both the polynomial are exhausted. For example after adding the above two polynomials, we get the following resultant polynomial as shown."
},
{
"code": null,
"e": 8148,
"s": 8106,
"text": "Further reference: Adding Two Polynomials"
},
{
"code": null,
"e": 8159,
"s": 8148,
"text": "andrew1234"
},
{
"code": null,
"e": 8175,
"s": 8159,
"text": "Data Structures"
},
{
"code": null,
"e": 8187,
"s": 8175,
"text": "Linked List"
},
{
"code": null,
"e": 8203,
"s": 8187,
"text": "Data Structures"
},
{
"code": null,
"e": 8215,
"s": 8203,
"text": "Linked List"
}
] |
PyQt5 QListWidget β Setting Selection Mode
|
06 Aug, 2020
In this article we will see how we can set the selection mode property to the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds which selection mode the view operates in. This property controls whether the user can select one or many items and, in many-item selections, whether the selection must be a continuous range of items.
In order to do this we will use setSelectionMode method with the list widget object.
Syntax : list_widget.setSelectionMode(mode)
Argument : It takes selection mode object as argument
Return : It returns None
Below is the implementation
# 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 QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem("A") item2 = QListWidgetItem("B") item3 = QListWidgetItem("C") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting selection mode property list_widget.setSelectionMode(QAbstractItemView.MultiSelection) # creating a label label = QLabel("GeesforGeeks", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QListWidget
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": "\n06 Aug, 2020"
},
{
"code": null,
"e": 547,
"s": 28,
"text": "In this article we will see how we can set the selection mode property to the QListWidget. QListWidget is a convenience class that provides a list view with a classic item-based interface for adding and removing items. QListWidget uses an internal model to manage each QListWidgetItem in the list. This property holds which selection mode the view operates in. This property controls whether the user can select one or many items and, in many-item selections, whether the selection must be a continuous range of items."
},
{
"code": null,
"e": 632,
"s": 547,
"text": "In order to do this we will use setSelectionMode method with the list widget object."
},
{
"code": null,
"e": 676,
"s": 632,
"text": "Syntax : list_widget.setSelectionMode(mode)"
},
{
"code": null,
"e": 730,
"s": 676,
"text": "Argument : It takes selection mode object as argument"
},
{
"code": null,
"e": 755,
"s": 730,
"text": "Return : It returns None"
},
{
"code": null,
"e": 783,
"s": 755,
"text": "Below is the implementation"
},
{
"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 QListWidget list_widget = QListWidget(self) # setting geometry to it list_widget.setGeometry(50, 70, 150, 60) # list widget items item1 = QListWidgetItem(\"A\") item2 = QListWidgetItem(\"B\") item3 = QListWidgetItem(\"C\") # adding items to the list widget list_widget.addItem(item1) list_widget.addItem(item2) list_widget.addItem(item3) # setting selection mode property list_widget.setSelectionMode(QAbstractItemView.MultiSelection) # creating a label label = QLabel(\"GeesforGeeks\", self) # setting geometry to the label label.setGeometry(230, 80, 280, 80) # making label multi line label.setWordWrap(True) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 2227,
"s": 783,
"text": null
},
{
"code": null,
"e": 2236,
"s": 2227,
"text": "Output :"
},
{
"code": null,
"e": 2260,
"s": 2236,
"text": "Python PyQt-QListWidget"
},
{
"code": null,
"e": 2271,
"s": 2260,
"text": "Python-gui"
},
{
"code": null,
"e": 2283,
"s": 2271,
"text": "Python-PyQt"
},
{
"code": null,
"e": 2290,
"s": 2283,
"text": "Python"
}
] |
Linked List Pair Sum
|
04 Apr, 2022
Given a linked list, and a number, check if their exist two numbers whose sum is equal to given number. If there exist two numbers, print them. If there are multiple answer, print any of them.Examples:
Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL
sum = 3
Output : Pair is (1, 2)
Input : 10 -> 12 -> 31 -> 42 -> 53 -> NULL
sum = 15
Output : NO PAIR EXIST
Method(Brute force) Iteratively check if their exist any pair or not
C++
Java
Python3
C#
Javascript
// CPP code to find the pair with given sum#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Takes head pointer of the linked list and sum*/int check_pair_sum(struct Node* head, int sum){ struct Node* p = head, *q; while (p != NULL) { q = p->next; while (q != NULL) { // check if both sum is equal to // given sum if ((p->data) + (q->data) == sum) { cout << p->data << " " << q->data; return true; } q = q->next; } p = p->next; } return 0;} /* Driver program to test above function */int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list*/ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_sum(head, 26); if (res == false) cout << "NO PAIR EXIST"; return 0;}
// Java code to find the pair with given sumimport java.util.*; class GFG { /* Link list node */ static class Node { int data; Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ // Inserting node at the beginning static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref; } /* Takes head pointer of the linked list and sum*/ static boolean check_pair_sum(Node head, int sum) { Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both sum is equal to // given sum if ((p.data) + (q.data) == sum) { System.out.print(p.data + " " + q.data); return true; } q = q.next; } p = p.next; } return false; } // Driver Code public static void main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ boolean res = check_pair_sum(head, 26); if (res == false) System.out.print("NO PAIR EXIST"); }} // This code is contributed by 29AjayKumar
# Python3 program for finding the pair with given sumimport mathimport sys # Link list node # class Node: def __init__(self, data): self.data = data self.next = None# Given a reference (pointer to pointer) to the head# of a list and an int, push a new node on the front# of the list. def push(head, data): if head == None: return Node(data) # allocate node temp = Node(data) # link the old list off the new node temp.next = head # move the head to point to the new node head = temp return head # Takes head pointer of the linked list and sum def check_pair_sum(head, _sum_): p = head q = None while(p): q = p.next while(q): if p.data+q.data == _sum_: print("{} {}".format(p.data, q.data)) return True q = q.next p = p.next return False # Driver program to test above functionif __name__ == '__main__': # Start with the empty list head = None # Use push() to construct linked list head = push(head, 1) head = push(head, 4) head = push(head, 1) head = push(head, 12) head = push(head, 1) head = push(head, 18) head = push(head, 47) head = push(head, 16) head = push(head, 12) head = push(head, 14) # function to print the result res = check_pair_sum(head, 26) if (res == False): print("NO PAIR EXIST") # This code is contributed by Vikash Kumar 37
// C# code to find the pair with given sumusing System; class GFG { /* Link list node */ public class Node { public int data; public Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ // Inserting node at the beginning static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref; } /* Takes head pointer of the linked list and sum*/ static Boolean check_pair_sum(Node head, int sum) { Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both sum is equal to // given sum if ((p.data) + (q.data) == sum) { Console.Write(p.data + " " + q.data); return true; } q = q.next; } p = p.next; } return false; } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ Boolean res = check_pair_sum(head, 26); if (res == false) Console.Write("NO PAIR EXIST"); }} // This code is contributed by Rajput-Ji
<script> // JavaScript code to find the pair with given sum /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }}; var head = null;/* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */// Inserting node at the beginningfunction push(head_ref, new_data){ /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref;}/* Takes head pointer of the linked list and sum*/function check_pair_sum(head, sum){ var p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both sum is equal to // given sum if ((p.data) + (q.data) == sum) { document.write(p.data + " " + q.data); return true; } q = q.next; } p = p.next; } return false;}// Driver Code/* Start with the empty list */head = null;/* Use push() to construct linked list*/push(head, 1);push(head, 4);push(head, 1);push(head, 12);push(head, 1);push(head, 18);push(head, 47);push(head, 16);push(head, 12);push(head, 14);/* function to print the result*/var res = check_pair_sum(head, 26);if (res == false) document.write("NO PAIR EXIST"); </script>
14 12
Time complexity: O(n*n)
Method 2 (using hashing) 1. Take a hashtable and mark all element with zero 2. Iteratively mark all the element as 1 in hashtable which are present in linked list 3. Iteratively find sum-current element of linked list is present in hashtable or not
C++
Java
Python3
C#
Javascript
// CPP program to for finding the pair with given sum#include <bits/stdc++.h>#define MAX 100000using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Takes head pointer of the linked list and sum*/bool check_pair_sum(struct Node* head, int sum){ unordered_set<int> s; struct Node* p = head; while (p != NULL) { int curr = p->data; if (s.find(sum - curr) != s.end()) { cout << curr << " " << sum - curr; return true; } s.insert(p->data); p = p->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_sum(head, 26); if (res == false) cout << "NO PAIR EXIST"; return 0;}
// Java program for finding// the pair with given sumimport java.util.*;class GFG { static int MAX = 100000; /* Link list node */ static class Node { int data; Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static void push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } /* Takes head pointer of the linked list and sum*/ static boolean check_pair_sum(Node head, int sum) { HashSet<Integer> s = new HashSet<Integer>(); Node p = head; while (p != null) { int curr = p.data; if (s.contains(sum - curr)) { System.out.print(curr + " " + (sum - curr)); return true; } s.add(p.data); p = p.next; } return false; } // Driver Code public static void main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ boolean res = check_pair_sum(head, 26); if (res == false) System.out.print("NO PAIR EXIST"); }} // This code is contributed by PrinciRaj1992
# Python3 program to for finding the pair with given sumMAX = 100000 ''' Link list node ''' class Node: def __init__(self, data): self.data = data self.next = None ''' Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. ''' def push(head_ref, new_data): ''' allocate node ''' new_node = Node(new_data) ''' put in the data ''' new_node.data = new_data ''' link the old list off the new node ''' new_node.next = (head_ref) ''' move the head to point to the new node ''' (head_ref) = new_node return head_ref ''' Takes head pointer of the linked list and sum''' def check_pair_sum(head, sum): s = set() p = head while (p != None): curr = p.data if((sum - curr) in s): print(curr, end=' ') print(sum-curr, end='') return True s.add(p.data) p = p.next return False ''' Driver program to test above function'''if __name__ == '__main__': ''' Start with the empty list ''' head = None ''' Use push() to construct linked list ''' head = push(head, 1) head = push(head, 4) head = push(head, 1) head = push(head, 12) head = push(head, 1) head = push(head, 18) head = push(head, 47) head = push(head, 16) head = push(head, 12) head = push(head, 14) ''' function to print the result''' res = check_pair_sum(head, 26) if (res == False): print("NO PAIR EXIST") # This code is contributed by rutvik_56
// C# program for finding// the pair with given sumusing System;using System.Collections.Generic; class GFG { static int MAX = 100000; /* Link list node */ public class Node { public int data; public Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static void push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } /* Takes head pointer of the linked list and sum*/ static Boolean check_pair_sum(Node head, int sum) { HashSet<int> s = new HashSet<int>(); Node p = head; while (p != null) { int curr = p.data; if (s.Contains(sum - curr)) { Console.Write(curr + " " + (sum - curr)); return true; } s.Add(p.data); p = p.next; } return false; } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ Boolean res = check_pair_sum(head, 26); if (res == false) Console.Write("NO PAIR EXIST"); }} // This code is contributed by Princi Singh
<script> // JavaScript program for finding // the pair with given sum const MAX = 100000; /* Link list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(head_ref, new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } /* Takes head pointer of the linked list and sum*/ function check_pair_sum(head, sum) { var s = new Set(); var p = head; while (p != null) { var curr = p.data; if (s.has(sum - curr)) { document.write(curr + " " + (sum - curr)); return true; } s.add(p.data); p = p.next; } return false; } // Driver Code /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ var res = check_pair_sum(head, 26); if (res == false) document.write("NO PAIR EXIST"); // This code is contributed by rdtank. </script>
12 14
Time complexity: O(n) Auxiliary Space: O(n)
Method 3 (using recursion)
Traverse through each node and find if element Sum-(node->data) is available in remaining linked list or not. if Not, current node will not be a part of solution. Single traversal of list is needed and no additional space is required for this solution. Although we are using additional stack space for recursion.
C
// C++ implementation of the above approach#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} bool findElement(struct Node* head, int element){ if (head == NULL) { return false; } else if (head->data == element) { return true; } return findElement(head->next, element);} bool check_pair_sum(struct Node* head, int sum){ bool found = false; while (head != NULL) { found = findElement(head, sum - head->data); if (found == true) { printf("%d and %d \n", head->data, sum - head->data); return found; } head = head->next; } return found;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list*/ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); push(&head, 0); /* Function to print the result*/ bool res = check_pair_sum(head, 26); if (res == false) printf("No pair found"); return 0;}
0 and 47
Vikash Kumar 37
29AjayKumar
Rajput-Ji
princiraj1992
princi singh
nidhi_biet
rutvik_56
saurabhjangir
noob2000
rdtank
surinderdawra388
Hash
Linked List
Linked List
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 255,
"s": 52,
"text": "Given a linked list, and a number, check if their exist two numbers whose sum is equal to given number. If there exist two numbers, print them. If there are multiple answer, print any of them.Examples: "
},
{
"code": null,
"e": 419,
"s": 255,
"text": "Input : 1 -> 2 -> 3 -> 4 -> 5 -> NULL \n sum = 3\nOutput : Pair is (1, 2)\n\nInput : 10 -> 12 -> 31 -> 42 -> 53 -> NULL \n sum = 15\nOutput : NO PAIR EXIST"
},
{
"code": null,
"e": 489,
"s": 419,
"text": "Method(Brute force) Iteratively check if their exist any pair or not "
},
{
"code": null,
"e": 493,
"s": 489,
"text": "C++"
},
{
"code": null,
"e": 498,
"s": 493,
"text": "Java"
},
{
"code": null,
"e": 506,
"s": 498,
"text": "Python3"
},
{
"code": null,
"e": 509,
"s": 506,
"text": "C#"
},
{
"code": null,
"e": 520,
"s": 509,
"text": "Javascript"
},
{
"code": "// CPP code to find the pair with given sum#include <bits/stdc++.h>using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Takes head pointer of the linked list and sum*/int check_pair_sum(struct Node* head, int sum){ struct Node* p = head, *q; while (p != NULL) { q = p->next; while (q != NULL) { // check if both sum is equal to // given sum if ((p->data) + (q->data) == sum) { cout << p->data << \" \" << q->data; return true; } q = q->next; } p = p->next; } return 0;} /* Driver program to test above function */int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list*/ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_sum(head, 26); if (res == false) cout << \"NO PAIR EXIST\"; return 0;}",
"e": 2166,
"s": 520,
"text": null
},
{
"code": "// Java code to find the pair with given sumimport java.util.*; class GFG { /* Link list node */ static class Node { int data; Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ // Inserting node at the beginning static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref; } /* Takes head pointer of the linked list and sum*/ static boolean check_pair_sum(Node head, int sum) { Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both sum is equal to // given sum if ((p.data) + (q.data) == sum) { System.out.print(p.data + \" \" + q.data); return true; } q = q.next; } p = p.next; } return false; } // Driver Code public static void main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ boolean res = check_pair_sum(head, 26); if (res == false) System.out.print(\"NO PAIR EXIST\"); }} // This code is contributed by 29AjayKumar",
"e": 4107,
"s": 2166,
"text": null
},
{
"code": "# Python3 program for finding the pair with given sumimport mathimport sys # Link list node # class Node: def __init__(self, data): self.data = data self.next = None# Given a reference (pointer to pointer) to the head# of a list and an int, push a new node on the front# of the list. def push(head, data): if head == None: return Node(data) # allocate node temp = Node(data) # link the old list off the new node temp.next = head # move the head to point to the new node head = temp return head # Takes head pointer of the linked list and sum def check_pair_sum(head, _sum_): p = head q = None while(p): q = p.next while(q): if p.data+q.data == _sum_: print(\"{} {}\".format(p.data, q.data)) return True q = q.next p = p.next return False # Driver program to test above functionif __name__ == '__main__': # Start with the empty list head = None # Use push() to construct linked list head = push(head, 1) head = push(head, 4) head = push(head, 1) head = push(head, 12) head = push(head, 1) head = push(head, 18) head = push(head, 47) head = push(head, 16) head = push(head, 12) head = push(head, 14) # function to print the result res = check_pair_sum(head, 26) if (res == False): print(\"NO PAIR EXIST\") # This code is contributed by Vikash Kumar 37",
"e": 5551,
"s": 4107,
"text": null
},
{
"code": "// C# code to find the pair with given sumusing System; class GFG { /* Link list node */ public class Node { public int data; public Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ // Inserting node at the beginning static Node push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref; } /* Takes head pointer of the linked list and sum*/ static Boolean check_pair_sum(Node head, int sum) { Node p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both sum is equal to // given sum if ((p.data) + (q.data) == sum) { Console.Write(p.data + \" \" + q.data); return true; } q = q.next; } p = p.next; } return false; } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list*/ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ Boolean res = check_pair_sum(head, 26); if (res == false) Console.Write(\"NO PAIR EXIST\"); }} // This code is contributed by Rajput-Ji",
"e": 7490,
"s": 5551,
"text": null
},
{
"code": "<script> // JavaScript code to find the pair with given sum /* Link list node */class Node { constructor() { this.data = 0; this.next = null; }}; var head = null;/* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */// Inserting node at the beginningfunction push(head_ref, new_data){ /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list to the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; return head = head_ref;}/* Takes head pointer of the linked list and sum*/function check_pair_sum(head, sum){ var p = head, q; while (p != null) { q = p.next; while (q != null) { // check if both sum is equal to // given sum if ((p.data) + (q.data) == sum) { document.write(p.data + \" \" + q.data); return true; } q = q.next; } p = p.next; } return false;}// Driver Code/* Start with the empty list */head = null;/* Use push() to construct linked list*/push(head, 1);push(head, 4);push(head, 1);push(head, 12);push(head, 1);push(head, 18);push(head, 47);push(head, 16);push(head, 12);push(head, 14);/* function to print the result*/var res = check_pair_sum(head, 26);if (res == false) document.write(\"NO PAIR EXIST\"); </script>",
"e": 9004,
"s": 7490,
"text": null
},
{
"code": null,
"e": 9010,
"s": 9004,
"text": "14 12"
},
{
"code": null,
"e": 9034,
"s": 9010,
"text": "Time complexity: O(n*n)"
},
{
"code": null,
"e": 9283,
"s": 9034,
"text": "Method 2 (using hashing) 1. Take a hashtable and mark all element with zero 2. Iteratively mark all the element as 1 in hashtable which are present in linked list 3. Iteratively find sum-current element of linked list is present in hashtable or not"
},
{
"code": null,
"e": 9287,
"s": 9283,
"text": "C++"
},
{
"code": null,
"e": 9292,
"s": 9287,
"text": "Java"
},
{
"code": null,
"e": 9300,
"s": 9292,
"text": "Python3"
},
{
"code": null,
"e": 9303,
"s": 9300,
"text": "C#"
},
{
"code": null,
"e": 9314,
"s": 9303,
"text": "Javascript"
},
{
"code": "// CPP program to for finding the pair with given sum#include <bits/stdc++.h>#define MAX 100000using namespace std; /* Link list node */struct Node { int data; struct Node* next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* link the old list off the new node */ new_node->next = (*head_ref); /* move the head to point to the new node */ (*head_ref) = new_node;} /* Takes head pointer of the linked list and sum*/bool check_pair_sum(struct Node* head, int sum){ unordered_set<int> s; struct Node* p = head; while (p != NULL) { int curr = p->data; if (s.find(sum - curr) != s.end()) { cout << curr << \" \" << sum - curr; return true; } s.insert(p->data); p = p->next; } return false;} /* Driver program to test above function*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list */ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); /* function to print the result*/ bool res = check_pair_sum(head, 26); if (res == false) cout << \"NO PAIR EXIST\"; return 0;}",
"e": 10899,
"s": 9314,
"text": null
},
{
"code": "// Java program for finding// the pair with given sumimport java.util.*;class GFG { static int MAX = 100000; /* Link list node */ static class Node { int data; Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static void push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } /* Takes head pointer of the linked list and sum*/ static boolean check_pair_sum(Node head, int sum) { HashSet<Integer> s = new HashSet<Integer>(); Node p = head; while (p != null) { int curr = p.data; if (s.contains(sum - curr)) { System.out.print(curr + \" \" + (sum - curr)); return true; } s.add(p.data); p = p.next; } return false; } // Driver Code public static void main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ boolean res = check_pair_sum(head, 26); if (res == false) System.out.print(\"NO PAIR EXIST\"); }} // This code is contributed by PrinciRaj1992",
"e": 12727,
"s": 10899,
"text": null
},
{
"code": "# Python3 program to for finding the pair with given sumMAX = 100000 ''' Link list node ''' class Node: def __init__(self, data): self.data = data self.next = None ''' Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. ''' def push(head_ref, new_data): ''' allocate node ''' new_node = Node(new_data) ''' put in the data ''' new_node.data = new_data ''' link the old list off the new node ''' new_node.next = (head_ref) ''' move the head to point to the new node ''' (head_ref) = new_node return head_ref ''' Takes head pointer of the linked list and sum''' def check_pair_sum(head, sum): s = set() p = head while (p != None): curr = p.data if((sum - curr) in s): print(curr, end=' ') print(sum-curr, end='') return True s.add(p.data) p = p.next return False ''' Driver program to test above function'''if __name__ == '__main__': ''' Start with the empty list ''' head = None ''' Use push() to construct linked list ''' head = push(head, 1) head = push(head, 4) head = push(head, 1) head = push(head, 12) head = push(head, 1) head = push(head, 18) head = push(head, 47) head = push(head, 16) head = push(head, 12) head = push(head, 14) ''' function to print the result''' res = check_pair_sum(head, 26) if (res == False): print(\"NO PAIR EXIST\") # This code is contributed by rutvik_56",
"e": 14270,
"s": 12727,
"text": null
},
{
"code": "// C# program for finding// the pair with given sumusing System;using System.Collections.Generic; class GFG { static int MAX = 100000; /* Link list node */ public class Node { public int data; public Node next; }; static Node head; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ static void push(Node head_ref, int new_data) { /* allocate node */ Node new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } /* Takes head pointer of the linked list and sum*/ static Boolean check_pair_sum(Node head, int sum) { HashSet<int> s = new HashSet<int>(); Node p = head; while (p != null) { int curr = p.data; if (s.Contains(sum - curr)) { Console.Write(curr + \" \" + (sum - curr)); return true; } s.Add(p.data); p = p.next; } return false; } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ Boolean res = check_pair_sum(head, 26); if (res == false) Console.Write(\"NO PAIR EXIST\"); }} // This code is contributed by Princi Singh",
"e": 16122,
"s": 14270,
"text": null
},
{
"code": "<script> // JavaScript program for finding // the pair with given sum const MAX = 100000; /* Link list node */ class Node { constructor() { this.data = 0; this.next = null; } } var head = null; /* Given a reference (pointer to pointer) to the head of a list and an int, push a new node on the front of the list. */ function push(head_ref, new_data) { /* allocate node */ var new_node = new Node(); /* put in the data */ new_node.data = new_data; /* link the old list off the new node */ new_node.next = head_ref; /* move the head to point to the new node */ head_ref = new_node; head = head_ref; } /* Takes head pointer of the linked list and sum*/ function check_pair_sum(head, sum) { var s = new Set(); var p = head; while (p != null) { var curr = p.data; if (s.has(sum - curr)) { document.write(curr + \" \" + (sum - curr)); return true; } s.add(p.data); p = p.next; } return false; } // Driver Code /* Start with the empty list */ head = null; /* Use push() to construct linked list */ push(head, 1); push(head, 4); push(head, 1); push(head, 12); push(head, 1); push(head, 18); push(head, 47); push(head, 16); push(head, 12); push(head, 14); /* function to print the result*/ var res = check_pair_sum(head, 26); if (res == false) document.write(\"NO PAIR EXIST\"); // This code is contributed by rdtank. </script>",
"e": 17831,
"s": 16122,
"text": null
},
{
"code": null,
"e": 17837,
"s": 17831,
"text": "12 14"
},
{
"code": null,
"e": 17881,
"s": 17837,
"text": "Time complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 17908,
"s": 17881,
"text": "Method 3 (using recursion)"
},
{
"code": null,
"e": 18221,
"s": 17908,
"text": "Traverse through each node and find if element Sum-(node->data) is available in remaining linked list or not. if Not, current node will not be a part of solution. Single traversal of list is needed and no additional space is required for this solution. Although we are using additional stack space for recursion."
},
{
"code": null,
"e": 18223,
"s": 18221,
"text": "C"
},
{
"code": "// C++ implementation of the above approach#include <stdbool.h>#include <stdio.h>#include <stdlib.h> /* Link list node */struct Node { int data; struct Node* next;}; void push(struct Node** head_ref, int new_data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} bool findElement(struct Node* head, int element){ if (head == NULL) { return false; } else if (head->data == element) { return true; } return findElement(head->next, element);} bool check_pair_sum(struct Node* head, int sum){ bool found = false; while (head != NULL) { found = findElement(head, sum - head->data); if (found == true) { printf(\"%d and %d \\n\", head->data, sum - head->data); return found; } head = head->next; } return found;} // Driver Codeint main(){ /* Start with the empty list */ struct Node* head = NULL; /* Use push() to construct linked list*/ push(&head, 1); push(&head, 4); push(&head, 1); push(&head, 12); push(&head, 1); push(&head, 18); push(&head, 47); push(&head, 16); push(&head, 12); push(&head, 14); push(&head, 0); /* Function to print the result*/ bool res = check_pair_sum(head, 26); if (res == false) printf(\"No pair found\"); return 0;}",
"e": 19677,
"s": 18223,
"text": null
},
{
"code": null,
"e": 19687,
"s": 19677,
"text": "0 and 47 "
},
{
"code": null,
"e": 19703,
"s": 19687,
"text": "Vikash Kumar 37"
},
{
"code": null,
"e": 19715,
"s": 19703,
"text": "29AjayKumar"
},
{
"code": null,
"e": 19725,
"s": 19715,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 19739,
"s": 19725,
"text": "princiraj1992"
},
{
"code": null,
"e": 19752,
"s": 19739,
"text": "princi singh"
},
{
"code": null,
"e": 19763,
"s": 19752,
"text": "nidhi_biet"
},
{
"code": null,
"e": 19773,
"s": 19763,
"text": "rutvik_56"
},
{
"code": null,
"e": 19787,
"s": 19773,
"text": "saurabhjangir"
},
{
"code": null,
"e": 19796,
"s": 19787,
"text": "noob2000"
},
{
"code": null,
"e": 19803,
"s": 19796,
"text": "rdtank"
},
{
"code": null,
"e": 19820,
"s": 19803,
"text": "surinderdawra388"
},
{
"code": null,
"e": 19825,
"s": 19820,
"text": "Hash"
},
{
"code": null,
"e": 19837,
"s": 19825,
"text": "Linked List"
},
{
"code": null,
"e": 19849,
"s": 19837,
"text": "Linked List"
},
{
"code": null,
"e": 19854,
"s": 19849,
"text": "Hash"
}
] |
Sagemaker β Exploring Ground truth labeling | ML
|
03 Jun, 2020
Have you ever thought of doing machine learning completely from the scratch and donβt know where to start? If yes, there is a place where you can enter by holding just the dataset in your hands and leaves the place with fully trained machine learning model which is ready to be deployed in the real-life scenarioβs. Amazon Sagemaker provides various services that offer labelling datasets, training the models, hyperparameters tuning, and creating inference for us to deploy. Sagemaker offers the following services:
Ground truthNotebook InstancesTraining Jobs/Hyperparameters.Inferences
Ground truth
Notebook Instances
Training Jobs/Hyperparameters.
Inferences
In this article, we are exploring the ground truth labelling and how it is helpful in reducing the burden of labelling datasets on developers.
Amazon sagemaker Ground truth:Ask any machine learning expert βWhat is the majority task that consumes a whole lot of time in the machine learning part?β And first, they will say preparing and cleaning datasets and secondly labelling them accurately that fits the models. So, in general labelling, the datasets consume 70% of the time and it would take more if the model you are feeding this dataset is sensitive enough. Amazon Ground truth provides the labelling service in which it not only just does the labelling but also creates the files that are required for the models to understand. Ground truth provides three services namely
Mechanical Turk workers which are useful in labelling small datasets and the labelling can be done by human workers.
Private labelling workforce, in which you have an option that the employees from your organization label the dataset
Third part vendors, as the name, implies that the datasets be labelled by some other vendors.
Ground truth also provides built-in five data labelling tasks
Bounding BoxesImage classificationSemantic segmentationText classificationNamed Entity Recognition.
Bounding Boxes
Image classification
Semantic segmentation
Text classification
Named Entity Recognition.
Customers can also bring their custom labelling tasks. So, how in the first place we are going to provide input data and what kind of output format that we can expect from ground truth?
Initially, the dataset that we are intending to the label has to be placed in the S3 bucket and while creating the labelling job, we can mention the location of the dataset in the S3 bucket so that it creates input manifest file automatically. We can also have to specify the output folder for the labelled data to be stored. As shown in the image that the labelling can be done whether by automatic labelling in which the machine learning models come into the picture and completes the job or by human labelling in which the humans can do the job. Auto labelling is performed if the dataset is so large. The label consolidation provides the majority voting or checks for the higher probabilities of a particular image, text or audio etc., in a given dataset. After the labelling has been done, the ground truth provides augmented manifest file which will be used to training the model. The augmented manifest file consists of
Source-ref: The source of the object in S3 bucket
Labelling job name: The name of the labelling job that was initiated while creating it.
Code: Labelling job looks like which was performed on a bird image.
[ { "boundingBox": { "boundingBoxes": [ { "height": 845, "label": "Bird", "left": 54, "top": 19, "width": 765 } ], "inputImageProperties": { "height": 1024, "width": 968 } } } ]
Now we have successfully labelled the dataset of our choice and we have with us are the augmented manifest files which are ready to be fed to the training model inside the sagemaker notebook!
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 545,
"s": 28,
"text": "Have you ever thought of doing machine learning completely from the scratch and donβt know where to start? If yes, there is a place where you can enter by holding just the dataset in your hands and leaves the place with fully trained machine learning model which is ready to be deployed in the real-life scenarioβs. Amazon Sagemaker provides various services that offer labelling datasets, training the models, hyperparameters tuning, and creating inference for us to deploy. Sagemaker offers the following services:"
},
{
"code": null,
"e": 616,
"s": 545,
"text": "Ground truthNotebook InstancesTraining Jobs/Hyperparameters.Inferences"
},
{
"code": null,
"e": 629,
"s": 616,
"text": "Ground truth"
},
{
"code": null,
"e": 648,
"s": 629,
"text": "Notebook Instances"
},
{
"code": null,
"e": 679,
"s": 648,
"text": "Training Jobs/Hyperparameters."
},
{
"code": null,
"e": 690,
"s": 679,
"text": "Inferences"
},
{
"code": null,
"e": 833,
"s": 690,
"text": "In this article, we are exploring the ground truth labelling and how it is helpful in reducing the burden of labelling datasets on developers."
},
{
"code": null,
"e": 1469,
"s": 833,
"text": "Amazon sagemaker Ground truth:Ask any machine learning expert βWhat is the majority task that consumes a whole lot of time in the machine learning part?β And first, they will say preparing and cleaning datasets and secondly labelling them accurately that fits the models. So, in general labelling, the datasets consume 70% of the time and it would take more if the model you are feeding this dataset is sensitive enough. Amazon Ground truth provides the labelling service in which it not only just does the labelling but also creates the files that are required for the models to understand. Ground truth provides three services namely"
},
{
"code": null,
"e": 1586,
"s": 1469,
"text": "Mechanical Turk workers which are useful in labelling small datasets and the labelling can be done by human workers."
},
{
"code": null,
"e": 1703,
"s": 1586,
"text": "Private labelling workforce, in which you have an option that the employees from your organization label the dataset"
},
{
"code": null,
"e": 1797,
"s": 1703,
"text": "Third part vendors, as the name, implies that the datasets be labelled by some other vendors."
},
{
"code": null,
"e": 1859,
"s": 1797,
"text": "Ground truth also provides built-in five data labelling tasks"
},
{
"code": null,
"e": 1959,
"s": 1859,
"text": "Bounding BoxesImage classificationSemantic segmentationText classificationNamed Entity Recognition."
},
{
"code": null,
"e": 1974,
"s": 1959,
"text": "Bounding Boxes"
},
{
"code": null,
"e": 1995,
"s": 1974,
"text": "Image classification"
},
{
"code": null,
"e": 2017,
"s": 1995,
"text": "Semantic segmentation"
},
{
"code": null,
"e": 2037,
"s": 2017,
"text": "Text classification"
},
{
"code": null,
"e": 2063,
"s": 2037,
"text": "Named Entity Recognition."
},
{
"code": null,
"e": 2249,
"s": 2063,
"text": "Customers can also bring their custom labelling tasks. So, how in the first place we are going to provide input data and what kind of output format that we can expect from ground truth?"
},
{
"code": null,
"e": 3176,
"s": 2249,
"text": "Initially, the dataset that we are intending to the label has to be placed in the S3 bucket and while creating the labelling job, we can mention the location of the dataset in the S3 bucket so that it creates input manifest file automatically. We can also have to specify the output folder for the labelled data to be stored. As shown in the image that the labelling can be done whether by automatic labelling in which the machine learning models come into the picture and completes the job or by human labelling in which the humans can do the job. Auto labelling is performed if the dataset is so large. The label consolidation provides the majority voting or checks for the higher probabilities of a particular image, text or audio etc., in a given dataset. After the labelling has been done, the ground truth provides augmented manifest file which will be used to training the model. The augmented manifest file consists of"
},
{
"code": null,
"e": 3226,
"s": 3176,
"text": "Source-ref: The source of the object in S3 bucket"
},
{
"code": null,
"e": 3314,
"s": 3226,
"text": "Labelling job name: The name of the labelling job that was initiated while creating it."
},
{
"code": null,
"e": 3382,
"s": 3314,
"text": "Code: Labelling job looks like which was performed on a bird image."
},
{
"code": "[ { \"boundingBox\": { \"boundingBoxes\": [ { \"height\": 845, \"label\": \"Bird\", \"left\": 54, \"top\": 19, \"width\": 765 } ], \"inputImageProperties\": { \"height\": 1024, \"width\": 968 } } } ]",
"e": 3676,
"s": 3382,
"text": null
},
{
"code": null,
"e": 3868,
"s": 3676,
"text": "Now we have successfully labelled the dataset of our choice and we have with us are the augmented manifest files which are ready to be fed to the training model inside the sagemaker notebook!"
},
{
"code": null,
"e": 3885,
"s": 3868,
"text": "Machine Learning"
},
{
"code": null,
"e": 3902,
"s": 3885,
"text": "Machine Learning"
}
] |
RESTful Routes in Node.js
|
14 Jul, 2020
Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them.
What is RESTful Routing?REST stands for Representational State Transfer which provides a way of mapping HTTP verbs (get, post, put, delete) and CRUD actions (create, read, update, delete) together. It is a convention for defining routes and when something follows the rest principle it is known as RESTFUL.
Instead of relying solely on the URL to indicate what site to visit, a RESTful route also depends on the HTTP verb and the URL.
This means that when your application receives an HTTP request, it introspects on that request and identifies the HTTP method and URL, connects that with a corresponding controller action that has that method and URL, executes the code in that action, and determines which response gets sent back to the client.
The internet would be a really confusing place without a convention for how to handle URLs β to delete a Facebook photo might be www.facebook.com/delete-this-photo, but on Instagram, it might be www.instagram.com/remove-this-post. Without a specific convention to follow, it would be hard to create new content, edit content, and delete it. RESTful routes provide a design pattern that allows for easy data manipulation.
For a route to be completely Restful it must do the following:
Separate the client from the server.
Not hold state between requests (i.e. all information necessary to respond to a request is available in each request: no data or state, is held by the server from request to request).
Use HTTP and HTTP methods.
Be reliable (for e.g most APIs follow the restful route pattern when specifying the process for authentication and important URLs).
There are 7 different restful routes pattern to follow when creating an application or web service that will interact with the server.
Example: For a blog website these Routes would be defined as:
Make sure you have Node, npm and mongoDB installed.
Installing the packages and creating the schema:
npm install express
npm install method-override
npm install mongoose
Filename: app.js
var express = require('express');var app = express();var methodOverride = require("method-override"); // APP configmongoose.connect("mongodb://localhost/restful_blog_app");app.set("view engine", "ejs");app.use(express.static("public"));app.use(methodOverride("_method")); // Creating the schemavar blogSchema = new mongoose.Schema({ title: String, image: String, body: String, created: {type: Date, default: Date.now}}); var Blog = mongoose.model("Blog", blogSchema); app.listen(process.env.PORT, process.env.IP, function() { console.log("SERVER IS RUNNING!");})
Name: INDEX
app.get("/blogs", function(req, res) { Blog.find({}, function(err, blogs) { if (err) { console.log("ERROR!"); } else { res.render("index", {blogs: blogs}); } }); });
Name: NEW
app.get("/blogs/new", function(req, res) { res.render("new"); });
Name: CREATE
app.post("/blogs", function(req, res) { // create blog Blog.create(req.body.blog, function(err, newBlog) { if (err) { res.render("new"); } else { //then, redirect to the index res.redirect("/blogs"); } }); });
Name: SHOW
app.get("/blogs/:id", function(req, res) { Blog.findById(req.params.id, function(err, foundBlog) { if (err) { res.redirect("/blogs"); } else { res.render("show", {blog: foundBlog}); } }) });
Name: EDIT
app.get("/blogs/:id/edit", function(req, res) { Blog.findById(req.params.id, function(err, foundBlog) { if (err) { res.redirect("/blogs"); } else { res.render("edit", {blog: foundBlog}); } });})
Name: UPDATE
app.put("/blogs/:id", function(req, res) { req.body.blog.body = req.sanitize(req.body.blog.body) Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err, updatedBlog) { if (err) { res.redirect("/blogs"); } else { res.redirect("/blogs/" + req.params.id); } });});
Name: DESTROY
app.delete("/blogs/:id", function(req, res) { //destroy blog Blog.findByIdAndRemove(req.params.id, function(err) { if (err) { res.redirect("/blogs"); } else { res.redirect("/blogs"); } }) //redirect somewhere});
The project structure will look like this:
This article focuses mainly on the app.js file. Styling can be done as per your preference.
Finally, after creating the routes and adding the styling as per your preference, run this on your command line:
node app.js
This was a really simple description of what RESTful routing is and what is its practical usage on websites.
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
JWT Authentication with Node.js
Installation of Node.js on Windows
Difference between dependencies, devDependencies and peerDependencies
Mongoose Populate() Method
How to connect Node.js with React.js ?
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 ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jul, 2020"
},
{
"code": null,
"e": 305,
"s": 28,
"text": "Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them."
},
{
"code": null,
"e": 612,
"s": 305,
"text": "What is RESTful Routing?REST stands for Representational State Transfer which provides a way of mapping HTTP verbs (get, post, put, delete) and CRUD actions (create, read, update, delete) together. It is a convention for defining routes and when something follows the rest principle it is known as RESTFUL."
},
{
"code": null,
"e": 740,
"s": 612,
"text": "Instead of relying solely on the URL to indicate what site to visit, a RESTful route also depends on the HTTP verb and the URL."
},
{
"code": null,
"e": 1052,
"s": 740,
"text": "This means that when your application receives an HTTP request, it introspects on that request and identifies the HTTP method and URL, connects that with a corresponding controller action that has that method and URL, executes the code in that action, and determines which response gets sent back to the client."
},
{
"code": null,
"e": 1473,
"s": 1052,
"text": "The internet would be a really confusing place without a convention for how to handle URLs β to delete a Facebook photo might be www.facebook.com/delete-this-photo, but on Instagram, it might be www.instagram.com/remove-this-post. Without a specific convention to follow, it would be hard to create new content, edit content, and delete it. RESTful routes provide a design pattern that allows for easy data manipulation."
},
{
"code": null,
"e": 1536,
"s": 1473,
"text": "For a route to be completely Restful it must do the following:"
},
{
"code": null,
"e": 1573,
"s": 1536,
"text": "Separate the client from the server."
},
{
"code": null,
"e": 1757,
"s": 1573,
"text": "Not hold state between requests (i.e. all information necessary to respond to a request is available in each request: no data or state, is held by the server from request to request)."
},
{
"code": null,
"e": 1784,
"s": 1757,
"text": "Use HTTP and HTTP methods."
},
{
"code": null,
"e": 1916,
"s": 1784,
"text": "Be reliable (for e.g most APIs follow the restful route pattern when specifying the process for authentication and important URLs)."
},
{
"code": null,
"e": 2051,
"s": 1916,
"text": "There are 7 different restful routes pattern to follow when creating an application or web service that will interact with the server."
},
{
"code": null,
"e": 2113,
"s": 2051,
"text": "Example: For a blog website these Routes would be defined as:"
},
{
"code": null,
"e": 2165,
"s": 2113,
"text": "Make sure you have Node, npm and mongoDB installed."
},
{
"code": null,
"e": 2214,
"s": 2165,
"text": "Installing the packages and creating the schema:"
},
{
"code": null,
"e": 2284,
"s": 2214,
"text": "npm install express\nnpm install method-override\nnpm install mongoose\n"
},
{
"code": null,
"e": 2301,
"s": 2284,
"text": "Filename: app.js"
},
{
"code": "var express = require('express');var app = express();var methodOverride = require(\"method-override\"); // APP configmongoose.connect(\"mongodb://localhost/restful_blog_app\");app.set(\"view engine\", \"ejs\");app.use(express.static(\"public\"));app.use(methodOverride(\"_method\")); // Creating the schemavar blogSchema = new mongoose.Schema({ title: String, image: String, body: String, created: {type: Date, default: Date.now}}); var Blog = mongoose.model(\"Blog\", blogSchema); app.listen(process.env.PORT, process.env.IP, function() { console.log(\"SERVER IS RUNNING!\");})",
"e": 2883,
"s": 2301,
"text": null
},
{
"code": null,
"e": 2895,
"s": 2883,
"text": "Name: INDEX"
},
{
"code": "app.get(\"/blogs\", function(req, res) { Blog.find({}, function(err, blogs) { if (err) { console.log(\"ERROR!\"); } else { res.render(\"index\", {blogs: blogs}); } }); });",
"e": 3110,
"s": 2895,
"text": null
},
{
"code": null,
"e": 3120,
"s": 3110,
"text": "Name: NEW"
},
{
"code": "app.get(\"/blogs/new\", function(req, res) { res.render(\"new\"); });",
"e": 3190,
"s": 3120,
"text": null
},
{
"code": null,
"e": 3203,
"s": 3190,
"text": "Name: CREATE"
},
{
"code": "app.post(\"/blogs\", function(req, res) { // create blog Blog.create(req.body.blog, function(err, newBlog) { if (err) { res.render(\"new\"); } else { //then, redirect to the index res.redirect(\"/blogs\"); } }); });",
"e": 3494,
"s": 3203,
"text": null
},
{
"code": null,
"e": 3505,
"s": 3494,
"text": "Name: SHOW"
},
{
"code": "app.get(\"/blogs/:id\", function(req, res) { Blog.findById(req.params.id, function(err, foundBlog) { if (err) { res.redirect(\"/blogs\"); } else { res.render(\"show\", {blog: foundBlog}); } }) });",
"e": 3745,
"s": 3505,
"text": null
},
{
"code": null,
"e": 3756,
"s": 3745,
"text": "Name: EDIT"
},
{
"code": "app.get(\"/blogs/:id/edit\", function(req, res) { Blog.findById(req.params.id, function(err, foundBlog) { if (err) { res.redirect(\"/blogs\"); } else { res.render(\"edit\", {blog: foundBlog}); } });})",
"e": 4000,
"s": 3756,
"text": null
},
{
"code": null,
"e": 4013,
"s": 4000,
"text": "Name: UPDATE"
},
{
"code": "app.put(\"/blogs/:id\", function(req, res) { req.body.blog.body = req.sanitize(req.body.blog.body) Blog.findByIdAndUpdate(req.params.id, req.body.blog, function(err, updatedBlog) { if (err) { res.redirect(\"/blogs\"); } else { res.redirect(\"/blogs/\" + req.params.id); } });});",
"e": 4327,
"s": 4013,
"text": null
},
{
"code": null,
"e": 4341,
"s": 4327,
"text": "Name: DESTROY"
},
{
"code": "app.delete(\"/blogs/:id\", function(req, res) { //destroy blog Blog.findByIdAndRemove(req.params.id, function(err) { if (err) { res.redirect(\"/blogs\"); } else { res.redirect(\"/blogs\"); } }) //redirect somewhere});",
"e": 4599,
"s": 4341,
"text": null
},
{
"code": null,
"e": 4642,
"s": 4599,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 4734,
"s": 4642,
"text": "This article focuses mainly on the app.js file. Styling can be done as per your preference."
},
{
"code": null,
"e": 4847,
"s": 4734,
"text": "Finally, after creating the routes and adding the styling as per your preference, run this on your command line:"
},
{
"code": null,
"e": 4859,
"s": 4847,
"text": "node app.js"
},
{
"code": null,
"e": 4968,
"s": 4859,
"text": "This was a really simple description of what RESTful routing is and what is its practical usage on websites."
},
{
"code": null,
"e": 4981,
"s": 4968,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 4989,
"s": 4981,
"text": "Node.js"
},
{
"code": null,
"e": 5006,
"s": 4989,
"text": "Web Technologies"
},
{
"code": null,
"e": 5104,
"s": 5006,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5136,
"s": 5104,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 5171,
"s": 5136,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 5241,
"s": 5171,
"text": "Difference between dependencies, devDependencies and peerDependencies"
},
{
"code": null,
"e": 5268,
"s": 5241,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 5307,
"s": 5268,
"text": "How to connect Node.js with React.js ?"
},
{
"code": null,
"e": 5369,
"s": 5307,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5430,
"s": 5369,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5480,
"s": 5430,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5523,
"s": 5480,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Recursive function to do substring search
|
30 Jun, 2022
Given a text txt[] and a pattern pat[], write a recursive function βcontains(char pat[], char txt[])β that returns true if pat[] is present in txt[], otherwise false. Examples:
1) Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: true
2) Input: txt[] = "geeksforgeeks"
pat[] = "quiz"
Output: false;
We strongly recommend to minimize the browser and try this yourself first. Below is recursive algorithm.
contains(tex[], pat[])
1) If the current character is the last character of the text, but pat
has more characters, return false.
2) Else If the current character is the last character of the pattern,
then return true
3) Else If current characters of pat and text match, then
return contains(text + 1, pat + 1);
4) Else If current characters of pat and text don't match
return contains(text + 1, pat);
Below is the implementation of the above algorithm.
C++
Java
Python3
Javascript
// Recursive C++ program to find if a given pattern is// present in a text#include<iostream>using namespace std; bool exactMatch(char *text, char *pat){ if (*text == '\0' && *pat != '\0') return false; // Else If last character of pattern reaches if (*pat == '\0') return true; if (*text == *pat) return exactMatch(text + 1, pat + 1); return false;} // This function returns true if 'text' contain 'pat'bool contains(char *text, char *pat){ // If last character of text reaches if (*text == '\0') return false; // If current characters of pat and text match if (*text == *pat) if(exactMatch(text, pat)) return 1; else return contains(text + 1, pat); // If current characters of pat and tex don't match return contains(text + 1, pat);} // Driver program to test above functionint main(){ cout << contains("geeksforgeeks", "geeks") << endl; cout << contains("geeksforgeeks", "geeksquiz") << endl; cout << contains("geeksquizgeeks", "quiz") << endl; return 0;}
// Recursive Java program to find if a given pattern is// present in a text class GFG { static int exactMatch(String text, String pat, int text_index, int pat_index) { if (text_index == text.length() && pat_index != pat.length()) return 0; // Else If last character of pattern reaches if (pat_index == pat.length()) return 1; if (text.charAt(text_index) == pat.charAt(pat_index)) return exactMatch(text, pat, text_index + 1, pat_index + 1); return 0; } // This function returns true if 'text' contain 'pat' static int contains(String text, String pat, int text_index, int pat_index) { // If last character of text reaches if (text_index == text.length()) return 0; // If current characters of pat and text match if (text.charAt(text_index) == pat.charAt(pat_index)) { if (exactMatch(text, pat, text_index, pat_index) == 1) return 1; else return contains(text, pat, text_index + 1, pat_index); } // If current characters of pat and tex don't match return contains(text, pat, text_index + 1, pat_index); } // Driver program to test the above function public static void main(String args[]) { System.out.println(contains("geeksforgeeks", "geeks", 0, 0)); System.out.println(contains("geeksforgeeks", "geeksquiz", 0, 0)); System.out.println(contains("geeksquizgeeks", "quiz", 0, 0)); }}// This code is contributed by Saurabh Jaiswal
# Recursive Python3 program to find if a given pattern is# present in a text def exactMatch(text, pat, text_index, pat_index): if text_index == len(text) and pat_index != len(pat): return 0 # Else If last character of pattern reaches if pat_index == len(pat): return 1 if text[text_index] == pat[pat_index]: return exactMatch(text, pat, text_index+1, pat_index+1) return 0 # This function returns true if 'text' contain 'pat'def contains(text, pat, text_index, pat_index): # If last character of text reaches if text_index == len(text): return 0 # If current characters of pat and text match if text[text_index] == pat[pat_index]: if exactMatch(text, pat, text_index, pat_index): return 1 else: return contains(text, pat, text_index+1, pat_index) # If current characters of pat and tex don't match return contains(text , pat, text_index+1, pat_index) # Driver program to test the above function print(contains("geeksforgeeks", "geeks", 0, 0))print(contains("geeksforgeeks", "geeksquiz", 0, 0))print(contains("geeksquizgeeks", "quiz", 0, 0)) # This code is contributed by ankush_953.
<script> // Recursive JavaScript program to find if a given pattern is// present in a text function exactMatch(text, pat, text_index, pat_index){ if(text_index == text.length && pat_index != pat.length) return 0 // Else If last character of pattern reaches if(pat_index == pat.length) return 1 if(text[text_index] == pat[pat_index]) return exactMatch(text, pat, text_index+1, pat_index+1) return 0} // This function returns true if 'text' contain 'pat'function contains(text, pat, text_index, pat_index){ // If last character of text reaches if(text_index == text.length) return 0 // If current characters of pat and text match if(text[text_index] == pat[pat_index]){ if(exactMatch(text, pat, text_index, pat_index)) return 1 else return contains(text, pat, text_index+1, pat_index) } // If current characters of pat and tex don't match return contains(text , pat, text_index+1, pat_index)} // Driver program to test the above function document.write(contains("geeksforgeeks", "geeks", 0, 0),"</br>")document.write(contains("geeksforgeeks", "geeksquiz", 0, 0),"</br>")document.write(contains("geeksquizgeeks", "quiz", 0, 0),"</br>") // This code is contributed by shinjanpatra. </script>
Output:
1
0
1
Time Complexity : O(n*m)Auxiliary Space : O(n+m)
This article is contributed by Bhupinder. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
san123
ankush_953
shinjanpatra
_saurabh_jaiswal
susobhanakhuli
hardikkoriintern
Searching
Strings
Searching
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 229,
"s": 52,
"text": "Given a text txt[] and a pattern pat[], write a recursive function βcontains(char pat[], char txt[])β that returns true if pat[] is present in txt[], otherwise false. Examples:"
},
{
"code": null,
"e": 397,
"s": 229,
"text": "1) Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\n Output: true\n\n\n2) Input: txt[] = \"geeksforgeeks\"\n pat[] = \"quiz\"\n Output: false;"
},
{
"code": null,
"e": 502,
"s": 397,
"text": "We strongly recommend to minimize the browser and try this yourself first. Below is recursive algorithm."
},
{
"code": null,
"e": 952,
"s": 502,
"text": "contains(tex[], pat[])\n 1) If the current character is the last character of the text, but pat\n has more characters, return false.\n\n 2) Else If the current character is the last character of the pattern,\n then return true\n\n 3) Else If current characters of pat and text match, then\n return contains(text + 1, pat + 1);\n\n 4) Else If current characters of pat and text don't match\n return contains(text + 1, pat);"
},
{
"code": null,
"e": 1005,
"s": 952,
"text": "Below is the implementation of the above algorithm. "
},
{
"code": null,
"e": 1009,
"s": 1005,
"text": "C++"
},
{
"code": null,
"e": 1014,
"s": 1009,
"text": "Java"
},
{
"code": null,
"e": 1022,
"s": 1014,
"text": "Python3"
},
{
"code": null,
"e": 1033,
"s": 1022,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to find if a given pattern is// present in a text#include<iostream>using namespace std; bool exactMatch(char *text, char *pat){ if (*text == '\\0' && *pat != '\\0') return false; // Else If last character of pattern reaches if (*pat == '\\0') return true; if (*text == *pat) return exactMatch(text + 1, pat + 1); return false;} // This function returns true if 'text' contain 'pat'bool contains(char *text, char *pat){ // If last character of text reaches if (*text == '\\0') return false; // If current characters of pat and text match if (*text == *pat) if(exactMatch(text, pat)) return 1; else return contains(text + 1, pat); // If current characters of pat and tex don't match return contains(text + 1, pat);} // Driver program to test above functionint main(){ cout << contains(\"geeksforgeeks\", \"geeks\") << endl; cout << contains(\"geeksforgeeks\", \"geeksquiz\") << endl; cout << contains(\"geeksquizgeeks\", \"quiz\") << endl; return 0;}",
"e": 2005,
"s": 1033,
"text": null
},
{
"code": "// Recursive Java program to find if a given pattern is// present in a text class GFG { static int exactMatch(String text, String pat, int text_index, int pat_index) { if (text_index == text.length() && pat_index != pat.length()) return 0; // Else If last character of pattern reaches if (pat_index == pat.length()) return 1; if (text.charAt(text_index) == pat.charAt(pat_index)) return exactMatch(text, pat, text_index + 1, pat_index + 1); return 0; } // This function returns true if 'text' contain 'pat' static int contains(String text, String pat, int text_index, int pat_index) { // If last character of text reaches if (text_index == text.length()) return 0; // If current characters of pat and text match if (text.charAt(text_index) == pat.charAt(pat_index)) { if (exactMatch(text, pat, text_index, pat_index) == 1) return 1; else return contains(text, pat, text_index + 1, pat_index); } // If current characters of pat and tex don't match return contains(text, pat, text_index + 1, pat_index); } // Driver program to test the above function public static void main(String args[]) { System.out.println(contains(\"geeksforgeeks\", \"geeks\", 0, 0)); System.out.println(contains(\"geeksforgeeks\", \"geeksquiz\", 0, 0)); System.out.println(contains(\"geeksquizgeeks\", \"quiz\", 0, 0)); }}// This code is contributed by Saurabh Jaiswal",
"e": 3567,
"s": 2005,
"text": null
},
{
"code": "# Recursive Python3 program to find if a given pattern is# present in a text def exactMatch(text, pat, text_index, pat_index): if text_index == len(text) and pat_index != len(pat): return 0 # Else If last character of pattern reaches if pat_index == len(pat): return 1 if text[text_index] == pat[pat_index]: return exactMatch(text, pat, text_index+1, pat_index+1) return 0 # This function returns true if 'text' contain 'pat'def contains(text, pat, text_index, pat_index): # If last character of text reaches if text_index == len(text): return 0 # If current characters of pat and text match if text[text_index] == pat[pat_index]: if exactMatch(text, pat, text_index, pat_index): return 1 else: return contains(text, pat, text_index+1, pat_index) # If current characters of pat and tex don't match return contains(text , pat, text_index+1, pat_index) # Driver program to test the above function print(contains(\"geeksforgeeks\", \"geeks\", 0, 0))print(contains(\"geeksforgeeks\", \"geeksquiz\", 0, 0))print(contains(\"geeksquizgeeks\", \"quiz\", 0, 0)) # This code is contributed by ankush_953.",
"e": 4760,
"s": 3567,
"text": null
},
{
"code": "<script> // Recursive JavaScript program to find if a given pattern is// present in a text function exactMatch(text, pat, text_index, pat_index){ if(text_index == text.length && pat_index != pat.length) return 0 // Else If last character of pattern reaches if(pat_index == pat.length) return 1 if(text[text_index] == pat[pat_index]) return exactMatch(text, pat, text_index+1, pat_index+1) return 0} // This function returns true if 'text' contain 'pat'function contains(text, pat, text_index, pat_index){ // If last character of text reaches if(text_index == text.length) return 0 // If current characters of pat and text match if(text[text_index] == pat[pat_index]){ if(exactMatch(text, pat, text_index, pat_index)) return 1 else return contains(text, pat, text_index+1, pat_index) } // If current characters of pat and tex don't match return contains(text , pat, text_index+1, pat_index)} // Driver program to test the above function document.write(contains(\"geeksforgeeks\", \"geeks\", 0, 0),\"</br>\")document.write(contains(\"geeksforgeeks\", \"geeksquiz\", 0, 0),\"</br>\")document.write(contains(\"geeksquizgeeks\", \"quiz\", 0, 0),\"</br>\") // This code is contributed by shinjanpatra. </script>",
"e": 6061,
"s": 4760,
"text": null
},
{
"code": null,
"e": 6069,
"s": 6061,
"text": "Output:"
},
{
"code": null,
"e": 6075,
"s": 6069,
"text": "1\n0\n1"
},
{
"code": null,
"e": 6124,
"s": 6075,
"text": "Time Complexity : O(n*m)Auxiliary Space : O(n+m)"
},
{
"code": null,
"e": 6290,
"s": 6124,
"text": "This article is contributed by Bhupinder. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 6297,
"s": 6290,
"text": "san123"
},
{
"code": null,
"e": 6308,
"s": 6297,
"text": "ankush_953"
},
{
"code": null,
"e": 6321,
"s": 6308,
"text": "shinjanpatra"
},
{
"code": null,
"e": 6338,
"s": 6321,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 6353,
"s": 6338,
"text": "susobhanakhuli"
},
{
"code": null,
"e": 6370,
"s": 6353,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6380,
"s": 6370,
"text": "Searching"
},
{
"code": null,
"e": 6388,
"s": 6380,
"text": "Strings"
},
{
"code": null,
"e": 6398,
"s": 6388,
"text": "Searching"
},
{
"code": null,
"e": 6406,
"s": 6398,
"text": "Strings"
}
] |
Find duplicate rows in a Dataframe based on all or selected columns
|
16 Feb, 2022
In this article, we will be discussing how to find duplicate rows in a Dataframe based on all or a list of columns. For this, we will use Dataframe.duplicated() method of Pandas.
Syntax : DataFrame.duplicated(subset = None, keep = βfirstβ)Parameters: subset: This Takes a column or list of column label. Itβs default value is None. After passing columns, it will consider them only for duplicates.keep: This Controls how to consider duplicate value. It has only three distinct value and default is βfirstβ.
If βfirstβ, This considers first value as unique and rest of the same values as duplicate.
If βlastβ, This considers last value as unique and rest of the same values as duplicate.
If βFalseβ, This considers all of the same values as duplicates.
Returns: Boolean Series denoting duplicate rows.
Letβs create a simple dataframe with a dictionary of lists, say column names are: βNameβ, βAgeβ and βCityβ.
Python3
# Import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Print the Dataframedf
Output :
Example 1: Select duplicate rows based on all columns. Here, We do not pass any argument, therefore, it takes default values for both the arguments i.e. subset = None and keep = βfirstβ.
Python3
# Import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows except first# occurrence based on all columnsduplicate = df[df.duplicated()] print("Duplicate Rows :") # Print the resultant Dataframeduplicate
Output :
Example 2: Select duplicate rows based on all columns. If you want to consider all duplicates except the last one then pass keep = βlastβ as an argument.
Python3
# Import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows except last# occurrence based on all columns.duplicate = df[df.duplicated(keep = 'last')] print("Duplicate Rows :") # Print the resultant Dataframeduplicate
Output :
Example 3: If you want to select duplicate rows based only on some selected columns then pass the list of column names in subset as an argument.
Python3
# import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows based# on 'City' columnduplicate = df[df.duplicated('City')] print("Duplicate Rows based on City :") # Print the resultant Dataframeduplicate
Output :
Example 4: Select duplicate rows based on more than one column name.
Python3
# import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame object df = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows based# on list of column namesduplicate = df[df.duplicated(['Name', 'Age'])] print("Duplicate Rows based on Name and Age :") # Print the resultant Dataframeduplicate
Output :
reenadevi98412200
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Feb, 2022"
},
{
"code": null,
"e": 208,
"s": 28,
"text": "In this article, we will be discussing how to find duplicate rows in a Dataframe based on all or a list of columns. For this, we will use Dataframe.duplicated() method of Pandas. "
},
{
"code": null,
"e": 538,
"s": 208,
"text": "Syntax : DataFrame.duplicated(subset = None, keep = βfirstβ)Parameters: subset: This Takes a column or list of column label. Itβs default value is None. After passing columns, it will consider them only for duplicates.keep: This Controls how to consider duplicate value. It has only three distinct value and default is βfirstβ. "
},
{
"code": null,
"e": 629,
"s": 538,
"text": "If βfirstβ, This considers first value as unique and rest of the same values as duplicate."
},
{
"code": null,
"e": 718,
"s": 629,
"text": "If βlastβ, This considers last value as unique and rest of the same values as duplicate."
},
{
"code": null,
"e": 783,
"s": 718,
"text": "If βFalseβ, This considers all of the same values as duplicates."
},
{
"code": null,
"e": 834,
"s": 783,
"text": "Returns: Boolean Series denoting duplicate rows. "
},
{
"code": null,
"e": 944,
"s": 834,
"text": "Letβs create a simple dataframe with a dictionary of lists, say column names are: βNameβ, βAgeβ and βCityβ. "
},
{
"code": null,
"e": 952,
"s": 944,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Print the Dataframedf",
"e": 1455,
"s": 952,
"text": null
},
{
"code": null,
"e": 1466,
"s": 1455,
"text": "Output : "
},
{
"code": null,
"e": 1654,
"s": 1466,
"text": "Example 1: Select duplicate rows based on all columns. Here, We do not pass any argument, therefore, it takes default values for both the arguments i.e. subset = None and keep = βfirstβ. "
},
{
"code": null,
"e": 1662,
"s": 1654,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows except first# occurrence based on all columnsduplicate = df[df.duplicated()] print(\"Duplicate Rows :\") # Print the resultant Dataframeduplicate",
"e": 2312,
"s": 1662,
"text": null
},
{
"code": null,
"e": 2323,
"s": 2312,
"text": "Output : "
},
{
"code": null,
"e": 2478,
"s": 2323,
"text": "Example 2: Select duplicate rows based on all columns. If you want to consider all duplicates except the last one then pass keep = βlastβ as an argument. "
},
{
"code": null,
"e": 2486,
"s": 2478,
"text": "Python3"
},
{
"code": "# Import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows except last# occurrence based on all columns.duplicate = df[df.duplicated(keep = 'last')] print(\"Duplicate Rows :\") # Print the resultant Dataframeduplicate",
"e": 3149,
"s": 2486,
"text": null
},
{
"code": null,
"e": 3160,
"s": 3149,
"text": "Output : "
},
{
"code": null,
"e": 3307,
"s": 3160,
"text": "Example 3: If you want to select duplicate rows based only on some selected columns then pass the list of column names in subset as an argument. "
},
{
"code": null,
"e": 3315,
"s": 3307,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame objectdf = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows based# on 'City' columnduplicate = df[df.duplicated('City')] print(\"Duplicate Rows based on City :\") # Print the resultant Dataframeduplicate",
"e": 3963,
"s": 3315,
"text": null
},
{
"code": null,
"e": 3974,
"s": 3963,
"text": "Output : "
},
{
"code": null,
"e": 4044,
"s": 3974,
"text": "Example 4: Select duplicate rows based on more than one column name. "
},
{
"code": null,
"e": 4052,
"s": 4044,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # List of Tuplesemployees = [('Stuti', 28, 'Varanasi'), ('Saumya', 32, 'Delhi'), ('Aaditya', 25, 'Mumbai'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Delhi'), ('Saumya', 32, 'Mumbai'), ('Aaditya', 40, 'Dehradun'), ('Seema', 32, 'Delhi') ] # Creating a DataFrame object df = pd.DataFrame(employees, columns = ['Name', 'Age', 'City']) # Selecting duplicate rows based# on list of column namesduplicate = df[df.duplicated(['Name', 'Age'])] print(\"Duplicate Rows based on Name and Age :\") # Print the resultant Dataframeduplicate",
"e": 4726,
"s": 4052,
"text": null
},
{
"code": null,
"e": 4737,
"s": 4726,
"text": "Output : "
},
{
"code": null,
"e": 4757,
"s": 4739,
"text": "reenadevi98412200"
},
{
"code": null,
"e": 4781,
"s": 4757,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4795,
"s": 4781,
"text": "Python-pandas"
},
{
"code": null,
"e": 4802,
"s": 4795,
"text": "Python"
}
] |
Method Chaining in JavaScript
|
31 Mar, 2021
As a good programming practice, we should write individual functions/methods for dealing with individual actions. And, writing only one method/function for all actions is a thing. However, sticking to good practice takes a toll on the readability and comprehensibility of the code, because defining a separate function for each action means that the output of a single function/method is input. This makes code comprehensibility even worse, as the function needs to be nested in reverse order. This is where method chaining comes to the rescue.
Method Chaining is a programming strategy that simplifies and embellishes your code. It is a mechanism of calling a method on another method of the same object.
this keyword in JavaScript refers to the current object in which it is called. Thus, when a method returns this, it simply returns an instance of the object in which it is returned. Since the returned value is an instance of an object, it is, therefore, possible to call another method of an object to the returned value, which is its instance. And this makes method chaining possible in JavaScript.
Example: In this example, each method in Land.prototype returns this, which refers to the entire instance of that Land object. And this would help in calling a method on another method of the same object.
Javascript
//creating a function Land()function Land() {this.area = '';this.status = 'for Sale';}//Setting status open for saleLand.prototype.open = function() {this.status = 'Open for Sale';return this;}//Setting status not for saleLand.prototype.close = function() {this.status = 'Not for Sale';return this;}//Setting ParametersLand.prototype.setParams = function(area) {this.area = area;return this;}//printing land statusLand.prototype.doorStatus = function() {console.log('The',this.area,'Land is',this.status);return this;}//creating a land objectvar land = new Land();land.setParams("500 sq ft").close().doorStatus().open().doorStatus();
Output:
The 500 sq ft Land is Not for Sale
The 500 sq ft Land is Open for Sale
Land { area: β500 sq ftβ, status: βOpen for Saleβ }
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 597,
"s": 52,
"text": "As a good programming practice, we should write individual functions/methods for dealing with individual actions. And, writing only one method/function for all actions is a thing. However, sticking to good practice takes a toll on the readability and comprehensibility of the code, because defining a separate function for each action means that the output of a single function/method is input. This makes code comprehensibility even worse, as the function needs to be nested in reverse order. This is where method chaining comes to the rescue."
},
{
"code": null,
"e": 758,
"s": 597,
"text": "Method Chaining is a programming strategy that simplifies and embellishes your code. It is a mechanism of calling a method on another method of the same object."
},
{
"code": null,
"e": 1158,
"s": 758,
"text": "this keyword in JavaScript refers to the current object in which it is called. Thus, when a method returns this, it simply returns an instance of the object in which it is returned. Since the returned value is an instance of an object, it is, therefore, possible to call another method of an object to the returned value, which is its instance. And this makes method chaining possible in JavaScript."
},
{
"code": null,
"e": 1363,
"s": 1158,
"text": "Example: In this example, each method in Land.prototype returns this, which refers to the entire instance of that Land object. And this would help in calling a method on another method of the same object."
},
{
"code": null,
"e": 1374,
"s": 1363,
"text": "Javascript"
},
{
"code": "//creating a function Land()function Land() {this.area = '';this.status = 'for Sale';}//Setting status open for saleLand.prototype.open = function() {this.status = 'Open for Sale';return this;}//Setting status not for saleLand.prototype.close = function() {this.status = 'Not for Sale';return this;}//Setting ParametersLand.prototype.setParams = function(area) {this.area = area;return this;}//printing land statusLand.prototype.doorStatus = function() {console.log('The',this.area,'Land is',this.status);return this;}//creating a land objectvar land = new Land();land.setParams(\"500 sq ft\").close().doorStatus().open().doorStatus();",
"e": 2008,
"s": 1374,
"text": null
},
{
"code": null,
"e": 2016,
"s": 2008,
"text": "Output:"
},
{
"code": null,
"e": 2051,
"s": 2016,
"text": "The 500 sq ft Land is Not for Sale"
},
{
"code": null,
"e": 2087,
"s": 2051,
"text": "The 500 sq ft Land is Open for Sale"
},
{
"code": null,
"e": 2139,
"s": 2087,
"text": "Land { area: β500 sq ftβ, status: βOpen for Saleβ }"
},
{
"code": null,
"e": 2160,
"s": 2139,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2171,
"s": 2160,
"text": "JavaScript"
},
{
"code": null,
"e": 2188,
"s": 2171,
"text": "Web Technologies"
}
] |
Stored Procedures classification based on Input and Output Parameters in SQL Server
|
18 Aug, 2021
Stored Procedure:
The stored procedure has the following key points as follows.
It is a collection of SQL statements such as if you want to write and read data from a database then you can use create a statement for write and select statement for reading the data from database and SQL command logic for the same, which is compiled and stored on the database.A stored procedure is a group of T-SQL (Transact SQL) statements.If you have a situation, where you can write the same query over and over again, you can save that specific query as a stored procedure and call it just by its name.
It is a collection of SQL statements such as if you want to write and read data from a database then you can use create a statement for write and select statement for reading the data from database and SQL command logic for the same, which is compiled and stored on the database.
A stored procedure is a group of T-SQL (Transact SQL) statements.
If you have a situation, where you can write the same query over and over again, you can save that specific query as a stored procedure and call it just by its name.
Classification of Stored Procedure
Create Stored Procedure without Parameter :
You can use the following stored procedure given below to create the stored procedure without a parameter.
create procedure sp_get_empno
as
begin
select * from emp where ename='WARD'
end
exec sp_get_empno
Create a Stored Procedure with Output Parameter :
You can use the following stored procedure given below to create the stored procedure with an output parameter.
declare @empId int
exec GetEmployeeID (@empId int out)
create procedure sp_get_empid(@name varchar(10) out)
as
begin
select id from emp where ename="Sam"
end
exec sp_get_empid @empID
Create a Stored Procedure with Input Parameter :
You can use the following stored procedure given below to create the stored procedure with an Input parameter.
USE Db1
GO
CREATE PROCEDURE dbo.GetEmployeeID(@Email varchar(30))
AS
SELECT * FROM employeeDetails WHERE email= @Email
GO
Create a Stored Procedure with both input and Output Parameter :
You can use the following stored procedure given below to create the stored procedure with both an input and output parameter.
create procedure sp_get_empname(@name varchar(10) out, @id int)
as
begin
select ename from emp where empno=@id
end
declare @en varchar(10)
exec sp_get_empname @en,7521
print @en
simranarora5sos
DBMS-SQL
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
SQL | Sub queries in From Clause
Window functions in SQL
What is Temporary Table in SQL?
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL using Python
SQL Query to Convert VARCHAR to INT
RANK() Function in SQL Server
How to Import JSON Data into SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 46,
"s": 28,
"text": "Stored Procedure:"
},
{
"code": null,
"e": 108,
"s": 46,
"text": "The stored procedure has the following key points as follows."
},
{
"code": null,
"e": 618,
"s": 108,
"text": "It is a collection of SQL statements such as if you want to write and read data from a database then you can use create a statement for write and select statement for reading the data from database and SQL command logic for the same, which is compiled and stored on the database.A stored procedure is a group of T-SQL (Transact SQL) statements.If you have a situation, where you can write the same query over and over again, you can save that specific query as a stored procedure and call it just by its name."
},
{
"code": null,
"e": 898,
"s": 618,
"text": "It is a collection of SQL statements such as if you want to write and read data from a database then you can use create a statement for write and select statement for reading the data from database and SQL command logic for the same, which is compiled and stored on the database."
},
{
"code": null,
"e": 964,
"s": 898,
"text": "A stored procedure is a group of T-SQL (Transact SQL) statements."
},
{
"code": null,
"e": 1130,
"s": 964,
"text": "If you have a situation, where you can write the same query over and over again, you can save that specific query as a stored procedure and call it just by its name."
},
{
"code": null,
"e": 1165,
"s": 1130,
"text": "Classification of Stored Procedure"
},
{
"code": null,
"e": 1209,
"s": 1165,
"text": "Create Stored Procedure without Parameter :"
},
{
"code": null,
"e": 1317,
"s": 1209,
"text": " You can use the following stored procedure given below to create the stored procedure without a parameter."
},
{
"code": null,
"e": 1421,
"s": 1317,
"text": "create procedure sp_get_empno\nas \nbegin \nselect * from emp where ename='WARD' \nend\nexec sp_get_empno"
},
{
"code": null,
"e": 1471,
"s": 1421,
"text": "Create a Stored Procedure with Output Parameter :"
},
{
"code": null,
"e": 1584,
"s": 1471,
"text": " You can use the following stored procedure given below to create the stored procedure with an output parameter."
},
{
"code": null,
"e": 1771,
"s": 1584,
"text": "declare @empId int\nexec GetEmployeeID (@empId int out)\ncreate procedure sp_get_empid(@name varchar(10) out)\nas \nbegin \nselect id from emp where ename=\"Sam\"\nend\nexec sp_get_empid @empID"
},
{
"code": null,
"e": 1820,
"s": 1771,
"text": "Create a Stored Procedure with Input Parameter :"
},
{
"code": null,
"e": 1932,
"s": 1820,
"text": " You can use the following stored procedure given below to create the stored procedure with an Input parameter."
},
{
"code": null,
"e": 2055,
"s": 1932,
"text": "USE Db1\nGO\nCREATE PROCEDURE dbo.GetEmployeeID(@Email varchar(30))\nAS\nSELECT * FROM employeeDetails WHERE email= @Email\nGO"
},
{
"code": null,
"e": 2120,
"s": 2055,
"text": "Create a Stored Procedure with both input and Output Parameter :"
},
{
"code": null,
"e": 2248,
"s": 2120,
"text": " You can use the following stored procedure given below to create the stored procedure with both an input and output parameter."
},
{
"code": null,
"e": 2426,
"s": 2248,
"text": "create procedure sp_get_empname(@name varchar(10) out, @id int)\nas\nbegin\nselect ename from emp where empno=@id\nend\ndeclare @en varchar(10)\nexec sp_get_empname @en,7521\nprint @en"
},
{
"code": null,
"e": 2442,
"s": 2426,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2451,
"s": 2442,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 2462,
"s": 2451,
"text": "SQL-Server"
},
{
"code": null,
"e": 2466,
"s": 2462,
"text": "SQL"
},
{
"code": null,
"e": 2470,
"s": 2466,
"text": "SQL"
},
{
"code": null,
"e": 2568,
"s": 2470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2634,
"s": 2568,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2667,
"s": 2634,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2691,
"s": 2667,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2723,
"s": 2691,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2801,
"s": 2723,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2818,
"s": 2801,
"text": "SQL using Python"
},
{
"code": null,
"e": 2854,
"s": 2818,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2884,
"s": 2854,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2925,
"s": 2884,
"text": "How to Import JSON Data into SQL Server?"
}
] |
MongoDB SELECT COUNT GROUP BY?
|
You can achieve this with the help of an aggregate framework. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows β
> db.countGroupByDemo.insertOne({"StudentId":10,"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7700871e9c5dd6f1f78296")
}
> db.countGroupByDemo.insertOne({"StudentId":10,"StudentName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77008f1e9c5dd6f1f78297")
}
> db.countGroupByDemo.insertOne({"StudentId":20,"StudentName":"Sam"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7700971e9c5dd6f1f78298")
}
> db.countGroupByDemo.insertOne({"StudentId":30,"StudentName":"Mike"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7700a21e9c5dd6f1f78299")
}
> db.countGroupByDemo.insertOne({"StudentId":30,"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7700aa1e9c5dd6f1f7829a")
}
> db.countGroupByDemo.insertOne({"StudentId":10,"StudentName":"Maxwell"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7700b41e9c5dd6f1f7829b")
}
> db.countGroupByDemo.insertOne({"StudentId":20,"StudentName":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c7700bd1e9c5dd6f1f7829c")
}
Display all documents from a collection with the help of find() method. The query is as follows β
> db.countGroupByDemo.find().pretty();
{
"_id" : ObjectId("5c7700871e9c5dd6f1f78296"),
"StudentId" : 10,
"StudentName" : "John"
}
{
"_id" : ObjectId("5c77008f1e9c5dd6f1f78297"),
"StudentId" : 10,
"StudentName" : "Carol"
}
{
"_id" : ObjectId("5c7700971e9c5dd6f1f78298"),
"StudentId" : 20,
"StudentName" : "Sam"
}
{
"_id" : ObjectId("5c7700a21e9c5dd6f1f78299"),
"StudentId" : 30,
"StudentName" : "Mike"
}
{
"_id" : ObjectId("5c7700aa1e9c5dd6f1f7829a"),
"StudentId" : 30,
"StudentName" : "David"
}
{
"_id" : ObjectId("5c7700b41e9c5dd6f1f7829b"),
"StudentId" : 10,
"StudentName" : "Maxwell"
}
{
"_id" : ObjectId("5c7700bd1e9c5dd6f1f7829c"),
"StudentId" : 20,
"StudentName" : "Bob"
}
Here is the query to select count group by β
> db.countGroupByDemo.aggregate([
... {"$group":{_id:"$StudentId",counter:{$sum:1}}}]);
{ "_id" : 30, "counter" : 2 }
{ "_id" : 20, "counter" : 2 }
{ "_id" : 10, "counter" : 3 }
|
[
{
"code": null,
"e": 1262,
"s": 1062,
"text": "You can achieve this with the help of an aggregate framework. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows β"
},
{
"code": null,
"e": 2364,
"s": 1262,
"text": "> db.countGroupByDemo.insertOne({\"StudentId\":10,\"StudentName\":\"John\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7700871e9c5dd6f1f78296\")\n}\n> db.countGroupByDemo.insertOne({\"StudentId\":10,\"StudentName\":\"Carol\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c77008f1e9c5dd6f1f78297\")\n}\n> db.countGroupByDemo.insertOne({\"StudentId\":20,\"StudentName\":\"Sam\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7700971e9c5dd6f1f78298\")\n}\n> db.countGroupByDemo.insertOne({\"StudentId\":30,\"StudentName\":\"Mike\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7700a21e9c5dd6f1f78299\")\n}\n> db.countGroupByDemo.insertOne({\"StudentId\":30,\"StudentName\":\"David\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7700aa1e9c5dd6f1f7829a\")\n}\n> db.countGroupByDemo.insertOne({\"StudentId\":10,\"StudentName\":\"Maxwell\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7700b41e9c5dd6f1f7829b\")\n}\n> db.countGroupByDemo.insertOne({\"StudentId\":20,\"StudentName\":\"Bob\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c7700bd1e9c5dd6f1f7829c\")\n}"
},
{
"code": null,
"e": 2462,
"s": 2364,
"text": "Display all documents from a collection with the help of find() method. The query is as follows β"
},
{
"code": null,
"e": 2501,
"s": 2462,
"text": "> db.countGroupByDemo.find().pretty();"
},
{
"code": null,
"e": 3204,
"s": 2501,
"text": "{\n \"_id\" : ObjectId(\"5c7700871e9c5dd6f1f78296\"),\n \"StudentId\" : 10,\n \"StudentName\" : \"John\"\n}\n{\n \"_id\" : ObjectId(\"5c77008f1e9c5dd6f1f78297\"),\n \"StudentId\" : 10,\n \"StudentName\" : \"Carol\"\n}\n{\n \"_id\" : ObjectId(\"5c7700971e9c5dd6f1f78298\"),\n \"StudentId\" : 20,\n \"StudentName\" : \"Sam\"\n}\n{\n \"_id\" : ObjectId(\"5c7700a21e9c5dd6f1f78299\"),\n \"StudentId\" : 30,\n \"StudentName\" : \"Mike\"\n}\n{\n \"_id\" : ObjectId(\"5c7700aa1e9c5dd6f1f7829a\"),\n \"StudentId\" : 30,\n \"StudentName\" : \"David\"\n}\n{\n \"_id\" : ObjectId(\"5c7700b41e9c5dd6f1f7829b\"),\n \"StudentId\" : 10,\n \"StudentName\" : \"Maxwell\"\n}\n{\n \"_id\" : ObjectId(\"5c7700bd1e9c5dd6f1f7829c\"),\n \"StudentId\" : 20,\n \"StudentName\" : \"Bob\"\n}"
},
{
"code": null,
"e": 3249,
"s": 3204,
"text": "Here is the query to select count group by β"
},
{
"code": null,
"e": 3337,
"s": 3249,
"text": "> db.countGroupByDemo.aggregate([\n... {\"$group\":{_id:\"$StudentId\",counter:{$sum:1}}}]);"
},
{
"code": null,
"e": 3427,
"s": 3337,
"text": "{ \"_id\" : 30, \"counter\" : 2 }\n{ \"_id\" : 20, \"counter\" : 2 }\n{ \"_id\" : 10, \"counter\" : 3 }"
}
] |
Restricting MySQL Connections to Secure Transport
|
MySQL will make secure connections easier when it has streamlined key generation for both MySQL Community and MySQL Enterprise. This way, the security is improved by expanding support for TLSv1.1 and TLSv1.2. This also helps administrators determine if clients are connecting securely or not with enhanced visibility into connection types.
Extending this importance on secure connections, MySQL server introduced a new server-side configuration option that allows MySQL administrators to restrict connections to clients who use secure transport. When we say about the connection needing secure transport, the first question that needs to be addressed is the kind of transport it uses.
Let us see the kinds of transport that are considered secure β
SSL/TLS
SSL/TLS
Socket
Socket
Shared Memory
Shared Memory
In particular, connections on Windows machines that use the named pipe transport are not considered to be secure. These connections are usually made locally, and named pipe connections can be made remotely. But they also lack data encryption that would protect payloads which are sent over the wire.
The - -require_secure_transport configuration option was newly added. Here, the boolean option default is OFF. This means that connections that use any of the above mentioned supported
protocols are accepted, if they are consistent with legacy behaviour. Setting -- require_secure_transport=ON makes the server reject new connections which donβt use one of the connection types shown above.
Clients that are rejected due to insecure connections would receive the below mentioned error β
D:\mysql-advanced-5.7.10-winx64>bin\mysql -uroot -P3310 --skip-ssl
ERROR 3159 (HY000): Connections using insecure transport are prohibited while
--require_secure_transport=ON.
D:\mysql-advanced-5.7.10-winx64>bin\mysql -uroot -P3310 --skip-ssl
ERROR 3159 (HY000): Connections using insecure transport are prohibited while
--require_secure_transport=ON.
MySQL also supports requiring TLS for specific accounts. This is done by including the REQUIRE SSL clause in CREATE or ALTER USER commands. The new --require_secure_transport option will add these account-level requirements by enforcing secure transport at a global level.
|
[
{
"code": null,
"e": 1402,
"s": 1062,
"text": "MySQL will make secure connections easier when it has streamlined key generation for both MySQL Community and MySQL Enterprise. This way, the security is improved by expanding support for TLSv1.1 and TLSv1.2. This also helps administrators determine if clients are connecting securely or not with enhanced visibility into connection types."
},
{
"code": null,
"e": 1747,
"s": 1402,
"text": "Extending this importance on secure connections, MySQL server introduced a new server-side configuration option that allows MySQL administrators to restrict connections to clients who use secure transport. When we say about the connection needing secure transport, the first question that needs to be addressed is the kind of transport it uses."
},
{
"code": null,
"e": 1810,
"s": 1747,
"text": "Let us see the kinds of transport that are considered secure β"
},
{
"code": null,
"e": 1818,
"s": 1810,
"text": "SSL/TLS"
},
{
"code": null,
"e": 1826,
"s": 1818,
"text": "SSL/TLS"
},
{
"code": null,
"e": 1833,
"s": 1826,
"text": "Socket"
},
{
"code": null,
"e": 1840,
"s": 1833,
"text": "Socket"
},
{
"code": null,
"e": 1854,
"s": 1840,
"text": "Shared Memory"
},
{
"code": null,
"e": 1868,
"s": 1854,
"text": "Shared Memory"
},
{
"code": null,
"e": 2168,
"s": 1868,
"text": "In particular, connections on Windows machines that use the named pipe transport are not considered to be secure. These connections are usually made locally, and named pipe connections can be made remotely. But they also lack data encryption that would protect payloads which are sent over the wire."
},
{
"code": null,
"e": 2353,
"s": 2168,
"text": "The - -require_secure_transport configuration option was newly added. Here, the boolean option default is OFF. This means that connections that use any of the above mentioned supported"
},
{
"code": null,
"e": 2559,
"s": 2353,
"text": "protocols are accepted, if they are consistent with legacy behaviour. Setting -- require_secure_transport=ON makes the server reject new connections which donβt use one of the connection types shown above."
},
{
"code": null,
"e": 2655,
"s": 2559,
"text": "Clients that are rejected due to insecure connections would receive the below mentioned error β"
},
{
"code": null,
"e": 2722,
"s": 2655,
"text": "D:\\mysql-advanced-5.7.10-winx64>bin\\mysql -uroot -P3310 --skip-ssl"
},
{
"code": null,
"e": 2831,
"s": 2722,
"text": "ERROR 3159 (HY000): Connections using insecure transport are prohibited while\n--require_secure_transport=ON."
},
{
"code": null,
"e": 2898,
"s": 2831,
"text": "D:\\mysql-advanced-5.7.10-winx64>bin\\mysql -uroot -P3310 --skip-ssl"
},
{
"code": null,
"e": 3007,
"s": 2898,
"text": "ERROR 3159 (HY000): Connections using insecure transport are prohibited while\n--require_secure_transport=ON."
},
{
"code": null,
"e": 3280,
"s": 3007,
"text": "MySQL also supports requiring TLS for specific accounts. This is done by including the REQUIRE SSL clause in CREATE or ALTER USER commands. The new --require_secure_transport option will add these account-level requirements by enforcing secure transport at a global level."
}
] |
Minimum operations required to make all the array elements equal in C++
|
Given an array with n positive integers. We need to find the minimum number of operation to make all elements equal. We can perform addition, multiplication, subtraction or division with any element on an array element.
If input array is = {1, 2, 3, 4} then we require minimum 3 operations to make all elements equal. For example, we can make elements 4 by doing 3 additions.
1. Select element with maximum frequency. Let us call it βxβ
2. Now we have to perform n-x operations as there are x element with same value
Live Demo
#include <bits/stdc++.h>
using namespace std;
int getMinOperations(int *arr, int n) {
unordered_map<int, int> hash;
for (int i = 0;i < n; ++i) {
hash[arr[i]]++;
}
int maxFrequency = 0;
for (auto elem : hash) {
if (elem.second > maxFrequency) {
maxFrequency = elem.second;
}
}
return (n - maxFrequency);
}
int main() {
int arr[] = {1, 2, 3, 4};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Minimum required operations = " <<
getMinOperations(arr, n) << endl;
return 0;
}
When you compile and execute above program. It generates following output:
Minimum required operations = 3
|
[
{
"code": null,
"e": 1282,
"s": 1062,
"text": "Given an array with n positive integers. We need to find the minimum number of operation to make all elements equal. We can perform addition, multiplication, subtraction or division with any element on an array element."
},
{
"code": null,
"e": 1438,
"s": 1282,
"text": "If input array is = {1, 2, 3, 4} then we require minimum 3 operations to make all elements equal. For example, we can make elements 4 by doing 3 additions."
},
{
"code": null,
"e": 1580,
"s": 1438,
"text": "1. Select element with maximum frequency. Let us call it βxβ \n2. Now we have to perform n-x operations as there are x element with same value"
},
{
"code": null,
"e": 1591,
"s": 1580,
"text": " Live Demo"
},
{
"code": null,
"e": 2123,
"s": 1591,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint getMinOperations(int *arr, int n) {\n unordered_map<int, int> hash;\n for (int i = 0;i < n; ++i) {\n hash[arr[i]]++;\n }\nint maxFrequency = 0;\n for (auto elem : hash) {\n if (elem.second > maxFrequency) {\n maxFrequency = elem.second;\n }\n }\n return (n - maxFrequency);\n}\nint main() {\n int arr[] = {1, 2, 3, 4};\n int n = sizeof(arr) / sizeof(arr[0]);\n cout << \"Minimum required operations = \" <<\n getMinOperations(arr, n) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2198,
"s": 2123,
"text": "When you compile and execute above program. It generates following output:"
},
{
"code": null,
"e": 2230,
"s": 2198,
"text": "Minimum required operations = 3"
}
] |
How to Make a DIV 100% of the Window Height using CSS
|
The CSS height property helps us specify the height of an element.
The syntax of CSS height property is as follows β
Selector {
height: /*value*/
}
The following examples illustrate CSS height property.
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
html, body {
margin: 0px;
height: 100vh;
}
div {
height: 100%;
text-align: center;
background: mistyrose;
}
</style>
</head>
<body>
<div>100% height!!</div>
</body>
</html>
This gives the following output
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<style>
html, body {
display: flex;
flex-direction: row;
justify-content: space-around;
margin: 0px;
height: 100vh;
box-shadow: inset 0 0 40px lightblue;
}
div {
width: 40%;
height: 100vh;
text-align: center;
box-shadow: inset 0 0 20px lightcoral;
}
</style>
</head>
<body>
<div>Watch This!</div>
<div>Let Me Show You How The Boss Does It!!</div>
<div>Open Up The Sky!!</div>
<div>GO! GO! GO!!</div>
</body>
</html>
This gives the following output
|
[
{
"code": null,
"e": 1129,
"s": 1062,
"text": "The CSS height property helps us specify the height of an element."
},
{
"code": null,
"e": 1179,
"s": 1129,
"text": "The syntax of CSS height property is as follows β"
},
{
"code": null,
"e": 1213,
"s": 1179,
"text": "Selector {\n height: /*value*/\n}"
},
{
"code": null,
"e": 1268,
"s": 1213,
"text": "The following examples illustrate CSS height property."
},
{
"code": null,
"e": 1279,
"s": 1268,
"text": " Live Demo"
},
{
"code": null,
"e": 1648,
"s": 1279,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Page Title</title>\n <style>\n html, body {\n margin: 0px;\n height: 100vh;\n }\n div {\n height: 100%;\n text-align: center;\n background: mistyrose;\n }\n </style>\n </head>\n <body>\n <div>100% height!!</div>\n </body>\n</html>"
},
{
"code": null,
"e": 1680,
"s": 1648,
"text": "This gives the following output"
},
{
"code": null,
"e": 1691,
"s": 1680,
"text": " Live Demo"
},
{
"code": null,
"e": 2373,
"s": 1691,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Page Title</title>\n <style>\n html, body {\n display: flex;\n flex-direction: row;\n justify-content: space-around;\n margin: 0px;\n height: 100vh;\n box-shadow: inset 0 0 40px lightblue;\n }\n div {\n width: 40%;\n height: 100vh;\n text-align: center;\n box-shadow: inset 0 0 20px lightcoral;\n }\n </style>\n </head>\n <body>\n <div>Watch This!</div>\n <div>Let Me Show You How The Boss Does It!!</div>\n <div>Open Up The Sky!!</div>\n <div>GO! GO! GO!!</div>\n </body>\n</html>"
},
{
"code": null,
"e": 2405,
"s": 2373,
"text": "This gives the following output"
}
] |
Hyperparameter Optimization with Scikit-Learn, Scikit-Opt and Keras | by Luke Newman | Towards Data Science
|
Hyperparameter optimization is often one of the final steps in a data science project. Once you have a shortlist of promising models you will want to fine-tune them so that they perform better on your particular dataset.
In this post, we will go over three techniques used to find optimal hyperparameters with examples on how to implement them on models in Scikit-Learn and then finally a neural network in Keras. The three techniques we will discuss are as follows:
Grid Search
Randomized Search
Bayesian Optimization
You can view the jupyter notebook here.
One option would be to fiddle around with the hyperparameters manually, until you find a great combination of hyperparameter values that optimize your performance metric. This would be very tedious work, and you may not have time to explore many combinations.
Instead, you should get Scikit-Learnβs GridSearchCV to do it for you. All you have to do is tell it which hyperparameters you want to experiment with and what values to try out, and it will use cross-validation to evaluate all the possible combinations of hyperparameter values.
Let's work through an example where we use GridSearchCV to search for the best combination of hyperparameter values for a RandomForestClassifier trained using the popular MNIST dataset.
To give you a feel for the complexity of the classification task, the figure below shows a few images from the MNIST dataset:
To implement GridSearchCV we need to define a few things. First being the hyperparameters we want to experiment with and the values we want to try out. Below we specify this in a dictionary called param_grid.
The param_grid tells Scikit-Learn to evaluate 1 x 2 x 2 x 2 x 2 x 2 = 32 combinations of bootstrap, max_depth, max_features, min_samples_leaf, min_samples_split and n_estimators hyperparameters specified. The grid search will explore 32 combinations of RandomForestClassifierβs hyperparameter values, and it will train each model 5 times (since we are using five-fold cross-validation). In other words, all in all, there will be 32 x 5 = 160 rounds of training! It may take a long time, but when it is done you can get the best combination of hyperparameters like this:
forest_grid_search.best_params_
Since n_estimators=350 and max_depth=10 are the maximum values that were evaluated, you should probably try searching again with higher values; the score may continue to improve.
You can also get the best estimator directly:
forest_grid_search.best_estimator_
And of course the evaluation score is also available:
forest_grid_search.best_score_
Our best score here is 94.59% accuracy which is not bad for such a small parameter grid.
The grid search approach is fine when you are exploring relatively few combinations, like in the previous example, but when the hyperparameter space is large, it is often preferable to use RandomizedSearchCV instead. This class can be used in much the same way as the GridSearchCV class, but instead of trying out all possible combinations, it evaluates a given number of random combinations by selecting a random value for each hyperparameter at every iteration. This approach has two main benefits:
If you let randomized search run for, say, 1,000 iterations, this approach will explore 1,000 different values for each hyperparameter (instead of just a few values per hyperparameter with the grid search approach).
Simply by setting the number of iterations, you have more control over the computing budget you want to allocate to hyperparameter search.
Letβs walk through the same example as before but instead use RandomizedSearchCV. Since we are using RandomizedSearchCV we can search a larger param space than we did with GridSearchCV:
Same as above we can see the best hyperparameters that were explored:
forest_rand_search.best_params_
Also the best estimator:
forest_rand_search.best_estimator_
And check the best score:
forest_rand_search.best_score_
Our best performance was 96.21% accuracy beating GridSearchCV by 1.5%. As you can see RandomizedSearchCV allows us to explore a larger hyperparameter space in relatively the same amount of time and generally outputs better results than GridSearchCV.
You can now save this model, evaluate it on the test set, and, if you are satisfied with its performance, deploy it into production. Using randomized search is not too hard, and it works well for many fairly simple problems.
When training is slow, however, (e.g., for more complex problems with larger datasets), this approach will only explore a tiny portion of the hyperparameter space. You can partially alleviate this problem by assisting the search process manually: first, run a quick random search using wide ranges of hyperparameter values, then run another search using smaller ranges of values centered on the best ones found during the first run, and so on. This approach will hopefully zoom in on a good set of hyperparameters. However, itβs very time consuming, and probably not the best use of your time.
Fortunately, there are many techniques to explore a search space much more efficiently than randomly. Their core idea is simple: when a region of the space turns out to be good, it should be explored more. Such techniques take care of the βzoomingβ process for you and lead to much better solutions in much less time.
One such technique is called Bayesian Optimization and we will use Scikit-Optimize (Skopt) https://scikit-optimize.github.io/ to perform Bayesian Optimization. Skopt is a general-purpose optimization library that performs Bayesian Optimization with its class BayesSearchCV using an interface similar to GridSearchCV.
If you donβt have Skopt already installed go ahead and run the following line of code in your virtual environment:
! pip install scikit-optimize
There are 2 main differences when performing Bayesian Optimization using Skoptβs BayesSearchCV. First, when creating your search space you need to make each hyperparameterβs space a probability distribution as opposed to using lists likeGridSearchCV. Skopt makes this easy for you with their library skopt.space which lets us import Real, Integer, and Categorical to create the probability distributions.
Real: Continuous hyperparameter space.
Integer: Discrete hyperparameter space.
Categorical: Categorical hyperparameter space.
Below you can see examples of using both the categorical and integer functions. For categorical spaces simply input a list inside the function. For Integer spaces input the minimum and maximum values you want BayesSearchCV to explore.
The function on_step allows us to implement a form of early stopping and also prints out the score after each iteration. Here we specified after each iteration we want to print the best score and if the best score is greater than 98% accuracy training is no longer necessary.
Just like in Scikit-Learn we can view the best parameters:
forest_bayes_search.best_params_
And the best estimator:
forest_bayes_search.best_estimator_
And the best score:
forest_bayes_search.best_score_
Bayesian Optimization allowed us to improve our accuracy by another whole percent in the same amount of iterations as Randomized Search. I hope this convinces you to stray away from your comfort zone using GridSearchCV and RandomizedSearchCV and try implementing something new like BayesSearchCV in your next project. Hyperparameter searching can be tedious, but there are tools that can do the tedious work for you.
The flexibility of neural networks is also one of their main drawbacks: there are many hyperparameters to tweak. Not only can you use any imaginable network architecture, but even in a simple MLP you can change the number of layers, the number of neurons per layer, the type of activation function to use in each layer, the weight initialization logic, and much more. It can be hard to know what combination of hyperparameters is best for your task.
One option is to simply try many combinations of hyperparameters and see which one works best on the validation set (or use K-fold cross-validation). For example, we can use GridSearchCV or RandomizedSearchCV to explore the hyperparameter space. To do this, we need to wrap our Keras models in objects that mimic regular Scikit-Learn classifiers. The first step is to create a function that will build and compile a Keras model, given a set of hyperparameters:
This function creates a simple Sequential model for multi-class classification with the given input shape and the given number of hidden layers and neurons, and it compiles it using an SGD optimizer configured with the specified learning rate.
Next, letβs create a KerasClassifier based on this build_model() function:
keras_clf = keras.wrappers.scikit_learn.KerasClassifier(build_model)
The KerasClassifier object is a thin wrapper around the Keras model built using build_model(). This will allow us to use this object like a regular Scikit-Learn classifier: we can train it using its fit() method, then evaluate it using its score() method, and use it to make predictions using its predict() method.
We donβt want to train and evaluate a single model like this though, we want to train hundreds of variants and see which one performs best on the validation set. Since there are many hyperparameters, it is preferable to use randomized search rather than grid search. Letβs try to explore the number of hidden layers, the number of neurons, and the learning rate:
Now we can access the best parameters, estimator and score like we did in Scikit-Learn:
keras_rand_search.best_params_
keras_rand_search.best_score_
Our accuracy increased by another .5%! The last step is to see how each model performed on the test set (see below).
Hyperparameter tuning is still an active area of research, and different algorithms are being produced today. But having basic algorithms in your back pocket can alleviate a lot of the tedious work searching for the best hyperparameters.
Remember, randomized search is almost always preferable then grid search unless you have very few hyperparameters to explore. If you have a more complex problem using a larger dataset you might want to turn to a technique that explores a search space much more efficiently like Bayesian Optimization.
As always, any feedback and constructive criticism are greatly appreciated.
Feel free to check out the Github repository if you would like to see the presentation slides or jupyter notebook complete with the code and descriptions here.
scikit-optimize.github.io
This post covers two different libraries that are capable of performing Bayesian Optimization and is definitely worth checking out:
|
[
{
"code": null,
"e": 392,
"s": 171,
"text": "Hyperparameter optimization is often one of the final steps in a data science project. Once you have a shortlist of promising models you will want to fine-tune them so that they perform better on your particular dataset."
},
{
"code": null,
"e": 638,
"s": 392,
"text": "In this post, we will go over three techniques used to find optimal hyperparameters with examples on how to implement them on models in Scikit-Learn and then finally a neural network in Keras. The three techniques we will discuss are as follows:"
},
{
"code": null,
"e": 650,
"s": 638,
"text": "Grid Search"
},
{
"code": null,
"e": 668,
"s": 650,
"text": "Randomized Search"
},
{
"code": null,
"e": 690,
"s": 668,
"text": "Bayesian Optimization"
},
{
"code": null,
"e": 730,
"s": 690,
"text": "You can view the jupyter notebook here."
},
{
"code": null,
"e": 990,
"s": 730,
"text": "One option would be to fiddle around with the hyperparameters manually, until you find a great combination of hyperparameter values that optimize your performance metric. This would be very tedious work, and you may not have time to explore many combinations."
},
{
"code": null,
"e": 1269,
"s": 990,
"text": "Instead, you should get Scikit-Learnβs GridSearchCV to do it for you. All you have to do is tell it which hyperparameters you want to experiment with and what values to try out, and it will use cross-validation to evaluate all the possible combinations of hyperparameter values."
},
{
"code": null,
"e": 1455,
"s": 1269,
"text": "Let's work through an example where we use GridSearchCV to search for the best combination of hyperparameter values for a RandomForestClassifier trained using the popular MNIST dataset."
},
{
"code": null,
"e": 1581,
"s": 1455,
"text": "To give you a feel for the complexity of the classification task, the figure below shows a few images from the MNIST dataset:"
},
{
"code": null,
"e": 1790,
"s": 1581,
"text": "To implement GridSearchCV we need to define a few things. First being the hyperparameters we want to experiment with and the values we want to try out. Below we specify this in a dictionary called param_grid."
},
{
"code": null,
"e": 2360,
"s": 1790,
"text": "The param_grid tells Scikit-Learn to evaluate 1 x 2 x 2 x 2 x 2 x 2 = 32 combinations of bootstrap, max_depth, max_features, min_samples_leaf, min_samples_split and n_estimators hyperparameters specified. The grid search will explore 32 combinations of RandomForestClassifierβs hyperparameter values, and it will train each model 5 times (since we are using five-fold cross-validation). In other words, all in all, there will be 32 x 5 = 160 rounds of training! It may take a long time, but when it is done you can get the best combination of hyperparameters like this:"
},
{
"code": null,
"e": 2392,
"s": 2360,
"text": "forest_grid_search.best_params_"
},
{
"code": null,
"e": 2571,
"s": 2392,
"text": "Since n_estimators=350 and max_depth=10 are the maximum values that were evaluated, you should probably try searching again with higher values; the score may continue to improve."
},
{
"code": null,
"e": 2617,
"s": 2571,
"text": "You can also get the best estimator directly:"
},
{
"code": null,
"e": 2652,
"s": 2617,
"text": "forest_grid_search.best_estimator_"
},
{
"code": null,
"e": 2706,
"s": 2652,
"text": "And of course the evaluation score is also available:"
},
{
"code": null,
"e": 2737,
"s": 2706,
"text": "forest_grid_search.best_score_"
},
{
"code": null,
"e": 2826,
"s": 2737,
"text": "Our best score here is 94.59% accuracy which is not bad for such a small parameter grid."
},
{
"code": null,
"e": 3327,
"s": 2826,
"text": "The grid search approach is fine when you are exploring relatively few combinations, like in the previous example, but when the hyperparameter space is large, it is often preferable to use RandomizedSearchCV instead. This class can be used in much the same way as the GridSearchCV class, but instead of trying out all possible combinations, it evaluates a given number of random combinations by selecting a random value for each hyperparameter at every iteration. This approach has two main benefits:"
},
{
"code": null,
"e": 3543,
"s": 3327,
"text": "If you let randomized search run for, say, 1,000 iterations, this approach will explore 1,000 different values for each hyperparameter (instead of just a few values per hyperparameter with the grid search approach)."
},
{
"code": null,
"e": 3682,
"s": 3543,
"text": "Simply by setting the number of iterations, you have more control over the computing budget you want to allocate to hyperparameter search."
},
{
"code": null,
"e": 3868,
"s": 3682,
"text": "Letβs walk through the same example as before but instead use RandomizedSearchCV. Since we are using RandomizedSearchCV we can search a larger param space than we did with GridSearchCV:"
},
{
"code": null,
"e": 3938,
"s": 3868,
"text": "Same as above we can see the best hyperparameters that were explored:"
},
{
"code": null,
"e": 3970,
"s": 3938,
"text": "forest_rand_search.best_params_"
},
{
"code": null,
"e": 3995,
"s": 3970,
"text": "Also the best estimator:"
},
{
"code": null,
"e": 4030,
"s": 3995,
"text": "forest_rand_search.best_estimator_"
},
{
"code": null,
"e": 4056,
"s": 4030,
"text": "And check the best score:"
},
{
"code": null,
"e": 4087,
"s": 4056,
"text": "forest_rand_search.best_score_"
},
{
"code": null,
"e": 4337,
"s": 4087,
"text": "Our best performance was 96.21% accuracy beating GridSearchCV by 1.5%. As you can see RandomizedSearchCV allows us to explore a larger hyperparameter space in relatively the same amount of time and generally outputs better results than GridSearchCV."
},
{
"code": null,
"e": 4562,
"s": 4337,
"text": "You can now save this model, evaluate it on the test set, and, if you are satisfied with its performance, deploy it into production. Using randomized search is not too hard, and it works well for many fairly simple problems."
},
{
"code": null,
"e": 5156,
"s": 4562,
"text": "When training is slow, however, (e.g., for more complex problems with larger datasets), this approach will only explore a tiny portion of the hyperparameter space. You can partially alleviate this problem by assisting the search process manually: first, run a quick random search using wide ranges of hyperparameter values, then run another search using smaller ranges of values centered on the best ones found during the first run, and so on. This approach will hopefully zoom in on a good set of hyperparameters. However, itβs very time consuming, and probably not the best use of your time."
},
{
"code": null,
"e": 5474,
"s": 5156,
"text": "Fortunately, there are many techniques to explore a search space much more efficiently than randomly. Their core idea is simple: when a region of the space turns out to be good, it should be explored more. Such techniques take care of the βzoomingβ process for you and lead to much better solutions in much less time."
},
{
"code": null,
"e": 5791,
"s": 5474,
"text": "One such technique is called Bayesian Optimization and we will use Scikit-Optimize (Skopt) https://scikit-optimize.github.io/ to perform Bayesian Optimization. Skopt is a general-purpose optimization library that performs Bayesian Optimization with its class BayesSearchCV using an interface similar to GridSearchCV."
},
{
"code": null,
"e": 5906,
"s": 5791,
"text": "If you donβt have Skopt already installed go ahead and run the following line of code in your virtual environment:"
},
{
"code": null,
"e": 5936,
"s": 5906,
"text": "! pip install scikit-optimize"
},
{
"code": null,
"e": 6341,
"s": 5936,
"text": "There are 2 main differences when performing Bayesian Optimization using Skoptβs BayesSearchCV. First, when creating your search space you need to make each hyperparameterβs space a probability distribution as opposed to using lists likeGridSearchCV. Skopt makes this easy for you with their library skopt.space which lets us import Real, Integer, and Categorical to create the probability distributions."
},
{
"code": null,
"e": 6380,
"s": 6341,
"text": "Real: Continuous hyperparameter space."
},
{
"code": null,
"e": 6420,
"s": 6380,
"text": "Integer: Discrete hyperparameter space."
},
{
"code": null,
"e": 6467,
"s": 6420,
"text": "Categorical: Categorical hyperparameter space."
},
{
"code": null,
"e": 6702,
"s": 6467,
"text": "Below you can see examples of using both the categorical and integer functions. For categorical spaces simply input a list inside the function. For Integer spaces input the minimum and maximum values you want BayesSearchCV to explore."
},
{
"code": null,
"e": 6978,
"s": 6702,
"text": "The function on_step allows us to implement a form of early stopping and also prints out the score after each iteration. Here we specified after each iteration we want to print the best score and if the best score is greater than 98% accuracy training is no longer necessary."
},
{
"code": null,
"e": 7037,
"s": 6978,
"text": "Just like in Scikit-Learn we can view the best parameters:"
},
{
"code": null,
"e": 7070,
"s": 7037,
"text": "forest_bayes_search.best_params_"
},
{
"code": null,
"e": 7094,
"s": 7070,
"text": "And the best estimator:"
},
{
"code": null,
"e": 7130,
"s": 7094,
"text": "forest_bayes_search.best_estimator_"
},
{
"code": null,
"e": 7150,
"s": 7130,
"text": "And the best score:"
},
{
"code": null,
"e": 7182,
"s": 7150,
"text": "forest_bayes_search.best_score_"
},
{
"code": null,
"e": 7599,
"s": 7182,
"text": "Bayesian Optimization allowed us to improve our accuracy by another whole percent in the same amount of iterations as Randomized Search. I hope this convinces you to stray away from your comfort zone using GridSearchCV and RandomizedSearchCV and try implementing something new like BayesSearchCV in your next project. Hyperparameter searching can be tedious, but there are tools that can do the tedious work for you."
},
{
"code": null,
"e": 8049,
"s": 7599,
"text": "The flexibility of neural networks is also one of their main drawbacks: there are many hyperparameters to tweak. Not only can you use any imaginable network architecture, but even in a simple MLP you can change the number of layers, the number of neurons per layer, the type of activation function to use in each layer, the weight initialization logic, and much more. It can be hard to know what combination of hyperparameters is best for your task."
},
{
"code": null,
"e": 8510,
"s": 8049,
"text": "One option is to simply try many combinations of hyperparameters and see which one works best on the validation set (or use K-fold cross-validation). For example, we can use GridSearchCV or RandomizedSearchCV to explore the hyperparameter space. To do this, we need to wrap our Keras models in objects that mimic regular Scikit-Learn classifiers. The first step is to create a function that will build and compile a Keras model, given a set of hyperparameters:"
},
{
"code": null,
"e": 8754,
"s": 8510,
"text": "This function creates a simple Sequential model for multi-class classification with the given input shape and the given number of hidden layers and neurons, and it compiles it using an SGD optimizer configured with the specified learning rate."
},
{
"code": null,
"e": 8829,
"s": 8754,
"text": "Next, letβs create a KerasClassifier based on this build_model() function:"
},
{
"code": null,
"e": 8898,
"s": 8829,
"text": "keras_clf = keras.wrappers.scikit_learn.KerasClassifier(build_model)"
},
{
"code": null,
"e": 9213,
"s": 8898,
"text": "The KerasClassifier object is a thin wrapper around the Keras model built using build_model(). This will allow us to use this object like a regular Scikit-Learn classifier: we can train it using its fit() method, then evaluate it using its score() method, and use it to make predictions using its predict() method."
},
{
"code": null,
"e": 9576,
"s": 9213,
"text": "We donβt want to train and evaluate a single model like this though, we want to train hundreds of variants and see which one performs best on the validation set. Since there are many hyperparameters, it is preferable to use randomized search rather than grid search. Letβs try to explore the number of hidden layers, the number of neurons, and the learning rate:"
},
{
"code": null,
"e": 9664,
"s": 9576,
"text": "Now we can access the best parameters, estimator and score like we did in Scikit-Learn:"
},
{
"code": null,
"e": 9695,
"s": 9664,
"text": "keras_rand_search.best_params_"
},
{
"code": null,
"e": 9725,
"s": 9695,
"text": "keras_rand_search.best_score_"
},
{
"code": null,
"e": 9842,
"s": 9725,
"text": "Our accuracy increased by another .5%! The last step is to see how each model performed on the test set (see below)."
},
{
"code": null,
"e": 10080,
"s": 9842,
"text": "Hyperparameter tuning is still an active area of research, and different algorithms are being produced today. But having basic algorithms in your back pocket can alleviate a lot of the tedious work searching for the best hyperparameters."
},
{
"code": null,
"e": 10381,
"s": 10080,
"text": "Remember, randomized search is almost always preferable then grid search unless you have very few hyperparameters to explore. If you have a more complex problem using a larger dataset you might want to turn to a technique that explores a search space much more efficiently like Bayesian Optimization."
},
{
"code": null,
"e": 10457,
"s": 10381,
"text": "As always, any feedback and constructive criticism are greatly appreciated."
},
{
"code": null,
"e": 10617,
"s": 10457,
"text": "Feel free to check out the Github repository if you would like to see the presentation slides or jupyter notebook complete with the code and descriptions here."
},
{
"code": null,
"e": 10643,
"s": 10617,
"text": "scikit-optimize.github.io"
}
] |
8085 program to add three 16 bit numbers stored in registers - GeeksforGeeks
|
22 May, 2018
Problem β Write an assembly language program to add three 16 bit numbers stored in register HL, DE, BC and store the result in DE with minimum number of instructions.
Example β
Assumptions β
Numbers to be added are already stored in register HL, DE, BCNumbers stored in register are such that final result should not be greater than FFFF
Numbers to be added are already stored in register HL, DE, BC
Numbers stored in register are such that final result should not be greater than FFFF
DAD D performs the following task:
H <- H + D
L <- L + E
DAD instruction take one argument and that argument can be register B, D, H or SP XCHG instruction exchanges the content of register D with H and E with L
Algorithm β
Add the content of DE register in HL and store the result in HL by help of DAD instructionMove the content of register B in D and C in ERepeat step 1Use XCHG instruction to swap the content of DE with HL. We will get the result in DE
Add the content of DE register in HL and store the result in HL by help of DAD instruction
Move the content of register B in D and C in E
Repeat step 1
Use XCHG instruction to swap the content of DE with HL. We will get the result in DE
Program β
Explanation β
DAD D β adds the content of register D in H and register E in L and store the result in HLMOV D, B β moves the value of register B in register DMOV E, C moves the value of register C in register ESame as step 1XCHG β exchange the content of register H with register D and L with E.HLT β stops executing the program and halts any further execution
DAD D β adds the content of register D in H and register E in L and store the result in HL
MOV D, B β moves the value of register B in register D
MOV E, C moves the value of register C in register E
Same as step 1
XCHG β exchange the content of register H with register D and L with E.
HLT β stops executing the program and halts any further execution
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
Addressing modes in 8085 microprocessor
Logical and Physical Address in Operating System
Architecture of 8085 microprocessor
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Architecture of 8086
I/O Interface (Interrupt and DMA Mode)
Computer Organization | RISC and CISC
Computer Organization | Booth's Algorithm
Flag register in 8085 microprocessor
|
[
{
"code": null,
"e": 25092,
"s": 25064,
"text": "\n22 May, 2018"
},
{
"code": null,
"e": 25259,
"s": 25092,
"text": "Problem β Write an assembly language program to add three 16 bit numbers stored in register HL, DE, BC and store the result in DE with minimum number of instructions."
},
{
"code": null,
"e": 25269,
"s": 25259,
"text": "Example β"
},
{
"code": null,
"e": 25283,
"s": 25269,
"text": "Assumptions β"
},
{
"code": null,
"e": 25430,
"s": 25283,
"text": "Numbers to be added are already stored in register HL, DE, BCNumbers stored in register are such that final result should not be greater than FFFF"
},
{
"code": null,
"e": 25492,
"s": 25430,
"text": "Numbers to be added are already stored in register HL, DE, BC"
},
{
"code": null,
"e": 25578,
"s": 25492,
"text": "Numbers stored in register are such that final result should not be greater than FFFF"
},
{
"code": null,
"e": 25613,
"s": 25578,
"text": "DAD D performs the following task:"
},
{
"code": null,
"e": 25641,
"s": 25613,
"text": " H <- H + D \n L <- L + E "
},
{
"code": null,
"e": 25796,
"s": 25641,
"text": "DAD instruction take one argument and that argument can be register B, D, H or SP XCHG instruction exchanges the content of register D with H and E with L"
},
{
"code": null,
"e": 25808,
"s": 25796,
"text": "Algorithm β"
},
{
"code": null,
"e": 26042,
"s": 25808,
"text": "Add the content of DE register in HL and store the result in HL by help of DAD instructionMove the content of register B in D and C in ERepeat step 1Use XCHG instruction to swap the content of DE with HL. We will get the result in DE"
},
{
"code": null,
"e": 26133,
"s": 26042,
"text": "Add the content of DE register in HL and store the result in HL by help of DAD instruction"
},
{
"code": null,
"e": 26180,
"s": 26133,
"text": "Move the content of register B in D and C in E"
},
{
"code": null,
"e": 26194,
"s": 26180,
"text": "Repeat step 1"
},
{
"code": null,
"e": 26279,
"s": 26194,
"text": "Use XCHG instruction to swap the content of DE with HL. We will get the result in DE"
},
{
"code": null,
"e": 26289,
"s": 26279,
"text": "Program β"
},
{
"code": null,
"e": 26303,
"s": 26289,
"text": "Explanation β"
},
{
"code": null,
"e": 26650,
"s": 26303,
"text": "DAD D β adds the content of register D in H and register E in L and store the result in HLMOV D, B β moves the value of register B in register DMOV E, C moves the value of register C in register ESame as step 1XCHG β exchange the content of register H with register D and L with E.HLT β stops executing the program and halts any further execution"
},
{
"code": null,
"e": 26741,
"s": 26650,
"text": "DAD D β adds the content of register D in H and register E in L and store the result in HL"
},
{
"code": null,
"e": 26796,
"s": 26741,
"text": "MOV D, B β moves the value of register B in register D"
},
{
"code": null,
"e": 26849,
"s": 26796,
"text": "MOV E, C moves the value of register C in register E"
},
{
"code": null,
"e": 26864,
"s": 26849,
"text": "Same as step 1"
},
{
"code": null,
"e": 26936,
"s": 26864,
"text": "XCHG β exchange the content of register H with register D and L with E."
},
{
"code": null,
"e": 27002,
"s": 26936,
"text": "HLT β stops executing the program and halts any further execution"
},
{
"code": null,
"e": 27017,
"s": 27002,
"text": "microprocessor"
},
{
"code": null,
"e": 27036,
"s": 27017,
"text": "system-programming"
},
{
"code": null,
"e": 27073,
"s": 27036,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 27088,
"s": 27073,
"text": "microprocessor"
},
{
"code": null,
"e": 27186,
"s": 27088,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27195,
"s": 27186,
"text": "Comments"
},
{
"code": null,
"e": 27208,
"s": 27195,
"text": "Old Comments"
},
{
"code": null,
"e": 27248,
"s": 27208,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 27297,
"s": 27248,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 27333,
"s": 27297,
"text": "Architecture of 8085 microprocessor"
},
{
"code": null,
"e": 27428,
"s": 27333,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 27476,
"s": 27428,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 27497,
"s": 27476,
"text": "Architecture of 8086"
},
{
"code": null,
"e": 27536,
"s": 27497,
"text": "I/O Interface (Interrupt and DMA Mode)"
},
{
"code": null,
"e": 27574,
"s": 27536,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 27616,
"s": 27574,
"text": "Computer Organization | Booth's Algorithm"
}
] |
High-Availability MySQL cluster with load balancing using HAProxy and Heartbeat. | by Alexey Nizhegolenko | Towards Data Science
|
Hello, in this article I wanna share some experience of building a high available MySQL database cluster, from two master MySQL nodes, with load balancing and failover capability based on HAProxy & Heartbeat.
On most of modern projects, the database availability is a matter of life and death. Good solution will be creation a distributed database cluster, from more then one MySQL server, that can take care of load balancing, failover capabilities and data replication. Also, you can split an incoming requests and take care about high load.
In this example I will show creating a MySQL cluster from two master nodes, main idea is to create a pair of servers with same configurations and one virtual IP for taking requests. This cluster will continue working even after totally losing one of the nodes.
Weβll use a two servers (virtual or bare metal) with pair of MySQL masters and a pair of HAProxy installed on them, the main virtual IP will be configured with Heartbeat. Please mind that in this example only one HAProxy be using in one time period, the second HAProxy will be standing in hot reserve. MySQL servers will be recycle with round robin type of load balancing.
The schema with two servers was chosen for making an example simpler. Of course if you have an additional servers, you can create a more complicated configurations, putting HAProxy with Heartbeat in external LB cluster and so on. But anyway, this example will be a quite enough for building a strong looking DB cluster inside your project.
First weβll need to choose few subnets for the MySQL replications and for the HAProxy with Heartbeat, better separate them and if your server have a few network interface put these subnets on different interfaces as well.
192.168.0.0/24 - network for DB traffic
192.168.0.1 IP for MySQL1, 192.168.0.2 IP for MySQL2.
10.10.10.0/24 - network for the Heartbeat & HAProxy.
10.10.10.1 Virtual IP for taking requests, 10.10.10.2 main IP for sever1, 10.10.10.3 main IP for server2.
The /29 subnets will be quite enough in fact :)
First we need to install MySQL on both of ours servers:
# apt-get update && apt-get upgrade -y# apt-get install mysql-server mysql-client
Then edit the /etc/mysql/my.cnf on first and second node, to enable replication between MySQL servers and make them use IPS from 192.168.0.0/24 subnet:
Server1 configuration.
[mysqld]bind-address = 192.168.0.1server_id = 1log_bin = /var/log/mysql/mysql-bin.loglog_bin_index = /var/log/mysql/mysql-bin.log.indexrelay_log = /var/log/mysql/mysql-relay-binrelay_log_index = /var/log/mysql/mysql-relay-bin.indexexpire_logs_days = 10max_binlog_size = 100Mlog_slave_updates = 1auto-increment-increment = 2auto-increment-offset = 1
Server2 configuration.
[mysqld]bind-address = 192.168.0.2server_id = 2log_bin = /var/log/mysql/mysql-bin.loglog_bin_index = /var/log/mysql/mysql-bin.log.indexrelay_log = /var/log/mysql/mysql-relay-binrelay_log_index = /var/log/mysql/mysql-relay-bin.indexexpire_logs_days = 10max_binlog_size = 100Mlog_slave_updates = 1auto-increment-increment = 2auto-increment-offset = 2
Then restart them both and make sure MySQL leaf on specified IP:
server1# systemctl restart mysqlserver1# netstat -ntlpActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.1:3306 0.0.0.0:* LISTEN 9057/mysqldserver2# systemctl restart mysqlserver2# netstat -ntlpActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.2:3306 0.0.0.0:* LISTEN 8740/mysqld
Now will create a user for replication between databases, you can use pwgen utility to generate strong enough password. Connect to each MySQL servers and create this user with IP from opposite server:
server1# mysql -u root -pMariaDB> GRANT REPLICATION SLAVE ON *.* TO 'replicauser'@'192.168.0.2' IDENTIFIED BY 'somestrongpassword';server2# mysql -u root -pMariaDB> GRANT REPLICATION SLAVE ON *.* TO 'replicauser'@'192.168.0.1' IDENTIFIED BY 'somestrongpassword';
Check that replicauser have access for each MySQL server.
server1# mysql -u replicauser -p -h 192.168.0.2Enter password: somestrongpasswordWelcome to the MariaDB monitor. Commands end with ; or \g.bla bla....server2# mysql -u replicauser -p -h 192.168.0.1Enter password: somestrongpasswordWelcome to the MariaDB monitor. Commands end with ; or \g.bla bla....
Fine, now we can continue with configuring replication between MySQL servers. From that time better to have opened two consoles from both of MySQL servers, as we need to input commands, based on output from another server.
Get the MySQL master status on server1:
server1# mysql -u root -pMariaDB> SHOW MASTER STATUS;+------------------+----------+--------------+------------------+| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |+------------------+----------+--------------+------------------+| mysql-bin.000002 | 531 | | |+------------------+----------+--------------+------------------+1 row in set (0.00 sec)
Weβll need the File and Position information, from this output. Open the MySQL console on server2 and configure the slave relation with first server.
server2# mysql -u root -pMariaDB> STOP SLAVE;MariaDB> CHANGE MASTER TO master_host='192.168.0.1', master_port=3306, master_user='replicauser', master_password='somestrongpassword', master_log_file='mysql-bin.000002', master_log_pos=531;MariaDB> START SLAVE;
Now query the master status from server2 and configure slave relation for MySQL on first server.
server2# mysql -u root -pMariaDB> SHOW MASTER STATUS;+------------------+----------+--------------+------------------+| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |+------------------+----------+--------------+------------------+| mysql-bin.000002 | 531 | | |+------------------+----------+--------------+------------------+1 row in set (0.00 sec)server1# mysql -u root -pMariaDB> STOP SLAVE;MariaDB> CHANGE MASTER TO master_host='192.168.0.2', master_port=3306, master_user='replicauser', master_password='somestrongpassword', master_log_file='mysql-bin.000002', master_log_pos=531;MariaDB> START SLAVE;
OK, if all was done right, we must have a working replication between MySQL masters. You can create some test DB and check this.
server1# mysql -u root -pMariaDB> CREATE DATABASE TESTDB;MariaDB> CREATE TABLE TESTDB.REPLICA (`id` varchar(40));
Then check this database was appeared on second server as well:
server2# mysql -u root -pMariaDB> SHOW TABLES IN TESTDB;+------------------+| Tables_in_TESTDB |+------------------+| REPLICA |+------------------+1 row in set (0.00 sec)
And as you can see, the TESTDB base was successfully replicated to server2. We just completed a first stage of creating our failover cluster.
In second stage weβll install and configure two absolutely identical HAProxy on both of our servers, for balancing a incoming requests between MySQL servers.
First we need to add additional user on our MySQL servers (user must be created without any password), this user will be used by HAProxy for checking a health status of MySQL servers.
server1# mysql -u root -pMariaDB> CREATE USER 'haproxy_check'@'%';MariaDB> FLUSH PRIVILEGES;
You can create this user on any of our MySQL servers, as we have a replication configured between them. Check that user was added, using this command:
server1# mysql -u root -p -e "SELECT User, Host FROM mysql.user"Enter password: +---------------+-------------+| User | Host |+---------------+-------------+| haproxy_check | % || replicauser | 192.168.0.2 || root | localhost |+---------------+-------------+server2# mysql -u root -p -e "SELECT User, Host FROM mysql.user"Enter password: +---------------+-------------+| User | Host |+---------------+-------------+| haproxy_check | % || replicauser | 192.168.0.1 || root | localhost |+---------------+-------------+
Also letβs create a user with root privileges, for making some test requests later:
server1# mysql -u root -pMariaDB> CREATE USER 'haproxy_root'@'%' IDENTIFIED BY 'password';MariaDB> GRANT ALL PRIVILEGES ON *.* TO 'haproxy_root'@'%';
Now itβs time for HAProxy installation:
server1# apt-get install haproxyserver2# apt-get install haproxy
Save original config and create new one:
server1# mv /etc/haproxy/haproxy.cfg{,.back}server1# vi /etc/haproxy/haproxy.cfg
Next add this configuration on both servers:
global user haproxy group haproxydefaults mode http log global retries 2 timeout connect 3000ms timeout server 5000ms timeout client 5000mslisten stats bind 10.10.10.1:9999 stats enable stats hide-version stats uri /stats stats auth statadmin:statadminpasslisten mysql-cluster bind 10.10.10.1:3306 mode tcp option mysql-check user haproxy_check balance roundrobin server mysql-1 192.168.0.1:3306 check server mysql-2 192.168.0.2:3306 check
As you can see, both HAProxy services will use 10.10.10.1, shared IP address. This virtual IP will move on between servers, so we need to make some trick and enable net.ipv4.ip_nonlocal_bind sysctl option, to allow system services binding on the non-local IP.
Add to the file /etc/sysctl.conf this option:
server1# vi /etc/sysctl.confnet.ipv4.ip_nonlocal_bind=1server2# vi /etc/sysctl.confnet.ipv4.ip_nonlocal_bind=1
Then run
sysctl -p
After this, we can start HAProxy on both servers:
server1# systemctl start haproxyserver2# systemctl start haproxy
Check they started on shared IP 10.10.10.1:
server1# netstat -ntlp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.1:3306 0.0.0.0:* LISTEN 918/mysqld tcp 0 0 10.10.10.1:3306 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.1:9999 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.2:22 0.0.0.0:* LISTEN 785/sshdserver2# netstat -ntlpActive Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.2:3306 0.0.0.0:* LISTEN 918/mysqld tcp 0 0 10.10.10.1:3306 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.1:9999 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.3:22 0.0.0.0:* LISTEN 785/sshd
Everything lookβs OK, both servers was started using virtual IP, also we configured a stats page on 9999 port, so you can check the HAProxy status on http://10.10.10.1:9999/stats using statadmin:statadminpass.
On last stage we need to configure the Heartbeat service on both of the servers, and create shared IP, that will be used for serving incoming requests. This IP will migrate between servers if something wrong happens to one of them.
Install Heartbeat on both servers:
server1# apt-get install heartbeatserver1# systemctl enable heartbeatserver2# apt-get install heartbeatserver2# systemctl enable heartbeat
Now we need to create a few configuration files for it, they will be mostly the same for the server1 and server2.
Create a /etc/ha.d/authkeys, in this file Heartbeat stored data to authenticate each other. File will be the same on both servers:
server1# vi /etc/ha.d/authkeysauth 11 md5 securepassserver2# vi /etc/ha.d/authkeysauth 11 md5 securepass
Change the securepass to your strong secure password. Also, this file need to be owned by root only, so:
server1# chmod 600 /etc/ha.d/authkeysserver2# chmod 600 /etc/ha.d/authkeys
Next will create a main configuration for Heartbeat on both servers, itβll be a bit different for server1 and server2, create /etc/ha.d/ha.cf:
server1
server1# vi /etc/ha.d/ha.cf# keepalive: how many seconds between heartbeats#keepalive 2## deadtime: seconds-to-declare-host-dead#deadtime 10## What UDP port to use for udp or ppp-udp communication?#udpport 694bcast ens18mcast ens18 225.0.0.1 694 1 0ucast ens18 10.10.10.3# What interfaces to heartbeat over?udp ens18## Facility to use for syslog()/logger (alternative to log/debugfile)#logfacility local0## Tell what machines are in the cluster# node nodename ... -- must match uname -nnode server1node server2
server2
server1# vi /etc/ha.d/ha.cf# keepalive: how many seconds between heartbeats#keepalive 2## deadtime: seconds-to-declare-host-dead#deadtime 10## What UDP port to use for udp or ppp-udp communication?#udpport 694bcast ens18mcast ens18 225.0.0.1 694 1 0ucast ens18 10.10.10.2# What interfaces to heartbeat over?udp ens18## Facility to use for syslog()/logger (alternative to log/debugfile)#logfacility local0## Tell what machines are in the cluster# node nodename ... -- must match uname -nnode server1node server2
The node names for this config you can get by running uname -n on your servers.
And last we need to create the /etc/ha.d/haresources file on server1 and server2. File be the same and in this file weβll declare our shared IP address and master node by default:
server1# vi /etc/ha.d/haresourcesserver1 10.10.10.1server2# vi /etc/ha.d/haresourcesserver1 10.10.10.1
After all letβs start our Heartbeat services on both servers, and you must see that on server1 we have the virtual IP up:
server1# ip a ....2: ens19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 192.168.0.1/24 brd 192.168.0.255 scope global ens19 valid_lft forever preferred_lft forever inet6 fe80::bla:bla:bla:bla/64 scope link valid_lft forever preferred_lft forever3: ens18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 10.10.10.2/24 brd 10.10.10.255 scope global ens18 valid_lft forever preferred_lft forever inet 10.10.10.1/24 brd 10.10.10.255 scope global secondary ....
OK, now we have virtual IP assigned on our server1 and HAProxy listening on it, so we can check how it works, making test requests. From some external server run this commands:
# mysql -h 10.10.10.1 -u haproxy_root -p -e "show variables like 'server_id'"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 1 |+---------------+-------+# mysql -h 10.10.10.1 -u haproxy_root -p -e "show variables like 'server_id'"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 2 |+---------------+-------+
All working fine, you can see the βround robinβ balancing between our MySQL servers. Now we need to check the failover when the server1 will go offline for example. Go and restart or shutdown the server1, and check that virtual IP was moved to server2 and requests to the MySQL servers still OK, but now there is only MySQL on server2 will respond:
server2# ip a ....2: ens19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 192.168.0.2/24 brd 192.168.0.255 scope global ens19 valid_lft forever preferred_lft forever inet6 fe80::bla:bla:bla:bla/64 scope link valid_lft forever preferred_lft forever3: ens18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 10.10.10.3/24 brd 10.10.10.255 scope global ens18 valid_lft forever preferred_lft forever inet 10.10.10.1/24 brd 10.10.10.255 scope global secondary ....
Check MySQL requests again:
# mysql -h 10.10.10.1 -u haproxy_root -p -e "show variables like 'server_id'"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 2 |+---------------+-------+# mysql -h 10.10.10.1 -u haproxy_root -p -e "show variables like 'server_id'"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 2 |+---------------+-------+
After the server1 will return online, the virtual IP will be moved back to it.
And we did, we just configured and tested our MySQL cluster, and it now readies to serve requests.
|
[
{
"code": null,
"e": 380,
"s": 171,
"text": "Hello, in this article I wanna share some experience of building a high available MySQL database cluster, from two master MySQL nodes, with load balancing and failover capability based on HAProxy & Heartbeat."
},
{
"code": null,
"e": 715,
"s": 380,
"text": "On most of modern projects, the database availability is a matter of life and death. Good solution will be creation a distributed database cluster, from more then one MySQL server, that can take care of load balancing, failover capabilities and data replication. Also, you can split an incoming requests and take care about high load."
},
{
"code": null,
"e": 976,
"s": 715,
"text": "In this example I will show creating a MySQL cluster from two master nodes, main idea is to create a pair of servers with same configurations and one virtual IP for taking requests. This cluster will continue working even after totally losing one of the nodes."
},
{
"code": null,
"e": 1349,
"s": 976,
"text": "Weβll use a two servers (virtual or bare metal) with pair of MySQL masters and a pair of HAProxy installed on them, the main virtual IP will be configured with Heartbeat. Please mind that in this example only one HAProxy be using in one time period, the second HAProxy will be standing in hot reserve. MySQL servers will be recycle with round robin type of load balancing."
},
{
"code": null,
"e": 1689,
"s": 1349,
"text": "The schema with two servers was chosen for making an example simpler. Of course if you have an additional servers, you can create a more complicated configurations, putting HAProxy with Heartbeat in external LB cluster and so on. But anyway, this example will be a quite enough for building a strong looking DB cluster inside your project."
},
{
"code": null,
"e": 1911,
"s": 1689,
"text": "First weβll need to choose few subnets for the MySQL replications and for the HAProxy with Heartbeat, better separate them and if your server have a few network interface put these subnets on different interfaces as well."
},
{
"code": null,
"e": 1951,
"s": 1911,
"text": "192.168.0.0/24 - network for DB traffic"
},
{
"code": null,
"e": 2005,
"s": 1951,
"text": "192.168.0.1 IP for MySQL1, 192.168.0.2 IP for MySQL2."
},
{
"code": null,
"e": 2058,
"s": 2005,
"text": "10.10.10.0/24 - network for the Heartbeat & HAProxy."
},
{
"code": null,
"e": 2164,
"s": 2058,
"text": "10.10.10.1 Virtual IP for taking requests, 10.10.10.2 main IP for sever1, 10.10.10.3 main IP for server2."
},
{
"code": null,
"e": 2212,
"s": 2164,
"text": "The /29 subnets will be quite enough in fact :)"
},
{
"code": null,
"e": 2268,
"s": 2212,
"text": "First we need to install MySQL on both of ours servers:"
},
{
"code": null,
"e": 2350,
"s": 2268,
"text": "# apt-get update && apt-get upgrade -y# apt-get install mysql-server mysql-client"
},
{
"code": null,
"e": 2502,
"s": 2350,
"text": "Then edit the /etc/mysql/my.cnf on first and second node, to enable replication between MySQL servers and make them use IPS from 192.168.0.0/24 subnet:"
},
{
"code": null,
"e": 2525,
"s": 2502,
"text": "Server1 configuration."
},
{
"code": null,
"e": 2928,
"s": 2525,
"text": "[mysqld]bind-address = 192.168.0.1server_id = 1log_bin = /var/log/mysql/mysql-bin.loglog_bin_index = /var/log/mysql/mysql-bin.log.indexrelay_log = /var/log/mysql/mysql-relay-binrelay_log_index = /var/log/mysql/mysql-relay-bin.indexexpire_logs_days = 10max_binlog_size = 100Mlog_slave_updates = 1auto-increment-increment = 2auto-increment-offset = 1"
},
{
"code": null,
"e": 2951,
"s": 2928,
"text": "Server2 configuration."
},
{
"code": null,
"e": 3354,
"s": 2951,
"text": "[mysqld]bind-address = 192.168.0.2server_id = 2log_bin = /var/log/mysql/mysql-bin.loglog_bin_index = /var/log/mysql/mysql-bin.log.indexrelay_log = /var/log/mysql/mysql-relay-binrelay_log_index = /var/log/mysql/mysql-relay-bin.indexexpire_logs_days = 10max_binlog_size = 100Mlog_slave_updates = 1auto-increment-increment = 2auto-increment-offset = 2"
},
{
"code": null,
"e": 3419,
"s": 3354,
"text": "Then restart them both and make sure MySQL leaf on specified IP:"
},
{
"code": null,
"e": 3994,
"s": 3419,
"text": "server1# systemctl restart mysqlserver1# netstat -ntlpActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.1:3306 0.0.0.0:* LISTEN 9057/mysqldserver2# systemctl restart mysqlserver2# netstat -ntlpActive Internet connections (only servers)Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.2:3306 0.0.0.0:* LISTEN 8740/mysqld"
},
{
"code": null,
"e": 4195,
"s": 3994,
"text": "Now will create a user for replication between databases, you can use pwgen utility to generate strong enough password. Connect to each MySQL servers and create this user with IP from opposite server:"
},
{
"code": null,
"e": 4458,
"s": 4195,
"text": "server1# mysql -u root -pMariaDB> GRANT REPLICATION SLAVE ON *.* TO 'replicauser'@'192.168.0.2' IDENTIFIED BY 'somestrongpassword';server2# mysql -u root -pMariaDB> GRANT REPLICATION SLAVE ON *.* TO 'replicauser'@'192.168.0.1' IDENTIFIED BY 'somestrongpassword';"
},
{
"code": null,
"e": 4516,
"s": 4458,
"text": "Check that replicauser have access for each MySQL server."
},
{
"code": null,
"e": 4819,
"s": 4516,
"text": "server1# mysql -u replicauser -p -h 192.168.0.2Enter password: somestrongpasswordWelcome to the MariaDB monitor. Commands end with ; or \\g.bla bla....server2# mysql -u replicauser -p -h 192.168.0.1Enter password: somestrongpasswordWelcome to the MariaDB monitor. Commands end with ; or \\g.bla bla...."
},
{
"code": null,
"e": 5042,
"s": 4819,
"text": "Fine, now we can continue with configuring replication between MySQL servers. From that time better to have opened two consoles from both of MySQL servers, as we need to input commands, based on output from another server."
},
{
"code": null,
"e": 5082,
"s": 5042,
"text": "Get the MySQL master status on server1:"
},
{
"code": null,
"e": 5484,
"s": 5082,
"text": "server1# mysql -u root -pMariaDB> SHOW MASTER STATUS;+------------------+----------+--------------+------------------+| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |+------------------+----------+--------------+------------------+| mysql-bin.000002 | 531 | | |+------------------+----------+--------------+------------------+1 row in set (0.00 sec)"
},
{
"code": null,
"e": 5634,
"s": 5484,
"text": "Weβll need the File and Position information, from this output. Open the MySQL console on server2 and configure the slave relation with first server."
},
{
"code": null,
"e": 5892,
"s": 5634,
"text": "server2# mysql -u root -pMariaDB> STOP SLAVE;MariaDB> CHANGE MASTER TO master_host='192.168.0.1', master_port=3306, master_user='replicauser', master_password='somestrongpassword', master_log_file='mysql-bin.000002', master_log_pos=531;MariaDB> START SLAVE;"
},
{
"code": null,
"e": 5989,
"s": 5892,
"text": "Now query the master status from server2 and configure slave relation for MySQL on first server."
},
{
"code": null,
"e": 6648,
"s": 5989,
"text": "server2# mysql -u root -pMariaDB> SHOW MASTER STATUS;+------------------+----------+--------------+------------------+| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |+------------------+----------+--------------+------------------+| mysql-bin.000002 | 531 | | |+------------------+----------+--------------+------------------+1 row in set (0.00 sec)server1# mysql -u root -pMariaDB> STOP SLAVE;MariaDB> CHANGE MASTER TO master_host='192.168.0.2', master_port=3306, master_user='replicauser', master_password='somestrongpassword', master_log_file='mysql-bin.000002', master_log_pos=531;MariaDB> START SLAVE;"
},
{
"code": null,
"e": 6777,
"s": 6648,
"text": "OK, if all was done right, we must have a working replication between MySQL masters. You can create some test DB and check this."
},
{
"code": null,
"e": 6891,
"s": 6777,
"text": "server1# mysql -u root -pMariaDB> CREATE DATABASE TESTDB;MariaDB> CREATE TABLE TESTDB.REPLICA (`id` varchar(40));"
},
{
"code": null,
"e": 6955,
"s": 6891,
"text": "Then check this database was appeared on second server as well:"
},
{
"code": null,
"e": 7135,
"s": 6955,
"text": "server2# mysql -u root -pMariaDB> SHOW TABLES IN TESTDB;+------------------+| Tables_in_TESTDB |+------------------+| REPLICA |+------------------+1 row in set (0.00 sec)"
},
{
"code": null,
"e": 7277,
"s": 7135,
"text": "And as you can see, the TESTDB base was successfully replicated to server2. We just completed a first stage of creating our failover cluster."
},
{
"code": null,
"e": 7435,
"s": 7277,
"text": "In second stage weβll install and configure two absolutely identical HAProxy on both of our servers, for balancing a incoming requests between MySQL servers."
},
{
"code": null,
"e": 7619,
"s": 7435,
"text": "First we need to add additional user on our MySQL servers (user must be created without any password), this user will be used by HAProxy for checking a health status of MySQL servers."
},
{
"code": null,
"e": 7712,
"s": 7619,
"text": "server1# mysql -u root -pMariaDB> CREATE USER 'haproxy_check'@'%';MariaDB> FLUSH PRIVILEGES;"
},
{
"code": null,
"e": 7863,
"s": 7712,
"text": "You can create this user on any of our MySQL servers, as we have a replication configured between them. Check that user was added, using this command:"
},
{
"code": null,
"e": 8458,
"s": 7863,
"text": "server1# mysql -u root -p -e \"SELECT User, Host FROM mysql.user\"Enter password: +---------------+-------------+| User | Host |+---------------+-------------+| haproxy_check | % || replicauser | 192.168.0.2 || root | localhost |+---------------+-------------+server2# mysql -u root -p -e \"SELECT User, Host FROM mysql.user\"Enter password: +---------------+-------------+| User | Host |+---------------+-------------+| haproxy_check | % || replicauser | 192.168.0.1 || root | localhost |+---------------+-------------+"
},
{
"code": null,
"e": 8542,
"s": 8458,
"text": "Also letβs create a user with root privileges, for making some test requests later:"
},
{
"code": null,
"e": 8692,
"s": 8542,
"text": "server1# mysql -u root -pMariaDB> CREATE USER 'haproxy_root'@'%' IDENTIFIED BY 'password';MariaDB> GRANT ALL PRIVILEGES ON *.* TO 'haproxy_root'@'%';"
},
{
"code": null,
"e": 8732,
"s": 8692,
"text": "Now itβs time for HAProxy installation:"
},
{
"code": null,
"e": 8797,
"s": 8732,
"text": "server1# apt-get install haproxyserver2# apt-get install haproxy"
},
{
"code": null,
"e": 8838,
"s": 8797,
"text": "Save original config and create new one:"
},
{
"code": null,
"e": 8919,
"s": 8838,
"text": "server1# mv /etc/haproxy/haproxy.cfg{,.back}server1# vi /etc/haproxy/haproxy.cfg"
},
{
"code": null,
"e": 8964,
"s": 8919,
"text": "Next add this configuration on both servers:"
},
{
"code": null,
"e": 9461,
"s": 8964,
"text": "global user haproxy group haproxydefaults mode http log global retries 2 timeout connect 3000ms timeout server 5000ms timeout client 5000mslisten stats bind 10.10.10.1:9999 stats enable stats hide-version stats uri /stats stats auth statadmin:statadminpasslisten mysql-cluster bind 10.10.10.1:3306 mode tcp option mysql-check user haproxy_check balance roundrobin server mysql-1 192.168.0.1:3306 check server mysql-2 192.168.0.2:3306 check"
},
{
"code": null,
"e": 9721,
"s": 9461,
"text": "As you can see, both HAProxy services will use 10.10.10.1, shared IP address. This virtual IP will move on between servers, so we need to make some trick and enable net.ipv4.ip_nonlocal_bind sysctl option, to allow system services binding on the non-local IP."
},
{
"code": null,
"e": 9767,
"s": 9721,
"text": "Add to the file /etc/sysctl.conf this option:"
},
{
"code": null,
"e": 9878,
"s": 9767,
"text": "server1# vi /etc/sysctl.confnet.ipv4.ip_nonlocal_bind=1server2# vi /etc/sysctl.confnet.ipv4.ip_nonlocal_bind=1"
},
{
"code": null,
"e": 9887,
"s": 9878,
"text": "Then run"
},
{
"code": null,
"e": 9897,
"s": 9887,
"text": "sysctl -p"
},
{
"code": null,
"e": 9947,
"s": 9897,
"text": "After this, we can start HAProxy on both servers:"
},
{
"code": null,
"e": 10012,
"s": 9947,
"text": "server1# systemctl start haproxyserver2# systemctl start haproxy"
},
{
"code": null,
"e": 10056,
"s": 10012,
"text": "Check they started on shared IP 10.10.10.1:"
},
{
"code": null,
"e": 10746,
"s": 10056,
"text": "server1# netstat -ntlp Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.1:3306 0.0.0.0:* LISTEN 918/mysqld tcp 0 0 10.10.10.1:3306 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.1:9999 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.2:22 0.0.0.0:* LISTEN 785/sshdserver2# netstat -ntlpActive Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 192.168.0.2:3306 0.0.0.0:* LISTEN 918/mysqld tcp 0 0 10.10.10.1:3306 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.1:9999 0.0.0.0:* LISTEN 802/haproxy tcp 0 0 10.10.10.3:22 0.0.0.0:* LISTEN 785/sshd"
},
{
"code": null,
"e": 10956,
"s": 10746,
"text": "Everything lookβs OK, both servers was started using virtual IP, also we configured a stats page on 9999 port, so you can check the HAProxy status on http://10.10.10.1:9999/stats using statadmin:statadminpass."
},
{
"code": null,
"e": 11188,
"s": 10956,
"text": "On last stage we need to configure the Heartbeat service on both of the servers, and create shared IP, that will be used for serving incoming requests. This IP will migrate between servers if something wrong happens to one of them."
},
{
"code": null,
"e": 11223,
"s": 11188,
"text": "Install Heartbeat on both servers:"
},
{
"code": null,
"e": 11362,
"s": 11223,
"text": "server1# apt-get install heartbeatserver1# systemctl enable heartbeatserver2# apt-get install heartbeatserver2# systemctl enable heartbeat"
},
{
"code": null,
"e": 11476,
"s": 11362,
"text": "Now we need to create a few configuration files for it, they will be mostly the same for the server1 and server2."
},
{
"code": null,
"e": 11607,
"s": 11476,
"text": "Create a /etc/ha.d/authkeys, in this file Heartbeat stored data to authenticate each other. File will be the same on both servers:"
},
{
"code": null,
"e": 11712,
"s": 11607,
"text": "server1# vi /etc/ha.d/authkeysauth 11 md5 securepassserver2# vi /etc/ha.d/authkeysauth 11 md5 securepass"
},
{
"code": null,
"e": 11817,
"s": 11712,
"text": "Change the securepass to your strong secure password. Also, this file need to be owned by root only, so:"
},
{
"code": null,
"e": 11892,
"s": 11817,
"text": "server1# chmod 600 /etc/ha.d/authkeysserver2# chmod 600 /etc/ha.d/authkeys"
},
{
"code": null,
"e": 12035,
"s": 11892,
"text": "Next will create a main configuration for Heartbeat on both servers, itβll be a bit different for server1 and server2, create /etc/ha.d/ha.cf:"
},
{
"code": null,
"e": 12043,
"s": 12035,
"text": "server1"
},
{
"code": null,
"e": 12624,
"s": 12043,
"text": "server1# vi /etc/ha.d/ha.cf# keepalive: how many seconds between heartbeats#keepalive 2## deadtime: seconds-to-declare-host-dead#deadtime 10## What UDP port to use for udp or ppp-udp communication?#udpport 694bcast ens18mcast ens18 225.0.0.1 694 1 0ucast ens18 10.10.10.3# What interfaces to heartbeat over?udp ens18## Facility to use for syslog()/logger (alternative to log/debugfile)#logfacility local0## Tell what machines are in the cluster# node nodename ... -- must match uname -nnode server1node server2"
},
{
"code": null,
"e": 12632,
"s": 12624,
"text": "server2"
},
{
"code": null,
"e": 13213,
"s": 12632,
"text": "server1# vi /etc/ha.d/ha.cf# keepalive: how many seconds between heartbeats#keepalive 2## deadtime: seconds-to-declare-host-dead#deadtime 10## What UDP port to use for udp or ppp-udp communication?#udpport 694bcast ens18mcast ens18 225.0.0.1 694 1 0ucast ens18 10.10.10.2# What interfaces to heartbeat over?udp ens18## Facility to use for syslog()/logger (alternative to log/debugfile)#logfacility local0## Tell what machines are in the cluster# node nodename ... -- must match uname -nnode server1node server2"
},
{
"code": null,
"e": 13293,
"s": 13213,
"text": "The node names for this config you can get by running uname -n on your servers."
},
{
"code": null,
"e": 13473,
"s": 13293,
"text": "And last we need to create the /etc/ha.d/haresources file on server1 and server2. File be the same and in this file weβll declare our shared IP address and master node by default:"
},
{
"code": null,
"e": 13576,
"s": 13473,
"text": "server1# vi /etc/ha.d/haresourcesserver1 10.10.10.1server2# vi /etc/ha.d/haresourcesserver1 10.10.10.1"
},
{
"code": null,
"e": 13698,
"s": 13576,
"text": "After all letβs start our Heartbeat services on both servers, and you must see that on server1 we have the virtual IP up:"
},
{
"code": null,
"e": 14402,
"s": 13698,
"text": "server1# ip a ....2: ens19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 192.168.0.1/24 brd 192.168.0.255 scope global ens19 valid_lft forever preferred_lft forever inet6 fe80::bla:bla:bla:bla/64 scope link valid_lft forever preferred_lft forever3: ens18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 10.10.10.2/24 brd 10.10.10.255 scope global ens18 valid_lft forever preferred_lft forever inet 10.10.10.1/24 brd 10.10.10.255 scope global secondary ...."
},
{
"code": null,
"e": 14579,
"s": 14402,
"text": "OK, now we have virtual IP assigned on our server1 and HAProxy listening on it, so we can check how it works, making test requests. From some external server run this commands:"
},
{
"code": null,
"e": 15016,
"s": 14579,
"text": "# mysql -h 10.10.10.1 -u haproxy_root -p -e \"show variables like 'server_id'\"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 1 |+---------------+-------+# mysql -h 10.10.10.1 -u haproxy_root -p -e \"show variables like 'server_id'\"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 2 |+---------------+-------+"
},
{
"code": null,
"e": 15365,
"s": 15016,
"text": "All working fine, you can see the βround robinβ balancing between our MySQL servers. Now we need to check the failover when the server1 will go offline for example. Go and restart or shutdown the server1, and check that virtual IP was moved to server2 and requests to the MySQL servers still OK, but now there is only MySQL on server2 will respond:"
},
{
"code": null,
"e": 16069,
"s": 15365,
"text": "server2# ip a ....2: ens19: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 192.168.0.2/24 brd 192.168.0.255 scope global ens19 valid_lft forever preferred_lft forever inet6 fe80::bla:bla:bla:bla/64 scope link valid_lft forever preferred_lft forever3: ens18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether bla:bla:bla:bla:bla:bla brd ff:ff:ff:ff:ff:ff inet 10.10.10.3/24 brd 10.10.10.255 scope global ens18 valid_lft forever preferred_lft forever inet 10.10.10.1/24 brd 10.10.10.255 scope global secondary ...."
},
{
"code": null,
"e": 16097,
"s": 16069,
"text": "Check MySQL requests again:"
},
{
"code": null,
"e": 16534,
"s": 16097,
"text": "# mysql -h 10.10.10.1 -u haproxy_root -p -e \"show variables like 'server_id'\"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 2 |+---------------+-------+# mysql -h 10.10.10.1 -u haproxy_root -p -e \"show variables like 'server_id'\"Enter password: +---------------+-------+| Variable_name | Value |+---------------+-------+| server_id | 2 |+---------------+-------+"
},
{
"code": null,
"e": 16613,
"s": 16534,
"text": "After the server1 will return online, the virtual IP will be moved back to it."
}
] |
Simple GUI calculator using Tkinter in Python
|
In this tutorial, we are going to create a simple GUI calculator using the Tkinter module. Tkinter is builtin the Python module for developing the GUI application. It's easy to use and comes with Python. We can visualize our data with GUI applications.
Let's see how to create a simple GUI calculator.
Import everything from the Tkinter using *.
Import everything from the Tkinter using *.
Create an interface for the calculator.
Create an interface for the calculator.
Create an input function that enters a number into the input field.
Create an input function that enters a number into the input field.
Create an apparent function that wipes everything from the input field.
Create an apparent function that wipes everything from the input field.
And finally, evaluate function that computes and gives the result of the expression.
And finally, evaluate function that computes and gives the result of the expression.
# importing everyting from tkinter
from tkinter import *
# expression to access among all the functions
expression = ""
# functions
def input_number(number, equation):
# accessing the global expression variable
global expression
# concatenation of string
expression = expression + str(number)
equation.set(expression)
def clear_input_field(equation):
global expression
expression = ""
# setting empty string in the input field
equation.set("Enter the expression")
def evaluate(equation):
global expression
# trying to evaluate the expression
try:
result = str(eval(expression))
# showing the result in the input field
equation.set(result)
# setting expression to empty string
expression = ""
except:
# some error occured
# showing it to the user equation.set("Enter a valid expression")
expression = ""
# creating the GUI
def main():
# main window window = Tk()
# setting the title of GUI window
window.title("Calculator")
# set the configuration of GUI window
window.geometry("325x175")
# varible class instantiation
equation = StringVar()
# input field for the expression
input_field = Entry(window, textvariable=equation)
input_field.place(height=100)
# we are using grid position
# for the arrangement of the widgets
input_field.grid(columnspan=4, ipadx=100, ipady=5)
# settin the placeholder message for users
equation.set("Enter the expression")
# creating buttons and placing them at respective positions
_1 = Button(window, text='1', fg='white', bg='black', bd=0, command=lambda: input_number(1, equation), height=2, width=7)
_1.grid(row=2, column=0)
_2 = Button(window, text='2', fg='white', bg='black', bd=0, command=lambda: input_number(2, equation), height=2, width=7)
_2.grid(row=2, column=1)
_3 = Button(window, text='3', fg='white', bg='black', bd=0, command=lambda: input_number(3, equation), height=2, width=7)
_3.grid(row=2, column=2)
_4 = Button(window, text='4', fg='white', bg='black', bd=0, command=lambda: input_number(4, equation), height=2, width=7)
_4.grid(row=3, column=0)
_5 = Button(window, text='5', fg='white', bg='black', bd=0, command=lambda: input_number(5, equation), height=2, width=7)
_5.grid(row=3, column=1)
_6 = Button(window, text='6', fg='white', bg='black', bd=0, command=lambda: input_number(6, equation), height=2, width=7)
_6.grid(row=3, column=2)
_7 = Button(window, text='7', fg='white', bg='black', bd=0, command=lambda: input_number(7, equation), height=2, width=7)
_7.grid(row=4, column=0)
_8 = Button(window, text='8', fg='white', bg='black', bd=0, command=lambda: input_number(8, equation), height=2, width=7)
_8.grid(row=4, column=1)
_9 = Button(window, text='9', fg='white', bg='black', bd=0, command=lambda: input_number(9, equation), height=2, width=7)
_9.grid(row=4, column=2)
_0 = Button(window, text='0', fg='white', bg='black', bd=0, command=lambda: input_number(0, equation), height=2, width=7)
_0.grid(row=5, column=0)
plus = Button(window, text='+', fg='white', bg='black', bd=0, command=lambda: input_number('+', equation), height=2, width=7)
plus.grid(row=2, column=3)
minus = Button(window, text='-', fg='white', bg='black', bd=0, command=lambda: input_number('-', equation), height=2, width=7)
minus.grid(row=3, column=3)
multiply = Button(window, text='*', fg='white', bg='black', bd=0, command=lambda: input_number('*', equation), height=2, width=7)
multiply.grid(row=4, column=3)
divide = Button(window, text='/', fg='white', bg='black', bd=0, command=lambda: input_number('/', equation), height=2, width=7)
divide.grid(row=5, column=3)
equal = Button(window, text='=', fg='white', bg='black', bd=0, command=lambda: evaluate(equation), height=2, width=7)
equal.grid(row=5, column=2)
clear = Button(window, text='Clear', fg='white', bg='black', bd=0, command=lambda: clear_input_field(equation), height=2, width=7)
clear.grid(row=5, column=1)
# showing the GUI
window.mainloop()
# start of the program
if __name__ == '__main__':
main()
If you run the above program, you will get a simple calculator as follows.
Result of the above expression generated after pression = button.
If you have any doubts in the tutorial, mention them in the comment section.
|
[
{
"code": null,
"e": 1315,
"s": 1062,
"text": "In this tutorial, we are going to create a simple GUI calculator using the Tkinter module. Tkinter is builtin the Python module for developing the GUI application. It's easy to use and comes with Python. We can visualize our data with GUI applications."
},
{
"code": null,
"e": 1364,
"s": 1315,
"text": "Let's see how to create a simple GUI calculator."
},
{
"code": null,
"e": 1408,
"s": 1364,
"text": "Import everything from the Tkinter using *."
},
{
"code": null,
"e": 1452,
"s": 1408,
"text": "Import everything from the Tkinter using *."
},
{
"code": null,
"e": 1492,
"s": 1452,
"text": "Create an interface for the calculator."
},
{
"code": null,
"e": 1532,
"s": 1492,
"text": "Create an interface for the calculator."
},
{
"code": null,
"e": 1600,
"s": 1532,
"text": "Create an input function that enters a number into the input field."
},
{
"code": null,
"e": 1668,
"s": 1600,
"text": "Create an input function that enters a number into the input field."
},
{
"code": null,
"e": 1740,
"s": 1668,
"text": "Create an apparent function that wipes everything from the input field."
},
{
"code": null,
"e": 1812,
"s": 1740,
"text": "Create an apparent function that wipes everything from the input field."
},
{
"code": null,
"e": 1897,
"s": 1812,
"text": "And finally, evaluate function that computes and gives the result of the expression."
},
{
"code": null,
"e": 1982,
"s": 1897,
"text": "And finally, evaluate function that computes and gives the result of the expression."
},
{
"code": null,
"e": 6073,
"s": 1982,
"text": "# importing everyting from tkinter\nfrom tkinter import *\n# expression to access among all the functions\nexpression = \"\"\n# functions\ndef input_number(number, equation):\n # accessing the global expression variable\n global expression\n # concatenation of string\n expression = expression + str(number)\n equation.set(expression)\ndef clear_input_field(equation):\n global expression\n expression = \"\"\n # setting empty string in the input field\n equation.set(\"Enter the expression\")\ndef evaluate(equation):\nglobal expression\n# trying to evaluate the expression\ntry:\nresult = str(eval(expression))\n# showing the result in the input field\nequation.set(result)\n# setting expression to empty string\nexpression = \"\"\nexcept:\n# some error occured\n# showing it to the user equation.set(\"Enter a valid expression\")\nexpression = \"\"\n# creating the GUI\ndef main():\n # main window window = Tk()\n # setting the title of GUI window\n window.title(\"Calculator\")\n # set the configuration of GUI window\n window.geometry(\"325x175\")\n # varible class instantiation\n equation = StringVar()\n # input field for the expression\n input_field = Entry(window, textvariable=equation)\n input_field.place(height=100)\n # we are using grid position\n # for the arrangement of the widgets\n input_field.grid(columnspan=4, ipadx=100, ipady=5)\n # settin the placeholder message for users\n equation.set(\"Enter the expression\")\n # creating buttons and placing them at respective positions\n _1 = Button(window, text='1', fg='white', bg='black', bd=0, command=lambda: input_number(1, equation), height=2, width=7)\n _1.grid(row=2, column=0)\n _2 = Button(window, text='2', fg='white', bg='black', bd=0, command=lambda: input_number(2, equation), height=2, width=7)\n _2.grid(row=2, column=1)\n _3 = Button(window, text='3', fg='white', bg='black', bd=0, command=lambda: input_number(3, equation), height=2, width=7)\n _3.grid(row=2, column=2)\n _4 = Button(window, text='4', fg='white', bg='black', bd=0, command=lambda: input_number(4, equation), height=2, width=7)\n _4.grid(row=3, column=0)\n _5 = Button(window, text='5', fg='white', bg='black', bd=0, command=lambda: input_number(5, equation), height=2, width=7)\n _5.grid(row=3, column=1)\n _6 = Button(window, text='6', fg='white', bg='black', bd=0, command=lambda: input_number(6, equation), height=2, width=7)\n _6.grid(row=3, column=2)\n _7 = Button(window, text='7', fg='white', bg='black', bd=0, command=lambda: input_number(7, equation), height=2, width=7)\n _7.grid(row=4, column=0)\n _8 = Button(window, text='8', fg='white', bg='black', bd=0, command=lambda: input_number(8, equation), height=2, width=7)\n _8.grid(row=4, column=1)\n _9 = Button(window, text='9', fg='white', bg='black', bd=0, command=lambda: input_number(9, equation), height=2, width=7)\n _9.grid(row=4, column=2)\n _0 = Button(window, text='0', fg='white', bg='black', bd=0, command=lambda: input_number(0, equation), height=2, width=7)\n _0.grid(row=5, column=0)\n plus = Button(window, text='+', fg='white', bg='black', bd=0, command=lambda: input_number('+', equation), height=2, width=7)\n plus.grid(row=2, column=3)\n minus = Button(window, text='-', fg='white', bg='black', bd=0, command=lambda: input_number('-', equation), height=2, width=7)\n minus.grid(row=3, column=3)\n multiply = Button(window, text='*', fg='white', bg='black', bd=0, command=lambda: input_number('*', equation), height=2, width=7)\n multiply.grid(row=4, column=3)\n divide = Button(window, text='/', fg='white', bg='black', bd=0, command=lambda: input_number('/', equation), height=2, width=7)\n divide.grid(row=5, column=3)\n equal = Button(window, text='=', fg='white', bg='black', bd=0, command=lambda: evaluate(equation), height=2, width=7)\n equal.grid(row=5, column=2)\n clear = Button(window, text='Clear', fg='white', bg='black', bd=0, command=lambda: clear_input_field(equation), height=2, width=7)\n clear.grid(row=5, column=1)\n # showing the GUI\n window.mainloop()\n# start of the program\nif __name__ == '__main__':\n main()\n"
},
{
"code": null,
"e": 6148,
"s": 6073,
"text": "If you run the above program, you will get a simple calculator as follows."
},
{
"code": null,
"e": 6214,
"s": 6148,
"text": "Result of the above expression generated after pression = button."
},
{
"code": null,
"e": 6291,
"s": 6214,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
] |
SWING - BorderLayout Class
|
The class BorderLayout arranges the components to fit in the five regions: east, west, north, south, and center. Each region can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER.
Following is the declaration for java.awt.BorderLayout class β
public class BorderLayout
extends Object
implements LayoutManager2, Serializable
Following are the fields for java.awt.BorderLayout class β
static String AFTER_LAST_LINE β Synonym for PAGE_END.
static String AFTER_LAST_LINE β Synonym for PAGE_END.
static String AFTER_LINE_ENDS β Synonym for LINE_END.
static String AFTER_LINE_ENDS β Synonym for LINE_END.
static String BEFORE_FIRST_LINE β Synonym for PAGE_START.
static String BEFORE_FIRST_LINE β Synonym for PAGE_START.
static String BEFORE_LINE_BEGINS β Synonym for LINE_START.
static String BEFORE_LINE_BEGINS β Synonym for LINE_START.
static String CENTER β The center layout constraint (middle of the container).
static String CENTER β The center layout constraint (middle of the container).
static String EAST β The east layout constraint (right side of the container).
static String EAST β The east layout constraint (right side of the container).
static String LINE_END β The component goes at the end of the line direction for the layout.
static String LINE_END β The component goes at the end of the line direction for the layout.
static String LINE_START β The component goes at the beginning of the line direction for the layout.
static String LINE_START β The component goes at the beginning of the line direction for the layout.
static String NORTH β The north layout constraint (top of the container).
static String NORTH β The north layout constraint (top of the container).
static String PAGE_END β The component comes after the last line of the layout's content.
static String PAGE_END β The component comes after the last line of the layout's content.
static String PAGE_START β The component comes before the first line of the layout's content.
static String PAGE_START β The component comes before the first line of the layout's content.
static String SOUTH β The south layout constraint (bottom of the container).
static String SOUTH β The south layout constraint (bottom of the container).
static String WEST β The west layout constraint (left side of the container).
static String WEST β The west layout constraint (left side of the container).
BorderLayout()
Constructs a new border layout with no gaps between the components.
BorderLayout(int hgap, int vgap)
Constructs a border layout with the specified gaps between the components.
void addLayoutComponent(Component comp, Object constraints)
Adds the specified component to the layout, using the specified constraint object.
void addLayoutComponent(String name, Component comp)
If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name.
int getHgap()
Returns the horizontal gap between the components.
float getLayoutAlignmentX(Container parent)
Returns the alignment along the x axis.
float getLayoutAlignmentY(Container parent)
Returns the alignment along the y axis.
int getVgap()
Returns the vertical gap between the components.
void invalidateLayout(Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
void layoutContainer(Container target)
Lays out the container argument using this border layout.
Dimension maximumLayoutSize(Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
Dimension minimumLayoutSize(Container target)
Determines the minimum size of the target container using this layout manager.
Dimension preferredLayoutSize(Container target)
Determines the preferred size of the target container using this layout manager, based on the components in the container.
void removeLayoutComponent(Component comp)
Removes the specified component from this border layout.
void setHgap(int hgap)
Sets the horizontal gap between the components.
void setVgap(int vgap)
Sets the vertical gap between the components.
String toString()
Returns a string representation of the state of this border layout.
This class inherits methods from the following class β
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingLayoutDemo.java
package com.tutorialspoint.gui;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SwingLayoutDemo {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;
private JLabel msglabel;
public SwingLayoutDemo(){
prepareGUI();
}
public static void main(String[] args){
SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo();
swingLayoutDemo.showBorderLayoutDemo();
}
private void prepareGUI(){
mainFrame = new JFrame("Java SWING Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
headerLabel = new JLabel("",JLabel.CENTER );
statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
private void showBorderLayoutDemo(){
headerLabel.setText("Layout in action: BorderLayout");
JPanel panel = new JPanel();
panel.setBackground(Color.darkGray);
panel.setSize(300,300);
BorderLayout layout = new BorderLayout();
layout.setHgap(10);
layout.setVgap(10);
panel.setLayout(layout);
panel.add(new JButton("Center"),BorderLayout.CENTER);
panel.add(new JButton("Line Start"),BorderLayout.LINE_START);
panel.add(new JButton("Line End"),BorderLayout.LINE_END);
panel.add(new JButton("East"),BorderLayout.EAST);
panel.add(new JButton("West"),BorderLayout.WEST);
panel.add(new JButton("North"),BorderLayout.NORTH);
panel.add(new JButton("South"),BorderLayout.SOUTH);
controlPanel.add(panel);
mainFrame.setVisible(true);
}
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingLayoutDemo.java
If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingLayoutDemo
Verify the following output.
30 Lectures
3.5 hours
Pranjal Srivastava
13 Lectures
1 hours
Pranjal Srivastava
25 Lectures
4.5 hours
Emenwa Global, Ejike IfeanyiChukwu
14 Lectures
1.5 hours
Travis Rose
14 Lectures
1 hours
Travis Rose
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2035,
"s": 1763,
"text": "The class BorderLayout arranges the components to fit in the five regions: east, west, north, south, and center. Each region can contain only one component and each component in each region is identified by the corresponding constant NORTH, SOUTH, EAST, WEST, and CENTER."
},
{
"code": null,
"e": 2098,
"s": 2035,
"text": "Following is the declaration for java.awt.BorderLayout class β"
},
{
"code": null,
"e": 2189,
"s": 2098,
"text": "public class BorderLayout\n extends Object\n implements LayoutManager2, Serializable\n"
},
{
"code": null,
"e": 2248,
"s": 2189,
"text": "Following are the fields for java.awt.BorderLayout class β"
},
{
"code": null,
"e": 2302,
"s": 2248,
"text": "static String AFTER_LAST_LINE β Synonym for PAGE_END."
},
{
"code": null,
"e": 2356,
"s": 2302,
"text": "static String AFTER_LAST_LINE β Synonym for PAGE_END."
},
{
"code": null,
"e": 2410,
"s": 2356,
"text": "static String AFTER_LINE_ENDS β Synonym for LINE_END."
},
{
"code": null,
"e": 2464,
"s": 2410,
"text": "static String AFTER_LINE_ENDS β Synonym for LINE_END."
},
{
"code": null,
"e": 2522,
"s": 2464,
"text": "static String BEFORE_FIRST_LINE β Synonym for PAGE_START."
},
{
"code": null,
"e": 2580,
"s": 2522,
"text": "static String BEFORE_FIRST_LINE β Synonym for PAGE_START."
},
{
"code": null,
"e": 2639,
"s": 2580,
"text": "static String BEFORE_LINE_BEGINS β Synonym for LINE_START."
},
{
"code": null,
"e": 2698,
"s": 2639,
"text": "static String BEFORE_LINE_BEGINS β Synonym for LINE_START."
},
{
"code": null,
"e": 2777,
"s": 2698,
"text": "static String CENTER β The center layout constraint (middle of the container)."
},
{
"code": null,
"e": 2856,
"s": 2777,
"text": "static String CENTER β The center layout constraint (middle of the container)."
},
{
"code": null,
"e": 2935,
"s": 2856,
"text": "static String EAST β The east layout constraint (right side of the container)."
},
{
"code": null,
"e": 3014,
"s": 2935,
"text": "static String EAST β The east layout constraint (right side of the container)."
},
{
"code": null,
"e": 3107,
"s": 3014,
"text": "static String LINE_END β The component goes at the end of the line direction for the layout."
},
{
"code": null,
"e": 3200,
"s": 3107,
"text": "static String LINE_END β The component goes at the end of the line direction for the layout."
},
{
"code": null,
"e": 3301,
"s": 3200,
"text": "static String LINE_START β The component goes at the beginning of the line direction for the layout."
},
{
"code": null,
"e": 3402,
"s": 3301,
"text": "static String LINE_START β The component goes at the beginning of the line direction for the layout."
},
{
"code": null,
"e": 3476,
"s": 3402,
"text": "static String NORTH β The north layout constraint (top of the container)."
},
{
"code": null,
"e": 3550,
"s": 3476,
"text": "static String NORTH β The north layout constraint (top of the container)."
},
{
"code": null,
"e": 3640,
"s": 3550,
"text": "static String PAGE_END β The component comes after the last line of the layout's content."
},
{
"code": null,
"e": 3730,
"s": 3640,
"text": "static String PAGE_END β The component comes after the last line of the layout's content."
},
{
"code": null,
"e": 3824,
"s": 3730,
"text": "static String PAGE_START β The component comes before the first line of the layout's content."
},
{
"code": null,
"e": 3918,
"s": 3824,
"text": "static String PAGE_START β The component comes before the first line of the layout's content."
},
{
"code": null,
"e": 3995,
"s": 3918,
"text": "static String SOUTH β The south layout constraint (bottom of the container)."
},
{
"code": null,
"e": 4072,
"s": 3995,
"text": "static String SOUTH β The south layout constraint (bottom of the container)."
},
{
"code": null,
"e": 4150,
"s": 4072,
"text": "static String WEST β The west layout constraint (left side of the container)."
},
{
"code": null,
"e": 4228,
"s": 4150,
"text": "static String WEST β The west layout constraint (left side of the container)."
},
{
"code": null,
"e": 4243,
"s": 4228,
"text": "BorderLayout()"
},
{
"code": null,
"e": 4311,
"s": 4243,
"text": "Constructs a new border layout with no gaps between the components."
},
{
"code": null,
"e": 4344,
"s": 4311,
"text": "BorderLayout(int hgap, int vgap)"
},
{
"code": null,
"e": 4419,
"s": 4344,
"text": "Constructs a border layout with the specified gaps between the components."
},
{
"code": null,
"e": 4479,
"s": 4419,
"text": "void addLayoutComponent(Component comp, Object constraints)"
},
{
"code": null,
"e": 4562,
"s": 4479,
"text": "Adds the specified component to the layout, using the specified constraint object."
},
{
"code": null,
"e": 4615,
"s": 4562,
"text": "void addLayoutComponent(String name, Component comp)"
},
{
"code": null,
"e": 4755,
"s": 4615,
"text": "If the layout manager uses a per-component string, adds the component comp to the layout, associating it with the string specified by name."
},
{
"code": null,
"e": 4769,
"s": 4755,
"text": "int getHgap()"
},
{
"code": null,
"e": 4820,
"s": 4769,
"text": "Returns the horizontal gap between the components."
},
{
"code": null,
"e": 4864,
"s": 4820,
"text": "float getLayoutAlignmentX(Container parent)"
},
{
"code": null,
"e": 4904,
"s": 4864,
"text": "Returns the alignment along the x axis."
},
{
"code": null,
"e": 4948,
"s": 4904,
"text": "float getLayoutAlignmentY(Container parent)"
},
{
"code": null,
"e": 4988,
"s": 4948,
"text": "Returns the alignment along the y axis."
},
{
"code": null,
"e": 5002,
"s": 4988,
"text": "int getVgap()"
},
{
"code": null,
"e": 5051,
"s": 5002,
"text": "Returns the vertical gap between the components."
},
{
"code": null,
"e": 5091,
"s": 5051,
"text": "void invalidateLayout(Container target)"
},
{
"code": null,
"e": 5200,
"s": 5091,
"text": "Invalidates the layout, indicating that if the layout manager has cached information it should be discarded."
},
{
"code": null,
"e": 5239,
"s": 5200,
"text": "void layoutContainer(Container target)"
},
{
"code": null,
"e": 5297,
"s": 5239,
"text": "Lays out the container argument using this border layout."
},
{
"code": null,
"e": 5343,
"s": 5297,
"text": "Dimension maximumLayoutSize(Container target)"
},
{
"code": null,
"e": 5446,
"s": 5343,
"text": "Returns the maximum dimensions for this layout given the components in the specified target container."
},
{
"code": null,
"e": 5492,
"s": 5446,
"text": "Dimension minimumLayoutSize(Container target)"
},
{
"code": null,
"e": 5571,
"s": 5492,
"text": "Determines the minimum size of the target container using this layout manager."
},
{
"code": null,
"e": 5619,
"s": 5571,
"text": "Dimension preferredLayoutSize(Container target)"
},
{
"code": null,
"e": 5742,
"s": 5619,
"text": "Determines the preferred size of the target container using this layout manager, based on the components in the container."
},
{
"code": null,
"e": 5785,
"s": 5742,
"text": "void removeLayoutComponent(Component comp)"
},
{
"code": null,
"e": 5842,
"s": 5785,
"text": "Removes the specified component from this border layout."
},
{
"code": null,
"e": 5865,
"s": 5842,
"text": "void setHgap(int hgap)"
},
{
"code": null,
"e": 5913,
"s": 5865,
"text": "Sets the horizontal gap between the components."
},
{
"code": null,
"e": 5936,
"s": 5913,
"text": "void setVgap(int vgap)"
},
{
"code": null,
"e": 5982,
"s": 5936,
"text": "Sets the vertical gap between the components."
},
{
"code": null,
"e": 6000,
"s": 5982,
"text": "String toString()"
},
{
"code": null,
"e": 6068,
"s": 6000,
"text": "Returns a string representation of the state of this border layout."
},
{
"code": null,
"e": 6123,
"s": 6068,
"text": "This class inherits methods from the following class β"
},
{
"code": null,
"e": 6140,
"s": 6123,
"text": "java.lang.Object"
},
{
"code": null,
"e": 6256,
"s": 6140,
"text": "Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >"
},
{
"code": null,
"e": 6277,
"s": 6256,
"text": "SwingLayoutDemo.java"
},
{
"code": null,
"e": 8369,
"s": 6277,
"text": "package com.tutorialspoint.gui;\n\nimport java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class SwingLayoutDemo {\n private JFrame mainFrame;\n private JLabel headerLabel;\n private JLabel statusLabel;\n private JPanel controlPanel;\n private JLabel msglabel;\n\n public SwingLayoutDemo(){\n prepareGUI();\n }\n public static void main(String[] args){\n SwingLayoutDemo swingLayoutDemo = new SwingLayoutDemo(); \n swingLayoutDemo.showBorderLayoutDemo(); \n }\n private void prepareGUI(){\n mainFrame = new JFrame(\"Java SWING Examples\");\n mainFrame.setSize(400,400);\n mainFrame.setLayout(new GridLayout(3, 1));\n\n headerLabel = new JLabel(\"\",JLabel.CENTER );\n statusLabel = new JLabel(\"\",JLabel.CENTER); \n statusLabel.setSize(350,100);\n \n mainFrame.addWindowListener(new WindowAdapter() {\n public void windowClosing(WindowEvent windowEvent){\n System.exit(0);\n } \n }); \n controlPanel = new JPanel();\n controlPanel.setLayout(new FlowLayout());\n\n mainFrame.add(headerLabel);\n mainFrame.add(controlPanel);\n mainFrame.add(statusLabel);\n mainFrame.setVisible(true); \n }\n private void showBorderLayoutDemo(){\n headerLabel.setText(\"Layout in action: BorderLayout\"); \n\n JPanel panel = new JPanel();\n panel.setBackground(Color.darkGray);\n panel.setSize(300,300);\n BorderLayout layout = new BorderLayout();\n layout.setHgap(10);\n layout.setVgap(10);\n \n panel.setLayout(layout); \n panel.add(new JButton(\"Center\"),BorderLayout.CENTER);\n panel.add(new JButton(\"Line Start\"),BorderLayout.LINE_START); \n panel.add(new JButton(\"Line End\"),BorderLayout.LINE_END);\n panel.add(new JButton(\"East\"),BorderLayout.EAST); \n panel.add(new JButton(\"West\"),BorderLayout.WEST); \n panel.add(new JButton(\"North\"),BorderLayout.NORTH); \n panel.add(new JButton(\"South\"),BorderLayout.SOUTH); \n\n controlPanel.add(panel);\n mainFrame.setVisible(true); \n }\n}"
},
{
"code": null,
"e": 8465,
"s": 8369,
"text": "Compile the program using the command prompt. Go to D:/ > SWING and type the following command."
},
{
"code": null,
"e": 8525,
"s": 8465,
"text": "D:\\SWING>javac com\\tutorialspoint\\gui\\SwingLayoutDemo.java\n"
},
{
"code": null,
"e": 8630,
"s": 8525,
"text": "If no error occurs, it means the compilation is successful. Run the program using the following command."
},
{
"code": null,
"e": 8684,
"s": 8630,
"text": "D:\\SWING>java com.tutorialspoint.gui.SwingLayoutDemo\n"
},
{
"code": null,
"e": 8713,
"s": 8684,
"text": "Verify the following output."
},
{
"code": null,
"e": 8748,
"s": 8713,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 8768,
"s": 8748,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8801,
"s": 8768,
"text": "\n 13 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8821,
"s": 8801,
"text": " Pranjal Srivastava"
},
{
"code": null,
"e": 8856,
"s": 8821,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8892,
"s": 8856,
"text": " Emenwa Global, Ejike IfeanyiChukwu"
},
{
"code": null,
"e": 8927,
"s": 8892,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8940,
"s": 8927,
"text": " Travis Rose"
},
{
"code": null,
"e": 8973,
"s": 8940,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8986,
"s": 8973,
"text": " Travis Rose"
},
{
"code": null,
"e": 8993,
"s": 8986,
"text": " Print"
},
{
"code": null,
"e": 9004,
"s": 8993,
"text": " Add Notes"
}
] |
The extern storage class in C++
|
The extern storage class specifier lets you declare objects that several source files can use. An extern declaration makes the described variable usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined.
An extern declaration can appear outside a function or at the beginning of a block. If the declaration describes a function or appears outside of a function and describes an object with external linkage, the keyword extern is optional.
If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage.
C++ restricts the use of the extern storage class specifier to the names of objects or functions. Using the extern specifier with type declarations is illegal. An extern declaration cannot appear in class scope.
You can use the extern keyword as follows to share the variable across files β
file3.h
extern int global_variable; /* Declaration of the variable */
file1.c
#include "file3.h" /* Declaration made available here */
#include "prog1.h" /* Function declarations */
/* Variable defined here */
int global_variable = 37; /* Definition checked against declaration */
int increment(void) {
return global_variable++;
}
file2.c
#include "file3.h"
#include "prog1.h"
#include <stdio.h>
void use_it(void)
{
printf("Global variable: %d\n", global_variable++);
}
The following question at stackoverflow completely captures the essence of the extern keyword: https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files.
|
[
{
"code": null,
"e": 1393,
"s": 1062,
"text": "The extern storage class specifier lets you declare objects that several source files can use. An extern declaration makes the described variable usable by the succeeding part of the current source file. This declaration does not replace the definition. The declaration is used to describe the variable that is externally defined."
},
{
"code": null,
"e": 1629,
"s": 1393,
"text": "An extern declaration can appear outside a function or at the beginning of a block. If the declaration describes a function or appears outside of a function and describes an object with external linkage, the keyword extern is optional."
},
{
"code": null,
"e": 1891,
"s": 1629,
"text": "If a declaration for an identifier already exists at file scope, any extern declaration of the same identifier found within a block refers to that same object. If no other declaration for the identifier exists at file scope, the identifier has external linkage."
},
{
"code": null,
"e": 2103,
"s": 1891,
"text": "C++ restricts the use of the extern storage class specifier to the names of objects or functions. Using the extern specifier with type declarations is illegal. An extern declaration cannot appear in class scope."
},
{
"code": null,
"e": 2182,
"s": 2103,
"text": "You can use the extern keyword as follows to share the variable across files β"
},
{
"code": null,
"e": 2190,
"s": 2182,
"text": "file3.h"
},
{
"code": null,
"e": 2253,
"s": 2190,
"text": "extern int global_variable; /* Declaration of the variable */"
},
{
"code": null,
"e": 2261,
"s": 2253,
"text": "file1.c"
},
{
"code": null,
"e": 2523,
"s": 2261,
"text": "#include \"file3.h\" /* Declaration made available here */\n#include \"prog1.h\" /* Function declarations */\n/* Variable defined here */\nint global_variable = 37; /* Definition checked against declaration */\n\nint increment(void) {\n return global_variable++;\n}"
},
{
"code": null,
"e": 2531,
"s": 2523,
"text": "file2.c"
},
{
"code": null,
"e": 2666,
"s": 2531,
"text": "#include \"file3.h\"\n#include \"prog1.h\"\n#include <stdio.h>\n\nvoid use_it(void)\n{\n printf(\"Global variable: %d\\n\", global_variable++);\n}"
},
{
"code": null,
"e": 2866,
"s": 2666,
"text": "The following question at stackoverflow completely captures the essence of the extern keyword: https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files."
}
] |
How to add rows in an R data frame?
|
To add rows in an R data frame, we can follow the below steps β
First of all, create a data frame.
First of all, create a data frame.
Then, use rbind function and the vectors that will be added as rows to the data frame.
Then, use rbind function and the vectors that will be added as rows to the data frame.
Letβs create a data frame as shown below β
x<-rpois(25,5)
y<-rpois(25,2)
df<-data.frame(x,y)
df
On executing, the above script generates the below output(this output will vary on your system due to randomization) β
x y
1 9 3
2 4 1
3 5 0
4 8 1
5 5 2
6 6 3
7 7 2
8 3 4
9 5 1
10 2 2
11 5 2
12 2 2
13 8 2
14 12 4
15 7 4
16 3 2
17 4 0
18 8 2
19 6 1
20 2 4
21 3 1
22 4 1
23 4 1
24 4 3
25 2 2
Add rows in the data frame
Using rbind function and the vectors to add rows in the data frame as shown below β
x<-rpois(25,5)
y<-rpois(25,2)
df<-data.frame(x,y)
df<-rbind(df,c(5,5),c(2,1),c(0,1),c(5,4),c(3,6))
df
x y
1 9 3
2 4 1
3 5 0
4 8 1
5 5 2
6 6 3
7 7 2
8 3 4
9 5 1
10 2 2
11 5 2
12 2 2
13 8 2
14 12 4
15 7 4
16 3 2
17 4 0
18 8 2
19 6 1
20 2 4
21 3 1
22 4 1
23 4 1
24 4 3
25 2 2
26 5 5
27 2 1
28 0 1
29 5 4
30 3 6
|
[
{
"code": null,
"e": 1126,
"s": 1062,
"text": "To add rows in an R data frame, we can follow the below steps β"
},
{
"code": null,
"e": 1161,
"s": 1126,
"text": "First of all, create a data frame."
},
{
"code": null,
"e": 1196,
"s": 1161,
"text": "First of all, create a data frame."
},
{
"code": null,
"e": 1283,
"s": 1196,
"text": "Then, use rbind function and the vectors that will be added as rows to the data frame."
},
{
"code": null,
"e": 1370,
"s": 1283,
"text": "Then, use rbind function and the vectors that will be added as rows to the data frame."
},
{
"code": null,
"e": 1413,
"s": 1370,
"text": "Letβs create a data frame as shown below β"
},
{
"code": null,
"e": 1466,
"s": 1413,
"text": "x<-rpois(25,5)\ny<-rpois(25,2)\ndf<-data.frame(x,y)\ndf"
},
{
"code": null,
"e": 1585,
"s": 1466,
"text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) β"
},
{
"code": null,
"e": 1793,
"s": 1585,
"text": " x y\n1 9 3\n2 4 1\n3 5 0\n4 8 1\n5 5 2\n6 6 3\n7 7 2\n8 3 4\n9 5 1\n10 2 2\n11 5 2\n12 2 2\n13 8 2\n14 12 4\n15 7 4\n16 3 2\n17 4 0\n18 8 2\n19 6 1\n20 2 4\n21 3 1\n22 4 1\n23 4 1\n24 4 3\n25 2 2"
},
{
"code": null,
"e": 1820,
"s": 1793,
"text": "Add rows in the data frame"
},
{
"code": null,
"e": 1904,
"s": 1820,
"text": "Using rbind function and the vectors to add rows in the data frame as shown below β"
},
{
"code": null,
"e": 2006,
"s": 1904,
"text": "x<-rpois(25,5)\ny<-rpois(25,2)\ndf<-data.frame(x,y)\ndf<-rbind(df,c(5,5),c(2,1),c(0,1),c(5,4),c(3,6))\ndf"
},
{
"code": null,
"e": 2254,
"s": 2006,
"text": " x y\n1 9 3\n2 4 1\n3 5 0\n4 8 1\n5 5 2\n6 6 3\n7 7 2\n8 3 4\n9 5 1\n10 2 2\n11 5 2\n12 2 2\n13 8 2\n14 12 4\n15 7 4\n16 3 2\n17 4 0\n18 8 2\n19 6 1\n20 2 4\n21 3 1\n22 4 1\n23 4 1\n24 4 3\n25 2 2\n26 5 5\n27 2 1\n28 0 1\n29 5 4\n30 3 6"
}
] |
How to Calculate Covariance in MATLAB - GeeksforGeeks
|
31 Aug, 2021
Covariance is the measure of the strength of correlation between two or more random variables. Covariance of two random variables X and Y can be defined as:
Where E(X) and E(Y) are expectation or mean of random variables X and Y respectively.
The covariance matrix of two random variables A and B is defined as
MATLAB language allows users to calculate the covariance of random variables using cov() method. Different syntax of cov() method are:
C = cov(A)C = cov(A,B)C = cov(___,w)C = cov(___,nanflag)
C = cov(A)
C = cov(A,B)
C = cov(___,w)
C = cov(___,nanflag)
It returns the covariance of array A.
If A is a scalar, then it returns 0.
If A is a vector, then it returns the variance of vector A.
If A is a matrix, then it considers each column as a random variable and returns the covariance matrix of matrix A.
Note: disp (x) displays the value of variable X without printing the variable name. Another way to display a variable is to type its name, which displays a leading βX =β before the value. If a variable contains an empty array, disp returns without displaying anything.
Example 1:
Matlab
% Input vectorA = [1 3 4];disp("Vector :");disp(A); % Variance of vector AC = cov(A);disp("Variance :");disp(C);
Output :
Example 2:
Matlab
% Input vectorA = [2 7 1; 3 5 1 4 1 2];disp("Matrix :");disp(A); % Covariance of matrix AC = cov(A);disp("Covariance matrix :");disp(C);
Output :
It returns the covariance matrix of arrays A and B.
If A and B vectors, then it returns the covariance matrix of A and B.
If A and B are matrices, then it considers them as vectors themselves by expanding the dimensions and returns the covariance matrix.
Example:
Matlab
% Input vectorA = [3 5 7];B = [-1 3 9];disp("Vector A:");disp(A);disp("Vector B:");disp(B); % Covariance of vectors A,BC = cov(A,B);disp("Covariance matrix :");disp(C);
Output :
It returns the covariance of the input array by normalizing it to w.
If w = 1, then covariance is normalized by the number of rows in the input matrix.
If w = 0, then covariance is normalized by the number of rows in the input matrix β 1.
Example:
Matlab
% Input vectorA = [2 4 6; 3 5 7 8 10 12];disp("Matrix :");disp(A); % Variance of matrix AC = cov(A,1);disp("Variance matrix:");disp(C);
Output :
It returns the covariance of the input array by considering the nanflag.
If nanflag = βincludenanβ, then it considers NaN values in array.
If nanflag = βomitrowsβ, then it omits the rows with at least one NaN value in the array.
Example:
Matlab
% Input vectorA = [3.2 -1.005 2.98; NaN -6.75 NaN; 5.37 0.19 1]disp("Matrix :");disp(A); % Variance of matrix AC = cov(A,'includenan');disp("Variance matrix including NaN:");disp(C); % Variance of matrix AC = cov(A,'omitrows');disp("Variance matrix omitting NaN:");disp(C);
Output :
varshagumber28
singghakshay
MATLAB-Maths
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
Differential or Derivatives in MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
Laplacian of Gaussian Filter in MATLAB
Boundary Extraction of image using MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Apply Median Filter For RGB Image in MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB
What is Upsampling in MATLAB?
|
[
{
"code": null,
"e": 24515,
"s": 24487,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 24672,
"s": 24515,
"text": "Covariance is the measure of the strength of correlation between two or more random variables. Covariance of two random variables X and Y can be defined as:"
},
{
"code": null,
"e": 24758,
"s": 24672,
"text": "Where E(X) and E(Y) are expectation or mean of random variables X and Y respectively."
},
{
"code": null,
"e": 24826,
"s": 24758,
"text": "The covariance matrix of two random variables A and B is defined as"
},
{
"code": null,
"e": 24961,
"s": 24826,
"text": "MATLAB language allows users to calculate the covariance of random variables using cov() method. Different syntax of cov() method are:"
},
{
"code": null,
"e": 25018,
"s": 24961,
"text": "C = cov(A)C = cov(A,B)C = cov(___,w)C = cov(___,nanflag)"
},
{
"code": null,
"e": 25029,
"s": 25018,
"text": "C = cov(A)"
},
{
"code": null,
"e": 25042,
"s": 25029,
"text": "C = cov(A,B)"
},
{
"code": null,
"e": 25057,
"s": 25042,
"text": "C = cov(___,w)"
},
{
"code": null,
"e": 25078,
"s": 25057,
"text": "C = cov(___,nanflag)"
},
{
"code": null,
"e": 25116,
"s": 25078,
"text": "It returns the covariance of array A."
},
{
"code": null,
"e": 25153,
"s": 25116,
"text": "If A is a scalar, then it returns 0."
},
{
"code": null,
"e": 25213,
"s": 25153,
"text": "If A is a vector, then it returns the variance of vector A."
},
{
"code": null,
"e": 25360,
"s": 25244,
"text": "If A is a matrix, then it considers each column as a random variable and returns the covariance matrix of matrix A."
},
{
"code": null,
"e": 25629,
"s": 25360,
"text": "Note: disp (x) displays the value of variable X without printing the variable name. Another way to display a variable is to type its name, which displays a leading βX =β before the value. If a variable contains an empty array, disp returns without displaying anything."
},
{
"code": null,
"e": 25640,
"s": 25629,
"text": "Example 1:"
},
{
"code": null,
"e": 25647,
"s": 25640,
"text": "Matlab"
},
{
"code": "% Input vectorA = [1 3 4];disp(\"Vector :\");disp(A); % Variance of vector AC = cov(A);disp(\"Variance :\");disp(C);",
"e": 25760,
"s": 25647,
"text": null
},
{
"code": null,
"e": 25772,
"s": 25763,
"text": "Output :"
},
{
"code": null,
"e": 25787,
"s": 25776,
"text": "Example 2:"
},
{
"code": null,
"e": 25796,
"s": 25789,
"text": "Matlab"
},
{
"code": "% Input vectorA = [2 7 1; 3 5 1 4 1 2];disp(\"Matrix :\");disp(A); % Covariance of matrix AC = cov(A);disp(\"Covariance matrix :\");disp(C);",
"e": 25941,
"s": 25796,
"text": null
},
{
"code": null,
"e": 25953,
"s": 25944,
"text": "Output :"
},
{
"code": null,
"e": 26007,
"s": 25955,
"text": "It returns the covariance matrix of arrays A and B."
},
{
"code": null,
"e": 26077,
"s": 26007,
"text": "If A and B vectors, then it returns the covariance matrix of A and B."
},
{
"code": null,
"e": 26210,
"s": 26077,
"text": "If A and B are matrices, then it considers them as vectors themselves by expanding the dimensions and returns the covariance matrix."
},
{
"code": null,
"e": 26219,
"s": 26210,
"text": "Example:"
},
{
"code": null,
"e": 26228,
"s": 26221,
"text": "Matlab"
},
{
"code": "% Input vectorA = [3 5 7];B = [-1 3 9];disp(\"Vector A:\");disp(A);disp(\"Vector B:\");disp(B); % Covariance of vectors A,BC = cov(A,B);disp(\"Covariance matrix :\");disp(C);",
"e": 26397,
"s": 26228,
"text": null
},
{
"code": null,
"e": 26409,
"s": 26400,
"text": "Output :"
},
{
"code": null,
"e": 26480,
"s": 26411,
"text": "It returns the covariance of the input array by normalizing it to w."
},
{
"code": null,
"e": 26563,
"s": 26480,
"text": "If w = 1, then covariance is normalized by the number of rows in the input matrix."
},
{
"code": null,
"e": 26650,
"s": 26563,
"text": "If w = 0, then covariance is normalized by the number of rows in the input matrix β 1."
},
{
"code": null,
"e": 26661,
"s": 26652,
"text": "Example:"
},
{
"code": null,
"e": 26670,
"s": 26663,
"text": "Matlab"
},
{
"code": "% Input vectorA = [2 4 6; 3 5 7 8 10 12];disp(\"Matrix :\");disp(A); % Variance of matrix AC = cov(A,1);disp(\"Variance matrix:\");disp(C);",
"e": 26814,
"s": 26670,
"text": null
},
{
"code": null,
"e": 26826,
"s": 26817,
"text": "Output :"
},
{
"code": null,
"e": 26901,
"s": 26828,
"text": "It returns the covariance of the input array by considering the nanflag."
},
{
"code": null,
"e": 26967,
"s": 26901,
"text": "If nanflag = βincludenanβ, then it considers NaN values in array."
},
{
"code": null,
"e": 27057,
"s": 26967,
"text": "If nanflag = βomitrowsβ, then it omits the rows with at least one NaN value in the array."
},
{
"code": null,
"e": 27068,
"s": 27059,
"text": "Example:"
},
{
"code": null,
"e": 27077,
"s": 27070,
"text": "Matlab"
},
{
"code": "% Input vectorA = [3.2 -1.005 2.98; NaN -6.75 NaN; 5.37 0.19 1]disp(\"Matrix :\");disp(A); % Variance of matrix AC = cov(A,'includenan');disp(\"Variance matrix including NaN:\");disp(C); % Variance of matrix AC = cov(A,'omitrows');disp(\"Variance matrix omitting NaN:\");disp(C);",
"e": 27364,
"s": 27077,
"text": null
},
{
"code": null,
"e": 27376,
"s": 27367,
"text": "Output :"
},
{
"code": null,
"e": 27395,
"s": 27380,
"text": "varshagumber28"
},
{
"code": null,
"e": 27408,
"s": 27395,
"text": "singghakshay"
},
{
"code": null,
"e": 27421,
"s": 27408,
"text": "MATLAB-Maths"
},
{
"code": null,
"e": 27428,
"s": 27421,
"text": "Picked"
},
{
"code": null,
"e": 27435,
"s": 27428,
"text": "MATLAB"
},
{
"code": null,
"e": 27533,
"s": 27435,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27542,
"s": 27533,
"text": "Comments"
},
{
"code": null,
"e": 27555,
"s": 27542,
"text": "Old Comments"
},
{
"code": null,
"e": 27628,
"s": 27555,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 27666,
"s": 27628,
"text": "Differential or Derivatives in MATLAB"
},
{
"code": null,
"e": 27726,
"s": 27666,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 27765,
"s": 27726,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 27807,
"s": 27765,
"text": "Boundary Extraction of image using MATLAB"
},
{
"code": null,
"e": 27872,
"s": 27807,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 27924,
"s": 27872,
"text": "How to Apply Median Filter For RGB Image in MATLAB?"
},
{
"code": null,
"e": 27964,
"s": 27924,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 27992,
"s": 27964,
"text": "Laplace Transform in MATLAB"
}
] |
How to use typeof with arguments in JavaScript?
|
Arguments object is the arguments passed to a function. It is a variable accessible for all functions. Letβs say two arguments are passed to a function, then you can access them like the following:
arguments[0]
arguments[1]
In the same way, you can use a type of with arguments in JavaScript. Firstly, letβs see how to work with the type of. The type of operator is a unary operator that is placed before its single operand, which can be of any type.
The following code shows how to implement type of operator
Live Demo
<html>
<body>
<script>
var a = 20;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
</script>
</body>
</html>
Let us now see how to use typeof with arguments in JavaScript. The typeof arguments will return an object like this:
document.write(typeof arguments);
Letβs say you have two arguments, then with typeof, you can refer them like the following, which will return the typeof arguments.
document.write(typeof arguments[0]);
document.write(typeof arguments[1]);
|
[
{
"code": null,
"e": 1260,
"s": 1062,
"text": "Arguments object is the arguments passed to a function. It is a variable accessible for all functions. Letβs say two arguments are passed to a function, then you can access them like the following:"
},
{
"code": null,
"e": 1286,
"s": 1260,
"text": "arguments[0]\narguments[1]"
},
{
"code": null,
"e": 1514,
"s": 1286,
"text": "In the same way, you can use a type of with arguments in JavaScript. Firstly, letβs see how to work with the type of. The type of operator is a unary operator that is placed before its single operand, which can be of any type. "
},
{
"code": null,
"e": 1573,
"s": 1514,
"text": "The following code shows how to implement type of operator"
},
{
"code": null,
"e": 1583,
"s": 1573,
"text": "Live Demo"
},
{
"code": null,
"e": 2101,
"s": 1583,
"text": "<html>\n <body>\n <script>\n var a = 20;\n var b = \"String\";\n var linebreak = \"<br />\";\n\n result = (typeof b == \"string\" ? \"B is String\" : \"B is Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n\n result = (typeof a == \"string\" ? \"A is String\" : \"A is Numeric\");\n document.write(\"Result => \");\n document.write(result);\n document.write(linebreak);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 2218,
"s": 2101,
"text": "Let us now see how to use typeof with arguments in JavaScript. The typeof arguments will return an object like this:"
},
{
"code": null,
"e": 2252,
"s": 2218,
"text": "document.write(typeof arguments);"
},
{
"code": null,
"e": 2383,
"s": 2252,
"text": "Letβs say you have two arguments, then with typeof, you can refer them like the following, which will return the typeof arguments."
},
{
"code": null,
"e": 2457,
"s": 2383,
"text": "document.write(typeof arguments[0]);\ndocument.write(typeof arguments[1]);"
}
] |
Dashboard Tutorial (II): HTML, CSS, PHP, and Heroku | by Denise Chen | Towards Data Science
|
The layout of a webpage often comes as an element to display the content through the CSS Selectors. Through CSS, you can determine text color, content display, and webpage background and image. When it comes to deploying the web page on the server, Heroku is often the common deployment platform. In the Heroku platform, it can host the website for free, manage several app folders, and easily work with the terminal. For this blog, weβll walk through the CSS Selector of web layout, file structure, and web deployment to Heroku.
In this article, you will learn to create a basic dashboard and deployment on Heroku server:
(1) Introduction to CSS layout
(2) Folder Structure of HTML, Javascript, and CSS files
(3) Deployment to Heroku
CSS is a stylesheet language to decorate the webpages. CSS enables the webpage to display customized presentations with layout on blocks, margin, padding, fonts, etc. In this tutorial, weβll dive in on the layout of Chart.JS plots with navbar.
CSS Grid is a two-dimensional element with horizontal and vertical lines β one set defining columns, and the other, rows.
First, we create a grid container
A grid container is created by declaring display: grid or display: inline-grid. All direct children of that element become grid items. From the example below, there are 4 separate charts created with canvas tags along with h3 as the plotsβ description. These 4 plots are wrapped within <div> elements of the class wrapper, and these children elements become grid items.
<div class="wrapper"><div><h3>Bar Chart of COVID active cases count in June</h3><canvas id="myChart" width="500" height="300"></canvas></div><div><h3>Line Chart of COVID cumulative cases in Canada</h3><canvas id="myChart1" width="500" height="300"></canvas></div><div><h3>Doughnut Chart of cumulative COVID cases count in Canada</h3><canvas id="myChart2" width="500" height="300"></canvas></div><div><h3>Bar Line Chart of COVID cases in Canada</h3><canvas id="myChart3" width="500" height="300"></canvas></div></div>
The example below shows the creation of a wrapperβs selector for the grid container. Next, we define grid tracks which are the space of 2 lines shown within the grid. In grid container, grid-template-columns and grid-template-rows are used to define the rows and columns. Property of grid-template-columns can define the size of the column tracks. Grid-template-columns is set to be an 800-pixel-wide column track. Also, I created both a 50-pixel gap on rows and columns.
.wrapper {display: grid;grid-template-columns: 800px 800px;column-gap: 50px;row-gap: 50px;}
The example below shows the method of embedding on the CSS file. Both external and internal CSS source shall be included in <link> element, and the <link> element needs to be placed between the <head> and </head> tags. Therefore, the HTML webpage would be linked to the stylesheet from the <link> element.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"><link rel="stylesheet" href="../static/styles/style.css">
For the dashboard, there are several different files like the dataset CSV files, plots javascript files, stylesheets CSS files, and webpages HTML files. Itβs better to store different files in each folder under the project main directory. Typically, thereβs a static folder to store all sorts of files in the subdirectory. For example, all my datasets are stored in the file folder, js files in the js folder, CSS files in the styles folder, and the HTML files in the template folder.
Below, it shows the ChartJS plots being created in the HTML file with the canvas id of βmyChartβ.
<div><h3>Bar Chart of COVID active cases count in June </h3><canvas id="myChart" width="500" height="300"></canvas></div>
In the Javascript file, weβll render the plot by calling the βmyChartβ id by using document.getElementById() function call .
var ctx = document.getElementById("myChart");
In the html file, we can call the Javascript file by using the <script> element. The directory is specified in the src parameter call. Besides, <script> elements are included within <body> and </body> tags.
<script src="../static/js/bar.js"></script><script src="../static/js/line_chart.js"></script><script src="../static/js/donut.js"></script><script src="../static/js/line_bar.js"></script>
Now, we dig into the fonts and text of CSS selection. We define the fonts for text by using the property font-family. The text alignment is specified as the center with text-align: center. Itβs also an option to specify the font-size as font-size: 10px;for the webpage. In terms of the margin, it shows the space around the text. With margin: 0 0 0.1em, the text is displayed with the upper, down, left, and right margin followed by the sequence. Since <body> is the parent element of the content page, all elements inside it inherit the same text-align and font-family.
body {font-family: Helvetica Neue, Arial, sans-serif;text-align: center;font-size: 10px;margin: 0 0 0.1em 0;color: rgb(89, 112, 240);}
Next, we work on the block concept in the CSS selector. In the HTML file, we use<a> the tag to define a hyperlink, which is used to link from one page to another. In the CSS file, the block element can have margin and other spacing values applied to it. However, <a> tag is an inline element with no margin value on it. To apply margins to the hyperlink tag, we need to add display parameter display: block;.Then, we can give margin value on top by margin-top: 50px;
a {margin-top: 50px;display: block;color: #3e95cd;}
To deploy the dashboard on a web server instead of a local host on your machine, Heroku is often a popular option for the deployment. From Heroku, it supports Ruby, Node.js, Clojure, Python, Java, Gradle, Grails, Scala, Play, PHP, Go. However, the programming languages are not offered for the typical HTML, CSS, Javascript languages. The good solution is to build a PHP app for the web page. Iβll walk you through the steps of Heroku setup, git set up, PHP file creation, and the project deployment to the Heroku platform. And tada, the project is displayed with an HTML link which is sharable for the external visit.
(1) Sign up an account and get Heroku installed. (link1, link2)
(2) In the terminal, type Heroku login with the required credentials.
(3) Initialize a local Git repository and commit your application code.In the terminal, type in the command line listed below
cd your_projectgit config --global user.email βyou@example.comβgit config --global user.name "Your Name"
(4) Prepare the PHP file to render the HTML pages. Head to the root directory of your project that contains index.html
(5) In this directory, run touch composer.json to create a file: composer.json. In the JSON file, add {}.
(6) In the same directory, run touch index.php to create a file: index.php. In the PHP file, add <?php include_once("index.html"); ?>
(7) In the terminal, we initialize the git repository and push the project folder to the Heroku server for deployment. In the terminal, type in the command line listed below
cd your_project# Create a local git repositorygit init # Add all your local files to repositorygit add .# Commit your filesgit commit βm βFirst commitβ# Create an empty Heroku app, make sure the app name is unique with your own creationheroku create php-dashboard-tutorial # push our application to Herokugit push heroku master# check one instance of the app is runningheroku ps:scale web=1
(8) The magic happens. Now, your dashboard is successfully deployed to the Heroku server and can be visited with an external web link.
CSS selector can be used to style the HTML tag elements defined with the class. Grid container can display column and row like layout for the web page items. <link> element is used to embed the internal and external CSS stylesheet in the HTML web file.
Itβs better to store different files in a specific folder under the static directory. In the HTML file, we can call the Javascript file by using the <script> element. CSS files selectors can set the text and fonts display through the parameter call. In the stylesheet, the block element can be applied for an inline element to give margin and other spacing values.
Heroku is served as a web server platform that supports Ruby, Node.js, Clojure, Python, Java, Gradle, Grails, Scala, Play, PHP, Go. As an alternative, the dashboard with HTML, CSS, Javascript can work for Heroku deployment with an additional PHP file. Besides, Heroku is required with a git repository to push the project folder to the webserver.
My simple COVID Dashboard link: https://dd-dashboard-3.herokuapp.com/
Hopefully, you get a dashboard created from the tutorial!
CSS basics: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics
CSS basics: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics
2. Basic Concepts of grid layout: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout
3. Deploying your Python web application to the Heroku cloud: https://pythonhow.com/deploying-your-web-application-to-the-cloud/
4. How to Run a Simple HTML/CSS/Javascript Application on Heroku: https://medium.com/@winnieliang/how-to-run-a-simple-html-css-javascript-application-on-heroku-4e664c541b0b
5. Heroku Deploying with Git: https://devcenter.heroku.com/articles/git
|
[
{
"code": null,
"e": 702,
"s": 172,
"text": "The layout of a webpage often comes as an element to display the content through the CSS Selectors. Through CSS, you can determine text color, content display, and webpage background and image. When it comes to deploying the web page on the server, Heroku is often the common deployment platform. In the Heroku platform, it can host the website for free, manage several app folders, and easily work with the terminal. For this blog, weβll walk through the CSS Selector of web layout, file structure, and web deployment to Heroku."
},
{
"code": null,
"e": 795,
"s": 702,
"text": "In this article, you will learn to create a basic dashboard and deployment on Heroku server:"
},
{
"code": null,
"e": 826,
"s": 795,
"text": "(1) Introduction to CSS layout"
},
{
"code": null,
"e": 882,
"s": 826,
"text": "(2) Folder Structure of HTML, Javascript, and CSS files"
},
{
"code": null,
"e": 907,
"s": 882,
"text": "(3) Deployment to Heroku"
},
{
"code": null,
"e": 1151,
"s": 907,
"text": "CSS is a stylesheet language to decorate the webpages. CSS enables the webpage to display customized presentations with layout on blocks, margin, padding, fonts, etc. In this tutorial, weβll dive in on the layout of Chart.JS plots with navbar."
},
{
"code": null,
"e": 1273,
"s": 1151,
"text": "CSS Grid is a two-dimensional element with horizontal and vertical lines β one set defining columns, and the other, rows."
},
{
"code": null,
"e": 1307,
"s": 1273,
"text": "First, we create a grid container"
},
{
"code": null,
"e": 1677,
"s": 1307,
"text": "A grid container is created by declaring display: grid or display: inline-grid. All direct children of that element become grid items. From the example below, there are 4 separate charts created with canvas tags along with h3 as the plotsβ description. These 4 plots are wrapped within <div> elements of the class wrapper, and these children elements become grid items."
},
{
"code": null,
"e": 2194,
"s": 1677,
"text": "<div class=\"wrapper\"><div><h3>Bar Chart of COVID active cases count in June</h3><canvas id=\"myChart\" width=\"500\" height=\"300\"></canvas></div><div><h3>Line Chart of COVID cumulative cases in Canada</h3><canvas id=\"myChart1\" width=\"500\" height=\"300\"></canvas></div><div><h3>Doughnut Chart of cumulative COVID cases count in Canada</h3><canvas id=\"myChart2\" width=\"500\" height=\"300\"></canvas></div><div><h3>Bar Line Chart of COVID cases in Canada</h3><canvas id=\"myChart3\" width=\"500\" height=\"300\"></canvas></div></div>"
},
{
"code": null,
"e": 2666,
"s": 2194,
"text": "The example below shows the creation of a wrapperβs selector for the grid container. Next, we define grid tracks which are the space of 2 lines shown within the grid. In grid container, grid-template-columns and grid-template-rows are used to define the rows and columns. Property of grid-template-columns can define the size of the column tracks. Grid-template-columns is set to be an 800-pixel-wide column track. Also, I created both a 50-pixel gap on rows and columns."
},
{
"code": null,
"e": 2758,
"s": 2666,
"text": ".wrapper {display: grid;grid-template-columns: 800px 800px;column-gap: 50px;row-gap: 50px;}"
},
{
"code": null,
"e": 3064,
"s": 2758,
"text": "The example below shows the method of embedding on the CSS file. Both external and internal CSS source shall be included in <link> element, and the <link> element needs to be placed between the <head> and </head> tags. Therefore, the HTML webpage would be linked to the stylesheet from the <link> element."
},
{
"code": null,
"e": 3333,
"s": 3064,
"text": "<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"><link rel=\"stylesheet\" href=\"../static/styles/style.css\">"
},
{
"code": null,
"e": 3818,
"s": 3333,
"text": "For the dashboard, there are several different files like the dataset CSV files, plots javascript files, stylesheets CSS files, and webpages HTML files. Itβs better to store different files in each folder under the project main directory. Typically, thereβs a static folder to store all sorts of files in the subdirectory. For example, all my datasets are stored in the file folder, js files in the js folder, CSS files in the styles folder, and the HTML files in the template folder."
},
{
"code": null,
"e": 3916,
"s": 3818,
"text": "Below, it shows the ChartJS plots being created in the HTML file with the canvas id of βmyChartβ."
},
{
"code": null,
"e": 4038,
"s": 3916,
"text": "<div><h3>Bar Chart of COVID active cases count in June </h3><canvas id=\"myChart\" width=\"500\" height=\"300\"></canvas></div>"
},
{
"code": null,
"e": 4163,
"s": 4038,
"text": "In the Javascript file, weβll render the plot by calling the βmyChartβ id by using document.getElementById() function call ."
},
{
"code": null,
"e": 4209,
"s": 4163,
"text": "var ctx = document.getElementById(\"myChart\");"
},
{
"code": null,
"e": 4416,
"s": 4209,
"text": "In the html file, we can call the Javascript file by using the <script> element. The directory is specified in the src parameter call. Besides, <script> elements are included within <body> and </body> tags."
},
{
"code": null,
"e": 4603,
"s": 4416,
"text": "<script src=\"../static/js/bar.js\"></script><script src=\"../static/js/line_chart.js\"></script><script src=\"../static/js/donut.js\"></script><script src=\"../static/js/line_bar.js\"></script>"
},
{
"code": null,
"e": 5174,
"s": 4603,
"text": "Now, we dig into the fonts and text of CSS selection. We define the fonts for text by using the property font-family. The text alignment is specified as the center with text-align: center. Itβs also an option to specify the font-size as font-size: 10px;for the webpage. In terms of the margin, it shows the space around the text. With margin: 0 0 0.1em, the text is displayed with the upper, down, left, and right margin followed by the sequence. Since <body> is the parent element of the content page, all elements inside it inherit the same text-align and font-family."
},
{
"code": null,
"e": 5309,
"s": 5174,
"text": "body {font-family: Helvetica Neue, Arial, sans-serif;text-align: center;font-size: 10px;margin: 0 0 0.1em 0;color: rgb(89, 112, 240);}"
},
{
"code": null,
"e": 5776,
"s": 5309,
"text": "Next, we work on the block concept in the CSS selector. In the HTML file, we use<a> the tag to define a hyperlink, which is used to link from one page to another. In the CSS file, the block element can have margin and other spacing values applied to it. However, <a> tag is an inline element with no margin value on it. To apply margins to the hyperlink tag, we need to add display parameter display: block;.Then, we can give margin value on top by margin-top: 50px;"
},
{
"code": null,
"e": 5828,
"s": 5776,
"text": "a {margin-top: 50px;display: block;color: #3e95cd;}"
},
{
"code": null,
"e": 6447,
"s": 5828,
"text": "To deploy the dashboard on a web server instead of a local host on your machine, Heroku is often a popular option for the deployment. From Heroku, it supports Ruby, Node.js, Clojure, Python, Java, Gradle, Grails, Scala, Play, PHP, Go. However, the programming languages are not offered for the typical HTML, CSS, Javascript languages. The good solution is to build a PHP app for the web page. Iβll walk you through the steps of Heroku setup, git set up, PHP file creation, and the project deployment to the Heroku platform. And tada, the project is displayed with an HTML link which is sharable for the external visit."
},
{
"code": null,
"e": 6511,
"s": 6447,
"text": "(1) Sign up an account and get Heroku installed. (link1, link2)"
},
{
"code": null,
"e": 6581,
"s": 6511,
"text": "(2) In the terminal, type Heroku login with the required credentials."
},
{
"code": null,
"e": 6707,
"s": 6581,
"text": "(3) Initialize a local Git repository and commit your application code.In the terminal, type in the command line listed below"
},
{
"code": null,
"e": 6812,
"s": 6707,
"text": "cd your_projectgit config --global user.email βyou@example.comβgit config --global user.name \"Your Name\""
},
{
"code": null,
"e": 6931,
"s": 6812,
"text": "(4) Prepare the PHP file to render the HTML pages. Head to the root directory of your project that contains index.html"
},
{
"code": null,
"e": 7037,
"s": 6931,
"text": "(5) In this directory, run touch composer.json to create a file: composer.json. In the JSON file, add {}."
},
{
"code": null,
"e": 7171,
"s": 7037,
"text": "(6) In the same directory, run touch index.php to create a file: index.php. In the PHP file, add <?php include_once(\"index.html\"); ?>"
},
{
"code": null,
"e": 7345,
"s": 7171,
"text": "(7) In the terminal, we initialize the git repository and push the project folder to the Heroku server for deployment. In the terminal, type in the command line listed below"
},
{
"code": null,
"e": 7736,
"s": 7345,
"text": "cd your_project# Create a local git repositorygit init # Add all your local files to repositorygit add .# Commit your filesgit commit βm βFirst commitβ# Create an empty Heroku app, make sure the app name is unique with your own creationheroku create php-dashboard-tutorial # push our application to Herokugit push heroku master# check one instance of the app is runningheroku ps:scale web=1"
},
{
"code": null,
"e": 7871,
"s": 7736,
"text": "(8) The magic happens. Now, your dashboard is successfully deployed to the Heroku server and can be visited with an external web link."
},
{
"code": null,
"e": 8124,
"s": 7871,
"text": "CSS selector can be used to style the HTML tag elements defined with the class. Grid container can display column and row like layout for the web page items. <link> element is used to embed the internal and external CSS stylesheet in the HTML web file."
},
{
"code": null,
"e": 8489,
"s": 8124,
"text": "Itβs better to store different files in a specific folder under the static directory. In the HTML file, we can call the Javascript file by using the <script> element. CSS files selectors can set the text and fonts display through the parameter call. In the stylesheet, the block element can be applied for an inline element to give margin and other spacing values."
},
{
"code": null,
"e": 8836,
"s": 8489,
"text": "Heroku is served as a web server platform that supports Ruby, Node.js, Clojure, Python, Java, Gradle, Grails, Scala, Play, PHP, Go. As an alternative, the dashboard with HTML, CSS, Javascript can work for Heroku deployment with an additional PHP file. Besides, Heroku is required with a git repository to push the project folder to the webserver."
},
{
"code": null,
"e": 8906,
"s": 8836,
"text": "My simple COVID Dashboard link: https://dd-dashboard-3.herokuapp.com/"
},
{
"code": null,
"e": 8964,
"s": 8906,
"text": "Hopefully, you get a dashboard created from the tutorial!"
},
{
"code": null,
"e": 9063,
"s": 8964,
"text": "CSS basics: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics"
},
{
"code": null,
"e": 9162,
"s": 9063,
"text": "CSS basics: https://developer.mozilla.org/en-US/docs/Learn/Getting_started_with_the_web/CSS_basics"
},
{
"code": null,
"e": 9291,
"s": 9162,
"text": "2. Basic Concepts of grid layout: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Basic_Concepts_of_Grid_Layout"
},
{
"code": null,
"e": 9420,
"s": 9291,
"text": "3. Deploying your Python web application to the Heroku cloud: https://pythonhow.com/deploying-your-web-application-to-the-cloud/"
},
{
"code": null,
"e": 9593,
"s": 9420,
"text": "4. How to Run a Simple HTML/CSS/Javascript Application on Heroku: https://medium.com/@winnieliang/how-to-run-a-simple-html-css-javascript-application-on-heroku-4e664c541b0b"
}
] |
How to compare two arrays in C#?
|
Firstly, set the two arrays to be compared β
// two arrays
int[] arr = new int[] { 99, 87, 56, 45};
int[] brr = new int[] { 99, 87, 56, 45 };
Now, use SequenceEqual() to compare the two arrays β
arr.SequenceEqual(brr);
The following is the code to compare two arrays β
using System;
using System.Linq;
namespace Demo {
class Program {
static void Main(string[] args) {
// two arrays
int[] arr = new int[] { 99, 87, 56, 45};
int[] brr = new int[] { 99, 87, 56, 45 };
// compare
Console.WriteLine(arr.SequenceEqual(brr));
}
}
}
|
[
{
"code": null,
"e": 1107,
"s": 1062,
"text": "Firstly, set the two arrays to be compared β"
},
{
"code": null,
"e": 1204,
"s": 1107,
"text": "// two arrays\nint[] arr = new int[] { 99, 87, 56, 45};\nint[] brr = new int[] { 99, 87, 56, 45 };"
},
{
"code": null,
"e": 1257,
"s": 1204,
"text": "Now, use SequenceEqual() to compare the two arrays β"
},
{
"code": null,
"e": 1281,
"s": 1257,
"text": "arr.SequenceEqual(brr);"
},
{
"code": null,
"e": 1331,
"s": 1281,
"text": "The following is the code to compare two arrays β"
},
{
"code": null,
"e": 1655,
"s": 1331,
"text": "using System;\nusing System.Linq;\n\nnamespace Demo {\n class Program {\n\n static void Main(string[] args) {\n\n // two arrays\n int[] arr = new int[] { 99, 87, 56, 45};\n int[] brr = new int[] { 99, 87, 56, 45 };\n\n // compare\n Console.WriteLine(arr.SequenceEqual(brr));\n }\n }\n}"
}
] |
Java MD5 Encryption Example | Java MD5 Hashing Example
|
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show you how to use Java MD5 Encryption.
The below example generate a MD5 encryption (generating hash value) for a given password (String).
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class JavaMD5Example {
public static String getMD5EncryptedValue(String password) {
final byte[] defaultBytes = password.getBytes();
try {
final MessageDigest md5MsgDigest = MessageDigest.getInstance("MD5");
md5MsgDigest.reset();
md5MsgDigest.update(defaultBytes);
final byte messageDigest[] = md5MsgDigest.digest();
final StringBuffer hexString = new StringBuffer();
for (final byte element : messageDigest) {
final String hex = Integer.toHexString(0xFF & element);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
password = hexString + "";
} catch (final NoSuchAlgorithmException nsae) {
nsae.printStackTrace();
}
return password;
}
public static void main(String[] args) {
System.out.println(getMD5EncryptedValue("chandra123"));
System.out.println(getMD5EncryptedValue("chandra123"));
}
}
Output :
b4a3f7314b7b5096b920a3a8c1ef0ac2
b4a3f7314b7b5096b920a3a8c1ef0ac2
MD5 wiki
Java MessageDigest
Binary Literals Java 7 Example Tutorials
Decimal To Hex Conversion Java Program
PDFBox β How to generate Encrypted pdf in Java
Difference between b++ and b=b+1
How to push docker image to docker hub ?
increment and decrement operators in Java (In Depth)
Java Swing Login Example
Binary To Hexadecimal Conversion Java Program
C How to Pass Arrays to Functions
Java Swing JList Example
How HashMap Works In Java
Java Swing JLabel Example
Binary Search using Java
String in Switch in Java 7 Example
Underscores in Numeric Literals Java 7
Binary Literals Java 7 Example Tutorials
Decimal To Hex Conversion Java Program
PDFBox β How to generate Encrypted pdf in Java
Difference between b++ and b=b+1
How to push docker image to docker hub ?
increment and decrement operators in Java (In Depth)
Java Swing Login Example
Binary To Hexadecimal Conversion Java Program
C How to Pass Arrays to Functions
Java Swing JList Example
How HashMap Works In Java
Java Swing JLabel Example
Binary Search using Java
String in Switch in Java 7 Example
Underscores in Numeric Literals Java 7
VRadhe
February 21, 2019 at 4:04 pm - Reply
have you any tutorial for MD5 decryption ?
Meepa
August 9, 2021 at 10:14 am - Reply
Any chance to get the rainbow table generation by doing a reduction formula into the generated-hash say 4 times, and then adding the word and the last hash to a table of some sort?
Preferably a table that can print to a file in the sorted by hash value and the word it came from?
There is very little clear examples of this on the internet so youβll be the first!
VRadhe
February 21, 2019 at 4:04 pm - Reply
have you any tutorial for MD5 decryption ?
have you any tutorial for MD5 decryption ?
Meepa
August 9, 2021 at 10:14 am - Reply
Any chance to get the rainbow table generation by doing a reduction formula into the generated-hash say 4 times, and then adding the word and the last hash to a table of some sort?
Preferably a table that can print to a file in the sorted by hash value and the word it came from?
There is very little clear examples of this on the internet so youβll be the first!
Any chance to get the rainbow table generation by doing a reduction formula into the generated-hash say 4 times, and then adding the word and the last hash to a table of some sort?
Preferably a table that can print to a file in the sorted by hash value and the word it came from?
There is very little clear examples of this on the internet so youβll be the first!
Ξ
Install Java on Mac OS
Install AWS CLI on Windows
Install Minikube on Windows
Install Docker Toolbox on Windows
Install SOAPUI on Windows
Install Gradle on Windows
Install RabbitMQ on Windows
Install PuTTY on windows
Install Mysql on Windows
Install Hibernate Tools in Eclipse
Install Elasticsearch on Windows
Install Maven on Windows
Install Maven on Ubuntu
Install Maven on Windows Command
Add OJDBC jar to Maven Repository
Install Ant on Windows
Install RabbitMQ on Windows
Install Apache Kafka on Ubuntu
Install Apache Kafka on Windows
Java8 β Install Windows
Java8 β foreach
Java8 β forEach with index
Java8 β Stream Filter Objects
Java8 β Comparator Userdefined
Java8 β GroupingBy
Java8 β SummingInt
Java8 β walk ReadFiles
Java8 β JAVA_HOME on Windows
Howto β Install Java on Mac OS
Howto β Convert Iterable to Stream
Howto β Get common elements from two Lists
Howto β Convert List to String
Howto β Concatenate Arrays using Stream
Howto β Remove duplicates from List
Howto β Filter null values from Stream
Howto β Convert List to Map
Howto β Convert Stream to List
Howto β Sort a Map
Howto β Filter a Map
Howto β Get Current UTC Time
Howto β Verify an Array contains a specific value
Howto β Convert ArrayList to Array
Howto β Read File Line By Line
Howto β Convert Date to LocalDate
Howto β Merge Streams
Howto β Resolve NullPointerException in toMap
Howto -Get Stream count
Howto β Get Min and Max values in a Stream
Howto β Convert InputStream to String
|
[
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 471,
"s": 398,
"text": "In this tutorial, I am going to show you how to use Java MD5 Encryption."
},
{
"code": null,
"e": 570,
"s": 471,
"text": "The below example generate a MD5 encryption (generating hash value) for a given password (String)."
},
{
"code": null,
"e": 1748,
"s": 570,
"text": "import java.security.MessageDigest;\nimport java.security.NoSuchAlgorithmException;\n\npublic class JavaMD5Example {\n\n public static String getMD5EncryptedValue(String password) {\n final byte[] defaultBytes = password.getBytes();\n try {\n final MessageDigest md5MsgDigest = MessageDigest.getInstance(\"MD5\");\n md5MsgDigest.reset();\n md5MsgDigest.update(defaultBytes);\n final byte messageDigest[] = md5MsgDigest.digest();\n\n final StringBuffer hexString = new StringBuffer();\n for (final byte element : messageDigest) {\n final String hex = Integer.toHexString(0xFF & element);\n if (hex.length() == 1) {\n hexString.append('0');\n }\n hexString.append(hex);\n }\n password = hexString + \"\";\n } catch (final NoSuchAlgorithmException nsae) {\n nsae.printStackTrace();\n }\n return password;\n }\n\n public static void main(String[] args) {\n System.out.println(getMD5EncryptedValue(\"chandra123\"));\n System.out.println(getMD5EncryptedValue(\"chandra123\"));\n }\n\n}"
},
{
"code": null,
"e": 1757,
"s": 1748,
"text": "Output :"
},
{
"code": null,
"e": 1823,
"s": 1757,
"text": "b4a3f7314b7b5096b920a3a8c1ef0ac2\nb4a3f7314b7b5096b920a3a8c1ef0ac2"
},
{
"code": null,
"e": 1832,
"s": 1823,
"text": "MD5 wiki"
},
{
"code": null,
"e": 1851,
"s": 1832,
"text": "Java MessageDigest"
},
{
"code": null,
"e": 2388,
"s": 1851,
"text": "\nBinary Literals Java 7 Example Tutorials\nDecimal To Hex Conversion Java Program\nPDFBox β How to generate Encrypted pdf in Java\nDifference between b++ and b=b+1\nHow to push docker image to docker hub ?\nincrement and decrement operators in Java (In Depth)\nJava Swing Login Example\nBinary To Hexadecimal Conversion Java Program\nC How to Pass Arrays to Functions\nJava Swing JList Example\nHow HashMap Works In Java\nJava Swing JLabel Example\nBinary Search using Java\nString in Switch in Java 7 Example\nUnderscores in Numeric Literals Java 7\n"
},
{
"code": null,
"e": 2429,
"s": 2388,
"text": "Binary Literals Java 7 Example Tutorials"
},
{
"code": null,
"e": 2468,
"s": 2429,
"text": "Decimal To Hex Conversion Java Program"
},
{
"code": null,
"e": 2515,
"s": 2468,
"text": "PDFBox β How to generate Encrypted pdf in Java"
},
{
"code": null,
"e": 2548,
"s": 2515,
"text": "Difference between b++ and b=b+1"
},
{
"code": null,
"e": 2589,
"s": 2548,
"text": "How to push docker image to docker hub ?"
},
{
"code": null,
"e": 2642,
"s": 2589,
"text": "increment and decrement operators in Java (In Depth)"
},
{
"code": null,
"e": 2667,
"s": 2642,
"text": "Java Swing Login Example"
},
{
"code": null,
"e": 2713,
"s": 2667,
"text": "Binary To Hexadecimal Conversion Java Program"
},
{
"code": null,
"e": 2747,
"s": 2713,
"text": "C How to Pass Arrays to Functions"
},
{
"code": null,
"e": 2772,
"s": 2747,
"text": "Java Swing JList Example"
},
{
"code": null,
"e": 2798,
"s": 2772,
"text": "How HashMap Works In Java"
},
{
"code": null,
"e": 2824,
"s": 2798,
"text": "Java Swing JLabel Example"
},
{
"code": null,
"e": 2849,
"s": 2824,
"text": "Binary Search using Java"
},
{
"code": null,
"e": 2884,
"s": 2849,
"text": "String in Switch in Java 7 Example"
},
{
"code": null,
"e": 2923,
"s": 2884,
"text": "Underscores in Numeric Literals Java 7"
},
{
"code": null,
"e": 3440,
"s": 2923,
"text": "\n\n\n\n\n\nVRadhe\nFebruary 21, 2019 at 4:04 pm - Reply \n\nhave you any tutorial for MD5 decryption ?\n\n\n\n\n\n\n\n\n\nMeepa\nAugust 9, 2021 at 10:14 am - Reply \n\nAny chance to get the rainbow table generation by doing a reduction formula into the generated-hash say 4 times, and then adding the word and the last hash to a table of some sort?\nPreferably a table that can print to a file in the sorted by hash value and the word it came from?\nThere is very little clear examples of this on the internet so youβll be the first!\n\n\n\n\n"
},
{
"code": null,
"e": 3539,
"s": 3440,
"text": "\n\n\n\n\nVRadhe\nFebruary 21, 2019 at 4:04 pm - Reply \n\nhave you any tutorial for MD5 decryption ?\n\n\n\n"
},
{
"code": null,
"e": 3583,
"s": 3539,
"text": "have you any tutorial for MD5 decryption ?"
},
{
"code": null,
"e": 3999,
"s": 3583,
"text": "\n\n\n\n\nMeepa\nAugust 9, 2021 at 10:14 am - Reply \n\nAny chance to get the rainbow table generation by doing a reduction formula into the generated-hash say 4 times, and then adding the word and the last hash to a table of some sort?\nPreferably a table that can print to a file in the sorted by hash value and the word it came from?\nThere is very little clear examples of this on the internet so youβll be the first!\n\n\n\n"
},
{
"code": null,
"e": 4279,
"s": 3999,
"text": "Any chance to get the rainbow table generation by doing a reduction formula into the generated-hash say 4 times, and then adding the word and the last hash to a table of some sort?\nPreferably a table that can print to a file in the sorted by hash value and the word it came from?"
},
{
"code": null,
"e": 4363,
"s": 4279,
"text": "There is very little clear examples of this on the internet so youβll be the first!"
},
{
"code": null,
"e": 4369,
"s": 4367,
"text": "Ξ"
},
{
"code": null,
"e": 4393,
"s": 4369,
"text": " Install Java on Mac OS"
},
{
"code": null,
"e": 4421,
"s": 4393,
"text": " Install AWS CLI on Windows"
},
{
"code": null,
"e": 4450,
"s": 4421,
"text": " Install Minikube on Windows"
},
{
"code": null,
"e": 4485,
"s": 4450,
"text": " Install Docker Toolbox on Windows"
},
{
"code": null,
"e": 4512,
"s": 4485,
"text": " Install SOAPUI on Windows"
},
{
"code": null,
"e": 4539,
"s": 4512,
"text": " Install Gradle on Windows"
},
{
"code": null,
"e": 4568,
"s": 4539,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 4594,
"s": 4568,
"text": " Install PuTTY on windows"
},
{
"code": null,
"e": 4620,
"s": 4594,
"text": " Install Mysql on Windows"
},
{
"code": null,
"e": 4656,
"s": 4620,
"text": " Install Hibernate Tools in Eclipse"
},
{
"code": null,
"e": 4690,
"s": 4656,
"text": " Install Elasticsearch on Windows"
},
{
"code": null,
"e": 4716,
"s": 4690,
"text": " Install Maven on Windows"
},
{
"code": null,
"e": 4741,
"s": 4716,
"text": " Install Maven on Ubuntu"
},
{
"code": null,
"e": 4775,
"s": 4741,
"text": " Install Maven on Windows Command"
},
{
"code": null,
"e": 4810,
"s": 4775,
"text": " Add OJDBC jar to Maven Repository"
},
{
"code": null,
"e": 4834,
"s": 4810,
"text": " Install Ant on Windows"
},
{
"code": null,
"e": 4863,
"s": 4834,
"text": " Install RabbitMQ on Windows"
},
{
"code": null,
"e": 4895,
"s": 4863,
"text": " Install Apache Kafka on Ubuntu"
},
{
"code": null,
"e": 4928,
"s": 4895,
"text": " Install Apache Kafka on Windows"
},
{
"code": null,
"e": 4953,
"s": 4928,
"text": " Java8 β Install Windows"
},
{
"code": null,
"e": 4970,
"s": 4953,
"text": " Java8 β foreach"
},
{
"code": null,
"e": 4998,
"s": 4970,
"text": " Java8 β forEach with index"
},
{
"code": null,
"e": 5029,
"s": 4998,
"text": " Java8 β Stream Filter Objects"
},
{
"code": null,
"e": 5061,
"s": 5029,
"text": " Java8 β Comparator Userdefined"
},
{
"code": null,
"e": 5081,
"s": 5061,
"text": " Java8 β GroupingBy"
},
{
"code": null,
"e": 5101,
"s": 5081,
"text": " Java8 β SummingInt"
},
{
"code": null,
"e": 5125,
"s": 5101,
"text": " Java8 β walk ReadFiles"
},
{
"code": null,
"e": 5155,
"s": 5125,
"text": " Java8 β JAVA_HOME on Windows"
},
{
"code": null,
"e": 5187,
"s": 5155,
"text": " Howto β Install Java on Mac OS"
},
{
"code": null,
"e": 5223,
"s": 5187,
"text": " Howto β Convert Iterable to Stream"
},
{
"code": null,
"e": 5267,
"s": 5223,
"text": " Howto β Get common elements from two Lists"
},
{
"code": null,
"e": 5299,
"s": 5267,
"text": " Howto β Convert List to String"
},
{
"code": null,
"e": 5340,
"s": 5299,
"text": " Howto β Concatenate Arrays using Stream"
},
{
"code": null,
"e": 5377,
"s": 5340,
"text": " Howto β Remove duplicates from List"
},
{
"code": null,
"e": 5417,
"s": 5377,
"text": " Howto β Filter null values from Stream"
},
{
"code": null,
"e": 5446,
"s": 5417,
"text": " Howto β Convert List to Map"
},
{
"code": null,
"e": 5478,
"s": 5446,
"text": " Howto β Convert Stream to List"
},
{
"code": null,
"e": 5498,
"s": 5478,
"text": " Howto β Sort a Map"
},
{
"code": null,
"e": 5520,
"s": 5498,
"text": " Howto β Filter a Map"
},
{
"code": null,
"e": 5550,
"s": 5520,
"text": " Howto β Get Current UTC Time"
},
{
"code": null,
"e": 5601,
"s": 5550,
"text": " Howto β Verify an Array contains a specific value"
},
{
"code": null,
"e": 5637,
"s": 5601,
"text": " Howto β Convert ArrayList to Array"
},
{
"code": null,
"e": 5669,
"s": 5637,
"text": " Howto β Read File Line By Line"
},
{
"code": null,
"e": 5704,
"s": 5669,
"text": " Howto β Convert Date to LocalDate"
},
{
"code": null,
"e": 5727,
"s": 5704,
"text": " Howto β Merge Streams"
},
{
"code": null,
"e": 5774,
"s": 5727,
"text": " Howto β Resolve NullPointerException in toMap"
},
{
"code": null,
"e": 5799,
"s": 5774,
"text": " Howto -Get Stream count"
},
{
"code": null,
"e": 5843,
"s": 5799,
"text": " Howto β Get Min and Max values in a Stream"
}
] |
java.time.LocalDate.minusMonths() Method Example
|
The java.time.LocalDate.minusMonths(long monthsToSubtract) method returns a copy of this date with the specified months subtracted.
Following is the declaration for java.time.LocalDate.minusMonths(long monthsToSubtract) method.
public LocalDate minusMonths(long monthsToSubtract)
monthsToSubtract β the months to subtract, may be negative.
a LocalDate based on this date with the months subtracted, not null.
DateTimeException β if the result exceeds the supported date range.
The following example shows the usage of java.time.LocalDate.minusMonths(long monthsToSubtract) method.
package com.tutorialspoint;
import java.time.LocalDate;
public class LocalDateDemo {
public static void main(String[] args) {
LocalDate date = LocalDate.parse("2017-02-03");
System.out.println(date.minusMonths(2));
}
}
Let us compile and run the above program, this will produce the following result β
2016-12-03
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2047,
"s": 1915,
"text": "The java.time.LocalDate.minusMonths(long monthsToSubtract) method returns a copy of this date with the specified months subtracted."
},
{
"code": null,
"e": 2143,
"s": 2047,
"text": "Following is the declaration for java.time.LocalDate.minusMonths(long monthsToSubtract) method."
},
{
"code": null,
"e": 2196,
"s": 2143,
"text": "public LocalDate minusMonths(long monthsToSubtract)\n"
},
{
"code": null,
"e": 2256,
"s": 2196,
"text": "monthsToSubtract β the months to subtract, may be negative."
},
{
"code": null,
"e": 2325,
"s": 2256,
"text": "a LocalDate based on this date with the months subtracted, not null."
},
{
"code": null,
"e": 2393,
"s": 2325,
"text": "DateTimeException β if the result exceeds the supported date range."
},
{
"code": null,
"e": 2497,
"s": 2393,
"text": "The following example shows the usage of java.time.LocalDate.minusMonths(long monthsToSubtract) method."
},
{
"code": null,
"e": 2742,
"s": 2497,
"text": "package com.tutorialspoint;\n\nimport java.time.LocalDate;\n\npublic class LocalDateDemo {\n public static void main(String[] args) {\n\t \n LocalDate date = LocalDate.parse(\"2017-02-03\");\n System.out.println(date.minusMonths(2)); \n }\n}"
},
{
"code": null,
"e": 2825,
"s": 2742,
"text": "Let us compile and run the above program, this will produce the following result β"
},
{
"code": null,
"e": 2837,
"s": 2825,
"text": "2016-12-03\n"
},
{
"code": null,
"e": 2844,
"s": 2837,
"text": " Print"
},
{
"code": null,
"e": 2855,
"s": 2844,
"text": " Add Notes"
}
] |
Async/Await Function in JavaScript - GeeksforGeeks
|
02 Dec, 2021
We all know that Javascript is a Synchronous which means that it has an event loop that allows you to queue up an action that wonβt take place until the loop is available sometime after the code that queued the action has finished executing. But thereβs a lot of functionalities in our program which makes our code Asynchronous. One of them is the Async/Await functionality.
Async/Await is the extension of promises which we get as a support in the language. You can refer Promises in Javascript to know more about it.
Async:It simply allows us to write promises based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event-loop. Async functions will always return a value. It makes sure that a promise is returned and if it is not returned then javascript automatically wraps it in a promise which is resolved with its value.
Examples:
const getData = async() => { var data = "Hello World"; return data;} getData().then(data => console.log(data));
Output:
Hello World
Await:Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It only makes the async block wait.
const getData = async() => { var y = await "Hello World"; console.log(y);} console.log(1);getData();console.log(2);
Output:
1
2
Hello World
Notice that the console prints 2 before the βHello Worldβ. This is due to the usage of the await keyword.
Supported Browsers: The browsers supported by Async/Await Function are listed below:
Google Chrome 55 and above
Firefox 52 and above
Apple Safari 10.1 and above
Opera 42 and above
Edge 14 and above
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
How to Open URL in New Tab using JavaScript ?
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": 23905,
"s": 23877,
"text": "\n02 Dec, 2021"
},
{
"code": null,
"e": 24280,
"s": 23905,
"text": "We all know that Javascript is a Synchronous which means that it has an event loop that allows you to queue up an action that wonβt take place until the loop is available sometime after the code that queued the action has finished executing. But thereβs a lot of functionalities in our program which makes our code Asynchronous. One of them is the Async/Await functionality."
},
{
"code": null,
"e": 24424,
"s": 24280,
"text": "Async/Await is the extension of promises which we get as a support in the language. You can refer Promises in Javascript to know more about it."
},
{
"code": null,
"e": 24809,
"s": 24424,
"text": "Async:It simply allows us to write promises based code as if it was synchronous and it checks that we are not breaking the execution thread. It operates asynchronously via the event-loop. Async functions will always return a value. It makes sure that a promise is returned and if it is not returned then javascript automatically wraps it in a promise which is resolved with its value."
},
{
"code": null,
"e": 24819,
"s": 24809,
"text": "Examples:"
},
{
"code": "const getData = async() => { var data = \"Hello World\"; return data;} getData().then(data => console.log(data));",
"e": 24938,
"s": 24819,
"text": null
},
{
"code": null,
"e": 24946,
"s": 24938,
"text": "Output:"
},
{
"code": null,
"e": 24959,
"s": 24946,
"text": "Hello World\n"
},
{
"code": null,
"e": 25154,
"s": 24959,
"text": "Await:Await function is used to wait for the promise. It could be used within the async block only. It makes the code wait until the promise returns a result. It only makes the async block wait."
},
{
"code": "const getData = async() => { var y = await \"Hello World\"; console.log(y);} console.log(1);getData();console.log(2);",
"e": 25277,
"s": 25154,
"text": null
},
{
"code": null,
"e": 25285,
"s": 25277,
"text": "Output:"
},
{
"code": null,
"e": 25302,
"s": 25285,
"text": "1\n2\nHello World\n"
},
{
"code": null,
"e": 25408,
"s": 25302,
"text": "Notice that the console prints 2 before the βHello Worldβ. This is due to the usage of the await keyword."
},
{
"code": null,
"e": 25493,
"s": 25408,
"text": "Supported Browsers: The browsers supported by Async/Await Function are listed below:"
},
{
"code": null,
"e": 25520,
"s": 25493,
"text": "Google Chrome 55 and above"
},
{
"code": null,
"e": 25541,
"s": 25520,
"text": "Firefox 52 and above"
},
{
"code": null,
"e": 25569,
"s": 25541,
"text": "Apple Safari 10.1 and above"
},
{
"code": null,
"e": 25588,
"s": 25569,
"text": "Opera 42 and above"
},
{
"code": null,
"e": 25606,
"s": 25588,
"text": "Edge 14 and above"
},
{
"code": null,
"e": 25825,
"s": 25606,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 25837,
"s": 25825,
"text": "ysachin2314"
},
{
"code": null,
"e": 25858,
"s": 25837,
"text": "javascript-functions"
},
{
"code": null,
"e": 25869,
"s": 25858,
"text": "JavaScript"
},
{
"code": null,
"e": 25886,
"s": 25869,
"text": "Web Technologies"
},
{
"code": null,
"e": 25984,
"s": 25886,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25993,
"s": 25984,
"text": "Comments"
},
{
"code": null,
"e": 26006,
"s": 25993,
"text": "Old Comments"
},
{
"code": null,
"e": 26067,
"s": 26006,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26112,
"s": 26067,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26184,
"s": 26112,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26236,
"s": 26184,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 26282,
"s": 26236,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 26338,
"s": 26282,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 26371,
"s": 26338,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26433,
"s": 26371,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 26476,
"s": 26433,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to predict an image using CNN with Keras? | by Anh T. Dang | Towards Data Science
|
There are the following six steps to determine what object does the image contains?
Load an image.
Resize it to a predefined size such as 224 x 224 pixels.
Scale the value of the pixels to the range [0, 255].
Select a pre-trained model.
Run the pre-trained model.
Display the results.
Install TensorFlow and Keras.
pip install tensorflow
First of all, we set up the environment.
# TensorFlow and tf.kerasimport tensorflow as tffrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictionsfrom tensorflow.keras.preprocessing import image# Helper librariesimport numpy as npimport matplotlib.pyplot as plprint(tf.__version__)
Then, we load and try to display the image that we want to predict.
img_path = "./samples/dog_1100x628.jpg"plt.imshow(img)plt.show()
It shows a vizsla dog, so how our model predict this image?
Keep in mind that before feeding any image to Keras, we need to convert it to a standard format since pre-trained models expect the input to be of a specific size. In this case, we need to resize our images to 224 x 224 pixels.
img = image.load_img(img_path, target_size=(224, 224))
The second is most deep learning models expect a batch of images as input. In this case, we create a batch of one image.
img_array = image.img_to_array(img)img_batch = np.expand_dims(img_array, axis=0)
The third is models perform well when they are fed with data within a consistent range. In this case, the image pixel values are range from 0 to 255. So, if we run the preprocess_input() function from Keras on input images will normalize each pixel to a standard range.
img_preprocessed = preprocess_input(img_batch)
Here, we will use a CNN network called ResNet-50.
model = tf.keras.applications.resnet50.ResNet50()
prediction = model.predict(img_preprocessed)
Keras also provides the decode_predictions function which tells us the probability of each category of objects contained in the image.
print(decode_predictions(prediction, top=3)[0])
Here is the output while running this program.
[(βn02099601β, βgolden_retrieverβ, 0.75317645), (βn02100583β, βvizslaβ, 0.061531797), (βn02099267β, βflat-coated_retrieverβ, 0.04048888)]
The predicted categories for this image are various types of dog.
Full source code for the finished.
|
[
{
"code": null,
"e": 256,
"s": 172,
"text": "There are the following six steps to determine what object does the image contains?"
},
{
"code": null,
"e": 271,
"s": 256,
"text": "Load an image."
},
{
"code": null,
"e": 328,
"s": 271,
"text": "Resize it to a predefined size such as 224 x 224 pixels."
},
{
"code": null,
"e": 381,
"s": 328,
"text": "Scale the value of the pixels to the range [0, 255]."
},
{
"code": null,
"e": 409,
"s": 381,
"text": "Select a pre-trained model."
},
{
"code": null,
"e": 436,
"s": 409,
"text": "Run the pre-trained model."
},
{
"code": null,
"e": 457,
"s": 436,
"text": "Display the results."
},
{
"code": null,
"e": 487,
"s": 457,
"text": "Install TensorFlow and Keras."
},
{
"code": null,
"e": 510,
"s": 487,
"text": "pip install tensorflow"
},
{
"code": null,
"e": 551,
"s": 510,
"text": "First of all, we set up the environment."
},
{
"code": null,
"e": 822,
"s": 551,
"text": "# TensorFlow and tf.kerasimport tensorflow as tffrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictionsfrom tensorflow.keras.preprocessing import image# Helper librariesimport numpy as npimport matplotlib.pyplot as plprint(tf.__version__)"
},
{
"code": null,
"e": 890,
"s": 822,
"text": "Then, we load and try to display the image that we want to predict."
},
{
"code": null,
"e": 955,
"s": 890,
"text": "img_path = \"./samples/dog_1100x628.jpg\"plt.imshow(img)plt.show()"
},
{
"code": null,
"e": 1015,
"s": 955,
"text": "It shows a vizsla dog, so how our model predict this image?"
},
{
"code": null,
"e": 1243,
"s": 1015,
"text": "Keep in mind that before feeding any image to Keras, we need to convert it to a standard format since pre-trained models expect the input to be of a specific size. In this case, we need to resize our images to 224 x 224 pixels."
},
{
"code": null,
"e": 1298,
"s": 1243,
"text": "img = image.load_img(img_path, target_size=(224, 224))"
},
{
"code": null,
"e": 1419,
"s": 1298,
"text": "The second is most deep learning models expect a batch of images as input. In this case, we create a batch of one image."
},
{
"code": null,
"e": 1500,
"s": 1419,
"text": "img_array = image.img_to_array(img)img_batch = np.expand_dims(img_array, axis=0)"
},
{
"code": null,
"e": 1770,
"s": 1500,
"text": "The third is models perform well when they are fed with data within a consistent range. In this case, the image pixel values are range from 0 to 255. So, if we run the preprocess_input() function from Keras on input images will normalize each pixel to a standard range."
},
{
"code": null,
"e": 1817,
"s": 1770,
"text": "img_preprocessed = preprocess_input(img_batch)"
},
{
"code": null,
"e": 1867,
"s": 1817,
"text": "Here, we will use a CNN network called ResNet-50."
},
{
"code": null,
"e": 1917,
"s": 1867,
"text": "model = tf.keras.applications.resnet50.ResNet50()"
},
{
"code": null,
"e": 1962,
"s": 1917,
"text": "prediction = model.predict(img_preprocessed)"
},
{
"code": null,
"e": 2097,
"s": 1962,
"text": "Keras also provides the decode_predictions function which tells us the probability of each category of objects contained in the image."
},
{
"code": null,
"e": 2145,
"s": 2097,
"text": "print(decode_predictions(prediction, top=3)[0])"
},
{
"code": null,
"e": 2192,
"s": 2145,
"text": "Here is the output while running this program."
},
{
"code": null,
"e": 2330,
"s": 2192,
"text": "[(βn02099601β, βgolden_retrieverβ, 0.75317645), (βn02100583β, βvizslaβ, 0.061531797), (βn02099267β, βflat-coated_retrieverβ, 0.04048888)]"
},
{
"code": null,
"e": 2396,
"s": 2330,
"text": "The predicted categories for this image are various types of dog."
}
] |
Hugging Face Transformers: Fine-tuning DistilBERT for Binary Classification Tasks | Towards Data Science
|
Creating high-performing natural language models is as time-consuming as it is expensive. After all, it took the team behind Google Brain 3.5 days on 8 Tesla P100 GPUs to train all 340 million parameters of the famous BERT-large model, and ever since its inception in 2018, natural language models have only increased in complexity.1
But what if a company doesnβt have the resources needed to train such large behemoths? Well, thanks to recent advances in transfer learning (the technique was previously well established in Computer Vision and only recently found applications in NLP), companies can more easily achieve state-of-the-art performance by simply adapting pre-trained models for their own natural language tasks.
In this article, I would like to share a practical example of how to do just that using Tensorflow 2.0 and the excellent Hugging Face Transformers library by walking you through how to fine-tune DistilBERT for sequence classification tasks on your own unique datasets.
And yes, I could have used the Hugging Face API to select a more powerful model such as BERT, RoBERTa, ELECTRA, MPNET, or ALBERT as my starting point. But I chose DistilBERT for this project due to its lighter memory footprint and its faster inference speed. Compared to its older cousin, DistilBERTβs 66 million parameters make it 40% smaller and 60% faster than BERT-base, all while retaining more than 95% of BERTβs performance.2 This makes DistilBERT an ideal candidate for businesses looking to scale their models in production, even up to more than 1 billion daily requests! And as we will see, DistilBERT can perform quite admirably with the proper fine-tuning. With that out of the way, letβs get started!
For this project, I will be classifying whether a comment is toxic or non-toxic using personally modified versions of the Jigsaw Toxic Comment dataset found on Kaggle (I converted the dataset from a multi-label classification problem to a binary classification problem).
Following conversion, the dataset exhibits class imbalance with toxic comments making up 9.58% of all data. This is a problem because any naive model could simply βlearnβ the class distribution and predict the majority class every time and still get 90.42% accuracy. So while this would seem like our model is successful, it would actually be completely ineffective at predicting toxic comments (the minority class), which is not at all what we want!
To deal with this, we will implement a combination of both undersampling and oversampling to balance out our class distribution.
(Note: Make sure to split your data beforehand and only oversample the training set to ensure your evaluation results remain as unbiased as possible!)
It is important to note, however, that a fine balance must be met when undersampling the majority class. If we oversample too much, we risk hurting model performance by losing out on valuable training data. But if we oversample too little (or not at all), the modelβs predictions might bias towards the majority class and be unable to predict the minority class.
Keeping this in mind, I attempted to find the right balance by undersampling the modified dataset until toxic comments made up ~20% of all training data. This dataset will henceforth be referred to as the unbalanced dataset , and it is the dataset on which I received the best empirical results for this specific problem.
Along with data science comes the beauty of experimentation, and I thought it could be fruitful to fine-tune DistilBERT on a fully balanced dataset as well. Not only would doing this completely eliminate the imbalanced classification problem, but I also hoped that adding synthetic data into our training set would allow our model to generalize to previously unseen data.
To do this, I took the unbalanced datasetβs training set and oversampled the minority class until both classes had approximately 48,000 representative texts, thus creating the balanced dataset.
For the oversampling, I performed data augmentation using the nlpaug library via word replacement using BERT contextual embeddings. Generating this data can be a slow process depending on which language model you choose (the library currently supports implementations for DistilBERT, BERT, RoBERTa, and XLNet), but the library offers additional methods for data augmentation that fall into three categories:
Character-level augmentation (can simulate typos in words while taking keyboard distance into account)Word-level augmentation (can apply back-translation, random insertion or deletion, word splitting, or thesaurus-based synonym replacement)Sentence-level augmentation (can generate sentences using next-sentence-prediction or abstractive text summarization)
Character-level augmentation (can simulate typos in words while taking keyboard distance into account)
Word-level augmentation (can apply back-translation, random insertion or deletion, word splitting, or thesaurus-based synonym replacement)
Sentence-level augmentation (can generate sentences using next-sentence-prediction or abstractive text summarization)
Furthermore, not only does nlpaug allows you to control how you generate new text, but it also allows you to control how much, or what percent, of the provided text should be modified to give rise to the newly generated text.
Because of this, it might be a bit confusing to know where to start, but in the 2019 paper βEDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks,β the authors provide the above figure to be used as a reference for your data augmentation pipeline.3 For my purposes, I chose to generate new sentences by replacing approximately 10% of all words in a given string of text (Ξ± = 0.1), but the best choice of hyperparameters may be different for your specific dataset. Try things out, and see how it goes!
For more information on text augmentation, go ahead and give this article a read: Link.
(Note: Building up a Pandas DataFrame using the .append() method is actually very inefficient, as you will be recopying the entire DataFrame with each method call. Instead, iteratively build up a dictionary containing your data and call the .from_dict() method to construct your final DataFrame. You can see me do this in lines 47β54.) Source
Unfortunately, in my case, training on the balanced dataset actually resulted in poorer performance (likely due to the fact that text augmentation performs better on small datasets), so all experiments in upcoming sections of this article will be performed on the unbalanced dataset instead.
Now that we have our datasets in order, itβs time to start building our model! To do so, we will take full advantage of the power of transfer learning by choosing a pre-trained model for our base and adding additional layers on top as it suits our classification task. This is effective because the pre-trained modelβs weights contain information representing a high-level understanding of the English language, so we can build on that general knowledge by adding additional layers whose weights will come to represent task-specific understanding of what makes a comment toxic vs non-toxic.
As we will see, the Hugging Face Transformers library makes transfer learning very approachable, as our general workflow can be divided into four main stages:
Tokenizing TextDefining a Model ArchitectureTraining Classification Layer WeightsFine-tuning DistilBERT and Training All Weights
Tokenizing Text
Defining a Model Architecture
Training Classification Layer Weights
Fine-tuning DistilBERT and Training All Weights
Once we select a pre-trained model, itβs time to convert human-readable strings of text into a format our model can interpret. This process is known as tokenization, and the intuitive Hugging Face API makes it extremely easy to convert words and sentences β sequences of tokens β sequences of numbers that can be converted into a tensor and fed into our model.
In general, different pre-trained models utilize different methods to tokenize textual inputs (in the figure above, see how DistilBERTβs tokenizer includes special tokens such as [CLS] and [SEP] in its tokenization scheme), so it will be necessary to instantiate a tokenizer object that is specific to our chosen model. To get the tokenizer used by distilbert-base-uncased, we pass our modelβs name to the .from_pretrained() method of the DistilBertTokenizerFast class.
(Note: Hugging Face provides both βslowβ and βfastβ versions of its tokenizers. Whereas the βslowβ version is written in Python, the βfastβ version is written in Rust and provides significant speedups when performing batched tokenization. In this article, we use the βfastβ version to take advantage of these performance benefits.)
Once we instantiate our tokenizer object, we can then go about encoding our training, validation, and test sets in batches using the tokenizerβs .batch_encode_plus() method.
Important arguments we may wish to set include:
max_length β Controls the maximum number of words to tokenize in a given text.
padding β If set to βlongest,β then pads to the longest sequence in the batch.
truncation β If True, then truncates text according to the value set by max_length.
return_attention_mask β If True, then returns the attention mask. This is optional, but attention masks tell your model what tokens to pay attention to and which to ignore (in the case of padding). Thus, including the attention mask as an input to your model may improve model performance.
return_token_type_ids β If True, then returns the token type IDs. This is required for some tasks that require multiple sequences as input (e.g. Question Answering requires a βquestionβ and an βanswerβ sequence), as the token IDs inform the model on where one sequence of the input ends and the other sequence begins. For our purposes, however, this is optional because our classification task only requires one sequence as input (the potentially toxic comment).
As seen in the code above, the batch_encode function I create ends up returning:
input_ids β Words of the text encoded as sequences of numbers.attention_mask β A binary sequence telling the model which numbers in input_ids to pay attention to and which to ignore (in the case of padding).
input_ids β Words of the text encoded as sequences of numbers.
attention_mask β A binary sequence telling the model which numbers in input_ids to pay attention to and which to ignore (in the case of padding).
Both input_ids and attention_mask have been converted into Tensorflow tf.Tensor objects so they can be readily fed into our model as inputs.
Now that we have encoded our training, validation, and test sets, it is time to define our model architecture. Since we will be using DistilBERT as our base model, we begin by importing distilbert-base-uncased from the Hugging Face library.
Initialize the Base Model
Importantly, we should note that the Hugging Face API gives us the option to tweak the base model architecture by changing several arguments in DistilBERTβs configuration class. Here, we instantiate a new config object by increasing dropout and attention_dropout from their defaults of 0.1 to their new values of 0.2, but there are many other options to choose from, all of which can be found in the configuration classβs documentation that is specific to your chosen model.
After (optionally) modifying DistilBERTβs configuration class, we can pass both the model name and configuration object to the .from_pretrained() method of the TFDistilBertModel class to instantiate the base DistilBERT model without any specific head on top (as opposed to other classes such as TFDistilBertForSequenceClassification that do have an added classification head). We do not want any task-specific head attached because we simply want the pre-trained weights of the base model to provide a general understanding of the English language, and it will be our job to add our own classification head during the fine-tuning process in order to help the model distinguish between toxic comments.
Because DistilBERTβs pre-trained weights will serve as the basis for our model, we wish to conserve and prevent them from updating during the initial stages of training when our model is beginning to learn reasonable weights for our added classification layers. To temporarily freeze DistilBERTβs pre-trained weights, set layer.trainable = False for each of DistilBERTβs layers, and we can later unfreeze them by setting layer.trainable = True once model performance converges.
Add a Classification Head
As we build up our model architecture, we will be adding a classification head on top of DistilBERTβs embedding layer that we get as model output in line 35 . In actuality, the modelβs output is a tuple containing:
last_hidden_state β Word-level embedding of shape (batch_size, sequence_length, hidden_size=768).hidden_states β [Optional] Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size=768). Returned when we set output_hidden_states=True in the config file.attentions β [Optional] Attentionβs weights after the attention softmax, used to compute the weighted average in the self-attention heads. Returned when we set output_attentions=True in the config file.
last_hidden_state β Word-level embedding of shape (batch_size, sequence_length, hidden_size=768).
hidden_states β [Optional] Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size=768). Returned when we set output_hidden_states=True in the config file.
attentions β [Optional] Attentionβs weights after the attention softmax, used to compute the weighted average in the self-attention heads. Returned when we set output_attentions=True in the config file.
Rather than accessing other layersβ hidden states, we select index 0 of this tuple to access last_hidden_state, as building off of this embedding usually leads to the best empirical results.4
Each hidden state is a tf.Tensor of shape (batch_size, sequence_length, hidden_size=768) and contains the word-level embedding output of one of DistilBERTβs 12 layers. Therefore, the last hidden state will be of the shape (64, 128, 768) in our case since we set BATCH_SIZE=64 andMAX_LENGTH=128 and DistilBERT has a hidden size of 768.
I should emphasize that all 128 sequence tokens in the embedding provide a word-level understanding, and one may be able to extract a great deal of information from the 3D embedding perhaps with a bi-directional LSTM and a max-pooling layer as was performed in this article.
However, for our purposes, we will instead make use of DistilBERTβs sentence-level understanding of the sequence by only looking at the first of these 128 tokens: the [CLS] token. Standing for βclassification,β the [CLS] token plays an important role, as it actually stores a sentence-level embedding that is useful for Next Sentence Prediction (NSP) during the pre-training phase. Thus, we can access this sentence-level embedding in line 41 by taking a slice of last_hidden_state such that we are left with a 2D tensor that represents the entire sequence of text.
To get a baseline for our modelβs performance, we can start out by just adding a single, dense output layer with sigmoid activation function on top of the [CLS] tokenβs sentence-level embedding. Finally, we compile the model with adam optimizerβs learning rate set to 5e-5 (the authors of the original BERT paper recommend learning rates of 3e-4, 1e-4, 5e-5, and 3e-5 as good starting points) and with the loss function set to focal loss instead of binary cross-entropy in order to properly handle the class imbalance of our dataset.
(Note: tf.keras does NOT provide focal loss as a built-in function you can use. Instead, you will have to implement focal loss as your own custom function and pass it in as an argument. Please see here to understand how focal loss works and here for an implementation of the focal loss function I used. )
Ok, weβve finally built up our model, so we can now begin to train the classification layerβs randomly initialized weights until model performance converges. In the case of a simple baseline model with just a single output layer, training all 768 available weights (since all of DistilBERTβs weights are frozen) over 6 epochs results in an accuracy of 85.7% and an AUC-ROC score of 0.926 on the test set. Not bad for a model trained with just a few lines of code!
However, we can definitely do better, and one thing we can think about at this stage is changing up our model architecture. After all, our model is pretty simple at this point with just a single output layer on top of DistilBERT, so it might be a good idea to add additional dense and/or dropout layers in between.
I do this for two dense layers by performing a grid-search using the Comet.ml API and find that the optimal model architecture for my specific classification problem looks like:
[DistilBERT CLS Embedding Layer] + [Dense 256] + [Dense 32] + [Single-node Output Layer]
with dropout of 0.2 between each layer.
As a result of this change, our new model scores an accuracy of 87.3% and an AUC-ROC of 0.930 on the test set by training only the added classification layers.
Once we finish training the added classification layers, we can squeeze even more performance out of our model by unfreezing DistilBERTβs embedding layer and fine-tuning all weights with a lower learning rate (to prevent major updates to the pre-trained weights). Note that it is necessary to recompile our model after unfreezing layer weights, but aside from that, the training procedure looks the same as the previous step.
As a result of fine-tuning DistilBERTβs pre-trained weights, our model achieves a final accuracy of 92.18% and an AUC-ROC of 0.969 on the test set π₯³π₯π.
As Dr. KaΜroly Zsolnai-FeheΜr from Two Minute Papers might say...
βWhat a time to be alive!β
As you can see, exciting times are upon us, as anyone with access to a computer can harness the power of state-of-the-art, multi-million dollar pre-trained models with relatively few lines of code. This ease of use is key to rapid development and model deployment, and the compact nature of smaller models such as DistilBERT make them scalable and able to produce real-time results while still maintaining high levels of performance.
As if DistilBERT wasnβt fast enough, inference speed can be further optimized using weight quantization and model serving using ONNX Runtime, but alas, Iβm getting ahead of myself, as this is a topic for a future article.
In any case, I hope the code and explanations in this article are helpful, and I hope you are now as excited about NLP and the Hugging Face Transformers library as I am! If you enjoyed the content, feel free to connect with me on LinkedIn, find me on Kaggle, or check out the code on GitHub.
Good luck out there in your NLP pursuits, and happy coding!
[1] A. Vaswani et al., Attention Is All You Need (2017), arXiv:1706.03762
[2] V. Sanh et al., DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter (2019), arXiv:1910.01108
[3] J. Wei and K. Zou, EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks (2019), arXiv:1901.11196
[4] C. Sun et al., How to Fine-Tune BERT for Text Classification? (2019), arXiv:1905.05583
|
[
{
"code": null,
"e": 505,
"s": 171,
"text": "Creating high-performing natural language models is as time-consuming as it is expensive. After all, it took the team behind Google Brain 3.5 days on 8 Tesla P100 GPUs to train all 340 million parameters of the famous BERT-large model, and ever since its inception in 2018, natural language models have only increased in complexity.1"
},
{
"code": null,
"e": 896,
"s": 505,
"text": "But what if a company doesnβt have the resources needed to train such large behemoths? Well, thanks to recent advances in transfer learning (the technique was previously well established in Computer Vision and only recently found applications in NLP), companies can more easily achieve state-of-the-art performance by simply adapting pre-trained models for their own natural language tasks."
},
{
"code": null,
"e": 1165,
"s": 896,
"text": "In this article, I would like to share a practical example of how to do just that using Tensorflow 2.0 and the excellent Hugging Face Transformers library by walking you through how to fine-tune DistilBERT for sequence classification tasks on your own unique datasets."
},
{
"code": null,
"e": 1879,
"s": 1165,
"text": "And yes, I could have used the Hugging Face API to select a more powerful model such as BERT, RoBERTa, ELECTRA, MPNET, or ALBERT as my starting point. But I chose DistilBERT for this project due to its lighter memory footprint and its faster inference speed. Compared to its older cousin, DistilBERTβs 66 million parameters make it 40% smaller and 60% faster than BERT-base, all while retaining more than 95% of BERTβs performance.2 This makes DistilBERT an ideal candidate for businesses looking to scale their models in production, even up to more than 1 billion daily requests! And as we will see, DistilBERT can perform quite admirably with the proper fine-tuning. With that out of the way, letβs get started!"
},
{
"code": null,
"e": 2150,
"s": 1879,
"text": "For this project, I will be classifying whether a comment is toxic or non-toxic using personally modified versions of the Jigsaw Toxic Comment dataset found on Kaggle (I converted the dataset from a multi-label classification problem to a binary classification problem)."
},
{
"code": null,
"e": 2601,
"s": 2150,
"text": "Following conversion, the dataset exhibits class imbalance with toxic comments making up 9.58% of all data. This is a problem because any naive model could simply βlearnβ the class distribution and predict the majority class every time and still get 90.42% accuracy. So while this would seem like our model is successful, it would actually be completely ineffective at predicting toxic comments (the minority class), which is not at all what we want!"
},
{
"code": null,
"e": 2730,
"s": 2601,
"text": "To deal with this, we will implement a combination of both undersampling and oversampling to balance out our class distribution."
},
{
"code": null,
"e": 2881,
"s": 2730,
"text": "(Note: Make sure to split your data beforehand and only oversample the training set to ensure your evaluation results remain as unbiased as possible!)"
},
{
"code": null,
"e": 3244,
"s": 2881,
"text": "It is important to note, however, that a fine balance must be met when undersampling the majority class. If we oversample too much, we risk hurting model performance by losing out on valuable training data. But if we oversample too little (or not at all), the modelβs predictions might bias towards the majority class and be unable to predict the minority class."
},
{
"code": null,
"e": 3566,
"s": 3244,
"text": "Keeping this in mind, I attempted to find the right balance by undersampling the modified dataset until toxic comments made up ~20% of all training data. This dataset will henceforth be referred to as the unbalanced dataset , and it is the dataset on which I received the best empirical results for this specific problem."
},
{
"code": null,
"e": 3938,
"s": 3566,
"text": "Along with data science comes the beauty of experimentation, and I thought it could be fruitful to fine-tune DistilBERT on a fully balanced dataset as well. Not only would doing this completely eliminate the imbalanced classification problem, but I also hoped that adding synthetic data into our training set would allow our model to generalize to previously unseen data."
},
{
"code": null,
"e": 4132,
"s": 3938,
"text": "To do this, I took the unbalanced datasetβs training set and oversampled the minority class until both classes had approximately 48,000 representative texts, thus creating the balanced dataset."
},
{
"code": null,
"e": 4540,
"s": 4132,
"text": "For the oversampling, I performed data augmentation using the nlpaug library via word replacement using BERT contextual embeddings. Generating this data can be a slow process depending on which language model you choose (the library currently supports implementations for DistilBERT, BERT, RoBERTa, and XLNet), but the library offers additional methods for data augmentation that fall into three categories:"
},
{
"code": null,
"e": 4898,
"s": 4540,
"text": "Character-level augmentation (can simulate typos in words while taking keyboard distance into account)Word-level augmentation (can apply back-translation, random insertion or deletion, word splitting, or thesaurus-based synonym replacement)Sentence-level augmentation (can generate sentences using next-sentence-prediction or abstractive text summarization)"
},
{
"code": null,
"e": 5001,
"s": 4898,
"text": "Character-level augmentation (can simulate typos in words while taking keyboard distance into account)"
},
{
"code": null,
"e": 5140,
"s": 5001,
"text": "Word-level augmentation (can apply back-translation, random insertion or deletion, word splitting, or thesaurus-based synonym replacement)"
},
{
"code": null,
"e": 5258,
"s": 5140,
"text": "Sentence-level augmentation (can generate sentences using next-sentence-prediction or abstractive text summarization)"
},
{
"code": null,
"e": 5484,
"s": 5258,
"text": "Furthermore, not only does nlpaug allows you to control how you generate new text, but it also allows you to control how much, or what percent, of the provided text should be modified to give rise to the newly generated text."
},
{
"code": null,
"e": 6024,
"s": 5484,
"text": "Because of this, it might be a bit confusing to know where to start, but in the 2019 paper βEDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks,β the authors provide the above figure to be used as a reference for your data augmentation pipeline.3 For my purposes, I chose to generate new sentences by replacing approximately 10% of all words in a given string of text (Ξ± = 0.1), but the best choice of hyperparameters may be different for your specific dataset. Try things out, and see how it goes!"
},
{
"code": null,
"e": 6112,
"s": 6024,
"text": "For more information on text augmentation, go ahead and give this article a read: Link."
},
{
"code": null,
"e": 6455,
"s": 6112,
"text": "(Note: Building up a Pandas DataFrame using the .append() method is actually very inefficient, as you will be recopying the entire DataFrame with each method call. Instead, iteratively build up a dictionary containing your data and call the .from_dict() method to construct your final DataFrame. You can see me do this in lines 47β54.) Source"
},
{
"code": null,
"e": 6747,
"s": 6455,
"text": "Unfortunately, in my case, training on the balanced dataset actually resulted in poorer performance (likely due to the fact that text augmentation performs better on small datasets), so all experiments in upcoming sections of this article will be performed on the unbalanced dataset instead."
},
{
"code": null,
"e": 7338,
"s": 6747,
"text": "Now that we have our datasets in order, itβs time to start building our model! To do so, we will take full advantage of the power of transfer learning by choosing a pre-trained model for our base and adding additional layers on top as it suits our classification task. This is effective because the pre-trained modelβs weights contain information representing a high-level understanding of the English language, so we can build on that general knowledge by adding additional layers whose weights will come to represent task-specific understanding of what makes a comment toxic vs non-toxic."
},
{
"code": null,
"e": 7497,
"s": 7338,
"text": "As we will see, the Hugging Face Transformers library makes transfer learning very approachable, as our general workflow can be divided into four main stages:"
},
{
"code": null,
"e": 7626,
"s": 7497,
"text": "Tokenizing TextDefining a Model ArchitectureTraining Classification Layer WeightsFine-tuning DistilBERT and Training All Weights"
},
{
"code": null,
"e": 7642,
"s": 7626,
"text": "Tokenizing Text"
},
{
"code": null,
"e": 7672,
"s": 7642,
"text": "Defining a Model Architecture"
},
{
"code": null,
"e": 7710,
"s": 7672,
"text": "Training Classification Layer Weights"
},
{
"code": null,
"e": 7758,
"s": 7710,
"text": "Fine-tuning DistilBERT and Training All Weights"
},
{
"code": null,
"e": 8119,
"s": 7758,
"text": "Once we select a pre-trained model, itβs time to convert human-readable strings of text into a format our model can interpret. This process is known as tokenization, and the intuitive Hugging Face API makes it extremely easy to convert words and sentences β sequences of tokens β sequences of numbers that can be converted into a tensor and fed into our model."
},
{
"code": null,
"e": 8589,
"s": 8119,
"text": "In general, different pre-trained models utilize different methods to tokenize textual inputs (in the figure above, see how DistilBERTβs tokenizer includes special tokens such as [CLS] and [SEP] in its tokenization scheme), so it will be necessary to instantiate a tokenizer object that is specific to our chosen model. To get the tokenizer used by distilbert-base-uncased, we pass our modelβs name to the .from_pretrained() method of the DistilBertTokenizerFast class."
},
{
"code": null,
"e": 8921,
"s": 8589,
"text": "(Note: Hugging Face provides both βslowβ and βfastβ versions of its tokenizers. Whereas the βslowβ version is written in Python, the βfastβ version is written in Rust and provides significant speedups when performing batched tokenization. In this article, we use the βfastβ version to take advantage of these performance benefits.)"
},
{
"code": null,
"e": 9095,
"s": 8921,
"text": "Once we instantiate our tokenizer object, we can then go about encoding our training, validation, and test sets in batches using the tokenizerβs .batch_encode_plus() method."
},
{
"code": null,
"e": 9143,
"s": 9095,
"text": "Important arguments we may wish to set include:"
},
{
"code": null,
"e": 9222,
"s": 9143,
"text": "max_length β Controls the maximum number of words to tokenize in a given text."
},
{
"code": null,
"e": 9301,
"s": 9222,
"text": "padding β If set to βlongest,β then pads to the longest sequence in the batch."
},
{
"code": null,
"e": 9385,
"s": 9301,
"text": "truncation β If True, then truncates text according to the value set by max_length."
},
{
"code": null,
"e": 9675,
"s": 9385,
"text": "return_attention_mask β If True, then returns the attention mask. This is optional, but attention masks tell your model what tokens to pay attention to and which to ignore (in the case of padding). Thus, including the attention mask as an input to your model may improve model performance."
},
{
"code": null,
"e": 10138,
"s": 9675,
"text": "return_token_type_ids β If True, then returns the token type IDs. This is required for some tasks that require multiple sequences as input (e.g. Question Answering requires a βquestionβ and an βanswerβ sequence), as the token IDs inform the model on where one sequence of the input ends and the other sequence begins. For our purposes, however, this is optional because our classification task only requires one sequence as input (the potentially toxic comment)."
},
{
"code": null,
"e": 10219,
"s": 10138,
"text": "As seen in the code above, the batch_encode function I create ends up returning:"
},
{
"code": null,
"e": 10427,
"s": 10219,
"text": "input_ids β Words of the text encoded as sequences of numbers.attention_mask β A binary sequence telling the model which numbers in input_ids to pay attention to and which to ignore (in the case of padding)."
},
{
"code": null,
"e": 10490,
"s": 10427,
"text": "input_ids β Words of the text encoded as sequences of numbers."
},
{
"code": null,
"e": 10636,
"s": 10490,
"text": "attention_mask β A binary sequence telling the model which numbers in input_ids to pay attention to and which to ignore (in the case of padding)."
},
{
"code": null,
"e": 10777,
"s": 10636,
"text": "Both input_ids and attention_mask have been converted into Tensorflow tf.Tensor objects so they can be readily fed into our model as inputs."
},
{
"code": null,
"e": 11018,
"s": 10777,
"text": "Now that we have encoded our training, validation, and test sets, it is time to define our model architecture. Since we will be using DistilBERT as our base model, we begin by importing distilbert-base-uncased from the Hugging Face library."
},
{
"code": null,
"e": 11044,
"s": 11018,
"text": "Initialize the Base Model"
},
{
"code": null,
"e": 11519,
"s": 11044,
"text": "Importantly, we should note that the Hugging Face API gives us the option to tweak the base model architecture by changing several arguments in DistilBERTβs configuration class. Here, we instantiate a new config object by increasing dropout and attention_dropout from their defaults of 0.1 to their new values of 0.2, but there are many other options to choose from, all of which can be found in the configuration classβs documentation that is specific to your chosen model."
},
{
"code": null,
"e": 12220,
"s": 11519,
"text": "After (optionally) modifying DistilBERTβs configuration class, we can pass both the model name and configuration object to the .from_pretrained() method of the TFDistilBertModel class to instantiate the base DistilBERT model without any specific head on top (as opposed to other classes such as TFDistilBertForSequenceClassification that do have an added classification head). We do not want any task-specific head attached because we simply want the pre-trained weights of the base model to provide a general understanding of the English language, and it will be our job to add our own classification head during the fine-tuning process in order to help the model distinguish between toxic comments."
},
{
"code": null,
"e": 12698,
"s": 12220,
"text": "Because DistilBERTβs pre-trained weights will serve as the basis for our model, we wish to conserve and prevent them from updating during the initial stages of training when our model is beginning to learn reasonable weights for our added classification layers. To temporarily freeze DistilBERTβs pre-trained weights, set layer.trainable = False for each of DistilBERTβs layers, and we can later unfreeze them by setting layer.trainable = True once model performance converges."
},
{
"code": null,
"e": 12724,
"s": 12698,
"text": "Add a Classification Head"
},
{
"code": null,
"e": 12939,
"s": 12724,
"text": "As we build up our model architecture, we will be adding a classification head on top of DistilBERTβs embedding layer that we get as model output in line 35 . In actuality, the modelβs output is a tuple containing:"
},
{
"code": null,
"e": 13482,
"s": 12939,
"text": "last_hidden_state β Word-level embedding of shape (batch_size, sequence_length, hidden_size=768).hidden_states β [Optional] Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size=768). Returned when we set output_hidden_states=True in the config file.attentions β [Optional] Attentionβs weights after the attention softmax, used to compute the weighted average in the self-attention heads. Returned when we set output_attentions=True in the config file."
},
{
"code": null,
"e": 13580,
"s": 13482,
"text": "last_hidden_state β Word-level embedding of shape (batch_size, sequence_length, hidden_size=768)."
},
{
"code": null,
"e": 13824,
"s": 13580,
"text": "hidden_states β [Optional] Tuple of tf.Tensor (one for the output of the embeddings + one for the output of each layer) of shape (batch_size, sequence_length, hidden_size=768). Returned when we set output_hidden_states=True in the config file."
},
{
"code": null,
"e": 14027,
"s": 13824,
"text": "attentions β [Optional] Attentionβs weights after the attention softmax, used to compute the weighted average in the self-attention heads. Returned when we set output_attentions=True in the config file."
},
{
"code": null,
"e": 14219,
"s": 14027,
"text": "Rather than accessing other layersβ hidden states, we select index 0 of this tuple to access last_hidden_state, as building off of this embedding usually leads to the best empirical results.4"
},
{
"code": null,
"e": 14554,
"s": 14219,
"text": "Each hidden state is a tf.Tensor of shape (batch_size, sequence_length, hidden_size=768) and contains the word-level embedding output of one of DistilBERTβs 12 layers. Therefore, the last hidden state will be of the shape (64, 128, 768) in our case since we set BATCH_SIZE=64 andMAX_LENGTH=128 and DistilBERT has a hidden size of 768."
},
{
"code": null,
"e": 14829,
"s": 14554,
"text": "I should emphasize that all 128 sequence tokens in the embedding provide a word-level understanding, and one may be able to extract a great deal of information from the 3D embedding perhaps with a bi-directional LSTM and a max-pooling layer as was performed in this article."
},
{
"code": null,
"e": 15395,
"s": 14829,
"text": "However, for our purposes, we will instead make use of DistilBERTβs sentence-level understanding of the sequence by only looking at the first of these 128 tokens: the [CLS] token. Standing for βclassification,β the [CLS] token plays an important role, as it actually stores a sentence-level embedding that is useful for Next Sentence Prediction (NSP) during the pre-training phase. Thus, we can access this sentence-level embedding in line 41 by taking a slice of last_hidden_state such that we are left with a 2D tensor that represents the entire sequence of text."
},
{
"code": null,
"e": 15929,
"s": 15395,
"text": "To get a baseline for our modelβs performance, we can start out by just adding a single, dense output layer with sigmoid activation function on top of the [CLS] tokenβs sentence-level embedding. Finally, we compile the model with adam optimizerβs learning rate set to 5e-5 (the authors of the original BERT paper recommend learning rates of 3e-4, 1e-4, 5e-5, and 3e-5 as good starting points) and with the loss function set to focal loss instead of binary cross-entropy in order to properly handle the class imbalance of our dataset."
},
{
"code": null,
"e": 16234,
"s": 15929,
"text": "(Note: tf.keras does NOT provide focal loss as a built-in function you can use. Instead, you will have to implement focal loss as your own custom function and pass it in as an argument. Please see here to understand how focal loss works and here for an implementation of the focal loss function I used. )"
},
{
"code": null,
"e": 16698,
"s": 16234,
"text": "Ok, weβve finally built up our model, so we can now begin to train the classification layerβs randomly initialized weights until model performance converges. In the case of a simple baseline model with just a single output layer, training all 768 available weights (since all of DistilBERTβs weights are frozen) over 6 epochs results in an accuracy of 85.7% and an AUC-ROC score of 0.926 on the test set. Not bad for a model trained with just a few lines of code!"
},
{
"code": null,
"e": 17013,
"s": 16698,
"text": "However, we can definitely do better, and one thing we can think about at this stage is changing up our model architecture. After all, our model is pretty simple at this point with just a single output layer on top of DistilBERT, so it might be a good idea to add additional dense and/or dropout layers in between."
},
{
"code": null,
"e": 17191,
"s": 17013,
"text": "I do this for two dense layers by performing a grid-search using the Comet.ml API and find that the optimal model architecture for my specific classification problem looks like:"
},
{
"code": null,
"e": 17280,
"s": 17191,
"text": "[DistilBERT CLS Embedding Layer] + [Dense 256] + [Dense 32] + [Single-node Output Layer]"
},
{
"code": null,
"e": 17320,
"s": 17280,
"text": "with dropout of 0.2 between each layer."
},
{
"code": null,
"e": 17480,
"s": 17320,
"text": "As a result of this change, our new model scores an accuracy of 87.3% and an AUC-ROC of 0.930 on the test set by training only the added classification layers."
},
{
"code": null,
"e": 17906,
"s": 17480,
"text": "Once we finish training the added classification layers, we can squeeze even more performance out of our model by unfreezing DistilBERTβs embedding layer and fine-tuning all weights with a lower learning rate (to prevent major updates to the pre-trained weights). Note that it is necessary to recompile our model after unfreezing layer weights, but aside from that, the training procedure looks the same as the previous step."
},
{
"code": null,
"e": 18058,
"s": 17906,
"text": "As a result of fine-tuning DistilBERTβs pre-trained weights, our model achieves a final accuracy of 92.18% and an AUC-ROC of 0.969 on the test set π₯³π₯π."
},
{
"code": null,
"e": 18124,
"s": 18058,
"text": "As Dr. KaΜroly Zsolnai-FeheΜr from Two Minute Papers might say..."
},
{
"code": null,
"e": 18151,
"s": 18124,
"text": "βWhat a time to be alive!β"
},
{
"code": null,
"e": 18585,
"s": 18151,
"text": "As you can see, exciting times are upon us, as anyone with access to a computer can harness the power of state-of-the-art, multi-million dollar pre-trained models with relatively few lines of code. This ease of use is key to rapid development and model deployment, and the compact nature of smaller models such as DistilBERT make them scalable and able to produce real-time results while still maintaining high levels of performance."
},
{
"code": null,
"e": 18807,
"s": 18585,
"text": "As if DistilBERT wasnβt fast enough, inference speed can be further optimized using weight quantization and model serving using ONNX Runtime, but alas, Iβm getting ahead of myself, as this is a topic for a future article."
},
{
"code": null,
"e": 19099,
"s": 18807,
"text": "In any case, I hope the code and explanations in this article are helpful, and I hope you are now as excited about NLP and the Hugging Face Transformers library as I am! If you enjoyed the content, feel free to connect with me on LinkedIn, find me on Kaggle, or check out the code on GitHub."
},
{
"code": null,
"e": 19159,
"s": 19099,
"text": "Good luck out there in your NLP pursuits, and happy coding!"
},
{
"code": null,
"e": 19233,
"s": 19159,
"text": "[1] A. Vaswani et al., Attention Is All You Need (2017), arXiv:1706.03762"
},
{
"code": null,
"e": 19356,
"s": 19233,
"text": "[2] V. Sanh et al., DistilBERT, a distilled version of BERT: smaller, faster, cheaper and lighter (2019), arXiv:1910.01108"
},
{
"code": null,
"e": 19497,
"s": 19356,
"text": "[3] J. Wei and K. Zou, EDA: Easy Data Augmentation Techniques for Boosting Performance on Text Classification Tasks (2019), arXiv:1901.11196"
}
] |
How can we see MySQL temporary tables in the list of tables?
|
As we know that we can see the list of tables in a database with the help of SHOW TABLES statement. But MySQL temporary tables are not stored in this list or in other words we can say that we cannot see the temporary tables with the help of SHOW TABLES statement. To illustrate it we are using the following example β
In this example, we are trying to get the temporary table named βSalesSummaryβ from SHOW TABLES statement as follows β
mysql> SHOW TABLES LIKE '%Sales%';
Empty set (0.00 sec)
mysql> SHOW TABLES LIKE '%SalesSummary%';
Empty set (0.00 sec)
The above query shows the empty result set means that the temporary table βSalesSummaryβ is not in the table list of database.
|
[
{
"code": null,
"e": 1380,
"s": 1062,
"text": "As we know that we can see the list of tables in a database with the help of SHOW TABLES statement. But MySQL temporary tables are not stored in this list or in other words we can say that we cannot see the temporary tables with the help of SHOW TABLES statement. To illustrate it we are using the following example β"
},
{
"code": null,
"e": 1499,
"s": 1380,
"text": "In this example, we are trying to get the temporary table named βSalesSummaryβ from SHOW TABLES statement as follows β"
},
{
"code": null,
"e": 1619,
"s": 1499,
"text": "mysql> SHOW TABLES LIKE '%Sales%';\nEmpty set (0.00 sec)\n\nmysql> SHOW TABLES LIKE '%SalesSummary%';\nEmpty set (0.00 sec)"
},
{
"code": null,
"e": 1746,
"s": 1619,
"text": "The above query shows the empty result set means that the temporary table βSalesSummaryβ is not in the table list of database."
}
] |
Tryit Editor v3.7
|
HTML Input types
Tryit: HTML input password
|
[
{
"code": null,
"e": 27,
"s": 10,
"text": "HTML Input types"
}
] |
strnset() function in C
|
26 Sep, 2018
The strnset() function is a builtin function in C and it sets the first n characters of a string to a given character. If n is greater than the length of string, the length of string is used in place of n.
Syntax:
char *strnset(const char *str, char ch, int n);
Parameters:
str: This is the original string in which some character are replaced by a given character.
ch: ch represents the given character.
n: n represents the number of character which is replaced by the given character.
Return Value: It returns the modified string obtained after replacing the first characters of the given string str.
Below programs illustrate the strnset() function in C:
Program 1:
// C program to illustrate // the strnset() function #include <stdio.h>#include <string.h> int main(){ char str[] = "GeeksforGeeks"; printf("Original String: %s\n", str); // First 5 character of string str // replaced by character '*' printf("Modified String: %s\n", strnset(str, '*', 5)); return 0;}
Output:
Original String: GeeksforGeeks
Modified String: *****forGeeks
Program 2:
// C program to illustrate // the strnset() function #include <stdio.h>#include <string.h> int main(){ char str[] = "Computer Science"; printf("Original String: %s\n", str); // First 5 character of string str // replaced by character '*' printf("Modified String: %s\n", strnset(str, '*', 5)); return 0;}
Output:
Original String: Computer Science
Modified String: *****ter Science
Note: The strnset() function is not a part of the standard C library and thus might not run on the online compilers.
C-Functions
C-String
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Operators in C / C++
Exception Handling in C++
TCP Server-Client implementation in C
Smart Pointers in C++ and How to Use Them
'this' pointer in C++
Ways to copy a vector in C++
Understanding "extern" keyword in C
Storage Classes in C
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Sep, 2018"
},
{
"code": null,
"e": 259,
"s": 53,
"text": "The strnset() function is a builtin function in C and it sets the first n characters of a string to a given character. If n is greater than the length of string, the length of string is used in place of n."
},
{
"code": null,
"e": 267,
"s": 259,
"text": "Syntax:"
},
{
"code": null,
"e": 316,
"s": 267,
"text": "char *strnset(const char *str, char ch, int n);\n"
},
{
"code": null,
"e": 328,
"s": 316,
"text": "Parameters:"
},
{
"code": null,
"e": 420,
"s": 328,
"text": "str: This is the original string in which some character are replaced by a given character."
},
{
"code": null,
"e": 459,
"s": 420,
"text": "ch: ch represents the given character."
},
{
"code": null,
"e": 541,
"s": 459,
"text": "n: n represents the number of character which is replaced by the given character."
},
{
"code": null,
"e": 658,
"s": 541,
"text": "Return Value: It returns the modified string obtained after replacing the first characters of the given string str."
},
{
"code": null,
"e": 713,
"s": 658,
"text": "Below programs illustrate the strnset() function in C:"
},
{
"code": null,
"e": 724,
"s": 713,
"text": "Program 1:"
},
{
"code": "// C program to illustrate // the strnset() function #include <stdio.h>#include <string.h> int main(){ char str[] = \"GeeksforGeeks\"; printf(\"Original String: %s\\n\", str); // First 5 character of string str // replaced by character '*' printf(\"Modified String: %s\\n\", strnset(str, '*', 5)); return 0;}",
"e": 1063,
"s": 724,
"text": null
},
{
"code": null,
"e": 1071,
"s": 1063,
"text": "Output:"
},
{
"code": null,
"e": 1134,
"s": 1071,
"text": "Original String: GeeksforGeeks\nModified String: *****forGeeks\n"
},
{
"code": null,
"e": 1145,
"s": 1134,
"text": "Program 2:"
},
{
"code": "// C program to illustrate // the strnset() function #include <stdio.h>#include <string.h> int main(){ char str[] = \"Computer Science\"; printf(\"Original String: %s\\n\", str); // First 5 character of string str // replaced by character '*' printf(\"Modified String: %s\\n\", strnset(str, '*', 5)); return 0;}",
"e": 1487,
"s": 1145,
"text": null
},
{
"code": null,
"e": 1495,
"s": 1487,
"text": "Output:"
},
{
"code": null,
"e": 1564,
"s": 1495,
"text": "Original String: Computer Science\nModified String: *****ter Science\n"
},
{
"code": null,
"e": 1681,
"s": 1564,
"text": "Note: The strnset() function is not a part of the standard C library and thus might not run on the online compilers."
},
{
"code": null,
"e": 1693,
"s": 1681,
"text": "C-Functions"
},
{
"code": null,
"e": 1702,
"s": 1693,
"text": "C-String"
},
{
"code": null,
"e": 1713,
"s": 1702,
"text": "C Language"
},
{
"code": null,
"e": 1811,
"s": 1713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1859,
"s": 1811,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1904,
"s": 1859,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 1925,
"s": 1904,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 1951,
"s": 1925,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 1989,
"s": 1951,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 2031,
"s": 1989,
"text": "Smart Pointers in C++ and How to Use Them"
},
{
"code": null,
"e": 2053,
"s": 2031,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 2082,
"s": 2053,
"text": "Ways to copy a vector in C++"
},
{
"code": null,
"e": 2118,
"s": 2082,
"text": "Understanding \"extern\" keyword in C"
}
] |
Ways to read input from console in Java
|
18 Mar, 2022
In Java, there are four different ways for reading input from the user in the command line environment(console).
1.Using Buffered Reader Class
This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line.
The input is buffered for efficient reading.
The wrapping code is hard to remember.
Implementation:
Java
// Java program to demonstrate BufferedReaderimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Test { public static void main(String[] args) throws IOException { // Enter data using BufferReader BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); // Reading data using readLine String name = reader.readLine(); // Printing the read line System.out.println(name); }}
Input:
Geek
Output:
Auxiliary Space : O(1)
Geek
Note:
To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we use split().
2. Using Scanner Class
This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however, it is also can be used to read input from the user in the command line.
Convenient methods for parsing primitives (nextInt(), nextFloat(), ...) from the tokenized input.
Regular expressions can be used to find tokens.
The reading methods are not synchronized
To see more differences, please see this article.
Java
// Java program to demonstrate working of Scanner in Javaimport java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { // Using Scanner for Getting Input from User Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println("You entered string " + s); int a = in.nextInt(); System.out.println("You entered integer " + a); float b = in.nextFloat(); System.out.println("You entered float " + b); }}
Input:
GeeksforGeeks
12
3.4
Output:
You entered string GeeksforGeeks
You entered integer 12
You entered float 3.4
3. Using Console Class
It has been becoming a preferred way for reading userβs input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()).
Advantages:
Reading password without echoing the entered characters.
Reading methods are synchronized.
Format string syntax can be used.
Does not work in non-interactive environment (such as in an IDE).
Java
// Java program to demonstrate working of System.console()// Note that this program does not work on IDEs as// System.console() may require consolepublic class Sample { public static void main(String[] args) { // Using Console to input data from user String name = System.console().readLine(); System.out.println("You entered string " + name); }}
Input:
GeeksforGeeks
Output:
You entered string GeeksforGeeks
4. Using Command line argument
Most used user input for competitive coding. The command-line arguments are stored in the String format. The parseInt method of the Integer class converts string argument into Integer. Similarly, for float and others during execution. The usage of args[] comes into existence in this input form. The passing of information takes place during the program run. The command line is given to args[]. These programs have to be run on cmd.
Code:
Java
// Program to check for command line argumentsclass Hello { public static void main(String[] args) { // check if length of args array is // greater than 0 if (args.length > 0) { System.out.println( "The command line arguments are:"); // iterating the args array and printing // the command line arguments for (String val : args) System.out.println(val); } else System.out.println("No command line " + "arguments found."); }}
Command Line Arguments:
javac GFG1.java
java Main Hello World
Output:
The command line arguments are:
Hello
World
Please refer this for more faster ways of reading input.
This article is contributed by D Raj Ranu. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or 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.
sanjayrajputcse
pallabipami32
itsyoursumit
rishavnitro
Java-I/O
Java
School Programming
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Mar, 2022"
},
{
"code": null,
"e": 166,
"s": 52,
"text": "In Java, there are four different ways for reading input from the user in the command line environment(console). "
},
{
"code": null,
"e": 196,
"s": 166,
"text": "1.Using Buffered Reader Class"
},
{
"code": null,
"e": 453,
"s": 196,
"text": "This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we can read input from the user in the command line. "
},
{
"code": null,
"e": 498,
"s": 453,
"text": "The input is buffered for efficient reading."
},
{
"code": null,
"e": 537,
"s": 498,
"text": "The wrapping code is hard to remember."
},
{
"code": null,
"e": 553,
"s": 537,
"text": "Implementation:"
},
{
"code": null,
"e": 558,
"s": 553,
"text": "Java"
},
{
"code": "// Java program to demonstrate BufferedReaderimport java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class Test { public static void main(String[] args) throws IOException { // Enter data using BufferReader BufferedReader reader = new BufferedReader( new InputStreamReader(System.in)); // Reading data using readLine String name = reader.readLine(); // Printing the read line System.out.println(name); }}",
"e": 1075,
"s": 558,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1078,
"text": "Input: "
},
{
"code": null,
"e": 1093,
"s": 1088,
"text": "Geek"
},
{
"code": null,
"e": 1102,
"s": 1093,
"text": "Output: "
},
{
"code": null,
"e": 1126,
"s": 1102,
"text": "Auxiliary Space : O(1) "
},
{
"code": null,
"e": 1131,
"s": 1126,
"text": "Geek"
},
{
"code": null,
"e": 1138,
"s": 1131,
"text": "Note: "
},
{
"code": null,
"e": 1266,
"s": 1140,
"text": "To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read multiple values, we use split()."
},
{
"code": null,
"e": 1291,
"s": 1268,
"text": "2. Using Scanner Class"
},
{
"code": null,
"e": 1538,
"s": 1293,
"text": "This is probably the most preferred method to take input. The main purpose of the Scanner class is to parse primitive types and strings using regular expressions, however, it is also can be used to read input from the user in the command line. "
},
{
"code": null,
"e": 1638,
"s": 1540,
"text": "Convenient methods for parsing primitives (nextInt(), nextFloat(), ...) from the tokenized input."
},
{
"code": null,
"e": 1686,
"s": 1638,
"text": "Regular expressions can be used to find tokens."
},
{
"code": null,
"e": 1727,
"s": 1686,
"text": "The reading methods are not synchronized"
},
{
"code": null,
"e": 1777,
"s": 1727,
"text": "To see more differences, please see this article."
},
{
"code": null,
"e": 1784,
"s": 1779,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of Scanner in Javaimport java.util.Scanner; class GetInputFromUser { public static void main(String args[]) { // Using Scanner for Getting Input from User Scanner in = new Scanner(System.in); String s = in.nextLine(); System.out.println(\"You entered string \" + s); int a = in.nextInt(); System.out.println(\"You entered integer \" + a); float b = in.nextFloat(); System.out.println(\"You entered float \" + b); }}",
"e": 2301,
"s": 1784,
"text": null
},
{
"code": null,
"e": 2312,
"s": 2304,
"text": "Input: "
},
{
"code": null,
"e": 2335,
"s": 2314,
"text": "GeeksforGeeks\n12\n3.4"
},
{
"code": null,
"e": 2343,
"s": 2335,
"text": "Output:"
},
{
"code": null,
"e": 2423,
"s": 2345,
"text": "You entered string GeeksforGeeks\nYou entered integer 12\nYou entered float 3.4"
},
{
"code": null,
"e": 2446,
"s": 2423,
"text": "3. Using Console Class"
},
{
"code": null,
"e": 2716,
"s": 2448,
"text": "It has been becoming a preferred way for reading userβs input from the command line. In addition, it can be used for reading password-like input without echoing the characters entered by the user; the format string syntax can also be used (like System.out.printf()). "
},
{
"code": null,
"e": 2730,
"s": 2718,
"text": "Advantages:"
},
{
"code": null,
"e": 2789,
"s": 2732,
"text": "Reading password without echoing the entered characters."
},
{
"code": null,
"e": 2823,
"s": 2789,
"text": "Reading methods are synchronized."
},
{
"code": null,
"e": 2857,
"s": 2823,
"text": "Format string syntax can be used."
},
{
"code": null,
"e": 2923,
"s": 2857,
"text": "Does not work in non-interactive environment (such as in an IDE)."
},
{
"code": null,
"e": 2930,
"s": 2925,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of System.console()// Note that this program does not work on IDEs as// System.console() may require consolepublic class Sample { public static void main(String[] args) { // Using Console to input data from user String name = System.console().readLine(); System.out.println(\"You entered string \" + name); }}",
"e": 3308,
"s": 2930,
"text": null
},
{
"code": null,
"e": 3319,
"s": 3311,
"text": "Input: "
},
{
"code": null,
"e": 3335,
"s": 3321,
"text": "GeeksforGeeks"
},
{
"code": null,
"e": 3343,
"s": 3335,
"text": "Output:"
},
{
"code": null,
"e": 3378,
"s": 3345,
"text": "You entered string GeeksforGeeks"
},
{
"code": null,
"e": 3409,
"s": 3378,
"text": "4. Using Command line argument"
},
{
"code": null,
"e": 3845,
"s": 3411,
"text": "Most used user input for competitive coding. The command-line arguments are stored in the String format. The parseInt method of the Integer class converts string argument into Integer. Similarly, for float and others during execution. The usage of args[] comes into existence in this input form. The passing of information takes place during the program run. The command line is given to args[]. These programs have to be run on cmd."
},
{
"code": null,
"e": 3855,
"s": 3847,
"text": "Code: "
},
{
"code": null,
"e": 3862,
"s": 3857,
"text": "Java"
},
{
"code": "// Program to check for command line argumentsclass Hello { public static void main(String[] args) { // check if length of args array is // greater than 0 if (args.length > 0) { System.out.println( \"The command line arguments are:\"); // iterating the args array and printing // the command line arguments for (String val : args) System.out.println(val); } else System.out.println(\"No command line \" + \"arguments found.\"); }}",
"e": 4447,
"s": 3862,
"text": null
},
{
"code": null,
"e": 4476,
"s": 4451,
"text": "Command Line Arguments: "
},
{
"code": null,
"e": 4516,
"s": 4478,
"text": "javac GFG1.java\njava Main Hello World"
},
{
"code": null,
"e": 4524,
"s": 4516,
"text": "Output:"
},
{
"code": null,
"e": 4570,
"s": 4526,
"text": "The command line arguments are:\nHello\nWorld"
},
{
"code": null,
"e": 4627,
"s": 4570,
"text": "Please refer this for more faster ways of reading input."
},
{
"code": null,
"e": 5052,
"s": 4629,
"text": "This article is contributed by D Raj Ranu. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or 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."
},
{
"code": null,
"e": 5070,
"s": 5054,
"text": "sanjayrajputcse"
},
{
"code": null,
"e": 5084,
"s": 5070,
"text": "pallabipami32"
},
{
"code": null,
"e": 5097,
"s": 5084,
"text": "itsyoursumit"
},
{
"code": null,
"e": 5109,
"s": 5097,
"text": "rishavnitro"
},
{
"code": null,
"e": 5118,
"s": 5109,
"text": "Java-I/O"
},
{
"code": null,
"e": 5123,
"s": 5118,
"text": "Java"
},
{
"code": null,
"e": 5142,
"s": 5123,
"text": "School Programming"
},
{
"code": null,
"e": 5161,
"s": 5142,
"text": "Technical Scripter"
},
{
"code": null,
"e": 5166,
"s": 5161,
"text": "Java"
}
] |
Joining two Pandas DataFrames using merge()
|
17 Aug, 2020
Let us see how to join two Pandas DataFrames using the merge() function.
Syntax : DataFrame.merge(parameters)
Parameters :
right : DataFrame or named Series
how : {βleftβ, βrightβ, βouterβ, βinnerβ}, default βinnerβ
on : label or list
left_on : label or list, or array-like
right_on : label or list, or array-like
left_index : bool, default False
right_index : bool, default False
sort : bool, default False
suffixes : tuple of (str, str), default (β_xβ, β_yβ)
copy : bool, default True
indicator : bool or str, default False
validate : str, optional
Returns : A DataFrame of the two merged objects.
Example 1 : Merging two Dataframe with same number of elements :
# importing the moduleimport pandas as pd # creating the first DataFramedf1 = pd.DataFrame({"fruit" : ["apple", "banana", "avocado"], "market_price" : [21, 14, 35]})display("The first DataFrame")display(df1) # creating the second DataFramedf2 = pd.DataFrame({"fruit" : ["banana", "apple", "avocado"], "wholesaler_price" : [65, 68, 75]})display("The second DataFrame")display(df2) # joining the DataFramesdisplay("The merged DataFrame")pd.merge(df1, df2, on = "fruit", how = "inner")
Output :
Example 2 : Merging two Dataframe with different number of elements :
# importing the moduleimport pandas as pd # creating the first DataFramedf1 = pd.DataFrame({"fruit" : ["apple", "banana", "avocado", "grape"], "market_price" : [21, 14, 35, 38]})display("The first DataFrame")display(df1) # creating the second DataFramedf2 = pd.DataFrame({"fruit" : ["apple", "banana", "grape"], "wholesaler_price" : [65, 68, 71]})display("The second DataFrame")display(df2) # joining the DataFrames# here both common DataFrame elements are in df1 and df2, # so it extracts apple, banana, grapes from df1 and df2. display("The merged DataFrame")pd.merge(df1, df2, on = "fruit", how = "inner")
Output :
If we use how = "Outer", it returns all elements in df1 and df2 but if element column are null then its return NaN value.
pd.merge(df1, df2, on = "fruit", how = "outer")
Output :
If we use how = "left", it returns all the elements that present in the left DataFrame.
pd.merge(df1, df2, on = "fruit", how = "left")
Output :
If we use how = "right", it returns all the elements that present in the right DataFrame.
pd.merge(df1, df2, on = "fruit", how = "right")
Output :
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
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
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Aug, 2020"
},
{
"code": null,
"e": 127,
"s": 54,
"text": "Let us see how to join two Pandas DataFrames using the merge() function."
},
{
"code": null,
"e": 164,
"s": 127,
"text": "Syntax : DataFrame.merge(parameters)"
},
{
"code": null,
"e": 177,
"s": 164,
"text": "Parameters :"
},
{
"code": null,
"e": 211,
"s": 177,
"text": "right : DataFrame or named Series"
},
{
"code": null,
"e": 270,
"s": 211,
"text": "how : {βleftβ, βrightβ, βouterβ, βinnerβ}, default βinnerβ"
},
{
"code": null,
"e": 289,
"s": 270,
"text": "on : label or list"
},
{
"code": null,
"e": 328,
"s": 289,
"text": "left_on : label or list, or array-like"
},
{
"code": null,
"e": 368,
"s": 328,
"text": "right_on : label or list, or array-like"
},
{
"code": null,
"e": 401,
"s": 368,
"text": "left_index : bool, default False"
},
{
"code": null,
"e": 435,
"s": 401,
"text": "right_index : bool, default False"
},
{
"code": null,
"e": 462,
"s": 435,
"text": "sort : bool, default False"
},
{
"code": null,
"e": 515,
"s": 462,
"text": "suffixes : tuple of (str, str), default (β_xβ, β_yβ)"
},
{
"code": null,
"e": 541,
"s": 515,
"text": "copy : bool, default True"
},
{
"code": null,
"e": 580,
"s": 541,
"text": "indicator : bool or str, default False"
},
{
"code": null,
"e": 605,
"s": 580,
"text": "validate : str, optional"
},
{
"code": null,
"e": 654,
"s": 605,
"text": "Returns : A DataFrame of the two merged objects."
},
{
"code": null,
"e": 719,
"s": 654,
"text": "Example 1 : Merging two Dataframe with same number of elements :"
},
{
"code": "# importing the moduleimport pandas as pd # creating the first DataFramedf1 = pd.DataFrame({\"fruit\" : [\"apple\", \"banana\", \"avocado\"], \"market_price\" : [21, 14, 35]})display(\"The first DataFrame\")display(df1) # creating the second DataFramedf2 = pd.DataFrame({\"fruit\" : [\"banana\", \"apple\", \"avocado\"], \"wholesaler_price\" : [65, 68, 75]})display(\"The second DataFrame\")display(df2) # joining the DataFramesdisplay(\"The merged DataFrame\")pd.merge(df1, df2, on = \"fruit\", how = \"inner\")",
"e": 1243,
"s": 719,
"text": null
},
{
"code": null,
"e": 1252,
"s": 1243,
"text": "Output :"
},
{
"code": null,
"e": 1322,
"s": 1252,
"text": "Example 2 : Merging two Dataframe with different number of elements :"
},
{
"code": "# importing the moduleimport pandas as pd # creating the first DataFramedf1 = pd.DataFrame({\"fruit\" : [\"apple\", \"banana\", \"avocado\", \"grape\"], \"market_price\" : [21, 14, 35, 38]})display(\"The first DataFrame\")display(df1) # creating the second DataFramedf2 = pd.DataFrame({\"fruit\" : [\"apple\", \"banana\", \"grape\"], \"wholesaler_price\" : [65, 68, 71]})display(\"The second DataFrame\")display(df2) # joining the DataFrames# here both common DataFrame elements are in df1 and df2, # so it extracts apple, banana, grapes from df1 and df2. display(\"The merged DataFrame\")pd.merge(df1, df2, on = \"fruit\", how = \"inner\")",
"e": 2004,
"s": 1322,
"text": null
},
{
"code": null,
"e": 2013,
"s": 2004,
"text": "Output :"
},
{
"code": null,
"e": 2135,
"s": 2013,
"text": "If we use how = \"Outer\", it returns all elements in df1 and df2 but if element column are null then its return NaN value."
},
{
"code": "pd.merge(df1, df2, on = \"fruit\", how = \"outer\")",
"e": 2183,
"s": 2135,
"text": null
},
{
"code": null,
"e": 2192,
"s": 2183,
"text": "Output :"
},
{
"code": null,
"e": 2280,
"s": 2192,
"text": "If we use how = \"left\", it returns all the elements that present in the left DataFrame."
},
{
"code": "pd.merge(df1, df2, on = \"fruit\", how = \"left\")",
"e": 2327,
"s": 2280,
"text": null
},
{
"code": null,
"e": 2336,
"s": 2327,
"text": "Output :"
},
{
"code": null,
"e": 2426,
"s": 2336,
"text": "If we use how = \"right\", it returns all the elements that present in the right DataFrame."
},
{
"code": "pd.merge(df1, df2, on = \"fruit\", how = \"right\")",
"e": 2474,
"s": 2426,
"text": null
},
{
"code": null,
"e": 2483,
"s": 2474,
"text": "Output :"
},
{
"code": null,
"e": 2508,
"s": 2483,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 2532,
"s": 2508,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2546,
"s": 2532,
"text": "Python-pandas"
},
{
"code": null,
"e": 2553,
"s": 2546,
"text": "Python"
},
{
"code": null,
"e": 2651,
"s": 2553,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2683,
"s": 2651,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2710,
"s": 2683,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2731,
"s": 2710,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2754,
"s": 2731,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2810,
"s": 2754,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2841,
"s": 2810,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2883,
"s": 2841,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2925,
"s": 2883,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2964,
"s": 2925,
"text": "Python | datetime.timedelta() function"
}
] |
How to Move a Column to First Position in Pandas DataFrame?
|
02 Feb, 2021
Prerequisites: Pandas
The basic idea to move a column in a pandas dataframe is to remove the column from its current place and insert it in the desired position. The pandas library offers many useful functions such as pop() and insert(). We will make use of these two functions to manipulate with our dataframe.
Functions Used:
Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop doesnβt require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly.
Syntax: DataFrame.pop(item)
Parameters:
item: Column name to be popped in string
Return type: Popped column in form of Pandas Series
Pandas insert() method allows the user to insert a column in a dataframe or series(1-D Data frame).
Syntax:
DataFrameName.insert(loc, column, value, allow_duplicates = False)
Parameters:
loc: loc is an integer which is the location of column where we want to insert new column. This will shift the existing column at that position to the right.
Column: column is a string which is name of column to be inserted.
Value: value is simply the value to be inserted. It can be int, string, float or anything or even series / List of values. Providing only one value will set the same value for all rows.
Allow_duplicates : allow_duplicates is a boolean value which checks if column with same name already exists or not.
Approach:
Import module
Create or load dataframe
Remove the column which needs to be shifted to First Position in dataframe using pop() function.
Insert the column at first position using insert() function.
Print dataframe.
Letβs understand above approach by below examples:
Example 1:
Python3
import pandas as pd # define datadata = {'Age': [55, 20, 35, 10], 'Name': ['Rohan', 'Ritik', 'Sangeeta', 'Yogesh'], 'Address': ['Lucknow', 'Delhi', 'Haridwar', 'Nainital'], 'Phone Number': [123456789, 234567890, 3456789012, 4567890123]} # create dataframedf = pd.DataFrame(data) # print original dataframeprint("Original Dataframe")display(df) # shift column 'Name' to first positionfirst_column = df.pop('Name') # insert column using insert(position,column_name,# first_column) functiondf.insert(0, 'Name', first_column) print()print("After Shifting column to first position")display(df)
Output:
Example 2:
Python3
import pandas as pd # define datadata = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} # create dataframedf = pd.DataFrame(data) print("Original DataFrame:")display(df) # shift column 'C' to first positionfirst_column = df.pop('C') # insert column using insert(position,column_name,first_column) functiondf.insert(0, 'C', first_column) print()print("Final DataFrame")display(df)
Output:
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
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 | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 50,
"s": 28,
"text": "Prerequisites: Pandas"
},
{
"code": null,
"e": 341,
"s": 50,
"text": "The basic idea to move a column in a pandas dataframe is to remove the column from its current place and insert it in the desired position. The pandas library offers many useful functions such as pop() and insert(). We will make use of these two functions to manipulate with our dataframe. "
},
{
"code": null,
"e": 357,
"s": 341,
"text": "Functions Used:"
},
{
"code": null,
"e": 656,
"s": 357,
"text": "Pandas Pop() method is common in most of the data structures but pop() method is a little bit different from the rest. In a stack, pop doesnβt require any parameters, it pops the last element every time. But the pandas pop method can take input of a column from a data frame and pop that directly. "
},
{
"code": null,
"e": 684,
"s": 656,
"text": "Syntax: DataFrame.pop(item)"
},
{
"code": null,
"e": 696,
"s": 684,
"text": "Parameters:"
},
{
"code": null,
"e": 737,
"s": 696,
"text": "item: Column name to be popped in string"
},
{
"code": null,
"e": 789,
"s": 737,
"text": "Return type: Popped column in form of Pandas Series"
},
{
"code": null,
"e": 890,
"s": 789,
"text": "Pandas insert() method allows the user to insert a column in a dataframe or series(1-D Data frame). "
},
{
"code": null,
"e": 898,
"s": 890,
"text": "Syntax:"
},
{
"code": null,
"e": 965,
"s": 898,
"text": "DataFrameName.insert(loc, column, value, allow_duplicates = False)"
},
{
"code": null,
"e": 977,
"s": 965,
"text": "Parameters:"
},
{
"code": null,
"e": 1135,
"s": 977,
"text": "loc: loc is an integer which is the location of column where we want to insert new column. This will shift the existing column at that position to the right."
},
{
"code": null,
"e": 1202,
"s": 1135,
"text": "Column: column is a string which is name of column to be inserted."
},
{
"code": null,
"e": 1388,
"s": 1202,
"text": "Value: value is simply the value to be inserted. It can be int, string, float or anything or even series / List of values. Providing only one value will set the same value for all rows."
},
{
"code": null,
"e": 1504,
"s": 1388,
"text": "Allow_duplicates : allow_duplicates is a boolean value which checks if column with same name already exists or not."
},
{
"code": null,
"e": 1514,
"s": 1504,
"text": "Approach:"
},
{
"code": null,
"e": 1528,
"s": 1514,
"text": "Import module"
},
{
"code": null,
"e": 1553,
"s": 1528,
"text": "Create or load dataframe"
},
{
"code": null,
"e": 1650,
"s": 1553,
"text": "Remove the column which needs to be shifted to First Position in dataframe using pop() function."
},
{
"code": null,
"e": 1711,
"s": 1650,
"text": "Insert the column at first position using insert() function."
},
{
"code": null,
"e": 1728,
"s": 1711,
"text": "Print dataframe."
},
{
"code": null,
"e": 1779,
"s": 1728,
"text": "Letβs understand above approach by below examples:"
},
{
"code": null,
"e": 1790,
"s": 1779,
"text": "Example 1:"
},
{
"code": null,
"e": 1798,
"s": 1790,
"text": "Python3"
},
{
"code": "import pandas as pd # define datadata = {'Age': [55, 20, 35, 10], 'Name': ['Rohan', 'Ritik', 'Sangeeta', 'Yogesh'], 'Address': ['Lucknow', 'Delhi', 'Haridwar', 'Nainital'], 'Phone Number': [123456789, 234567890, 3456789012, 4567890123]} # create dataframedf = pd.DataFrame(data) # print original dataframeprint(\"Original Dataframe\")display(df) # shift column 'Name' to first positionfirst_column = df.pop('Name') # insert column using insert(position,column_name,# first_column) functiondf.insert(0, 'Name', first_column) print()print(\"After Shifting column to first position\")display(df)",
"e": 2411,
"s": 1798,
"text": null
},
{
"code": null,
"e": 2419,
"s": 2411,
"text": "Output:"
},
{
"code": null,
"e": 2430,
"s": 2419,
"text": "Example 2:"
},
{
"code": null,
"e": 2438,
"s": 2430,
"text": "Python3"
},
{
"code": "import pandas as pd # define datadata = {'A': [1, 2, 3], 'B': [4, 5, 6], 'C': [7, 8, 9]} # create dataframedf = pd.DataFrame(data) print(\"Original DataFrame:\")display(df) # shift column 'C' to first positionfirst_column = df.pop('C') # insert column using insert(position,column_name,first_column) functiondf.insert(0, 'C', first_column) print()print(\"Final DataFrame\")display(df)",
"e": 2825,
"s": 2438,
"text": null
},
{
"code": null,
"e": 2833,
"s": 2825,
"text": "Output:"
},
{
"code": null,
"e": 2840,
"s": 2833,
"text": "Picked"
},
{
"code": null,
"e": 2864,
"s": 2840,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2887,
"s": 2864,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 2901,
"s": 2887,
"text": "Python-pandas"
},
{
"code": null,
"e": 2908,
"s": 2901,
"text": "Python"
},
{
"code": null,
"e": 3006,
"s": 2908,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3038,
"s": 3006,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3065,
"s": 3038,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3096,
"s": 3065,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3119,
"s": 3096,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3140,
"s": 3119,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3196,
"s": 3140,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3238,
"s": 3196,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3280,
"s": 3238,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3319,
"s": 3280,
"text": "Python | Get unique values from a list"
}
] |
Count distinct elements in an array in Python
|
In a list in Python we may have duplicate elements. When we count the length of the list we get the total length including the duplicate elements. But in this article we will see how to get the total count of the distinct elements or unique elements in a list.
In the below example we use the counter() from the collections module. In this module a Counter is a dict subclass for counting hashable objects. Counter is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. So from the original list we create another list made up of only the elements whose key values are present once. This is a distinct list of elements. And then we find the length of this new list.
from collections import Counter
list = ['Mon', 'Tue', 'Wed', 'Mon','Tue']
print("Length of original list",len(list))
distinct_list= (Counter(list).keys())
print("List with distinct elements:\n",distinct_list)
print("Length of distinct list:",len(distinct_list))
Running the above code gives us the following result β
Length of original list 5
List with distinct elements:
dict_keys(['Mon', 'Tue', 'Wed'])
Length of distinct list: 3
|
[
{
"code": null,
"e": 1448,
"s": 1187,
"text": "In a list in Python we may have duplicate elements. When we count the length of the list we get the total length including the duplicate elements. But in this article we will see how to get the total count of the distinct elements or unique elements in a list."
},
{
"code": null,
"e": 1920,
"s": 1448,
"text": "In the below example we use the counter() from the collections module. In this module a Counter is a dict subclass for counting hashable objects. Counter is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. So from the original list we create another list made up of only the elements whose key values are present once. This is a distinct list of elements. And then we find the length of this new list."
},
{
"code": null,
"e": 2183,
"s": 1920,
"text": "from collections import Counter\nlist = ['Mon', 'Tue', 'Wed', 'Mon','Tue']\nprint(\"Length of original list\",len(list))\n\ndistinct_list= (Counter(list).keys())\nprint(\"List with distinct elements:\\n\",distinct_list)\nprint(\"Length of distinct list:\",len(distinct_list))"
},
{
"code": null,
"e": 2238,
"s": 2183,
"text": "Running the above code gives us the following result β"
},
{
"code": null,
"e": 2356,
"s": 2238,
"text": "Length of original list 5\nList with distinct elements:\n dict_keys(['Mon', 'Tue', 'Wed'])\nLength of distinct list: 3"
}
] |
How to apply functions in a Group in a Pandas DataFrame?
|
03 Jan, 2021
In this article, letβs see how to apply functions in a group in a Pandas Dataframe. Steps to be followed for performing this task are β
Import the necessary libraries.
Set up the data as a Pandas DataFrame.
Use apply function to find different statistical measures like Rolling Mean, Average, Sum, Maximum, and Minimum. You can use the lambda function for this.
Below is the implementation-
Letβs create the dataframe.
Python3
#import librariesimport pandas as pd # set up the datadata_dict = {"Student House": ["Lavender", "Lavender", "Lavender", "Lavender", "Daisy", "Daisy", "Daisy", "Daisy", "Daffodils", "Daffodils", "Daffodils", "Daffodils"], "Points": [10, 4, 6, 7, 3, 8, 9, 10, 4, 5, 6, 7]} data_df = pd.DataFrame(data_dict)print("Dataframe : ")data_df
Output:
Example 1:
Python3
# finding rolling meanrolling_mean = data_df.groupby("Student House")["Points"].apply( lambda x: x.rolling(center=False, window=2).mean()) print("Rolling Mean:")print(rolling_mean)
Output:
Example 2:
Python3
# finding meanmean = data_df.groupby("Student House")["Points"].apply( lambda x: x.mean()) print("Mean:")print(mean)
Output:
Example 3:
Python3
# finding sumsum = data_df.groupby("Student House")["Points"].apply( lambda x: x.sum()) print("Sum:")print(sum)
Output:
Picked
Python pandas-groupby
Python-pandas
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": "\n03 Jan, 2021"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "In this article, letβs see how to apply functions in a group in a Pandas Dataframe. Steps to be followed for performing this task are β "
},
{
"code": null,
"e": 197,
"s": 165,
"text": "Import the necessary libraries."
},
{
"code": null,
"e": 236,
"s": 197,
"text": "Set up the data as a Pandas DataFrame."
},
{
"code": null,
"e": 391,
"s": 236,
"text": "Use apply function to find different statistical measures like Rolling Mean, Average, Sum, Maximum, and Minimum. You can use the lambda function for this."
},
{
"code": null,
"e": 420,
"s": 391,
"text": "Below is the implementation-"
},
{
"code": null,
"e": 448,
"s": 420,
"text": "Letβs create the dataframe."
},
{
"code": null,
"e": 456,
"s": 448,
"text": "Python3"
},
{
"code": "#import librariesimport pandas as pd # set up the datadata_dict = {\"Student House\": [\"Lavender\", \"Lavender\", \"Lavender\", \"Lavender\", \"Daisy\", \"Daisy\", \"Daisy\", \"Daisy\", \"Daffodils\", \"Daffodils\", \"Daffodils\", \"Daffodils\"], \"Points\": [10, 4, 6, 7, 3, 8, 9, 10, 4, 5, 6, 7]} data_df = pd.DataFrame(data_dict)print(\"Dataframe : \")data_df",
"e": 911,
"s": 456,
"text": null
},
{
"code": null,
"e": 919,
"s": 911,
"text": "Output:"
},
{
"code": null,
"e": 930,
"s": 919,
"text": "Example 1:"
},
{
"code": null,
"e": 938,
"s": 930,
"text": "Python3"
},
{
"code": "# finding rolling meanrolling_mean = data_df.groupby(\"Student House\")[\"Points\"].apply( lambda x: x.rolling(center=False, window=2).mean()) print(\"Rolling Mean:\")print(rolling_mean)",
"e": 1123,
"s": 938,
"text": null
},
{
"code": null,
"e": 1131,
"s": 1123,
"text": "Output:"
},
{
"code": null,
"e": 1142,
"s": 1131,
"text": "Example 2:"
},
{
"code": null,
"e": 1150,
"s": 1142,
"text": "Python3"
},
{
"code": "# finding meanmean = data_df.groupby(\"Student House\")[\"Points\"].apply( lambda x: x.mean()) print(\"Mean:\")print(mean)",
"e": 1269,
"s": 1150,
"text": null
},
{
"code": null,
"e": 1277,
"s": 1269,
"text": "Output:"
},
{
"code": null,
"e": 1288,
"s": 1277,
"text": "Example 3:"
},
{
"code": null,
"e": 1296,
"s": 1288,
"text": "Python3"
},
{
"code": "# finding sumsum = data_df.groupby(\"Student House\")[\"Points\"].apply( lambda x: x.sum()) print(\"Sum:\")print(sum)",
"e": 1410,
"s": 1296,
"text": null
},
{
"code": null,
"e": 1418,
"s": 1410,
"text": "Output:"
},
{
"code": null,
"e": 1425,
"s": 1418,
"text": "Picked"
},
{
"code": null,
"e": 1447,
"s": 1425,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 1461,
"s": 1447,
"text": "Python-pandas"
},
{
"code": null,
"e": 1468,
"s": 1461,
"text": "Python"
},
{
"code": null,
"e": 1566,
"s": 1468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1598,
"s": 1566,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1625,
"s": 1598,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1646,
"s": 1625,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1669,
"s": 1646,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1725,
"s": 1669,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1756,
"s": 1725,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1798,
"s": 1756,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1840,
"s": 1798,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1879,
"s": 1840,
"text": "Python | Get unique values from a list"
}
] |
Shell Script to Demonstrate Wait Command in Linux
|
02 Jun, 2022
Wait command is one of the process management commands. There are different process commands in Linux mainly 5 commands are widely used which are ps, wait, sleep, kill, exit.
ps is an acronym for process status. It displays information about the active processes. wait command will suspend execution of the calling thread until one of its children terminate. It will return the exit status of that command. The sleep command is used to delay the execution of the next command for a given number of seconds, hours, minutes, days. kill is used to terminate a background running process. It sends a terminate signal to the process and then processes halts. It takes process ID as an argument. exit command is used to exit from the current shell environment.
Letβs take some examples to understand more about wait commands:
wait is an inbuilt command in the Linux shell. It waits for the process to change its state i.e. it waits for any running process to complete and returns the exit status.
Syntax:
wait [ID]
Here, ID is a PID (Process Identifier) which is unique for each running process. To find the process ID of a process you can use the command:
pidof [process_name]
Example: Finding PID of VLC (video player)
Finding PID of process
Here, VLC is the process name. And 3868 is its Process ID.
Creating a simple process.
Using a special variable($!) to find the PID(process ID) for that particular process.
Print the process ID.
Using wait command with process ID as an argument to wait until the process finishes.
After the process is finished printing process ID with its exit status.
Note: Exist status 0 indicates that the process is executed successfully without any issue. Any value other than 0 indicates that the process has not been completed successfully.
Script:
#!/bin/bash
# creating simple process that will create file and write into it
cat > GEEKSFORGEEKS.txt <<< "Something is going to save into this file" &
# this will store the process id of the running process
# $! is a special variable in bash
# that will hold the PID of the last active process i.e. creating a file.
pid=$!
# print process is running with its PID
echo "Process with PID $pid is running"
# Waiting until process is Completed
wait $pid
# print process id with its Exit status
# $? is special variable that holds the return value of the recently executed command.
echo "Process with PID $pid has finished with Exit status: $?"
Output:
Using wait command
Here, we are creating a process that will create a file with a given string and store it into the storage device. Then using a special variable β$!β we will store the PID of that process into another variable pid. Then we are displaying the process ID and using the wait command to wait until the process is completed. After the process has been executed we are returning the process exit status code and its PID. If the Exit status code is 0 then we can say that the process is executed successfully.
Approach:
Creating multiple processes.Creating a text file and writing into it.Sleep 2 will pause the shell for 2 seconds.Again creating a text file and writing into it.
Creating a text file and writing into it.
Sleep 2 will pause the shell for 2 seconds.
Again creating a text file and writing into it.
Display that we are running multiple processes.
Using wait -f to wait until all the above process has been executed successfully.
After the process is finished we are printing its exit status using a special variable $?.
Script:
#!/bin/bash
# creating multiple processes
cat > Geeks.txt <<< "GeeksGeeks" &
sleep 2 &
cat > something_new.txt <<< "Something new is created" &
echo "Multiple processes are running"
# using wait to wait for the processes to finish
# -f will wait until all the processes is executed.
wait -f
#printing process Exit status
# $? is special variable that holds the return value of the recently executed command.
echo "All Processes end with Exit status: $?"
Output:
Using wait command
Here, we are creating 3 processes. Then we simply use the wait command to wait for all processes to be finished. -f is used to wait for all processes to be finished before returning the exit code. After that, we simply print the exit status of these processes using a special variable β$?β
akshaysingh98088
anikakapoor
varshagumber28
nikhatkhan11
Picked
Shell Script
How To
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n02 Jun, 2022"
},
{
"code": null,
"e": 228,
"s": 53,
"text": "Wait command is one of the process management commands. There are different process commands in Linux mainly 5 commands are widely used which are ps, wait, sleep, kill, exit."
},
{
"code": null,
"e": 808,
"s": 228,
"text": "ps is an acronym for process status. It displays information about the active processes. wait command will suspend execution of the calling thread until one of its children terminate. It will return the exit status of that command. The sleep command is used to delay the execution of the next command for a given number of seconds, hours, minutes, days. kill is used to terminate a background running process. It sends a terminate signal to the process and then processes halts. It takes process ID as an argument. exit command is used to exit from the current shell environment."
},
{
"code": null,
"e": 873,
"s": 808,
"text": "Letβs take some examples to understand more about wait commands:"
},
{
"code": null,
"e": 1044,
"s": 873,
"text": "wait is an inbuilt command in the Linux shell. It waits for the process to change its state i.e. it waits for any running process to complete and returns the exit status."
},
{
"code": null,
"e": 1052,
"s": 1044,
"text": "Syntax:"
},
{
"code": null,
"e": 1062,
"s": 1052,
"text": "wait [ID]"
},
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Here, ID is a PID (Process Identifier) which is unique for each running process. To find the process ID of a process you can use the command:"
},
{
"code": null,
"e": 1225,
"s": 1204,
"text": "pidof [process_name]"
},
{
"code": null,
"e": 1268,
"s": 1225,
"text": "Example: Finding PID of VLC (video player)"
},
{
"code": null,
"e": 1291,
"s": 1268,
"text": "Finding PID of process"
},
{
"code": null,
"e": 1350,
"s": 1291,
"text": "Here, VLC is the process name. And 3868 is its Process ID."
},
{
"code": null,
"e": 1377,
"s": 1350,
"text": "Creating a simple process."
},
{
"code": null,
"e": 1463,
"s": 1377,
"text": "Using a special variable($!) to find the PID(process ID) for that particular process."
},
{
"code": null,
"e": 1485,
"s": 1463,
"text": "Print the process ID."
},
{
"code": null,
"e": 1571,
"s": 1485,
"text": "Using wait command with process ID as an argument to wait until the process finishes."
},
{
"code": null,
"e": 1643,
"s": 1571,
"text": "After the process is finished printing process ID with its exit status."
},
{
"code": null,
"e": 1822,
"s": 1643,
"text": "Note: Exist status 0 indicates that the process is executed successfully without any issue. Any value other than 0 indicates that the process has not been completed successfully."
},
{
"code": null,
"e": 1830,
"s": 1822,
"text": "Script:"
},
{
"code": null,
"e": 2477,
"s": 1830,
"text": "#!/bin/bash\n\n# creating simple process that will create file and write into it\ncat > GEEKSFORGEEKS.txt <<< \"Something is going to save into this file\" &\n\n# this will store the process id of the running process\n# $! is a special variable in bash \n# that will hold the PID of the last active process i.e. creating a file.\npid=$!\n\n# print process is running with its PID\necho \"Process with PID $pid is running\"\n\n# Waiting until process is Completed\nwait $pid\n\n# print process id with its Exit status\n# $? is special variable that holds the return value of the recently executed command.\necho \"Process with PID $pid has finished with Exit status: $?\""
},
{
"code": null,
"e": 2485,
"s": 2477,
"text": "Output:"
},
{
"code": null,
"e": 2504,
"s": 2485,
"text": "Using wait command"
},
{
"code": null,
"e": 3006,
"s": 2504,
"text": "Here, we are creating a process that will create a file with a given string and store it into the storage device. Then using a special variable β$!β we will store the PID of that process into another variable pid. Then we are displaying the process ID and using the wait command to wait until the process is completed. After the process has been executed we are returning the process exit status code and its PID. If the Exit status code is 0 then we can say that the process is executed successfully."
},
{
"code": null,
"e": 3016,
"s": 3006,
"text": "Approach:"
},
{
"code": null,
"e": 3176,
"s": 3016,
"text": "Creating multiple processes.Creating a text file and writing into it.Sleep 2 will pause the shell for 2 seconds.Again creating a text file and writing into it."
},
{
"code": null,
"e": 3218,
"s": 3176,
"text": "Creating a text file and writing into it."
},
{
"code": null,
"e": 3262,
"s": 3218,
"text": "Sleep 2 will pause the shell for 2 seconds."
},
{
"code": null,
"e": 3310,
"s": 3262,
"text": "Again creating a text file and writing into it."
},
{
"code": null,
"e": 3358,
"s": 3310,
"text": "Display that we are running multiple processes."
},
{
"code": null,
"e": 3440,
"s": 3358,
"text": "Using wait -f to wait until all the above process has been executed successfully."
},
{
"code": null,
"e": 3531,
"s": 3440,
"text": "After the process is finished we are printing its exit status using a special variable $?."
},
{
"code": null,
"e": 3539,
"s": 3531,
"text": "Script:"
},
{
"code": null,
"e": 3997,
"s": 3539,
"text": "#!/bin/bash\n\n# creating multiple processes\ncat > Geeks.txt <<< \"GeeksGeeks\" &\nsleep 2 &\ncat > something_new.txt <<< \"Something new is created\" &\n\necho \"Multiple processes are running\"\n\n# using wait to wait for the processes to finish\n# -f will wait until all the processes is executed.\nwait -f\n\n#printing process Exit status\n# $? is special variable that holds the return value of the recently executed command.\necho \"All Processes end with Exit status: $?\""
},
{
"code": null,
"e": 4005,
"s": 3997,
"text": "Output:"
},
{
"code": null,
"e": 4024,
"s": 4005,
"text": "Using wait command"
},
{
"code": null,
"e": 4314,
"s": 4024,
"text": "Here, we are creating 3 processes. Then we simply use the wait command to wait for all processes to be finished. -f is used to wait for all processes to be finished before returning the exit code. After that, we simply print the exit status of these processes using a special variable β$?β"
},
{
"code": null,
"e": 4331,
"s": 4314,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 4343,
"s": 4331,
"text": "anikakapoor"
},
{
"code": null,
"e": 4358,
"s": 4343,
"text": "varshagumber28"
},
{
"code": null,
"e": 4371,
"s": 4358,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 4378,
"s": 4371,
"text": "Picked"
},
{
"code": null,
"e": 4391,
"s": 4378,
"text": "Shell Script"
},
{
"code": null,
"e": 4398,
"s": 4391,
"text": "How To"
},
{
"code": null,
"e": 4409,
"s": 4398,
"text": "Linux-Unix"
}
] |
median_grouped() function in Python statistics module
|
30 May, 2022
Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data function as well and this is the best part about this robust and convenient language. median_grouped() function under the Statistics module, helps to calculate median value from a set of continuous data.The data are assumed to be grouped into intervals of width intervals. Each data point in the array is the midpoint of the interval containing the true value. The median is calculated by interpolation within the median interval (the interval containing the median value), assuming that the true values within that interval are distributed uniformly :
median = L + interval * (N / 2 - CF) / FL = lower limit of the median interval
N = total number of data points
CF = number of data points below the median interval
F = number of data points in the median interval
Syntax : median_grouped( [data-set], interval)Parameters : [data-set] : List or tuple or an iterable with a set of numeric values. interval (1 by default) : Determines the width of grouped data and changing. It will also change the interpolation of calculated median.Returntype : Return the median of grouped continuous data, calculated as 50th percentile.Exceptions : StatisticsError is raised when iterable passed is empty or when list is null.
Code #1 :
Python3
# Python3 code to demonstrate median_grouped() # importing median_grouped from# the statistics modulefrom statistics import median_grouped # creating an simple data-setdata1 = [15, 20, 25, 30, 35] # printing median_grouped for the setprint("Grouped Median of the median is %s" %(median_grouped(data1)))
Output :
Grouped Median of the median is 25.0
Code #2 : Working of median_grouped on a range of varying data
Python3
# Python code to demonstrate the# working of median_grouped() # importing statistics modulefrom statistics import median_grouped # tuple of a set of positive integersset1 = [2, 5, 3, 4, 8, 9] # tuple of a set of negative integersset2 = [-6, -2, -9, -12] # tuple of a set of positive# and negative integersset3 = [2, 4, 8, 9, -2, -3, -5, -6] # Printing grouped median for# the given set of dataprint("Grouped Median of set 1 is % s" % (median_grouped(set1)))print("Grouped Median of set 2 is % s" % (median_grouped(set2)))print("Grouped Median of set 3 is % s" % (median_grouped(set3)))
Output :
Grouped Median of set 1 is 4.5
Grouped Median of set 2 is -6.5
Grouped Median of set 3 is 1.5
Code #3 : Working of interval
Python3
# Python code to demonstrate the working of# interval in median_grouped() function # importing statistics modulefrom statistics import median_grouped # creating a tuple of simple dataset1 = (10, 12, 13, 12, 13, 15) # Printing median_grouped()# keeping default interval at 1print("Grouped Median for Interval set as "\ "(default) 1 is % s" %(median_grouped(set1))) # For interval value of 2print("Grouped Median for Interval set as "\ "2 is % s" %(median_grouped(set1, interval = 2))) # Now for interval value of 5print("Grouped Median for Interval set as "\ "5 is % s" %(median_grouped(set1, interval = 5)))
Output :
Grouped Median for Interval set as (default) 1 is 12.5
Grouped Median for Interval set as 2 is 12.0
Grouped Median for Interval set as 5 is 10.5
Grouped Median for Interval set as 10 is 8.0
Note : Observe a pattern that as the interval value is increased the median value decreases. Code #4 : Demonstrates StatisticsError
Python3
# Python code to demonstrate StatisticsError # importing the statistics moduleimport statistics # creating an empty datasetlist1 = [] # Will raise StatisticsErrorprint(statistics.median_grouped(list1))
Output :
Traceback (most recent call last):
File "/home/0990a4a3f5206c7cd12a596cf82a1587.py", line 10, in
print(statistics.median_grouped(list1))
File "/usr/lib/python3.5/statistics.py", line 431, in median_grouped
raise StatisticsError("no median for empty data")
statistics.StatisticsError: no median for empty data
Applications : Grouped Median has all the same applications as median. It is commonly used in calculations where large number of data is involved like banking and finance. It is an essential part of statistics which is the most powerful tool in data calculation.
simmytarika5
Python-Built-in-functions
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": "\n30 May, 2022"
},
{
"code": null,
"e": 926,
"s": 28,
"text": "Coming to Statistical functions, median of a data-set is the measure of robust central tendency, which is less affected by the presence of outliers in data. As seen previously, medians of an ungrouped data-set using median(), median_high(), median_low() functions. Python gives the option to calculate the median of grouped and continuous data function as well and this is the best part about this robust and convenient language. median_grouped() function under the Statistics module, helps to calculate median value from a set of continuous data.The data are assumed to be grouped into intervals of width intervals. Each data point in the array is the midpoint of the interval containing the true value. The median is calculated by interpolation within the median interval (the interval containing the median value), assuming that the true values within that interval are distributed uniformly : "
},
{
"code": null,
"e": 1139,
"s": 926,
"text": "median = L + interval * (N / 2 - CF) / FL = lower limit of the median interval\nN = total number of data points\nCF = number of data points below the median interval\nF = number of data points in the median interval"
},
{
"code": null,
"e": 1590,
"s": 1141,
"text": "Syntax : median_grouped( [data-set], interval)Parameters : [data-set] : List or tuple or an iterable with a set of numeric values. interval (1 by default) : Determines the width of grouped data and changing. It will also change the interpolation of calculated median.Returntype : Return the median of grouped continuous data, calculated as 50th percentile.Exceptions : StatisticsError is raised when iterable passed is empty or when list is null. "
},
{
"code": null,
"e": 1604,
"s": 1590,
"text": " Code #1 : "
},
{
"code": null,
"e": 1612,
"s": 1604,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate median_grouped() # importing median_grouped from# the statistics modulefrom statistics import median_grouped # creating an simple data-setdata1 = [15, 20, 25, 30, 35] # printing median_grouped for the setprint(\"Grouped Median of the median is %s\" %(median_grouped(data1)))",
"e": 1930,
"s": 1612,
"text": null
},
{
"code": null,
"e": 1941,
"s": 1930,
"text": "Output : "
},
{
"code": null,
"e": 1978,
"s": 1941,
"text": "Grouped Median of the median is 25.0"
},
{
"code": null,
"e": 2045,
"s": 1978,
"text": " Code #2 : Working of median_grouped on a range of varying data "
},
{
"code": null,
"e": 2053,
"s": 2045,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the# working of median_grouped() # importing statistics modulefrom statistics import median_grouped # tuple of a set of positive integersset1 = [2, 5, 3, 4, 8, 9] # tuple of a set of negative integersset2 = [-6, -2, -9, -12] # tuple of a set of positive# and negative integersset3 = [2, 4, 8, 9, -2, -3, -5, -6] # Printing grouped median for# the given set of dataprint(\"Grouped Median of set 1 is % s\" % (median_grouped(set1)))print(\"Grouped Median of set 2 is % s\" % (median_grouped(set2)))print(\"Grouped Median of set 3 is % s\" % (median_grouped(set3)))",
"e": 2639,
"s": 2053,
"text": null
},
{
"code": null,
"e": 2650,
"s": 2639,
"text": "Output : "
},
{
"code": null,
"e": 2744,
"s": 2650,
"text": "Grouped Median of set 1 is 4.5\nGrouped Median of set 2 is -6.5\nGrouped Median of set 3 is 1.5"
},
{
"code": null,
"e": 2778,
"s": 2744,
"text": " Code #3 : Working of interval "
},
{
"code": null,
"e": 2786,
"s": 2778,
"text": "Python3"
},
{
"code": "# Python code to demonstrate the working of# interval in median_grouped() function # importing statistics modulefrom statistics import median_grouped # creating a tuple of simple dataset1 = (10, 12, 13, 12, 13, 15) # Printing median_grouped()# keeping default interval at 1print(\"Grouped Median for Interval set as \"\\ \"(default) 1 is % s\" %(median_grouped(set1))) # For interval value of 2print(\"Grouped Median for Interval set as \"\\ \"2 is % s\" %(median_grouped(set1, interval = 2))) # Now for interval value of 5print(\"Grouped Median for Interval set as \"\\ \"5 is % s\" %(median_grouped(set1, interval = 5)))",
"e": 3409,
"s": 2786,
"text": null
},
{
"code": null,
"e": 3420,
"s": 3409,
"text": "Output : "
},
{
"code": null,
"e": 3610,
"s": 3420,
"text": "Grouped Median for Interval set as (default) 1 is 12.5\nGrouped Median for Interval set as 2 is 12.0\nGrouped Median for Interval set as 5 is 10.5\nGrouped Median for Interval set as 10 is 8.0"
},
{
"code": null,
"e": 3748,
"s": 3610,
"text": " Note : Observe a pattern that as the interval value is increased the median value decreases. Code #4 : Demonstrates StatisticsError "
},
{
"code": null,
"e": 3756,
"s": 3748,
"text": "Python3"
},
{
"code": "# Python code to demonstrate StatisticsError # importing the statistics moduleimport statistics # creating an empty datasetlist1 = [] # Will raise StatisticsErrorprint(statistics.median_grouped(list1))",
"e": 3958,
"s": 3756,
"text": null
},
{
"code": null,
"e": 3969,
"s": 3958,
"text": "Output : "
},
{
"code": null,
"e": 4291,
"s": 3969,
"text": "Traceback (most recent call last):\n File \"/home/0990a4a3f5206c7cd12a596cf82a1587.py\", line 10, in \n print(statistics.median_grouped(list1))\n File \"/usr/lib/python3.5/statistics.py\", line 431, in median_grouped\n raise StatisticsError(\"no median for empty data\")\nstatistics.StatisticsError: no median for empty data"
},
{
"code": null,
"e": 4557,
"s": 4291,
"text": " Applications : Grouped Median has all the same applications as median. It is commonly used in calculations where large number of data is involved like banking and finance. It is an essential part of statistics which is the most powerful tool in data calculation. "
},
{
"code": null,
"e": 4570,
"s": 4557,
"text": "simmytarika5"
},
{
"code": null,
"e": 4596,
"s": 4570,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 4603,
"s": 4596,
"text": "Python"
},
{
"code": null,
"e": 4701,
"s": 4603,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4733,
"s": 4701,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4760,
"s": 4733,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4781,
"s": 4760,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4804,
"s": 4781,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4860,
"s": 4804,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4891,
"s": 4860,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4933,
"s": 4891,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4975,
"s": 4933,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5014,
"s": 4975,
"text": "Python | Get unique values from a list"
}
] |
Understanding Rainbow Table Attack
|
17 Jun, 2021
What is a Rainbow Table?
The passwords in a computer system are not stored directly as plain texts but are hashed using encryption. A hash function is a 1-way function, which means that it canβt be decrypted. Whenever a user enters a password, it is converted into a hash value and is compared with the already stored hash value. If the values match, the user is authenticated. A rainbow table is a database that is used to gain authentication by cracking the password hash. It is a precomputed dictionary of plaintext passwords and their corresponding hash values that can be used to find out what plaintext password produces a particular hash. Since more than one text can produce the same hash, itβs not important to know what the original password really was, as long as it produces the same hash.
How does the Rainbow Table Attack work?
A rainbow table works by doing a cryptanalysis very quickly and effectively. Unlike bruteforce attack, which works by calculating the hash function of every string present with them, calculating their hash value and then compare it with the one in the computer, at every step. A rainbow table attack eliminates this need by already computing hashes of the large set of available strings. There are two main steps in this:
Creating a Table Here, the hash of a string is taken and then reduced to create a new string, which is reduced again, repeatedly. For example, letβs create a table of the most common password, 12345678, using MD5 hash function on first 8 characters:
First we take the string and pass it through md5 hash function.
hashMD5(12345678) = 25d55ad283aa400af464c76d713c07ad
We reduce the hash by taking only the first 8 characters. Then, we re-hash it.
hashMD5(25d55ad2) = 5c41c6b3958e798662d8853ece970f70
This is repeated until enough hashes in output chain. This represents one chain, which starts from the first plain text and ends at the last hash.
After obtaining enough chains, we store them in a table.
Cracking the Password Starting off with the hashed text (the password) its checked if it exists in the database. If so, go to the start of the chain and start hashing until there is a match. As soon as the match is obtained, the process ceases and the authentication is cracked. The following flowchart explains the steps:
Advantages and Disadvantages of Rainbow Table Attack
Advantages:
Unlike brute-forcing, performing the hash function isnβt the problem here (since everything is precomputed). With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table.The exact password string isnβt needed to be known. If the hash is matched, it doesnβt matter if the string isnβt the password itself. It will be authenticated.
Unlike brute-forcing, performing the hash function isnβt the problem here (since everything is precomputed). With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table.
The exact password string isnβt needed to be known. If the hash is matched, it doesnβt matter if the string isnβt the password itself. It will be authenticated.
Disadvantages:
A large amount of storage is required for store tables.With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table.
A large amount of storage is required for store tables.
With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table.
Defense against Rainbow Table Attacks
Rainbow table attacks can easily be prevented by using salt techniques, which is a random data that is passed into the hash function along with the plain text. This ensures that every password has a unique generated hash and hence, rainbow table attack, which works on the principle that more than one text can have the same hash value, is prevented.
Another technique that helps prevent precomputation attacks is key stretching. Using this, the salt, the password, and some intermediate hash values are run through the hash function multiple times to increase the computation time required to hash each password. An alternative approach, called key strengthening, extends the key with a random salt, but then (unlike in key stretching) securely deletes the salt. This forces both the attacker and legitimate users to perform a brute-force search for the salt value. Therefore, there is no point of bypassing salting.
surindertarika1234
cryptography
Web Technologies
cryptography
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 79,
"s": 54,
"text": "What is a Rainbow Table?"
},
{
"code": null,
"e": 857,
"s": 79,
"text": "The passwords in a computer system are not stored directly as plain texts but are hashed using encryption. A hash function is a 1-way function, which means that it canβt be decrypted. Whenever a user enters a password, it is converted into a hash value and is compared with the already stored hash value. If the values match, the user is authenticated. A rainbow table is a database that is used to gain authentication by cracking the password hash. It is a precomputed dictionary of plaintext passwords and their corresponding hash values that can be used to find out what plaintext password produces a particular hash. Since more than one text can produce the same hash, itβs not important to know what the original password really was, as long as it produces the same hash. "
},
{
"code": null,
"e": 897,
"s": 857,
"text": "How does the Rainbow Table Attack work?"
},
{
"code": null,
"e": 1320,
"s": 897,
"text": "A rainbow table works by doing a cryptanalysis very quickly and effectively. Unlike bruteforce attack, which works by calculating the hash function of every string present with them, calculating their hash value and then compare it with the one in the computer, at every step. A rainbow table attack eliminates this need by already computing hashes of the large set of available strings. There are two main steps in this: "
},
{
"code": null,
"e": 1571,
"s": 1320,
"text": "Creating a Table Here, the hash of a string is taken and then reduced to create a new string, which is reduced again, repeatedly. For example, letβs create a table of the most common password, 12345678, using MD5 hash function on first 8 characters: "
},
{
"code": null,
"e": 1636,
"s": 1571,
"text": "First we take the string and pass it through md5 hash function. "
},
{
"code": null,
"e": 1689,
"s": 1636,
"text": "hashMD5(12345678) = 25d55ad283aa400af464c76d713c07ad"
},
{
"code": null,
"e": 1769,
"s": 1689,
"text": "We reduce the hash by taking only the first 8 characters. Then, we re-hash it. "
},
{
"code": null,
"e": 1822,
"s": 1769,
"text": "hashMD5(25d55ad2) = 5c41c6b3958e798662d8853ece970f70"
},
{
"code": null,
"e": 1969,
"s": 1822,
"text": "This is repeated until enough hashes in output chain. This represents one chain, which starts from the first plain text and ends at the last hash."
},
{
"code": null,
"e": 2026,
"s": 1969,
"text": "After obtaining enough chains, we store them in a table."
},
{
"code": null,
"e": 2350,
"s": 2026,
"text": "Cracking the Password Starting off with the hashed text (the password) its checked if it exists in the database. If so, go to the start of the chain and start hashing until there is a match. As soon as the match is obtained, the process ceases and the authentication is cracked. The following flowchart explains the steps: "
},
{
"code": null,
"e": 2403,
"s": 2350,
"text": "Advantages and Disadvantages of Rainbow Table Attack"
},
{
"code": null,
"e": 2417,
"s": 2403,
"text": "Advantages: "
},
{
"code": null,
"e": 2803,
"s": 2417,
"text": "Unlike brute-forcing, performing the hash function isnβt the problem here (since everything is precomputed). With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table.The exact password string isnβt needed to be known. If the hash is matched, it doesnβt matter if the string isnβt the password itself. It will be authenticated."
},
{
"code": null,
"e": 3029,
"s": 2803,
"text": "Unlike brute-forcing, performing the hash function isnβt the problem here (since everything is precomputed). With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table."
},
{
"code": null,
"e": 3190,
"s": 3029,
"text": "The exact password string isnβt needed to be known. If the hash is matched, it doesnβt matter if the string isnβt the password itself. It will be authenticated."
},
{
"code": null,
"e": 3207,
"s": 3190,
"text": "Disadvantages: "
},
{
"code": null,
"e": 3379,
"s": 3207,
"text": "A large amount of storage is required for store tables.With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table."
},
{
"code": null,
"e": 3435,
"s": 3379,
"text": "A large amount of storage is required for store tables."
},
{
"code": null,
"e": 3552,
"s": 3435,
"text": "With all of the values already computed, itβs simplified to just a simple search-and-compare operation on the table."
},
{
"code": null,
"e": 3590,
"s": 3552,
"text": "Defense against Rainbow Table Attacks"
},
{
"code": null,
"e": 3942,
"s": 3590,
"text": "Rainbow table attacks can easily be prevented by using salt techniques, which is a random data that is passed into the hash function along with the plain text. This ensures that every password has a unique generated hash and hence, rainbow table attack, which works on the principle that more than one text can have the same hash value, is prevented. "
},
{
"code": null,
"e": 4510,
"s": 3942,
"text": "Another technique that helps prevent precomputation attacks is key stretching. Using this, the salt, the password, and some intermediate hash values are run through the hash function multiple times to increase the computation time required to hash each password. An alternative approach, called key strengthening, extends the key with a random salt, but then (unlike in key stretching) securely deletes the salt. This forces both the attacker and legitimate users to perform a brute-force search for the salt value. Therefore, there is no point of bypassing salting. "
},
{
"code": null,
"e": 4529,
"s": 4510,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4542,
"s": 4529,
"text": "cryptography"
},
{
"code": null,
"e": 4559,
"s": 4542,
"text": "Web Technologies"
},
{
"code": null,
"e": 4572,
"s": 4559,
"text": "cryptography"
}
] |
Return all dates between two dates in an array in PHP
|
21 Nov, 2018
Given two dates (start date and end date) and the task is to return all the dates in an array.
Example 1: In this example, use date interval class which stores fixed amount of time (in years, months, days, hours etc) or relative time string in the format that DateTime.
<?php // Function to get all the dates in given rangefunction getDatesFromRange($start, $end, $format = 'Y-m-d') { // Declare an empty array $array = array(); // Variable that store the date interval // of period 1 day $interval = new DateInterval('P1D'); $realEnd = new DateTime($end); $realEnd->add($interval); $period = new DatePeriod(new DateTime($start), $interval, $realEnd); // Use loop to store date into array foreach($period as $date) { $array[] = $date->format($format); } // Return the array elements return $array;} // Function call with passing the start date and end date$Date = getDatesFromRange('2010-10-01', '2010-10-05'); var_dump($Date); ?>
array(5) {
[0]=>
string(10) "2010-10-01"
[1]=>
string(10) "2010-10-02"
[2]=>
string(10) "2010-10-03"
[3]=>
string(10) "2010-10-04"
[4]=>
string(10) "2010-10-05"
}
Example 2: This example use strtotime() function which is used to convert an English textual date-time description to a UNIX timestamp. It returns a timestamp on success, False otherwise.
<?php // Declare two dates$Date1 = '01-10-2010';$Date2 = '05-10-2010'; // Declare an empty array$array = array(); // Use strtotime function$Variable1 = strtotime($Date1);$Variable2 = strtotime($Date2); // Use for loop to store dates into array// 86400 sec = 24 hrs = 60*60*24 = 1 dayfor ($currentDate = $Variable1; $currentDate <= $Variable2; $currentDate += (86400)) { $Store = date('Y-m-d', $currentDate);$array[] = $Store;} // Display the dates in array formatprint_r($array);?>
Array
(
[0] => 2010-10-01
[1] => 2010-10-02
[2] => 2010-10-03
[3] => 2010-10-04
[4] => 2010-10-05
)
PHP-date-time
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Nov, 2018"
},
{
"code": null,
"e": 123,
"s": 28,
"text": "Given two dates (start date and end date) and the task is to return all the dates in an array."
},
{
"code": null,
"e": 298,
"s": 123,
"text": "Example 1: In this example, use date interval class which stores fixed amount of time (in years, months, days, hours etc) or relative time string in the format that DateTime."
},
{
"code": "<?php // Function to get all the dates in given rangefunction getDatesFromRange($start, $end, $format = 'Y-m-d') { // Declare an empty array $array = array(); // Variable that store the date interval // of period 1 day $interval = new DateInterval('P1D'); $realEnd = new DateTime($end); $realEnd->add($interval); $period = new DatePeriod(new DateTime($start), $interval, $realEnd); // Use loop to store date into array foreach($period as $date) { $array[] = $date->format($format); } // Return the array elements return $array;} // Function call with passing the start date and end date$Date = getDatesFromRange('2010-10-01', '2010-10-05'); var_dump($Date); ?>",
"e": 1047,
"s": 298,
"text": null
},
{
"code": null,
"e": 1231,
"s": 1047,
"text": "array(5) {\n [0]=>\n string(10) \"2010-10-01\"\n [1]=>\n string(10) \"2010-10-02\"\n [2]=>\n string(10) \"2010-10-03\"\n [3]=>\n string(10) \"2010-10-04\"\n [4]=>\n string(10) \"2010-10-05\"\n}\n"
},
{
"code": null,
"e": 1419,
"s": 1231,
"text": "Example 2: This example use strtotime() function which is used to convert an English textual date-time description to a UNIX timestamp. It returns a timestamp on success, False otherwise."
},
{
"code": "<?php // Declare two dates$Date1 = '01-10-2010';$Date2 = '05-10-2010'; // Declare an empty array$array = array(); // Use strtotime function$Variable1 = strtotime($Date1);$Variable2 = strtotime($Date2); // Use for loop to store dates into array// 86400 sec = 24 hrs = 60*60*24 = 1 dayfor ($currentDate = $Variable1; $currentDate <= $Variable2; $currentDate += (86400)) { $Store = date('Y-m-d', $currentDate);$array[] = $Store;} // Display the dates in array formatprint_r($array);?>",
"e": 1975,
"s": 1419,
"text": null
},
{
"code": null,
"e": 2096,
"s": 1975,
"text": "Array\n(\n [0] => 2010-10-01\n [1] => 2010-10-02\n [2] => 2010-10-03\n [3] => 2010-10-04\n [4] => 2010-10-05\n)\n"
},
{
"code": null,
"e": 2110,
"s": 2096,
"text": "PHP-date-time"
},
{
"code": null,
"e": 2117,
"s": 2110,
"text": "Picked"
},
{
"code": null,
"e": 2121,
"s": 2117,
"text": "PHP"
},
{
"code": null,
"e": 2134,
"s": 2121,
"text": "PHP Programs"
},
{
"code": null,
"e": 2151,
"s": 2134,
"text": "Web Technologies"
},
{
"code": null,
"e": 2155,
"s": 2151,
"text": "PHP"
},
{
"code": null,
"e": 2253,
"s": 2155,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2298,
"s": 2253,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2348,
"s": 2298,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2372,
"s": 2348,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 2424,
"s": 2372,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2464,
"s": 2424,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2509,
"s": 2464,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 2559,
"s": 2509,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2611,
"s": 2559,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 2651,
"s": 2611,
"text": "How to convert array to string in PHP ?"
}
] |
reset_actions method β Action Chains in Selenium Python
|
15 May, 2020
Seleniumβs Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around reset_actions method on Action Chains in Python Selenium. reset_actions method clears actions that are already stored locally and on the remote end. It is one of most used methods, since after some operation, action instance needs to be reset to perform next operation.
Syntax β
reset_actions
Example β
<input type ="text" name ="passwd" id ="passwd-id" />
To find an element one needs to use one of the locating strategies, For example,
element = driver.find_element_by_id("passwd-id")another_element = driver.find_element_by_name("passwd")
Now one can use reset_actions method as an Action chain as below β
action.click(on_element = element)
action.reset_actions()
action.click(on_element = another_element)
To demonstrate, reset_actions method of Action Chains in Selenium Python. Letβ s visit https://www.geeksforgeeks.org/ and operate on an element.
Program β
# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("Courses") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform() # get another element another_element = driver.find_element_by_link_text("Courses") # reset the actionaction.reset_actions() # click the itemaction.click(on_element = another_element) # perform the operationaction.perform()
Output β
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 750,
"s": 28,
"text": "Seleniumβs Python Module is built to perform automated testing with Python. ActionChains are a way to automate low-level interactions such as mouse movements, mouse button actions, keypress, and context menu interactions. This is useful for doing more complex actions like hover over and drag and drop. Action chain methods are used by advanced scripts where we need to drag an element, click an element, double click, etc.This article revolves around reset_actions method on Action Chains in Python Selenium. reset_actions method clears actions that are already stored locally and on the remote end. It is one of most used methods, since after some operation, action instance needs to be reset to perform next operation."
},
{
"code": null,
"e": 759,
"s": 750,
"text": "Syntax β"
},
{
"code": null,
"e": 773,
"s": 759,
"text": "reset_actions"
},
{
"code": null,
"e": 783,
"s": 773,
"text": "Example β"
},
{
"code": "<input type =\"text\" name =\"passwd\" id =\"passwd-id\" />",
"e": 837,
"s": 783,
"text": null
},
{
"code": null,
"e": 918,
"s": 837,
"text": "To find an element one needs to use one of the locating strategies, For example,"
},
{
"code": "element = driver.find_element_by_id(\"passwd-id\")another_element = driver.find_element_by_name(\"passwd\")",
"e": 1022,
"s": 918,
"text": null
},
{
"code": null,
"e": 1089,
"s": 1022,
"text": "Now one can use reset_actions method as an Action chain as below β"
},
{
"code": null,
"e": 1191,
"s": 1089,
"text": "action.click(on_element = element)\naction.reset_actions()\naction.click(on_element = another_element)\n"
},
{
"code": null,
"e": 1336,
"s": 1191,
"text": "To demonstrate, reset_actions method of Action Chains in Selenium Python. Letβ s visit https://www.geeksforgeeks.org/ and operate on an element."
},
{
"code": null,
"e": 1346,
"s": 1336,
"text": "Program β"
},
{
"code": "# import webdriverfrom selenium import webdriver # import Action chains from selenium.webdriver.common.action_chains import ActionChains # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"Courses\") # create action chain objectaction = ActionChains(driver) # click the itemaction.click(on_element = element) # perform the operationaction.perform() # get another element another_element = driver.find_element_by_link_text(\"Courses\") # reset the actionaction.reset_actions() # click the itemaction.click(on_element = another_element) # perform the operationaction.perform()",
"e": 2057,
"s": 1346,
"text": null
},
{
"code": null,
"e": 2066,
"s": 2057,
"text": "Output β"
},
{
"code": null,
"e": 2082,
"s": 2066,
"text": "Python-selenium"
},
{
"code": null,
"e": 2091,
"s": 2082,
"text": "selenium"
},
{
"code": null,
"e": 2098,
"s": 2091,
"text": "Python"
}
] |
How to set the Size of the DateTimePicker in C#?
|
02 Aug, 2019
In Windows Forms, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you can set the size of the DateTimePicker using the Size Property. This property represents both height and width in pixels. You can set this property in two different ways:
1. Design-Time: It is the easiest way to set the Size of the DateTimePicker as shown in the following steps:
Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:
Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the Size of the DateTimePicker as shown in the below image:Output:
Output:
2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Size of the DateTimePicker control programmatically with the help of given syntax:
public System.Drawing.Size Size { get; set; }
Here, the Size indicates both height and width in pixels. The following steps show how to set the Size of the DateTimePicker dynamically:
Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker
DateTimePicker dt = new DateTimePicker();
// Creating a DateTimePicker
DateTimePicker dt = new DateTimePicker();
Step 2: After creating DateTimePicker, set the Size property of the DateTimePicker provided by the DateTimePicker class.// Setting the size
dt.Size = new Size(292, 26);
// Setting the size
dt.Size = new Size(292, 26);
Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form
this.Controls.Add(dt);
// Adding this control to the form
this.Controls.Add(dt);
Example:
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = "Select Date and Time"; lab.Font = new Font("Comic Sans MS", 12); // Adding this control to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Long; dt.Name = "MyPicker"; dt.Font = new Font("Comic Sans MS", 12); dt.Visible = true; dt.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(dt); }}}
Output:
CSharp-Windows-Forms-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 352,
"s": 28,
"text": "In Windows Forms, the DateTimePicker control is used to select and display date/time with a specific format in your form. In DateTimePicker control, you can set the size of the DateTimePicker using the Size Property. This property represents both height and width in pixels. You can set this property in two different ways:"
},
{
"code": null,
"e": 461,
"s": 352,
"text": "1. Design-Time: It is the easiest way to set the Size of the DateTimePicker as shown in the following steps:"
},
{
"code": null,
"e": 577,
"s": 461,
"text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp"
},
{
"code": null,
"e": 690,
"s": 577,
"text": "Step 2: Next, drag and drop the DateTimePicker control from the toolbox to the form as shown in the below image:"
},
{
"code": null,
"e": 845,
"s": 690,
"text": "Step 3: After drag and drop you will go to the properties of the DateTimePicker and set the Size of the DateTimePicker as shown in the below image:Output:"
},
{
"code": null,
"e": 853,
"s": 845,
"text": "Output:"
},
{
"code": null,
"e": 1032,
"s": 853,
"text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the Size of the DateTimePicker control programmatically with the help of given syntax:"
},
{
"code": null,
"e": 1078,
"s": 1032,
"text": "public System.Drawing.Size Size { get; set; }"
},
{
"code": null,
"e": 1216,
"s": 1078,
"text": "Here, the Size indicates both height and width in pixels. The following steps show how to set the Size of the DateTimePicker dynamically:"
},
{
"code": null,
"e": 1399,
"s": 1216,
"text": "Step 1: Create a DateTimePicker using the DateTimePicker() constructor is provided by the DateTimePicker class.// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n"
},
{
"code": null,
"e": 1471,
"s": 1399,
"text": "// Creating a DateTimePicker\nDateTimePicker dt = new DateTimePicker();\n"
},
{
"code": null,
"e": 1641,
"s": 1471,
"text": "Step 2: After creating DateTimePicker, set the Size property of the DateTimePicker provided by the DateTimePicker class.// Setting the size\ndt.Size = new Size(292, 26);\n"
},
{
"code": null,
"e": 1691,
"s": 1641,
"text": "// Setting the size\ndt.Size = new Size(292, 26);\n"
},
{
"code": null,
"e": 1841,
"s": 1691,
"text": "Step 3: And last add this DateTimePicker control to the form using the following statement:// Adding this control to the form\nthis.Controls.Add(dt);\n"
},
{
"code": null,
"e": 1900,
"s": 1841,
"text": "// Adding this control to the form\nthis.Controls.Add(dt);\n"
},
{
"code": null,
"e": 1909,
"s": 1900,
"text": "Example:"
},
{
"code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp48 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting the // properties of the Label Label lab = new Label(); lab.Location = new Point(183, 162); lab.Size = new Size(172, 20); lab.Text = \"Select Date and Time\"; lab.Font = new Font(\"Comic Sans MS\", 12); // Adding this control to the form this.Controls.Add(lab); // Creating and setting the // properties of the DateTimePicker DateTimePicker dt = new DateTimePicker(); dt.Location = new Point(360, 162); dt.Size = new Size(292, 26); dt.MaxDate = new DateTime(2500, 12, 20); dt.MinDate = new DateTime(1753, 1, 1); dt.Format = DateTimePickerFormat.Long; dt.Name = \"MyPicker\"; dt.Font = new Font(\"Comic Sans MS\", 12); dt.Visible = true; dt.Value = DateTime.Today; // Adding this control // to the form this.Controls.Add(dt); }}}",
"e": 3229,
"s": 1909,
"text": null
},
{
"code": null,
"e": 3237,
"s": 3229,
"text": "Output:"
},
{
"code": null,
"e": 3268,
"s": 3237,
"text": "CSharp-Windows-Forms-Namespace"
},
{
"code": null,
"e": 3271,
"s": 3268,
"text": "C#"
}
] |
Difference between @Bean and @Component annotation in Spring.
|
Spring supports multiple types annotations such as @Component,@Controller,@service @Repository and @Bean. All theses can be found under the org.springframework.stereotype package.
When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using @componentScan) each class and inject the instance of the classes to the IOC container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean.
@Component
public class Pizza{
........
}
@Configuration
class AppConfiguration{
@Bean
public User getUse(){
return new User();
}
}
|
[
{
"code": null,
"e": 1368,
"s": 1187,
"text": " Spring supports multiple types annotations such as @Component,@Controller,@service @Repository and @Bean. All theses can be found under the org.springframework.stereotype package."
},
{
"code": null,
"e": 1735,
"s": 1368,
"text": "When classes in our application are annotated with any of the above mentioned annotation then during project startup spring scan(using @componentScan) each class and inject the instance of the classes to the IOC container. Another thing the @ComponentScan would do is running the methods with @Bean on it and restore the return object to the Ioc Container as a bean."
},
{
"code": null,
"e": 1783,
"s": 1735,
"text": "@Component\npublic class Pizza{\n\n ........\n\n\n}"
},
{
"code": null,
"e": 1889,
"s": 1783,
"text": "@Configuration\nclass AppConfiguration{\n\n @Bean\n public User getUse(){\n return new User();\n }\n}"
}
] |
Validation of file size while uploading using JavaScript / jQuery
|
10 May, 2022
In this article, we will learn how to implement file size validation by checking file size before upload using Javascript and jQuery. This is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it consumes less time. For instance, if we donβt allow uploading a file more than 4MB or less than 2MB, we could use client-side validation to check that the file the user has chosen follows the given requirements and if it doesnβt, give them a message so they donβt spend all the time uploading the file only to get an error thrown away by the server.
Approach-1:
Listen for the change event on the input.
Check if any file is selected files.length > 0.
Get the size of the file by files.item(i).size.
The value will be in bytes. Convert it into any unit as you desire, Megabytes in this case by Math.round((filesize/1024)).
Check if the size follows your desired criteria.
Example-1:
Javascript
<!DOCTYPE html><html> <head> <title>File Validation-1</title></head> <body> <p> <input type="file" id="file" onchange="Filevalidation()" /> </p> <p id="size"></p> </body> <script> Filevalidation = () => { const fi = document.getElementById('file'); // Check if any file is selected. if (fi.files.length > 0) { for (const i = 0; i <= fi.files.length - 1; i++) { const fsize = fi.files.item(i).size; const file = Math.round((fsize / 1024)); // The size of the file. if (file >= 4096) { alert( "File too Big, please select a file less than 4mb"); } else if (file < 2048) { alert( "File too small, please select a file greater than 2mb"); } else { document.getElementById('size').innerHTML = '<b>' + file + '</b> KB'; } } } }</script> </html>
Output:Before uploading a file:
If the file is greater than 4MB:
If the file is less than 2MB:
On successful upload:
Approach-2: In the below example, we will learn how to do the same using jQuery.
Listen for the change event on the input.
Get the size of the file by this.files[0].size.
You can round off the obtained value as well by toFixed() method.
Check if the size follows your desired criteria.
Example-2:
Javascript
<!DOCTYPE HTML><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>JQuery File Validation</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body> <input id="file" type="file" name="file" /> <p id="output"></p> <script type="text/javascript"> $('#file').on('change', function() { const size = (this.files[0].size / 1024 / 1024).toFixed(2); if (size > 4 || size < 2) { alert("File must be between the size of 2-4 MB"); } else { $("#output").html('<b>' + 'This file size is: ' + size + " MB" + '</b>'); } }); </script></body> </html>
Output: Before uploading a file:
If the file is less than 2MB or greater than 4MB:
On successful upload:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
japperan123
hardikkoriintern
JavaScript-Misc
Picked
HTML
JavaScript
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)
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 750,
"s": 54,
"text": "In this article, we will learn how to implement file size validation by checking file size before upload using Javascript and jQuery. This is a demonstration of client-side validation and is implemented to provide a nice user experience. In some cases, client-side validation is a much better method in comparison to the server-side method as it consumes less time. For instance, if we donβt allow uploading a file more than 4MB or less than 2MB, we could use client-side validation to check that the file the user has chosen follows the given requirements and if it doesnβt, give them a message so they donβt spend all the time uploading the file only to get an error thrown away by the server."
},
{
"code": null,
"e": 763,
"s": 750,
"text": "Approach-1: "
},
{
"code": null,
"e": 805,
"s": 763,
"text": "Listen for the change event on the input."
},
{
"code": null,
"e": 853,
"s": 805,
"text": "Check if any file is selected files.length > 0."
},
{
"code": null,
"e": 901,
"s": 853,
"text": "Get the size of the file by files.item(i).size."
},
{
"code": null,
"e": 1024,
"s": 901,
"text": "The value will be in bytes. Convert it into any unit as you desire, Megabytes in this case by Math.round((filesize/1024))."
},
{
"code": null,
"e": 1073,
"s": 1024,
"text": "Check if the size follows your desired criteria."
},
{
"code": null,
"e": 1086,
"s": 1073,
"text": "Example-1: "
},
{
"code": null,
"e": 1097,
"s": 1086,
"text": "Javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <title>File Validation-1</title></head> <body> <p> <input type=\"file\" id=\"file\" onchange=\"Filevalidation()\" /> </p> <p id=\"size\"></p> </body> <script> Filevalidation = () => { const fi = document.getElementById('file'); // Check if any file is selected. if (fi.files.length > 0) { for (const i = 0; i <= fi.files.length - 1; i++) { const fsize = fi.files.item(i).size; const file = Math.round((fsize / 1024)); // The size of the file. if (file >= 4096) { alert( \"File too Big, please select a file less than 4mb\"); } else if (file < 2048) { alert( \"File too small, please select a file greater than 2mb\"); } else { document.getElementById('size').innerHTML = '<b>' + file + '</b> KB'; } } } }</script> </html>",
"e": 2169,
"s": 1097,
"text": null
},
{
"code": null,
"e": 2203,
"s": 2169,
"text": "Output:Before uploading a file: "
},
{
"code": null,
"e": 2238,
"s": 2203,
"text": "If the file is greater than 4MB: "
},
{
"code": null,
"e": 2270,
"s": 2238,
"text": "If the file is less than 2MB: "
},
{
"code": null,
"e": 2294,
"s": 2270,
"text": "On successful upload: "
},
{
"code": null,
"e": 2376,
"s": 2294,
"text": "Approach-2: In the below example, we will learn how to do the same using jQuery. "
},
{
"code": null,
"e": 2418,
"s": 2376,
"text": "Listen for the change event on the input."
},
{
"code": null,
"e": 2466,
"s": 2418,
"text": "Get the size of the file by this.files[0].size."
},
{
"code": null,
"e": 2532,
"s": 2466,
"text": "You can round off the obtained value as well by toFixed() method."
},
{
"code": null,
"e": 2581,
"s": 2532,
"text": "Check if the size follows your desired criteria."
},
{
"code": null,
"e": 2594,
"s": 2581,
"text": "Example-2: "
},
{
"code": null,
"e": 2605,
"s": 2594,
"text": "Javascript"
},
{
"code": "<!DOCTYPE HTML><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" /> <title>JQuery File Validation</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body> <input id=\"file\" type=\"file\" name=\"file\" /> <p id=\"output\"></p> <script type=\"text/javascript\"> $('#file').on('change', function() { const size = (this.files[0].size / 1024 / 1024).toFixed(2); if (size > 4 || size < 2) { alert(\"File must be between the size of 2-4 MB\"); } else { $(\"#output\").html('<b>' + 'This file size is: ' + size + \" MB\" + '</b>'); } }); </script></body> </html>",
"e": 3412,
"s": 2605,
"text": null
},
{
"code": null,
"e": 3447,
"s": 3412,
"text": "Output: Before uploading a file: "
},
{
"code": null,
"e": 3499,
"s": 3447,
"text": "If the file is less than 2MB or greater than 4MB: "
},
{
"code": null,
"e": 3523,
"s": 3499,
"text": "On successful upload: "
},
{
"code": null,
"e": 3744,
"s": 3525,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 3756,
"s": 3744,
"text": "japperan123"
},
{
"code": null,
"e": 3773,
"s": 3756,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 3789,
"s": 3773,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3796,
"s": 3789,
"text": "Picked"
},
{
"code": null,
"e": 3801,
"s": 3796,
"text": "HTML"
},
{
"code": null,
"e": 3812,
"s": 3801,
"text": "JavaScript"
},
{
"code": null,
"e": 3817,
"s": 3812,
"text": "HTML"
},
{
"code": null,
"e": 3915,
"s": 3817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3963,
"s": 3915,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3987,
"s": 3963,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 4037,
"s": 3987,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 4076,
"s": 4037,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4113,
"s": 4076,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 4174,
"s": 4113,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4246,
"s": 4174,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 4286,
"s": 4246,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 4338,
"s": 4286,
"text": "How to append HTML code to a div using JavaScript ?"
}
] |
Special two digit number
|
16 Apr, 2021
A special two-digit number is a number such that when the sum of the digits of the number is added to the product of its digits, the result is equal to the original two-digit number. Examples :
input : 59.
output : 59 is a Special Two-Digit Number
Explanation:
Sum of digits = 5 + 9 = 14
Product of its digits = 5 x 9 = 45
Sum of the sum of digits
and product of digits = 14 + 45 = 59
input: 29
output: 29 is a Special Two-digit Number
Explanation:
Sum of digits = 9 + 2 = 11
Product of digits = 9 * 2 = 18
Sum of the sum of digits
and product of digits = 11 + 18 = 29
Approach: Extract the first and last digit of the number and add and multiply the digits separately. Then, add the sum and product of the digits of the two-digit number and compare it to the original number. If they are same, then it is a Special Two-Digit Number, else it is not.Below is the implementation of above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find if number is// a Special Two-Digit number or not#include<bits/stdc++.h>using namespace std; // function to find if number// is special or notvoid specialNumber(int n){ // Checking whether entered // number is 2 digit or not if (n < 10 || n > 99) cout << "Invalid Input! Number" << " should have 2 digits only"; else { // Finding the first digit int first = n / 10; // Finding the last digit int last = n % 10; // Finding the sum of // the digits int sum = first + last; // Finding the product // of the digits int pro = first * last; if ((sum + pro) == n) { cout << n <<" is a Special " << "Two-Digit Number"; } else { cout << n << " is Not a " << "Special Two-Digit Number"; } }} // Driver Codeint main(){ int n = 59; // function calling specialNumber(n); return 0;}
// Java program to find if number is// a Special Two-Digit number or notimport java.io.*; class GFG{ // function to find if number // is special or not static void specialNumber(int n) { // Checking whether entered // number is 2 digit or not if(n < 10 || n > 99) System.out.println("Invalid Input! " + "Number should have " + "2 digits only"); else { // Finding the first digit int first = n / 10; // Finding the last digit int last = n % 10; // Finding the sum // of the digits int sum = first + last; // Finding the product // of the digits int pro = first * last; if((sum + pro) == n) { System.out.println(n + " is a Special" + " Two-Digit Number"); } else { System.out.println(n +" is Not a Special" + " Two-Digit Number"); } } } // Driver Code public static void main(String args[]) { int n = 59; specialNumber(n); }}
# Python3 code to find if# number is a Special# Two-Digit number or not # Function to find if number# is special or notdef specialNumber(n): # Checking whether entered # number is 2 digit or not if (n < 10 or n > 99): print("Invalid Input! Number", " should have 2 digits only") else: # Finding the first digit first = n // 10 # Finding the last digit last = n % 10 # Finding the sum # of the digits sum = first + last # Finding the product # of the digits pro = first * last if ((sum + pro) == n): print(n ," is a Special ", "Two-Digit Number") else: print(n , " is Not a ", "Special Two-Digit Number") # Driver coden = 59specialNumber(n) # This code is contributed# by Anant Agarwal.
// C# program to find if number is// a Special Two-Digit number or notusing System; class GFG{ // function to find if number // is special or not static void specialNumber(int n) { // Checking whether entered // number is 2 digit or not if(n < 10 || n > 99) Console.WriteLine("Invalid Input!" + " Number should have"+ " 2 digits only"); else { // Finding the first digit int first = n / 10; // Finding the last digit int last = n % 10; // Finding the sum // of the digits int sum = first + last; // Finding the product // of the digits int pro = first * last; if((sum + pro) == n) { Console.WriteLine(n + " is a Special"+ " Two-Digit Number"); } else { Console.WriteLine(n + " is Not a Special" + " Two-Digit Number"); } } } // Driver Code public static void Main() { int n = 59; specialNumber(n); }} // This code is contributed by vt_m.
<?php// PHP program to find if number is// a Special Two-Digit number or not // function to find if number// is special or not function specialNumber($n){ // Checking whether entered // number is 2 digit or not if ($n < 10 || $n > 99) echo "Invalid Input! Number should have 2 digits only"; else { // Finding the first digit $first = $n / 10; // Finding the last digit $last = $n % 10; // Finding the sum // of the digits $sum = $first + $last; // Finding the product // of the digits $pro = $first * $last; if (($sum + $pro) != $n) { echo $n ," is a Special " . "Two-Digit Number"; } else { echo $n, " is Not a Special". " Two-Digit Number"; } }} // Driver Code$n = 59; // function callingspecialNumber($n); // This code is contributed by ajit.?>
<script> // JavaScript program to find if number is // a Special Two-Digit number or not // function to find if number // is special or not function specialNumber(n) { // Checking whether entered // number is 2 digit or not if (n < 10 || n > 99) document.write( "Invalid Input! Number" + " should have 2 digits only" ); else { // Finding the first digit var first = parseInt(n / 10); // Finding the last digit var last = parseInt(n % 10); // Finding the sum of // the digits var sum = first + last; // Finding the product // of the digits var pro = first * last; if (sum + pro === n) { document.write( n + (" is a Special " + "Two-Digit Number") ); } else { document.write( n + (" is Not a " + "Special Two-Digit Number") ); } } } // Driver Code var n = 59; // function calling specialNumber(n); </script>
Output :
59 is a Special Two-Digit Number
jit_t
rdtank
number-digits
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Apr, 2021"
},
{
"code": null,
"e": 248,
"s": 52,
"text": "A special two-digit number is a number such that when the sum of the digits of the number is added to the product of its digits, the result is equal to the original two-digit number. Examples : "
},
{
"code": null,
"e": 626,
"s": 248,
"text": "input : 59.\noutput : 59 is a Special Two-Digit Number\nExplanation:\nSum of digits = 5 + 9 = 14\nProduct of its digits = 5 x 9 = 45\nSum of the sum of digits \nand product of digits = 14 + 45 = 59\n\ninput: 29\noutput: 29 is a Special Two-digit Number\nExplanation:\nSum of digits = 9 + 2 = 11\nProduct of digits = 9 * 2 = 18\nSum of the sum of digits \nand product of digits = 11 + 18 = 29"
},
{
"code": null,
"e": 957,
"s": 628,
"text": "Approach: Extract the first and last digit of the number and add and multiply the digits separately. Then, add the sum and product of the digits of the two-digit number and compare it to the original number. If they are same, then it is a Special Two-Digit Number, else it is not.Below is the implementation of above approach: "
},
{
"code": null,
"e": 961,
"s": 957,
"text": "C++"
},
{
"code": null,
"e": 966,
"s": 961,
"text": "Java"
},
{
"code": null,
"e": 974,
"s": 966,
"text": "Python3"
},
{
"code": null,
"e": 977,
"s": 974,
"text": "C#"
},
{
"code": null,
"e": 981,
"s": 977,
"text": "PHP"
},
{
"code": null,
"e": 992,
"s": 981,
"text": "Javascript"
},
{
"code": "// CPP program to find if number is// a Special Two-Digit number or not#include<bits/stdc++.h>using namespace std; // function to find if number// is special or notvoid specialNumber(int n){ // Checking whether entered // number is 2 digit or not if (n < 10 || n > 99) cout << \"Invalid Input! Number\" << \" should have 2 digits only\"; else { // Finding the first digit int first = n / 10; // Finding the last digit int last = n % 10; // Finding the sum of // the digits int sum = first + last; // Finding the product // of the digits int pro = first * last; if ((sum + pro) == n) { cout << n <<\" is a Special \" << \"Two-Digit Number\"; } else { cout << n << \" is Not a \" << \"Special Two-Digit Number\"; } }} // Driver Codeint main(){ int n = 59; // function calling specialNumber(n); return 0;}",
"e": 2039,
"s": 992,
"text": null
},
{
"code": "// Java program to find if number is// a Special Two-Digit number or notimport java.io.*; class GFG{ // function to find if number // is special or not static void specialNumber(int n) { // Checking whether entered // number is 2 digit or not if(n < 10 || n > 99) System.out.println(\"Invalid Input! \" + \"Number should have \" + \"2 digits only\"); else { // Finding the first digit int first = n / 10; // Finding the last digit int last = n % 10; // Finding the sum // of the digits int sum = first + last; // Finding the product // of the digits int pro = first * last; if((sum + pro) == n) { System.out.println(n + \" is a Special\" + \" Two-Digit Number\"); } else { System.out.println(n +\" is Not a Special\" + \" Two-Digit Number\"); } } } // Driver Code public static void main(String args[]) { int n = 59; specialNumber(n); }}",
"e": 3349,
"s": 2039,
"text": null
},
{
"code": "# Python3 code to find if# number is a Special# Two-Digit number or not # Function to find if number# is special or notdef specialNumber(n): # Checking whether entered # number is 2 digit or not if (n < 10 or n > 99): print(\"Invalid Input! Number\", \" should have 2 digits only\") else: # Finding the first digit first = n // 10 # Finding the last digit last = n % 10 # Finding the sum # of the digits sum = first + last # Finding the product # of the digits pro = first * last if ((sum + pro) == n): print(n ,\" is a Special \", \"Two-Digit Number\") else: print(n , \" is Not a \", \"Special Two-Digit Number\") # Driver coden = 59specialNumber(n) # This code is contributed# by Anant Agarwal.",
"e": 4274,
"s": 3349,
"text": null
},
{
"code": "// C# program to find if number is// a Special Two-Digit number or notusing System; class GFG{ // function to find if number // is special or not static void specialNumber(int n) { // Checking whether entered // number is 2 digit or not if(n < 10 || n > 99) Console.WriteLine(\"Invalid Input!\" + \" Number should have\"+ \" 2 digits only\"); else { // Finding the first digit int first = n / 10; // Finding the last digit int last = n % 10; // Finding the sum // of the digits int sum = first + last; // Finding the product // of the digits int pro = first * last; if((sum + pro) == n) { Console.WriteLine(n + \" is a Special\"+ \" Two-Digit Number\"); } else { Console.WriteLine(n + \" is Not a Special\" + \" Two-Digit Number\"); } } } // Driver Code public static void Main() { int n = 59; specialNumber(n); }} // This code is contributed by vt_m.",
"e": 5628,
"s": 4274,
"text": null
},
{
"code": "<?php// PHP program to find if number is// a Special Two-Digit number or not // function to find if number// is special or not function specialNumber($n){ // Checking whether entered // number is 2 digit or not if ($n < 10 || $n > 99) echo \"Invalid Input! Number should have 2 digits only\"; else { // Finding the first digit $first = $n / 10; // Finding the last digit $last = $n % 10; // Finding the sum // of the digits $sum = $first + $last; // Finding the product // of the digits $pro = $first * $last; if (($sum + $pro) != $n) { echo $n ,\" is a Special \" . \"Two-Digit Number\"; } else { echo $n, \" is Not a Special\". \" Two-Digit Number\"; } }} // Driver Code$n = 59; // function callingspecialNumber($n); // This code is contributed by ajit.?>",
"e": 6636,
"s": 5628,
"text": null
},
{
"code": "<script> // JavaScript program to find if number is // a Special Two-Digit number or not // function to find if number // is special or not function specialNumber(n) { // Checking whether entered // number is 2 digit or not if (n < 10 || n > 99) document.write( \"Invalid Input! Number\" + \" should have 2 digits only\" ); else { // Finding the first digit var first = parseInt(n / 10); // Finding the last digit var last = parseInt(n % 10); // Finding the sum of // the digits var sum = first + last; // Finding the product // of the digits var pro = first * last; if (sum + pro === n) { document.write( n + (\" is a Special \" + \"Two-Digit Number\") ); } else { document.write( n + (\" is Not a \" + \"Special Two-Digit Number\") ); } } } // Driver Code var n = 59; // function calling specialNumber(n); </script>",
"e": 7785,
"s": 6636,
"text": null
},
{
"code": null,
"e": 7795,
"s": 7785,
"text": "Output : "
},
{
"code": null,
"e": 7828,
"s": 7795,
"text": "59 is a Special Two-Digit Number"
},
{
"code": null,
"e": 7836,
"s": 7830,
"text": "jit_t"
},
{
"code": null,
"e": 7843,
"s": 7836,
"text": "rdtank"
},
{
"code": null,
"e": 7857,
"s": 7843,
"text": "number-digits"
},
{
"code": null,
"e": 7876,
"s": 7857,
"text": "School Programming"
}
] |
How to append a slice in Golang?
|
05 Sep, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. A slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array.As we already know that slice is dynamic, so the new element can be appended to a slice with the help of append() function. This function appends the new element at the end of the slice.
Syntax:
func append(s []T, x ...T) []T
Here, this function takes s slice and x...T means this function takes a variable number of arguments for the x parameter. Such type of function is also known as a variadic function.
If the slice is backed by the array and arrays are fixed length, then how is that possible a slice is a dynamic length?.
Well, the answer is when the new elements append to the slice a new array is created. Now, the elements present in the existing array are copied into a new array and return a new slice reference to this array(new array). So, due to this, the capacity of the slice is going to be double from the old capacity(As shown in example 1). But if the existing slice has enough capacity to hold new elements, then no new array is created and the elements store in the existing underlying array(As shown in example 2).
Example 1:
// Go program to illustrate the// concept of appending slices.package main import ( "fmt") func main() { // Creating and initializing slice // Using shorthand declaration s1 := []int{234, 567, 7890, 1234, 234} s2 := []string{"Geeks", "For", "Geeks"} // Displaying slices with // their length and capacity fmt.Println("Slice_1: ", s1) fmt.Println("Length of Slice_1: ", len(s1)) fmt.Println("Capacity of Slice_1: ", cap(s1)) fmt.Println() fmt.Println("Slice_2: ", s2) fmt.Println("Length of Slice_2: ", len(s2)) fmt.Println("Capacity of Slice_2: ", cap(s2)) // Appending slices // Using append() function res1 := append(s1, 1000) res2 := append(s2, "GFG") // Displaying results fmt.Println() fmt.Println("New slice_1: ", res1) fmt.Println("New length of slice_1: ", len(res1)) fmt.Println("New capacity of slice_1: ", cap(res1)) fmt.Println() fmt.Println("New slice_2: ", res2) fmt.Println("New length of slice_2: ", len(res2)) fmt.Println("New capacity of slice_2: ", cap(res2))}
Output:
Slice_1: [234 567 7890 1234 234]
Length of Slice_1: 5
Capacity of Slice_1: 5
Slice_2: [Geeks For Geeks]
Length of Slice_2: 3
Capacity of Slice_2: 3
New slice_1: [234 567 7890 1234 234 1000]
New length of slice_1: 6
New capacity of slice_1: 12
New slice_2: [Geeks For Geeks GFG]
New length of slice_2: 4
New capacity of slice_2: 6
Example 2:
// Go program to illustrate the// concept of appending slices.package main import "fmt" func main() { // Creating and initializing slice // Using make() function // Here 4 and 6 is the length // and capacity of the slice s1 := make([]int, 4, 6) // Copying the elements in the slice // Using copy() function copy(s1, []int{123, 456, 789, 977}) // Displaying slice fmt.Println("Slice : ", s1) fmt.Println("Length: ", len(s1)) fmt.Println("Capacity: ", cap(s1)) // Appending slice // Using append() function s2 := append(s1, 3454, 678) // Displaying slice fmt.Println() fmt.Println("Slice : ", s2) fmt.Println("Length: ", len(s2)) fmt.Println("Capacity: ", cap(s2)) }
Output:
Slice : [123 456 789 977]
Length: 4
Capacity: 6
Slice : [123 456 789 977 3454 678]
Length: 6
Capacity: 6
Appending to nil slice: As we know that zero value slice type is nil and the capacity and the length of such type of slice is 0. But with the help of append function, it is possible to append values to nil slice.
Example:
// Go program to illustrate the// concept of appending to nil slice.package main import "fmt" func main() { // Creating nil slice var s1 []int // Displaying slice fmt.Println("Slice : ", s1) fmt.Println("Length: ", len(s1)) fmt.Println("Capacity: ", cap(s1)) // Appending to nil slice // Using append() function s2 := append(s1, 89, 45, 67, 23) // Displaying slice fmt.Println() fmt.Println("Slice : ", s2) fmt.Println("Length: ", len(s2)) fmt.Println("Capacity: ", cap(s2)) }
Output:
Slice : []
Length: 0
Capacity: 0
Slice : [89 45 67 23]
Length: 4
Capacity: 4
Appending to another slice using ... operator: You are allowed to append one slice to another with the help of ... operator.
Example:
// Go program to illustrate the concept // of appending to another slice.package main import "fmt" func main() { // Creating and initializing slice // Using shorthand declaration s1 := []int{234, 567, 7890, 1234, 234} s2 := []int{10, 100, 1000, 10000} // Displaying slices with their // length and capacity fmt.Println("Slice_1: ", s1) fmt.Println("Length of Slice_1: ", len(s1)) fmt.Println("Capacity of Slice_1: ", cap(s1)) fmt.Println() fmt.Println("Slice_2: ", s2) fmt.Println("Length of Slice_2: ", len(s2)) fmt.Println("Capacity of Slice_2: ", cap(s2)) // Appending to another slice // Using append() function res1 := append(s1, s2...) // Displaying result fmt.Println() fmt.Println("New slice_1: ", res1) fmt.Println("New length of slice_1: ", len(res1)) fmt.Println("New capacity of slice_1: ", cap(res1)) }
Output:
Slice_1: [234 567 7890 1234 234]
Length of Slice_1: 5
Capacity of Slice_1: 5
Slice_2: [10 100 1000 10000]
Length of Slice_2: 4
Capacity of Slice_2: 4
New slice_1: [234 567 7890 1234 234 10 100 1000 10000]
New length of slice_1: 9
New capacity of slice_1: 12
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Golang Maps
Arrays in Go
How to copy one slice into another slice in Golang?
Time Durations in Golang
Interfaces in Golang
Inheritance in GoLang
Check if the String starts with specified prefix in Golang
How to iterate over an Array using for loop in Golang?
How to compare two slices of bytes in Golang?
Type Casting or Type Conversion in Golang
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Sep, 2019"
},
{
"code": null,
"e": 623,
"s": 28,
"text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. A slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. It is just like an array having an index value and length, but the size of the slice is resized they are not in fixed-size just like an array.As we already know that slice is dynamic, so the new element can be appended to a slice with the help of append() function. This function appends the new element at the end of the slice."
},
{
"code": null,
"e": 631,
"s": 623,
"text": "Syntax:"
},
{
"code": null,
"e": 662,
"s": 631,
"text": "func append(s []T, x ...T) []T"
},
{
"code": null,
"e": 844,
"s": 662,
"text": "Here, this function takes s slice and x...T means this function takes a variable number of arguments for the x parameter. Such type of function is also known as a variadic function."
},
{
"code": null,
"e": 965,
"s": 844,
"text": "If the slice is backed by the array and arrays are fixed length, then how is that possible a slice is a dynamic length?."
},
{
"code": null,
"e": 1474,
"s": 965,
"text": "Well, the answer is when the new elements append to the slice a new array is created. Now, the elements present in the existing array are copied into a new array and return a new slice reference to this array(new array). So, due to this, the capacity of the slice is going to be double from the old capacity(As shown in example 1). But if the existing slice has enough capacity to hold new elements, then no new array is created and the elements store in the existing underlying array(As shown in example 2)."
},
{
"code": null,
"e": 1485,
"s": 1474,
"text": "Example 1:"
},
{
"code": "// Go program to illustrate the// concept of appending slices.package main import ( \"fmt\") func main() { // Creating and initializing slice // Using shorthand declaration s1 := []int{234, 567, 7890, 1234, 234} s2 := []string{\"Geeks\", \"For\", \"Geeks\"} // Displaying slices with // their length and capacity fmt.Println(\"Slice_1: \", s1) fmt.Println(\"Length of Slice_1: \", len(s1)) fmt.Println(\"Capacity of Slice_1: \", cap(s1)) fmt.Println() fmt.Println(\"Slice_2: \", s2) fmt.Println(\"Length of Slice_2: \", len(s2)) fmt.Println(\"Capacity of Slice_2: \", cap(s2)) // Appending slices // Using append() function res1 := append(s1, 1000) res2 := append(s2, \"GFG\") // Displaying results fmt.Println() fmt.Println(\"New slice_1: \", res1) fmt.Println(\"New length of slice_1: \", len(res1)) fmt.Println(\"New capacity of slice_1: \", cap(res1)) fmt.Println() fmt.Println(\"New slice_2: \", res2) fmt.Println(\"New length of slice_2: \", len(res2)) fmt.Println(\"New capacity of slice_2: \", cap(res2))}",
"e": 2556,
"s": 1485,
"text": null
},
{
"code": null,
"e": 2564,
"s": 2556,
"text": "Output:"
},
{
"code": null,
"e": 2910,
"s": 2564,
"text": "Slice_1: [234 567 7890 1234 234]\nLength of Slice_1: 5\nCapacity of Slice_1: 5\n\nSlice_2: [Geeks For Geeks]\nLength of Slice_2: 3\nCapacity of Slice_2: 3\n\nNew slice_1: [234 567 7890 1234 234 1000]\nNew length of slice_1: 6\nNew capacity of slice_1: 12\n\nNew slice_2: [Geeks For Geeks GFG]\nNew length of slice_2: 4\nNew capacity of slice_2: 6\n"
},
{
"code": null,
"e": 2921,
"s": 2910,
"text": "Example 2:"
},
{
"code": "// Go program to illustrate the// concept of appending slices.package main import \"fmt\" func main() { // Creating and initializing slice // Using make() function // Here 4 and 6 is the length // and capacity of the slice s1 := make([]int, 4, 6) // Copying the elements in the slice // Using copy() function copy(s1, []int{123, 456, 789, 977}) // Displaying slice fmt.Println(\"Slice : \", s1) fmt.Println(\"Length: \", len(s1)) fmt.Println(\"Capacity: \", cap(s1)) // Appending slice // Using append() function s2 := append(s1, 3454, 678) // Displaying slice fmt.Println() fmt.Println(\"Slice : \", s2) fmt.Println(\"Length: \", len(s2)) fmt.Println(\"Capacity: \", cap(s2)) }",
"e": 3659,
"s": 2921,
"text": null
},
{
"code": null,
"e": 3667,
"s": 3659,
"text": "Output:"
},
{
"code": null,
"e": 3780,
"s": 3667,
"text": "Slice : [123 456 789 977]\nLength: 4\nCapacity: 6\n\nSlice : [123 456 789 977 3454 678]\nLength: 6\nCapacity: 6\n"
},
{
"code": null,
"e": 3993,
"s": 3780,
"text": "Appending to nil slice: As we know that zero value slice type is nil and the capacity and the length of such type of slice is 0. But with the help of append function, it is possible to append values to nil slice."
},
{
"code": null,
"e": 4002,
"s": 3993,
"text": "Example:"
},
{
"code": "// Go program to illustrate the// concept of appending to nil slice.package main import \"fmt\" func main() { // Creating nil slice var s1 []int // Displaying slice fmt.Println(\"Slice : \", s1) fmt.Println(\"Length: \", len(s1)) fmt.Println(\"Capacity: \", cap(s1)) // Appending to nil slice // Using append() function s2 := append(s1, 89, 45, 67, 23) // Displaying slice fmt.Println() fmt.Println(\"Slice : \", s2) fmt.Println(\"Length: \", len(s2)) fmt.Println(\"Capacity: \", cap(s2)) }",
"e": 4532,
"s": 4002,
"text": null
},
{
"code": null,
"e": 4540,
"s": 4532,
"text": "Output:"
},
{
"code": null,
"e": 4625,
"s": 4540,
"text": "Slice : []\nLength: 0\nCapacity: 0\n\nSlice : [89 45 67 23]\nLength: 4\nCapacity: 4\n"
},
{
"code": null,
"e": 4750,
"s": 4625,
"text": "Appending to another slice using ... operator: You are allowed to append one slice to another with the help of ... operator."
},
{
"code": null,
"e": 4759,
"s": 4750,
"text": "Example:"
},
{
"code": "// Go program to illustrate the concept // of appending to another slice.package main import \"fmt\" func main() { // Creating and initializing slice // Using shorthand declaration s1 := []int{234, 567, 7890, 1234, 234} s2 := []int{10, 100, 1000, 10000} // Displaying slices with their // length and capacity fmt.Println(\"Slice_1: \", s1) fmt.Println(\"Length of Slice_1: \", len(s1)) fmt.Println(\"Capacity of Slice_1: \", cap(s1)) fmt.Println() fmt.Println(\"Slice_2: \", s2) fmt.Println(\"Length of Slice_2: \", len(s2)) fmt.Println(\"Capacity of Slice_2: \", cap(s2)) // Appending to another slice // Using append() function res1 := append(s1, s2...) // Displaying result fmt.Println() fmt.Println(\"New slice_1: \", res1) fmt.Println(\"New length of slice_1: \", len(res1)) fmt.Println(\"New capacity of slice_1: \", cap(res1)) }",
"e": 5661,
"s": 4759,
"text": null
},
{
"code": null,
"e": 5669,
"s": 5661,
"text": "Output:"
},
{
"code": null,
"e": 5939,
"s": 5669,
"text": "Slice_1: [234 567 7890 1234 234]\nLength of Slice_1: 5\nCapacity of Slice_1: 5\n\nSlice_2: [10 100 1000 10000]\nLength of Slice_2: 4\nCapacity of Slice_2: 4\n\nNew slice_1: [234 567 7890 1234 234 10 100 1000 10000]\nNew length of slice_1: 9\nNew capacity of slice_1: 12\n"
},
{
"code": null,
"e": 5946,
"s": 5939,
"text": "Golang"
},
{
"code": null,
"e": 5960,
"s": 5946,
"text": "Golang-Slices"
},
{
"code": null,
"e": 5972,
"s": 5960,
"text": "Go Language"
},
{
"code": null,
"e": 6070,
"s": 5972,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6082,
"s": 6070,
"text": "Golang Maps"
},
{
"code": null,
"e": 6095,
"s": 6082,
"text": "Arrays in Go"
},
{
"code": null,
"e": 6147,
"s": 6095,
"text": "How to copy one slice into another slice in Golang?"
},
{
"code": null,
"e": 6172,
"s": 6147,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 6193,
"s": 6172,
"text": "Interfaces in Golang"
},
{
"code": null,
"e": 6215,
"s": 6193,
"text": "Inheritance in GoLang"
},
{
"code": null,
"e": 6274,
"s": 6215,
"text": "Check if the String starts with specified prefix in Golang"
},
{
"code": null,
"e": 6329,
"s": 6274,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 6375,
"s": 6329,
"text": "How to compare two slices of bytes in Golang?"
}
] |
Maximum sum of elements in a diagonal parallel to the main diagonal of a given Matrix
|
17 Mar, 2021
Give a square matrix mat[][] of dimensions N * N, the task is to find the maximum sum of elements present in the given matrix along the diagonals which are parallel to the main diagonal. Below is the image of the same.
Examples:
Input: mat[][] = {{1, 2, 5, 7}, {2, 6, 7, 3}, {12, 3, 2, 4}, {3, 6, 9, 4}}Output: 18Explanation:Sum of elements present in the diagonal having cells (2, 0) and (3, 1) is 12 + 6 = 18 which is maximum among all diagonals.
Input: mat[][] = {{5, 2, 5, 7}, {2, 5, 7, 3}, {12, 3, 5, 4}, {3, 6, 9, 5}}Output: 18Explanation:Sum of elements present in the main diagonal having cells (0, 0), (1, 1), (2, 2) and (3, 3) is 5 + 5 + 5 + 5 = 20 which is maximum among all diagonals.
Approach: The idea is to traverse cells of each diagonal that is parallel to the main diagonal and observe that for any diagonal above the main diagonal starting at cell (x, y), itβs corresponding diagonal that is below the main diagonal will start at cell (y, x). For each diagonal, starting at cell (x, y) all its elements will be on cells (x + k, y + k) where 0 <= x + k, y + k < N. Follow the below steps to solve the problem:
Initialize a variable maxSum with 0 which will store the maximum diagonal sum.
Traverse the columns of 0th row from i over the range [0, N β 1].
Initialize variables sum1 and sum2 which will store the diagonal sums starting from the cell (row, col) and from the cell (col, row) respectively where r is 0 and c is col.
Increment both row and c by 1. Add mat[row][col] to sum1 and mat[col][row] to sum2 while row and col are smaller than N. Finally, update maxSum to store the maximum of maxSum, sum1, and sum2.
After traversing the given matrix, print the value maxSum as the maximum sum.
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 maximum diagonal// sum that are parallel to main diagonalint maxDiagonalSum(vector<vector<int> > arr, int N){ // Initialize maxSum int maxSum = 0; // Traverse through the columns for (int i = 0; i < N; i++) { // Initialize r and c int row = 0, col = i; // Diagonal sums int sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row][col]; sum2 += arr[col][row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = max({ sum1, maxSum, sum2 }); } // Return the maxSum return maxSum;} // Driver Codeint main(){ // Given matrix mat[][] vector<vector<int> > mat = { { 1, 2, 5, 7 }, { 2, 6, 7, 3 }, { 12, 3, 2, 4 }, { 3, 6, 9, 4 } }; int N = mat.size(); // Function Call cout << maxDiagonalSum(mat, N); return 0;}
// Java program for the above approachimport java.io.*; class GFG{ // Function to return maximum diagonal// sum that are parallel to main diagonalstatic int maxDiagonalSum(int arr[][], int N){ // Initialize maxSum int maxSum = 0; // Traverse through the columns for(int i = 0; i < N; i++) { // Initialize r and c int row = 0, col = i; // Diagonal sums int sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row][col]; sum2 += arr[col][row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = Math.max(maxSum, Math.max(sum1, sum2)); } // Return the maxSum return maxSum;} // Driver codepublic static void main (String[] args){ // Given matrix mat[][] int mat[][] = { { 1, 2, 5, 7 }, { 2, 6, 7, 3 }, { 12, 3, 2, 4 }, { 3, 6, 9, 4 } }; int N = mat.length; // Function Call System.out.println(maxDiagonalSum(mat, N));}} // This code is contributed by math_lover
# Python3 program for the above approach # Function to return maximum diagonal# sum that are parallel to main diagonaldef maxDiagonalSum(arr, N): # Initialize maxSum maxSum = 0 # Traverse through the columns for i in range(N): # Initialize r and c row = 0 col = i # Diagonal sums sum1 = 0 sum2 = 0 while col < N and row < N: sum1 += arr[row][col] sum2 += arr[col][row] row += 1 col += 1 # Update maxSum with # the maximum sum maxSum = max([ sum1, maxSum, sum2]) # Return the maxSum return maxSum # Driver Codeif __name__ == '__main__': # Given matrix mat[][] mat = [ [ 1, 2, 5, 7 ], [ 2, 6, 7, 3 ], [ 12, 3, 2, 4 ], [ 3, 6, 9, 4 ] ] N = len(mat) # Function Call print(maxDiagonalSum(mat, N)) # This code is contributed by mohit kumar 29
// C# program for the// above approachusing System;class GFG{ // Function to return maximum// diagonal sum that are parallel// to main diagonalstatic int maxDiagonalSum(int [,]arr, int N){ // Initialize maxSum int maxSum = 0; // Traverse through the // columns for(int i = 0; i < N; i++) { // Initialize r and c int row = 0, col = i; // Diagonal sums int sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row,col]; sum2 += arr[col,row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = Math.Max(maxSum, Math.Max(sum1, sum2)); } // Return the maxSum return maxSum;} // Driver codepublic static void Main(String[] args){ // Given matrix [,]mat int [,]mat = {{1, 2, 5, 7}, {2, 6, 7, 3}, {12, 3, 2, 4}, {3, 6, 9, 4}}; int N = mat.GetLength(0); // Function Call Console.WriteLine(maxDiagonalSum(mat, N));}} // This code is contributed by gauravrajput1
<script>// javascript program for the above approach // Function to return maximum diagonal// sum that are parallel to main diagonalfunction maxDiagonalSum( arr, N){ // Initialize maxSum let maxSum = 0; // Traverse through the columns for (let i = 0; i < N; i++) { // Initialize r and c let row = 0, col = i; // Diagonal sums let sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row][col]; sum2 += arr[col][row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = Math.max(Math.max(sum1, maxSum), sum2 ); } // Return the maxSum return maxSum;} // Driver Code // Given matrix mat[][] let mat = [[ 1, 2, 5, 7 ], [ 2, 6, 7, 3 ], [ 12, 3, 2, 4 ], [ 3, 6, 9, 4 ]]; let N = mat[0].length; // Function Call document.write(maxDiagonalSum(mat, N)); // This code is contributed by todaysgaurav</script>
18
Time Complexity: O(N2)Auxiliary Space: O(N2)
mohit kumar 29
math_lover
GauravRajput1
todaysgaurav
array-traversal-question
Mathematical
Matrix
Mathematical
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Minimum number of jumps to reach end
Find minimum number of coins that make a given value
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
The Celebrity Problem
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Mar, 2021"
},
{
"code": null,
"e": 273,
"s": 54,
"text": "Give a square matrix mat[][] of dimensions N * N, the task is to find the maximum sum of elements present in the given matrix along the diagonals which are parallel to the main diagonal. Below is the image of the same."
},
{
"code": null,
"e": 284,
"s": 273,
"text": "Examples: "
},
{
"code": null,
"e": 504,
"s": 284,
"text": "Input: mat[][] = {{1, 2, 5, 7}, {2, 6, 7, 3}, {12, 3, 2, 4}, {3, 6, 9, 4}}Output: 18Explanation:Sum of elements present in the diagonal having cells (2, 0) and (3, 1) is 12 + 6 = 18 which is maximum among all diagonals."
},
{
"code": null,
"e": 752,
"s": 504,
"text": "Input: mat[][] = {{5, 2, 5, 7}, {2, 5, 7, 3}, {12, 3, 5, 4}, {3, 6, 9, 5}}Output: 18Explanation:Sum of elements present in the main diagonal having cells (0, 0), (1, 1), (2, 2) and (3, 3) is 5 + 5 + 5 + 5 = 20 which is maximum among all diagonals."
},
{
"code": null,
"e": 1183,
"s": 752,
"text": "Approach: The idea is to traverse cells of each diagonal that is parallel to the main diagonal and observe that for any diagonal above the main diagonal starting at cell (x, y), itβs corresponding diagonal that is below the main diagonal will start at cell (y, x). For each diagonal, starting at cell (x, y) all its elements will be on cells (x + k, y + k) where 0 <= x + k, y + k < N. Follow the below steps to solve the problem:"
},
{
"code": null,
"e": 1262,
"s": 1183,
"text": "Initialize a variable maxSum with 0 which will store the maximum diagonal sum."
},
{
"code": null,
"e": 1328,
"s": 1262,
"text": "Traverse the columns of 0th row from i over the range [0, N β 1]."
},
{
"code": null,
"e": 1501,
"s": 1328,
"text": "Initialize variables sum1 and sum2 which will store the diagonal sums starting from the cell (row, col) and from the cell (col, row) respectively where r is 0 and c is col."
},
{
"code": null,
"e": 1693,
"s": 1501,
"text": "Increment both row and c by 1. Add mat[row][col] to sum1 and mat[col][row] to sum2 while row and col are smaller than N. Finally, update maxSum to store the maximum of maxSum, sum1, and sum2."
},
{
"code": null,
"e": 1771,
"s": 1693,
"text": "After traversing the given matrix, print the value maxSum as the maximum sum."
},
{
"code": null,
"e": 1822,
"s": 1771,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1826,
"s": 1822,
"text": "C++"
},
{
"code": null,
"e": 1831,
"s": 1826,
"text": "Java"
},
{
"code": null,
"e": 1839,
"s": 1831,
"text": "Python3"
},
{
"code": null,
"e": 1842,
"s": 1839,
"text": "C#"
},
{
"code": null,
"e": 1853,
"s": 1842,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to return maximum diagonal// sum that are parallel to main diagonalint maxDiagonalSum(vector<vector<int> > arr, int N){ // Initialize maxSum int maxSum = 0; // Traverse through the columns for (int i = 0; i < N; i++) { // Initialize r and c int row = 0, col = i; // Diagonal sums int sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row][col]; sum2 += arr[col][row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = max({ sum1, maxSum, sum2 }); } // Return the maxSum return maxSum;} // Driver Codeint main(){ // Given matrix mat[][] vector<vector<int> > mat = { { 1, 2, 5, 7 }, { 2, 6, 7, 3 }, { 12, 3, 2, 4 }, { 3, 6, 9, 4 } }; int N = mat.size(); // Function Call cout << maxDiagonalSum(mat, N); return 0;}",
"e": 2880,
"s": 1853,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to return maximum diagonal// sum that are parallel to main diagonalstatic int maxDiagonalSum(int arr[][], int N){ // Initialize maxSum int maxSum = 0; // Traverse through the columns for(int i = 0; i < N; i++) { // Initialize r and c int row = 0, col = i; // Diagonal sums int sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row][col]; sum2 += arr[col][row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = Math.max(maxSum, Math.max(sum1, sum2)); } // Return the maxSum return maxSum;} // Driver codepublic static void main (String[] args){ // Given matrix mat[][] int mat[][] = { { 1, 2, 5, 7 }, { 2, 6, 7, 3 }, { 12, 3, 2, 4 }, { 3, 6, 9, 4 } }; int N = mat.length; // Function Call System.out.println(maxDiagonalSum(mat, N));}} // This code is contributed by math_lover",
"e": 4058,
"s": 2880,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to return maximum diagonal# sum that are parallel to main diagonaldef maxDiagonalSum(arr, N): # Initialize maxSum maxSum = 0 # Traverse through the columns for i in range(N): # Initialize r and c row = 0 col = i # Diagonal sums sum1 = 0 sum2 = 0 while col < N and row < N: sum1 += arr[row][col] sum2 += arr[col][row] row += 1 col += 1 # Update maxSum with # the maximum sum maxSum = max([ sum1, maxSum, sum2]) # Return the maxSum return maxSum # Driver Codeif __name__ == '__main__': # Given matrix mat[][] mat = [ [ 1, 2, 5, 7 ], [ 2, 6, 7, 3 ], [ 12, 3, 2, 4 ], [ 3, 6, 9, 4 ] ] N = len(mat) # Function Call print(maxDiagonalSum(mat, N)) # This code is contributed by mohit kumar 29",
"e": 5009,
"s": 4058,
"text": null
},
{
"code": "// C# program for the// above approachusing System;class GFG{ // Function to return maximum// diagonal sum that are parallel// to main diagonalstatic int maxDiagonalSum(int [,]arr, int N){ // Initialize maxSum int maxSum = 0; // Traverse through the // columns for(int i = 0; i < N; i++) { // Initialize r and c int row = 0, col = i; // Diagonal sums int sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row,col]; sum2 += arr[col,row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = Math.Max(maxSum, Math.Max(sum1, sum2)); } // Return the maxSum return maxSum;} // Driver codepublic static void Main(String[] args){ // Given matrix [,]mat int [,]mat = {{1, 2, 5, 7}, {2, 6, 7, 3}, {12, 3, 2, 4}, {3, 6, 9, 4}}; int N = mat.GetLength(0); // Function Call Console.WriteLine(maxDiagonalSum(mat, N));}} // This code is contributed by gauravrajput1",
"e": 6064,
"s": 5009,
"text": null
},
{
"code": "<script>// javascript program for the above approach // Function to return maximum diagonal// sum that are parallel to main diagonalfunction maxDiagonalSum( arr, N){ // Initialize maxSum let maxSum = 0; // Traverse through the columns for (let i = 0; i < N; i++) { // Initialize r and c let row = 0, col = i; // Diagonal sums let sum1 = 0, sum2 = 0; while (col < N && row < N) { sum1 += arr[row][col]; sum2 += arr[col][row]; row++; col++; } // Update maxSum with // the maximum sum maxSum = Math.max(Math.max(sum1, maxSum), sum2 ); } // Return the maxSum return maxSum;} // Driver Code // Given matrix mat[][] let mat = [[ 1, 2, 5, 7 ], [ 2, 6, 7, 3 ], [ 12, 3, 2, 4 ], [ 3, 6, 9, 4 ]]; let N = mat[0].length; // Function Call document.write(maxDiagonalSum(mat, N)); // This code is contributed by todaysgaurav</script>",
"e": 7076,
"s": 6064,
"text": null
},
{
"code": null,
"e": 7079,
"s": 7076,
"text": "18"
},
{
"code": null,
"e": 7124,
"s": 7079,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 7139,
"s": 7124,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7150,
"s": 7139,
"text": "math_lover"
},
{
"code": null,
"e": 7164,
"s": 7150,
"text": "GauravRajput1"
},
{
"code": null,
"e": 7177,
"s": 7164,
"text": "todaysgaurav"
},
{
"code": null,
"e": 7202,
"s": 7177,
"text": "array-traversal-question"
},
{
"code": null,
"e": 7215,
"s": 7202,
"text": "Mathematical"
},
{
"code": null,
"e": 7222,
"s": 7215,
"text": "Matrix"
},
{
"code": null,
"e": 7235,
"s": 7222,
"text": "Mathematical"
},
{
"code": null,
"e": 7242,
"s": 7235,
"text": "Matrix"
},
{
"code": null,
"e": 7340,
"s": 7242,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7364,
"s": 7340,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 7385,
"s": 7364,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 7399,
"s": 7385,
"text": "Prime Numbers"
},
{
"code": null,
"e": 7436,
"s": 7399,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 7489,
"s": 7436,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 7524,
"s": 7489,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 7568,
"s": 7524,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 7599,
"s": 7568,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 7623,
"s": 7599,
"text": "Sudoku | Backtracking-7"
}
] |
Scala Tutorial β Learn Scala with Step By Step Guide
|
03 Jan, 2022
Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. Scala doesnβt provide any support for .Net Framework. Scala was designed by the Martin Odersky, professor of programming methods at EΜcole Polytechnique FeΜdeΜrale de Lausanne (EPFL) in Switzerland and a German computer scientist. Scala was first released publicly in 2004 on the Java platform as its first version. In June 2004. The latest version of scala is 2.12.6 which released on 27-Apr-2018.
Topics:
Scala has many reasons for being popular and in demand. Few of the reasons are mentioned below:
Object- Oriented: Every value in Scala is an object so it is a purely object-oriented programming language. The behavior and type of objects are depicted by the classes and traits in Scala.
Functional: It is also a functional programming language as every function is a value and every value is an object. It provides the support for the high-order functions, nested functions, anonymous functions etc.
Statically Typed: The process of verifying and enforcing the constraints of types is done at compile time in Scala. Unlike other statically typed programming languages like C++, C etc., Scala doesnβt expect the redundant type of information from the user. In most cases, the user has no need to specify a type.
Extensible: New language constructs can be added to Scala in form of libraries. Scala is designed to interpolate with the JRE(Java Runtime Environment).
Concurrent & Synchronize Processing: Scala allows the user to write the codes in an immutable manner that makes it easy to apply the parallelism(Synchronize) and concurrency.
Scala is a very compatible language and thus can very easily be installed into the Windows and the Unix operating systems both very easily. Since Scala is a lot similar to other widely used languages syntactically, it is easier to code and learn in Scala. scala programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Scala codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc. To begin with, writing Scala Codes and performing various intriguing and useful operations, one must have scala installed on their system. This can be done by following the step by step instructions provided below:
Verifying Java Packages The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them.Now install Scala We are done with installing the java now letβs install the scala packages. The best option to download these packages is to download from the official site only: https://www.scala-lang.org/download/ The packages in the link above is the approximately of 100MB storage. Once the packages are downloaded then open the downloaded .msi file.Testing and Running the Scala Commands Open the command prompt now and type in the following codes.
Verifying Java Packages The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them.
Now install Scala We are done with installing the java now letβs install the scala packages. The best option to download these packages is to download from the official site only: https://www.scala-lang.org/download/ The packages in the link above is the approximately of 100MB storage. Once the packages are downloaded then open the downloaded .msi file.
Testing and Running the Scala Commands Open the command prompt now and type in the following codes.
C:\Users\Your_PC_username>scala
We will receive an output as shown below:
We will receive an output as shown below:
Output of the command.
Output of the command.
Letβs consider a simple Hello World Program.
Scala
// Scala program to print Hello World // Creating objectobject Geeks { // Main methoddef main(args: Array[String]){ // prints Hello, Geeks! println("Hello, World!")}}
Output:
Hello, World!
Generally, there are two ways to Run a Scala program-
Using Online IDEs: We can use various online IDEs which can be used to run Scala programs without installing.
Using Command-Line: We can also use command line options to run a Scala program. Below steps demonstrate how to run a Scala program on Command line in Windows/Unix Operating System: Open Commandline and then to compile the code type scala Hello.scala. If your code has no error then it will execute properly and output will be displayed.
Variables are simply a storage location. Every variable is known by its name and stores some known and unknown piece of information known as value. In Scala there are two types of variable:
Mutable Variables: These variables are those variables which allow us to change a value after the declaration of a variable. Mutable variables are defined by using the βvarβ keyword.
Immutable Variables: These variables are those variables which do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the βvalβ keyword.
Example:
// Mutable Variable
var name: String = "geekforgeeks";
// Immutable Variable
val name: String = "geekforgeeks";
To know more about Scala Variables refer β Variables in Scala, Scope of Variable in Scala.
An operator is a symbol that represents an operation to be performed with one or more operand. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows:
Arithmetic Operators
Relational Operators
Logical Operators
Assignment Operators
Bitwise Operators
Example :
Scala
// Scala program to demonstrate// the Operators // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Operands var a = 10; var b = 4; var c = true; var d = false; var result = 0; // using arithmetic operators println ("Addition is: "+ (a + b) ); println ("Subtraction is: "+ (a - b) ) ; // using Relational Operators if (a == b) { println ("Equal To Operator is True"); } else { println ("Equal To Operator is False"); } // using Logical Operator 'OR' println("Logical Or of a || b = " + (c || d)); // using Bitwise AND Operator result = a & b; println ("Bitwise AND: " + result ); // using Assignment Operators println ("Addition Assignment Operator: " + (a += b) ); }}
Addition is: 14
Subtraction is: 6
Equal To Operator is False
Logical Or of a || b = true
Bitwise AND: 0
Addition Assignment Operator: ()
Decision Making in programming is similar to decision making in real life. Scala uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program.
If
If β else
Nested β If
if β elsif ladder
Example 1: To illustrate use of if and if-else
Scala
// Scala program to illustrate the if and if-else statementobject Test{ // Main Methoddef main(args: Array[String]){ // taking a variable var a: Int = 650 // if condition to check // for even number if(a % 2 == 0) { println("Even Number") } if (a > 698) { // This statement will not // execute as a > 698 is false println("GeeksforGeeks") } else { // This statement will execute println("Sudo Placement") }}}
Even Number
Sudo Placement
Example 2: To illustrate the use of Nested-if
Scala
// Scala program to illustrate // Nested if statementobject Test{ // Main Methoddef main(args: Array[String]){ var a: Int = 10; if(a % 2 == 0) { // Nested - if statement // Will only be executed // if above if statement // is true if(a % 5 == 0) { println("Number is divisible by 2 and 5\n") } }}}
Number is divisible by 2 and 5
To know more about Decision Making please refer to Decision making in Scala
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmerβs task simpler. Scala provides the different types of loop to handle the condition based situation in the program. The loops in Scala are :
for loop
Scala
// Scala program to illustrate for loopobject forloopDemo { // Main Method def main(args: Array[String]) { var y = 0; // for loop execution with range for(y <- 1 to 4) { println("Value of y is: " + y); } }}
Value of y is: 1
Value of y is: 2
Value of y is: 3
Value of y is: 4
While loop
Scala
// Scala program to illustrate while loopobject whileLoopDemo{ // Main method def main(args: Array[String]) { var x = 1; // Exit when x becomes greater than 4 while (x <= 4) { println("Value of x: " + x); // Increment the value of x for // next iteration x = x + 1; } }}
Value of x: 1
Value of x: 2
Value of x: 3
Value of x: 4
do-while loop
Scala
// Scala program to illustrate do..while loopobject dowhileLoopDemo{ // Main method def main(args: Array[String]) { var a = 10; // using do..while loop do { print(a + " "); a = a - 1; }while(a > 0); }}
10 9 8 7 6 5 4 3 2 1
To know more about Loops please refer to Loops in Scala
Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. It is a collection of mutable values. Below is the syntax. Syntax :
var arrayname = new Array[datatype](size)
It will create an array of integers which contains the value 40, 55, 63, 17 and many more. Below is the syntax to access a single element of an array, if weβve created an array named number.
number(0)
It will produce the output as 40. Iterating through an Array:
In this example we create an array while providing the values of its elements at the same time. In this case, the type is inferred.
Scala
// Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array("gfg", "geeks", "GeeksQuize", "geeksforgeeks" ) println("second element of an array is: ") // Accessing an array element println(name(1) ) }}
second element of an array is:
geeks
To know more about arrays please refer to Arrays in Scala
A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In Scala a String type is specified before meeting the string literal. but when the compiler meet to a string literal and creates a string object str. Syntax :
var str = "Hello! GFG"
or
val str = "Hello! GFG"
var str: String = "Hello! GFG"
or
val str: String = "Hello! GFG"
Scala
// Scala program to illustrate how to // create a stringobject Main{ // str1 and str2 are two different strings var str1 = "Hello! GFG" val str2: String = "GeeksforGeeks" def main(args: Array[String]) { // Display both strings println(str1); println(str2); }}
Hello! GFG
GeeksforGeeks
when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. You can also use β+β operator to concatenate two strings.
Scala
// Scala program to illustrate how to // concatenate stringsobject Main { // str1 and str2 are two strings var str1 = "Welcome! GeeksforGeeks " var str2 = " to Portal" // Main function def main(args: Array[String]) { // concatenate str1 and str2 strings // using concat() function var Newstr = str1.concat(str2); // Display strings println("String 1:" +str1); println("String 2:" +str2); println("New String :" +Newstr); // Concatenate strings using '+' operator println("This is the tutorial" + " of Scala language" + " on GFG portal"); }}
String 1:Welcome! GeeksforGeeks
String 2: to Portal
New String :Welcome! GeeksforGeeks to Portal
This is the tutorial of Scala language on GFG portal
To know more about Strings please refer to Strings in Scala
A function is a collection of statements that perform a certain task. Scala is assumed as functional programming language so these play an important role. It makes easier to debug and modify the code. Scala functions are first class values. Below is the syntax of Scala Functions. Syntax:
def function_name ([parameter_list]) : [return_type] = {
// function body
}
def keyword is used to declare a function in Scala.Function Calling : There are mainly two ways to call the function in Scala. First way is the standard way as follows:
function_name(paramter_list)
In the Second way, a user can also call the function with the help of the instance and dot notation as follows:
[instance].function_name(paramter_list)
Scala
// Scala program of function callingobject GeeksforGeeks { def main(args: Array[String]) { // Calling the function println("Sum is: " + functionToAdd(5, 3)); } // declaration and definition of function def functionToAdd(a:Int, b:Int) : Int = { var sum:Int = 0 sum = a + b // returning the value of sum return sum }}
Output :
Sum is: 8
Anonymous Functions in Scala : In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function.Syntax :
(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)
Scala
// Scala program to illustrate the anonymous methodobject Main { def main(args: Array[String]) { // Creating anonymous functions // with multiple parameters Assign // anonymous functions to variables var myfc1 = (str1:String, str2:String) => str1 + str2 // An anonymous function is created // using _ wildcard instead of // variable name because str1 and // str2 variable appear only once var myfc2 = (_:String) + (_:String) // Here, the variable invoke like a function call println(myfc1("Geeks", "12Geeks")) println(myfc2("Geeks", "forGeeks")) }}
Output :
Geeks12Geeks
GeeksforGeeks
Scala Nested Functions: A function definition inside an another function is known as Nested Function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions.Syntax :
def FunctionName1( perameter1, peramete2, ..) = {
def FunctionName2() = {
// code
}
}
Scala
// Scala program of Single Nested Functionobject MaxAndMin { // Main method def main(args: Array[String]) { println("Min and Max from 5, 7") maxAndMin(5, 7); } // Function def maxAndMin(a: Int, b: Int) = { // Nested Function def maxValue() = { if(a > b) { println("Max is: " + a) } else { println("Max is: " + b) } } // Nested Function def minValue() = { if (a < b) { println("Min is: " + a) } else { println("Min is: " + b) } } maxValue(); minValue(); }}
Output:
Min and Max from 5, 7
Max is: 7
Min is: 5
Currying Functions in Scala : Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument.Syntax :
def function name(argument1, argument2) = operation
Scala
// Scala program add two numbers// using currying Functionobject Curry{ // Define currying function def add(x: Int, y: Int) = x + y; def main(args: Array[String]) { println(add(20, 19)); }}
Output:
39
Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. OOPs Concepts:
Polymorphism
Inheritance
Abstract-Classes
Class and Object
Constructors
Creation of a Class and an Object: Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created.
Scala
// A Scala program to illustrate// how to create a class // Name of the class is Smartphoneclass Smartphone{ // Class variables var number: Int = 16 var nameofcompany: String = "Apple" // Class method def Display() { println("Name of the company : " + nameofcompany); println("Total number of Smartphone generation: " + number); }}object Main { // Main method def main(args: Array[String]) { // Class object var obj = new Smartphone(); obj.Display(); }}
Name of the company : Apple
Total number of Smartphone generation: 16
Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its members.Creating a trait β
Scala
// Scala program to illustrate how to // create traits // Trait trait MyTrait{ def pet def pet_color} // MyClass inherits traitclass MyClass extends MyTrait{ // Implementation of methods of MyTrait def pet() { println("Pet: Dog") } def pet_color() { println("Pet_color: White") } // Class method def pet_name() { println("Pet_name: Dollar") }} object Main { // Main method def main(args: Array[String]) { val obj = new MyClass(); obj.pet(); obj.pet_color(); obj.pet_name(); }}
Output :
Pet: Dog
Pet_color: White
Pet_name: Dollar
To know more about Traits please refer to Traits in Scala
Regular Expressions explain a common pattern utilized to match a series of input data so, it is helpful in Pattern Matching in numerous programming languages. In Scala Regular Expressions are generally termed as Scala Regex.
Scala
// Scala program for Regular// Expressions // Creating objectobject GfG{ // Main method def main(args : Array[String]) { // Applying r() method val portal = "GeeksforGeeks".r val CS = "GeeksforGeeks is a CS portal." // Displays the first match println(portal findFirstIn CS) }}
Output :
Some(GeeksforGeeks)
To know more about tuple please refer to Regular Expressions in Scala.
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution.
In scala, All exceptions are unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception.The Throwing Exceptions :
Scala
// Scala program of throw keyword // Creating objectobject Main { // Define function def validate(article:Int)= { // Using throw keyword if(article < 20) throw new ArithmeticException("You are not eligible for internship") else println("You are eligible for internship") } // Main method def main(args: Array[String]) { validate(22) }}
Output :
You are eligible for internship
Try-Catch Exceptions :
Scala
// Scala program of try-catch Exception import java.io.IOException // Creating objectobject GFG{ // Main method def main(args:Array[String]) { try { var N = 5/0 } catch { // Catch block contain cases. case i: IOException => { println("IOException occurred.") } case a : ArithmeticException => { println("Arithmetic Exception occurred.") } } } }
Output :
Arithmetic Exception occurred.
File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we donβt have a class to write into a file, in the Scala standard library. We could also import java.io.File and java.io.PrintWriter.
Creating a new file : java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.File(String pathname) converts theparameter string to abstract path name, creating a new file instance.
java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.File(String pathname) converts theparameter string to abstract path name, creating a new file instance.
java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.
File(String pathname) converts theparameter string to abstract path name, creating a new file instance.
Writing to the file : java.io.PrintWriter includes all the printing methods included in PrintStream. Below is the implementation for creating a new file and writing into it.
Scala
// Scala File handling programimport java.io.Fileimport java.io.PrintWriter // Creating objectobject Geeks{ // Main method def main(args:Array[String]) { // Creating a file val file_Object = new File("abc.txt" ) // Passing reference of file to the printwriter val print_Writer = new PrintWriter(file_Object) // Writing to the file print_Writer.write("Hello, This is Geeks For Geeks") // Closing printwriter print_Writer.close() }}
Reading a File : Below is the example to reading a file.
Scala
// Scala File handling programimport scala.io.Source // Creating object object GeeksScala{ // Main method def main(args : Array[String]) { // file name val fname = "abc.txt" // creates iterable representation // of the source file val fSource = Source.fromFile(fname) while (fSource.hasNext) { println(fSource.next) } // closing file fSource.close() }}
To know more about various different File Handling, please refer to File Handling in Scala
A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Lists are immutable whereas arrays are mutable in Scala. In a Scala list, each element must be of the same type. list is defined under scala.collection.immutable package. Syntax :
val variable_name: List[type] = List(item1, item2, item3)
or
val variable_name = List(item1, item2, item3)
Create and initialize Scala List Example :
Scala
// Scala program to print immutable listsimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist1: List[String] = List("Geeks", "GFG", "GeeksforGeeks", "Geek123") val mylist2 = List("C", "C#", "Java", "Scala", "PHP", "Ruby") // Display the value of mylist1 println("List 1:") println(mylist1) // Display the value of mylist2 using for loop println("\nList 2:") for(mylist<-mylist2) { println(mylist) } }}
Output :
List 1:
List(Geeks, GFG, GeeksforGeeks, Geek123)
List 2:
C
C#
Java
Scala
PHP
Ruby
To know more about List please refer to List in Scala.
Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. In order to use mutable Map, we must import scala.collection.mutable.Map class explicitly. Creating a map and accessing the value Example :
Scala
// Scala map program of // Accessing Values Using Keys // Creating object object GFG{ // Main method def main(args:Array[String]) { val mapIm = Map("Ajay" -> 30, "Bhavesh" -> 20, "Charlie" -> 50) // Accessing score of Ajay val ajay = mapIm("Ajay") println(ajay) }}
Output :
30
To know more about Map please refer to Map in Scala.
An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. To access elements we can make use of hasNext() to check if there are elements available and next() to print the next element. Syntax:
val v = Iterator(5, 1, 2, 3, 6, 4)
//checking for availability of next element
while(v.hasNext)
//printing the element
println(v.next)
Example :
Scala
//Scala iterator program//for defining iterator //Creating objectobject GFG{ // Main method def main(args:Array[String]) { val v = Array(5, 1, 2, 3, 6, 4) //val v = List(5, 1, 2, 3, 6, 4) // defining an iterator // for a collection val i = v.iterator while (i.hasNext) print(i.next + " ") }}
Output:
5 1 2 3 6 4
To know more about tuple please refer to Iterators in Scala.
A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax :
// Immutable set
val variable_name: Set[type] = Set(item1, item2, item3)
or
val variable_name = Set(item1, item2, item3)
// Mutable Set
var variable_name: Set[type] = Set(item1, item2, item3)
or
var variable_name = Set(item1, item2, item3)
Creating and initializing Immutable set Example :
Scala
// Scala program to illustrate the // use of immutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing immutable sets val myset1: Set[String] = Set("Geeks", "GFG", "GeeksforGeeks", "Geek123") val myset2 = Set("C", "C#", "Java", "Scala", "PHP", "Ruby") // Display the value of myset1 println("Set 1:") println(myset1) // Display the value of myset2 using for loop println("\nSet 2:") for(myset<-myset2) { println(myset) } }}
Output :
Set 1:
Set(Geeks, GFG, GeeksforGeeks, Geek123)
Set 2:
Scala
C#
Ruby
PHP
C
Java
Creating and initializing mutable set Example :
Scala
// Scala program to illustrate the // use of mutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing mutable sets var myset1: Set[String] = Set("Geeks", "GFG", "GeeksforGeeks", "Geek123") var myset2 = Set(10, 100, 1000, 10000, 100000) // Display the value of myset1 println("Set 1:") println(myset1) // Display the value of myset2 // using a foreach loop println("\nSet 2:") myset2.foreach((item:Int)=>println(item)) }}
Output :
Set 1:
Set(Geeks, GFG, GeeksforGeeks, Geek123)
Set 2:
10
100000
10000
1000
100
To know more about Set please refer to Set in Scala | Set-1 and Set in Scala | Set-2.
Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. Creating a tuple and accessing an element Example :
Scala
// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, "chandan", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}
Output :
15
chandan
true
To know more about tuple please refer to tuple in Scala.
surinderdawra388
simranarora5sos
varshagumber28
kalrap615
malikm
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 772,
"s": 54,
"text": "Scala is a general-purpose, high-level, multi-paradigm programming language. It is a pure object-oriented programming language which also provides support to the functional programming approach. Scala programs can convert to bytecodes and can run on the JVM(Java Virtual Machine). Scala stands for Scalable language. Scala doesnβt provide any support for .Net Framework. Scala was designed by the Martin Odersky, professor of programming methods at EΜcole Polytechnique FeΜdeΜrale de Lausanne (EPFL) in Switzerland and a German computer scientist. Scala was first released publicly in 2004 on the Java platform as its first version. In June 2004. The latest version of scala is 2.12.6 which released on 27-Apr-2018. "
},
{
"code": null,
"e": 783,
"s": 772,
"text": "Topics: "
},
{
"code": null,
"e": 880,
"s": 783,
"text": "Scala has many reasons for being popular and in demand. Few of the reasons are mentioned below: "
},
{
"code": null,
"e": 1070,
"s": 880,
"text": "Object- Oriented: Every value in Scala is an object so it is a purely object-oriented programming language. The behavior and type of objects are depicted by the classes and traits in Scala."
},
{
"code": null,
"e": 1283,
"s": 1070,
"text": "Functional: It is also a functional programming language as every function is a value and every value is an object. It provides the support for the high-order functions, nested functions, anonymous functions etc."
},
{
"code": null,
"e": 1594,
"s": 1283,
"text": "Statically Typed: The process of verifying and enforcing the constraints of types is done at compile time in Scala. Unlike other statically typed programming languages like C++, C etc., Scala doesnβt expect the redundant type of information from the user. In most cases, the user has no need to specify a type."
},
{
"code": null,
"e": 1747,
"s": 1594,
"text": "Extensible: New language constructs can be added to Scala in form of libraries. Scala is designed to interpolate with the JRE(Java Runtime Environment)."
},
{
"code": null,
"e": 1922,
"s": 1747,
"text": "Concurrent & Synchronize Processing: Scala allows the user to write the codes in an immutable manner that makes it easy to apply the parallelism(Synchronize) and concurrency."
},
{
"code": null,
"e": 2740,
"s": 1928,
"text": "Scala is a very compatible language and thus can very easily be installed into the Windows and the Unix operating systems both very easily. Since Scala is a lot similar to other widely used languages syntactically, it is easier to code and learn in Scala. scala programs can be written on any plain text editor like notepad, notepad++, or anything of that sort. One can also use an online IDE for writing Scala codes or can even install one on their system to make it more feasible to write these codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc. To begin with, writing Scala Codes and performing various intriguing and useful operations, one must have scala installed on their system. This can be done by following the step by step instructions provided below: "
},
{
"code": null,
"e": 3395,
"s": 2740,
"text": "Verifying Java Packages The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them.Now install Scala We are done with installing the java now letβs install the scala packages. The best option to download these packages is to download from the official site only: https://www.scala-lang.org/download/ The packages in the link above is the approximately of 100MB storage. Once the packages are downloaded then open the downloaded .msi file.Testing and Running the Scala Commands Open the command prompt now and type in the following codes. "
},
{
"code": null,
"e": 3594,
"s": 3395,
"text": "Verifying Java Packages The first thing we need to have is a Java Software Development Kit(SDK) installed on the computer. We need to verify this SDK packages and if not installed then install them."
},
{
"code": null,
"e": 3950,
"s": 3594,
"text": "Now install Scala We are done with installing the java now letβs install the scala packages. The best option to download these packages is to download from the official site only: https://www.scala-lang.org/download/ The packages in the link above is the approximately of 100MB storage. Once the packages are downloaded then open the downloaded .msi file."
},
{
"code": null,
"e": 4052,
"s": 3950,
"text": "Testing and Running the Scala Commands Open the command prompt now and type in the following codes. "
},
{
"code": null,
"e": 4084,
"s": 4052,
"text": "C:\\Users\\Your_PC_username>scala"
},
{
"code": null,
"e": 4128,
"s": 4084,
"text": "We will receive an output as shown below: "
},
{
"code": null,
"e": 4172,
"s": 4128,
"text": "We will receive an output as shown below: "
},
{
"code": null,
"e": 4195,
"s": 4172,
"text": "Output of the command."
},
{
"code": null,
"e": 4218,
"s": 4195,
"text": "Output of the command."
},
{
"code": null,
"e": 4266,
"s": 4220,
"text": "Letβs consider a simple Hello World Program. "
},
{
"code": null,
"e": 4272,
"s": 4266,
"text": "Scala"
},
{
"code": "// Scala program to print Hello World // Creating objectobject Geeks { // Main methoddef main(args: Array[String]){ // prints Hello, Geeks! println(\"Hello, World!\")}} ",
"e": 4451,
"s": 4272,
"text": null
},
{
"code": null,
"e": 4461,
"s": 4451,
"text": "Output: "
},
{
"code": null,
"e": 4475,
"s": 4461,
"text": "Hello, World!"
},
{
"code": null,
"e": 4531,
"s": 4475,
"text": "Generally, there are two ways to Run a Scala program- "
},
{
"code": null,
"e": 4641,
"s": 4531,
"text": "Using Online IDEs: We can use various online IDEs which can be used to run Scala programs without installing."
},
{
"code": null,
"e": 4982,
"s": 4641,
"text": "Using Command-Line: We can also use command line options to run a Scala program. Below steps demonstrate how to run a Scala program on Command line in Windows/Unix Operating System: Open Commandline and then to compile the code type scala Hello.scala. If your code has no error then it will execute properly and output will be displayed. "
},
{
"code": null,
"e": 5178,
"s": 4986,
"text": "Variables are simply a storage location. Every variable is known by its name and stores some known and unknown piece of information known as value. In Scala there are two types of variable: "
},
{
"code": null,
"e": 5361,
"s": 5178,
"text": "Mutable Variables: These variables are those variables which allow us to change a value after the declaration of a variable. Mutable variables are defined by using the βvarβ keyword."
},
{
"code": null,
"e": 5556,
"s": 5361,
"text": "Immutable Variables: These variables are those variables which do not allow you to change a value after the declaration of a variable. Immutable variables are defined by using the βvalβ keyword."
},
{
"code": null,
"e": 5567,
"s": 5556,
"text": "Example: "
},
{
"code": null,
"e": 5680,
"s": 5567,
"text": "// Mutable Variable\nvar name: String = \"geekforgeeks\";\n\n// Immutable Variable\nval name: String = \"geekforgeeks\";"
},
{
"code": null,
"e": 5773,
"s": 5680,
"text": "To know more about Scala Variables refer β Variables in Scala, Scope of Variable in Scala. "
},
{
"code": null,
"e": 6008,
"s": 5773,
"text": "An operator is a symbol that represents an operation to be performed with one or more operand. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Scala as follows: "
},
{
"code": null,
"e": 6030,
"s": 6008,
"text": "Arithmetic Operators "
},
{
"code": null,
"e": 6051,
"s": 6030,
"text": "Relational Operators"
},
{
"code": null,
"e": 6069,
"s": 6051,
"text": "Logical Operators"
},
{
"code": null,
"e": 6090,
"s": 6069,
"text": "Assignment Operators"
},
{
"code": null,
"e": 6108,
"s": 6090,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 6120,
"s": 6108,
"text": "Example : "
},
{
"code": null,
"e": 6126,
"s": 6120,
"text": "Scala"
},
{
"code": "// Scala program to demonstrate// the Operators // Creating objectobject Geeks{ // Main method def main(args: Array[String]) { // Operands var a = 10; var b = 4; var c = true; var d = false; var result = 0; // using arithmetic operators println (\"Addition is: \"+ (a + b) ); println (\"Subtraction is: \"+ (a - b) ) ; // using Relational Operators if (a == b) { println (\"Equal To Operator is True\"); } else { println (\"Equal To Operator is False\"); } // using Logical Operator 'OR' println(\"Logical Or of a || b = \" + (c || d)); // using Bitwise AND Operator result = a & b; println (\"Bitwise AND: \" + result ); // using Assignment Operators println (\"Addition Assignment Operator: \" + (a += b) ); }}",
"e": 7101,
"s": 6126,
"text": null
},
{
"code": null,
"e": 7238,
"s": 7101,
"text": "Addition is: 14\nSubtraction is: 6\nEqual To Operator is False\nLogical Or of a || b = true\nBitwise AND: 0\nAddition Assignment Operator: ()"
},
{
"code": null,
"e": 7535,
"s": 7240,
"text": "Decision Making in programming is similar to decision making in real life. Scala uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance and branch based on changes to the state of a program. "
},
{
"code": null,
"e": 7540,
"s": 7537,
"text": "If"
},
{
"code": null,
"e": 7550,
"s": 7540,
"text": "If β else"
},
{
"code": null,
"e": 7562,
"s": 7550,
"text": "Nested β If"
},
{
"code": null,
"e": 7580,
"s": 7562,
"text": "if β elsif ladder"
},
{
"code": null,
"e": 7629,
"s": 7580,
"text": "Example 1: To illustrate use of if and if-else "
},
{
"code": null,
"e": 7635,
"s": 7629,
"text": "Scala"
},
{
"code": "// Scala program to illustrate the if and if-else statementobject Test{ // Main Methoddef main(args: Array[String]){ // taking a variable var a: Int = 650 // if condition to check // for even number if(a % 2 == 0) { println(\"Even Number\") } if (a > 698) { // This statement will not // execute as a > 698 is false println(\"GeeksforGeeks\") } else { // This statement will execute println(\"Sudo Placement\") }}}",
"e": 8163,
"s": 7635,
"text": null
},
{
"code": null,
"e": 8190,
"s": 8163,
"text": "Even Number\nSudo Placement"
},
{
"code": null,
"e": 8240,
"s": 8192,
"text": "Example 2: To illustrate the use of Nested-if "
},
{
"code": null,
"e": 8246,
"s": 8240,
"text": "Scala"
},
{
"code": "// Scala program to illustrate // Nested if statementobject Test{ // Main Methoddef main(args: Array[String]){ var a: Int = 10; if(a % 2 == 0) { // Nested - if statement // Will only be executed // if above if statement // is true if(a % 5 == 0) { println(\"Number is divisible by 2 and 5\\n\") } }}}",
"e": 8641,
"s": 8246,
"text": null
},
{
"code": null,
"e": 8672,
"s": 8641,
"text": "Number is divisible by 2 and 5"
},
{
"code": null,
"e": 8751,
"s": 8674,
"text": "To know more about Decision Making please refer to Decision making in Scala "
},
{
"code": null,
"e": 9083,
"s": 8751,
"text": "Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Loops make the programmerβs task simpler. Scala provides the different types of loop to handle the condition based situation in the program. The loops in Scala are : "
},
{
"code": null,
"e": 9094,
"s": 9083,
"text": "for loop "
},
{
"code": null,
"e": 9100,
"s": 9094,
"text": "Scala"
},
{
"code": "// Scala program to illustrate for loopobject forloopDemo { // Main Method def main(args: Array[String]) { var y = 0; // for loop execution with range for(y <- 1 to 4) { println(\"Value of y is: \" + y); } }}",
"e": 9372,
"s": 9100,
"text": null
},
{
"code": null,
"e": 9442,
"s": 9374,
"text": "Value of y is: 1\nValue of y is: 2\nValue of y is: 3\nValue of y is: 4"
},
{
"code": null,
"e": 9459,
"s": 9446,
"text": "While loop "
},
{
"code": null,
"e": 9465,
"s": 9459,
"text": "Scala"
},
{
"code": "// Scala program to illustrate while loopobject whileLoopDemo{ // Main method def main(args: Array[String]) { var x = 1; // Exit when x becomes greater than 4 while (x <= 4) { println(\"Value of x: \" + x); // Increment the value of x for // next iteration x = x + 1; } }}",
"e": 9840,
"s": 9465,
"text": null
},
{
"code": null,
"e": 9898,
"s": 9842,
"text": "Value of x: 1\nValue of x: 2\nValue of x: 3\nValue of x: 4"
},
{
"code": null,
"e": 9918,
"s": 9902,
"text": "do-while loop "
},
{
"code": null,
"e": 9924,
"s": 9918,
"text": "Scala"
},
{
"code": "// Scala program to illustrate do..while loopobject dowhileLoopDemo{ // Main method def main(args: Array[String]) { var a = 10; // using do..while loop do { print(a + \" \"); a = a - 1; }while(a > 0); }}",
"e": 10205,
"s": 9924,
"text": null
},
{
"code": null,
"e": 10229,
"s": 10207,
"text": "10 9 8 7 6 5 4 3 2 1 "
},
{
"code": null,
"e": 10290,
"s": 10233,
"text": "To know more about Loops please refer to Loops in Scala "
},
{
"code": null,
"e": 10486,
"s": 10290,
"text": "Array is a special kind of collection in scala. it is a fixed size data structure that stores elements of the same data type. It is a collection of mutable values. Below is the syntax. Syntax : "
},
{
"code": null,
"e": 10528,
"s": 10486,
"text": "var arrayname = new Array[datatype](size)"
},
{
"code": null,
"e": 10722,
"s": 10530,
"text": "It will create an array of integers which contains the value 40, 55, 63, 17 and many more. Below is the syntax to access a single element of an array, if weβve created an array named number. "
},
{
"code": null,
"e": 10732,
"s": 10722,
"text": "number(0)"
},
{
"code": null,
"e": 10795,
"s": 10732,
"text": "It will produce the output as 40. Iterating through an Array: "
},
{
"code": null,
"e": 10929,
"s": 10795,
"text": "In this example we create an array while providing the values of its elements at the same time. In this case, the type is inferred. "
},
{
"code": null,
"e": 10935,
"s": 10929,
"text": "Scala"
},
{
"code": "// Scala program to accessing an array // of the string as name.object GFG{ // Main method def main(args: Array[String]) { // allocating memory of 1D Array of string. var name = Array(\"gfg\", \"geeks\", \"GeeksQuize\", \"geeksforgeeks\" ) println(\"second element of an array is: \") // Accessing an array element println(name(1) ) }}",
"e": 11348,
"s": 10935,
"text": null
},
{
"code": null,
"e": 11386,
"s": 11348,
"text": "second element of an array is: \ngeeks"
},
{
"code": null,
"e": 11447,
"s": 11388,
"text": "To know more about arrays please refer to Arrays in Scala "
},
{
"code": null,
"e": 11748,
"s": 11447,
"text": "A string is a sequence of characters. In Scala, objects of String are immutable which means a constant and cannot be changed once created. In Scala a String type is specified before meeting the string literal. but when the compiler meet to a string literal and creates a string object str. Syntax : "
},
{
"code": null,
"e": 11863,
"s": 11748,
"text": "var str = \"Hello! GFG\"\nor\nval str = \"Hello! GFG\"\n\nvar str: String = \"Hello! GFG\"\nor\nval str: String = \"Hello! GFG\""
},
{
"code": null,
"e": 11871,
"s": 11865,
"text": "Scala"
},
{
"code": "// Scala program to illustrate how to // create a stringobject Main{ // str1 and str2 are two different strings var str1 = \"Hello! GFG\" val str2: String = \"GeeksforGeeks\" def main(args: Array[String]) { // Display both strings println(str1); println(str2); }}",
"e": 12189,
"s": 11871,
"text": null
},
{
"code": null,
"e": 12214,
"s": 12189,
"text": "Hello! GFG\nGeeksforGeeks"
},
{
"code": null,
"e": 12495,
"s": 12216,
"text": "when a new string is created by adding two strings is known as a concatenation of strings. Scala provides concat() method to concatenate two strings, this method returns a new string which is created using two strings. You can also use β+β operator to concatenate two strings. "
},
{
"code": null,
"e": 12501,
"s": 12495,
"text": "Scala"
},
{
"code": "// Scala program to illustrate how to // concatenate stringsobject Main { // str1 and str2 are two strings var str1 = \"Welcome! GeeksforGeeks \" var str2 = \" to Portal\" // Main function def main(args: Array[String]) { // concatenate str1 and str2 strings // using concat() function var Newstr = str1.concat(str2); // Display strings println(\"String 1:\" +str1); println(\"String 2:\" +str2); println(\"New String :\" +Newstr); // Concatenate strings using '+' operator println(\"This is the tutorial\" + \" of Scala language\" + \" on GFG portal\"); }}",
"e": 13214,
"s": 12501,
"text": null
},
{
"code": null,
"e": 13366,
"s": 13214,
"text": "String 1:Welcome! GeeksforGeeks \nString 2: to Portal\nNew String :Welcome! GeeksforGeeks to Portal\nThis is the tutorial of Scala language on GFG portal"
},
{
"code": null,
"e": 13429,
"s": 13368,
"text": "To know more about Strings please refer to Strings in Scala "
},
{
"code": null,
"e": 13720,
"s": 13429,
"text": "A function is a collection of statements that perform a certain task. Scala is assumed as functional programming language so these play an important role. It makes easier to debug and modify the code. Scala functions are first class values. Below is the syntax of Scala Functions. Syntax: "
},
{
"code": null,
"e": 13803,
"s": 13720,
"text": "def function_name ([parameter_list]) : [return_type] = {\n \n // function body\n\n}"
},
{
"code": null,
"e": 13974,
"s": 13803,
"text": "def keyword is used to declare a function in Scala.Function Calling : There are mainly two ways to call the function in Scala. First way is the standard way as follows: "
},
{
"code": null,
"e": 14003,
"s": 13974,
"text": "function_name(paramter_list)"
},
{
"code": null,
"e": 14117,
"s": 14003,
"text": "In the Second way, a user can also call the function with the help of the instance and dot notation as follows: "
},
{
"code": null,
"e": 14157,
"s": 14117,
"text": "[instance].function_name(paramter_list)"
},
{
"code": null,
"e": 14165,
"s": 14159,
"text": "Scala"
},
{
"code": "// Scala program of function callingobject GeeksforGeeks { def main(args: Array[String]) { // Calling the function println(\"Sum is: \" + functionToAdd(5, 3)); } // declaration and definition of function def functionToAdd(a:Int, b:Int) : Int = { var sum:Int = 0 sum = a + b // returning the value of sum return sum }}",
"e": 14569,
"s": 14165,
"text": null
},
{
"code": null,
"e": 14580,
"s": 14569,
"text": "Output : "
},
{
"code": null,
"e": 14590,
"s": 14580,
"text": "Sum is: 8"
},
{
"code": null,
"e": 14777,
"s": 14590,
"text": " Anonymous Functions in Scala : In Scala, An anonymous function is also known as a function literal. A function which does not contain a name is known as an anonymous function.Syntax : "
},
{
"code": null,
"e": 14816,
"s": 14777,
"text": "(z:Int, y:Int)=> z*y\nOr\n(_:Int)*(_Int)"
},
{
"code": null,
"e": 14824,
"s": 14818,
"text": "Scala"
},
{
"code": "// Scala program to illustrate the anonymous methodobject Main { def main(args: Array[String]) { // Creating anonymous functions // with multiple parameters Assign // anonymous functions to variables var myfc1 = (str1:String, str2:String) => str1 + str2 // An anonymous function is created // using _ wildcard instead of // variable name because str1 and // str2 variable appear only once var myfc2 = (_:String) + (_:String) // Here, the variable invoke like a function call println(myfc1(\"Geeks\", \"12Geeks\")) println(myfc2(\"Geeks\", \"forGeeks\")) }}",
"e": 15504,
"s": 14824,
"text": null
},
{
"code": null,
"e": 15515,
"s": 15504,
"text": "Output : "
},
{
"code": null,
"e": 15542,
"s": 15515,
"text": "Geeks12Geeks\nGeeksforGeeks"
},
{
"code": null,
"e": 15791,
"s": 15542,
"text": " Scala Nested Functions: A function definition inside an another function is known as Nested Function. In Scala, we can define functions inside a function and functions defined inside other functions are called nested or local functions.Syntax : "
},
{
"code": null,
"e": 15877,
"s": 15791,
"text": "def FunctionName1( perameter1, peramete2, ..) = {\ndef FunctionName2() = {\n// code\n}\n}"
},
{
"code": null,
"e": 15885,
"s": 15879,
"text": "Scala"
},
{
"code": "// Scala program of Single Nested Functionobject MaxAndMin { // Main method def main(args: Array[String]) { println(\"Min and Max from 5, 7\") maxAndMin(5, 7); } // Function def maxAndMin(a: Int, b: Int) = { // Nested Function def maxValue() = { if(a > b) { println(\"Max is: \" + a) } else { println(\"Max is: \" + b) } } // Nested Function def minValue() = { if (a < b) { println(\"Min is: \" + a) } else { println(\"Min is: \" + b) } } maxValue(); minValue(); }}",
"e": 16616,
"s": 15885,
"text": null
},
{
"code": null,
"e": 16626,
"s": 16616,
"text": "Output: "
},
{
"code": null,
"e": 16668,
"s": 16626,
"text": "Min and Max from 5, 7\nMax is: 7\nMin is: 5"
},
{
"code": null,
"e": 16873,
"s": 16668,
"text": " Currying Functions in Scala : Currying in Scala is simply a technique or a process of transforming a function. This function takes multiple arguments into a function that takes single argument.Syntax : "
},
{
"code": null,
"e": 16925,
"s": 16873,
"text": "def function name(argument1, argument2) = operation"
},
{
"code": null,
"e": 16933,
"s": 16927,
"text": "Scala"
},
{
"code": "// Scala program add two numbers// using currying Functionobject Curry{ // Define currying function def add(x: Int, y: Int) = x + y; def main(args: Array[String]) { println(add(20, 19)); }}",
"e": 17148,
"s": 16933,
"text": null
},
{
"code": null,
"e": 17158,
"s": 17148,
"text": "Output: "
},
{
"code": null,
"e": 17161,
"s": 17158,
"text": "39"
},
{
"code": null,
"e": 17472,
"s": 17164,
"text": "Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function. OOPs Concepts: "
},
{
"code": null,
"e": 17485,
"s": 17472,
"text": "Polymorphism"
},
{
"code": null,
"e": 17499,
"s": 17485,
"text": "Inheritance "
},
{
"code": null,
"e": 17516,
"s": 17499,
"text": "Abstract-Classes"
},
{
"code": null,
"e": 17533,
"s": 17516,
"text": "Class and Object"
},
{
"code": null,
"e": 17546,
"s": 17533,
"text": "Constructors"
},
{
"code": null,
"e": 17781,
"s": 17548,
"text": "Creation of a Class and an Object: Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. "
},
{
"code": null,
"e": 17787,
"s": 17781,
"text": "Scala"
},
{
"code": "// A Scala program to illustrate// how to create a class // Name of the class is Smartphoneclass Smartphone{ // Class variables var number: Int = 16 var nameofcompany: String = \"Apple\" // Class method def Display() { println(\"Name of the company : \" + nameofcompany); println(\"Total number of Smartphone generation: \" + number); }}object Main { // Main method def main(args: Array[String]) { // Class object var obj = new Smartphone(); obj.Display(); }}",
"e": 18344,
"s": 17787,
"text": null
},
{
"code": null,
"e": 18414,
"s": 18344,
"text": "Name of the company : Apple\nTotal number of Smartphone generation: 16"
},
{
"code": null,
"e": 18674,
"s": 18416,
"text": "Traits are like interfaces in Java. But they are more powerful than the interface in Java because in the traits you are allowed to implement the members. Traits can have methods(both abstract and non-abstract), and fields as its members.Creating a trait β "
},
{
"code": null,
"e": 18680,
"s": 18674,
"text": "Scala"
},
{
"code": "// Scala program to illustrate how to // create traits // Trait trait MyTrait{ def pet def pet_color} // MyClass inherits traitclass MyClass extends MyTrait{ // Implementation of methods of MyTrait def pet() { println(\"Pet: Dog\") } def pet_color() { println(\"Pet_color: White\") } // Class method def pet_name() { println(\"Pet_name: Dollar\") }} object Main { // Main method def main(args: Array[String]) { val obj = new MyClass(); obj.pet(); obj.pet_color(); obj.pet_name(); }}",
"e": 19294,
"s": 18680,
"text": null
},
{
"code": null,
"e": 19305,
"s": 19294,
"text": "Output : "
},
{
"code": null,
"e": 19348,
"s": 19305,
"text": "Pet: Dog\nPet_color: White\nPet_name: Dollar"
},
{
"code": null,
"e": 19407,
"s": 19348,
"text": "To know more about Traits please refer to Traits in Scala "
},
{
"code": null,
"e": 19634,
"s": 19407,
"text": "Regular Expressions explain a common pattern utilized to match a series of input data so, it is helpful in Pattern Matching in numerous programming languages. In Scala Regular Expressions are generally termed as Scala Regex. "
},
{
"code": null,
"e": 19640,
"s": 19634,
"text": "Scala"
},
{
"code": "// Scala program for Regular// Expressions // Creating objectobject GfG{ // Main method def main(args : Array[String]) { // Applying r() method val portal = \"GeeksforGeeks\".r val CS = \"GeeksforGeeks is a CS portal.\" // Displays the first match println(portal findFirstIn CS) }}",
"e": 20016,
"s": 19640,
"text": null
},
{
"code": null,
"e": 20027,
"s": 20016,
"text": "Output : "
},
{
"code": null,
"e": 20047,
"s": 20027,
"text": "Some(GeeksforGeeks)"
},
{
"code": null,
"e": 20119,
"s": 20047,
"text": "To know more about tuple please refer to Regular Expressions in Scala. "
},
{
"code": null,
"e": 20299,
"s": 20119,
"text": "An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time. These events change the flow control of the program in execution. "
},
{
"code": null,
"e": 20518,
"s": 20299,
"text": "In scala, All exceptions are unchecked. there is no concept of checked exception Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception.The Throwing Exceptions : "
},
{
"code": null,
"e": 20524,
"s": 20518,
"text": "Scala"
},
{
"code": "// Scala program of throw keyword // Creating objectobject Main { // Define function def validate(article:Int)= { // Using throw keyword if(article < 20) throw new ArithmeticException(\"You are not eligible for internship\") else println(\"You are eligible for internship\") } // Main method def main(args: Array[String]) { validate(22) }}",
"e": 20947,
"s": 20524,
"text": null
},
{
"code": null,
"e": 20958,
"s": 20947,
"text": "Output : "
},
{
"code": null,
"e": 20990,
"s": 20958,
"text": "You are eligible for internship"
},
{
"code": null,
"e": 21015,
"s": 20990,
"text": "Try-Catch Exceptions : "
},
{
"code": null,
"e": 21021,
"s": 21015,
"text": "Scala"
},
{
"code": "// Scala program of try-catch Exception import java.io.IOException // Creating objectobject GFG{ // Main method def main(args:Array[String]) { try { var N = 5/0 } catch { // Catch block contain cases. case i: IOException => { println(\"IOException occurred.\") } case a : ArithmeticException => { println(\"Arithmetic Exception occurred.\") } } } } ",
"e": 21573,
"s": 21021,
"text": null
},
{
"code": null,
"e": 21584,
"s": 21573,
"text": "Output : "
},
{
"code": null,
"e": 21615,
"s": 21584,
"text": "Arithmetic Exception occurred."
},
{
"code": null,
"e": 21970,
"s": 21617,
"text": "File Handling is a way to store the fetched information in a file. Scala provides packages from which we can create, open, read and write the files. For writing to a file in scala we borrow java.io._ from Java because we donβt have a class to write into a file, in the Scala standard library. We could also import java.io.File and java.io.PrintWriter. "
},
{
"code": null,
"e": 22194,
"s": 21970,
"text": "Creating a new file : java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.File(String pathname) converts theparameter string to abstract path name, creating a new file instance."
},
{
"code": null,
"e": 22396,
"s": 22194,
"text": "java.io.File defines classes and interfaces for the JVM access files, file systems and attributes.File(String pathname) converts theparameter string to abstract path name, creating a new file instance."
},
{
"code": null,
"e": 22495,
"s": 22396,
"text": "java.io.File defines classes and interfaces for the JVM access files, file systems and attributes."
},
{
"code": null,
"e": 22599,
"s": 22495,
"text": "File(String pathname) converts theparameter string to abstract path name, creating a new file instance."
},
{
"code": null,
"e": 22775,
"s": 22599,
"text": "Writing to the file : java.io.PrintWriter includes all the printing methods included in PrintStream. Below is the implementation for creating a new file and writing into it. "
},
{
"code": null,
"e": 22781,
"s": 22775,
"text": "Scala"
},
{
"code": "// Scala File handling programimport java.io.Fileimport java.io.PrintWriter // Creating objectobject Geeks{ // Main method def main(args:Array[String]) { // Creating a file val file_Object = new File(\"abc.txt\" ) // Passing reference of file to the printwriter val print_Writer = new PrintWriter(file_Object) // Writing to the file print_Writer.write(\"Hello, This is Geeks For Geeks\") // Closing printwriter print_Writer.close() }} ",
"e": 23320,
"s": 22781,
"text": null
},
{
"code": null,
"e": 23381,
"s": 23322,
"text": "Reading a File : Below is the example to reading a file. "
},
{
"code": null,
"e": 23387,
"s": 23381,
"text": "Scala"
},
{
"code": "// Scala File handling programimport scala.io.Source // Creating object object GeeksScala{ // Main method def main(args : Array[String]) { // file name val fname = \"abc.txt\" // creates iterable representation // of the source file val fSource = Source.fromFile(fname) while (fSource.hasNext) { println(fSource.next) } // closing file fSource.close() }}",
"e": 23856,
"s": 23387,
"text": null
},
{
"code": null,
"e": 23950,
"s": 23858,
"text": "To know more about various different File Handling, please refer to File Handling in Scala "
},
{
"code": null,
"e": 24288,
"s": 23952,
"text": "A list is a collection which contains immutable data. List represents linked list in Scala. The Scala List class holds a sequenced, linear list of items. Lists are immutable whereas arrays are mutable in Scala. In a Scala list, each element must be of the same type. list is defined under scala.collection.immutable package. Syntax : "
},
{
"code": null,
"e": 24395,
"s": 24288,
"text": "val variable_name: List[type] = List(item1, item2, item3)\nor\nval variable_name = List(item1, item2, item3)"
},
{
"code": null,
"e": 24440,
"s": 24395,
"text": "Create and initialize Scala List Example : "
},
{
"code": null,
"e": 24446,
"s": 24440,
"text": "Scala"
},
{
"code": "// Scala program to print immutable listsimport scala.collection.immutable._ // Creating objectobject GFG{ // Main method def main(args:Array[String]) { // Creating and initializing immutable lists val mylist1: List[String] = List(\"Geeks\", \"GFG\", \"GeeksforGeeks\", \"Geek123\") val mylist2 = List(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") // Display the value of mylist1 println(\"List 1:\") println(mylist1) // Display the value of mylist2 using for loop println(\"\\nList 2:\") for(mylist<-mylist2) { println(mylist) } }}",
"e": 25139,
"s": 24446,
"text": null
},
{
"code": null,
"e": 25150,
"s": 25139,
"text": "Output : "
},
{
"code": null,
"e": 25233,
"s": 25150,
"text": "List 1:\nList(Geeks, GFG, GeeksforGeeks, Geek123)\n\nList 2:\nC\nC#\nJava\nScala\nPHP\nRuby"
},
{
"code": null,
"e": 25289,
"s": 25233,
"text": "To know more about List please refer to List in Scala. "
},
{
"code": null,
"e": 25572,
"s": 25289,
"text": "Map is a collection of key-value pairs. In other words, it is similar to dictionary. Keys are always unique while values need not be unique. In order to use mutable Map, we must import scala.collection.mutable.Map class explicitly. Creating a map and accessing the value Example : "
},
{
"code": null,
"e": 25578,
"s": 25572,
"text": "Scala"
},
{
"code": "// Scala map program of // Accessing Values Using Keys // Creating object object GFG{ // Main method def main(args:Array[String]) { val mapIm = Map(\"Ajay\" -> 30, \"Bhavesh\" -> 20, \"Charlie\" -> 50) // Accessing score of Ajay val ajay = mapIm(\"Ajay\") println(ajay) }} ",
"e": 25939,
"s": 25578,
"text": null
},
{
"code": null,
"e": 25950,
"s": 25939,
"text": "Output : "
},
{
"code": null,
"e": 25953,
"s": 25950,
"text": "30"
},
{
"code": null,
"e": 26007,
"s": 25953,
"text": "To know more about Map please refer to Map in Scala. "
},
{
"code": null,
"e": 26309,
"s": 26007,
"text": "An iterator is a way to access elements of a collection one-by-one. It resembles to a collection in terms of syntax but works differently in terms of functionality. To access elements we can make use of hasNext() to check if there are elements available and next() to print the next element. Syntax: "
},
{
"code": null,
"e": 26446,
"s": 26309,
"text": "val v = Iterator(5, 1, 2, 3, 6, 4)\n\n//checking for availability of next element\nwhile(v.hasNext)\n\n//printing the element\nprintln(v.next)"
},
{
"code": null,
"e": 26458,
"s": 26446,
"text": "Example : "
},
{
"code": null,
"e": 26464,
"s": 26458,
"text": "Scala"
},
{
"code": "//Scala iterator program//for defining iterator //Creating objectobject GFG{ // Main method def main(args:Array[String]) { val v = Array(5, 1, 2, 3, 6, 4) //val v = List(5, 1, 2, 3, 6, 4) // defining an iterator // for a collection val i = v.iterator while (i.hasNext) print(i.next + \" \") }}",
"e": 26837,
"s": 26464,
"text": null
},
{
"code": null,
"e": 26847,
"s": 26837,
"text": "Output: "
},
{
"code": null,
"e": 26860,
"s": 26847,
"text": "5 1 2 3 6 4 "
},
{
"code": null,
"e": 26922,
"s": 26860,
"text": "To know more about tuple please refer to Iterators in Scala. "
},
{
"code": null,
"e": 27156,
"s": 26922,
"text": "A set is a collection which only contains unique items. The uniqueness of a set are defined by the == method of the type that set holds. If you try to add a duplicate item in the set, then set quietly discard your request. Syntax : "
},
{
"code": null,
"e": 27397,
"s": 27156,
"text": "// Immutable set\nval variable_name: Set[type] = Set(item1, item2, item3)\nor\nval variable_name = Set(item1, item2, item3)\n\n// Mutable Set\nvar variable_name: Set[type] = Set(item1, item2, item3)\nor\nvar variable_name = Set(item1, item2, item3)"
},
{
"code": null,
"e": 27449,
"s": 27397,
"text": "Creating and initializing Immutable set Example : "
},
{
"code": null,
"e": 27455,
"s": 27449,
"text": "Scala"
},
{
"code": "// Scala program to illustrate the // use of immutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing immutable sets val myset1: Set[String] = Set(\"Geeks\", \"GFG\", \"GeeksforGeeks\", \"Geek123\") val myset2 = Set(\"C\", \"C#\", \"Java\", \"Scala\", \"PHP\", \"Ruby\") // Display the value of myset1 println(\"Set 1:\") println(myset1) // Display the value of myset2 using for loop println(\"\\nSet 2:\") for(myset<-myset2) { println(myset) } }}",
"e": 28148,
"s": 27455,
"text": null
},
{
"code": null,
"e": 28159,
"s": 28148,
"text": "Output : "
},
{
"code": null,
"e": 28239,
"s": 28159,
"text": "Set 1:\nSet(Geeks, GFG, GeeksforGeeks, Geek123)\n\nSet 2:\nScala\nC#\nRuby\nPHP\nC\nJava"
},
{
"code": null,
"e": 28289,
"s": 28239,
"text": "Creating and initializing mutable set Example : "
},
{
"code": null,
"e": 28295,
"s": 28289,
"text": "Scala"
},
{
"code": "// Scala program to illustrate the // use of mutable setimport scala.collection.immutable._ object Main { def main(args: Array[String]) { // Creating and initializing mutable sets var myset1: Set[String] = Set(\"Geeks\", \"GFG\", \"GeeksforGeeks\", \"Geek123\") var myset2 = Set(10, 100, 1000, 10000, 100000) // Display the value of myset1 println(\"Set 1:\") println(myset1) // Display the value of myset2 // using a foreach loop println(\"\\nSet 2:\") myset2.foreach((item:Int)=>println(item)) }}",
"e": 28924,
"s": 28295,
"text": null
},
{
"code": null,
"e": 28935,
"s": 28924,
"text": "Output : "
},
{
"code": null,
"e": 29015,
"s": 28935,
"text": "Set 1:\nSet(Geeks, GFG, GeeksforGeeks, Geek123)\n\nSet 2:\n10\n100000\n10000\n1000\n100"
},
{
"code": null,
"e": 29102,
"s": 29015,
"text": "To know more about Set please refer to Set in Scala | Set-1 and Set in Scala | Set-2. "
},
{
"code": null,
"e": 29356,
"s": 29102,
"text": "Tuple is a collection of elements. Tuples are heterogeneous data structures, i.e., is they can store elements of different data types. A tuple is immutable, unlike an array in scala which is mutable. Creating a tuple and accessing an element Example : "
},
{
"code": null,
"e": 29362,
"s": 29356,
"text": "Scala"
},
{
"code": "// Scala program to access // element using underscore method // Creating objectobject gfg { // Main method def main(args: Array[String]) { var name = (15, \"chandan\", true) println(name._1) // print 1st element println(name._2) // print 2st element println(name._3) // print 3st element }}",
"e": 29701,
"s": 29362,
"text": null
},
{
"code": null,
"e": 29712,
"s": 29701,
"text": "Output : "
},
{
"code": null,
"e": 29728,
"s": 29712,
"text": "15\nchandan\ntrue"
},
{
"code": null,
"e": 29786,
"s": 29728,
"text": "To know more about tuple please refer to tuple in Scala. "
},
{
"code": null,
"e": 29803,
"s": 29786,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29819,
"s": 29803,
"text": "simranarora5sos"
},
{
"code": null,
"e": 29834,
"s": 29819,
"text": "varshagumber28"
},
{
"code": null,
"e": 29844,
"s": 29834,
"text": "kalrap615"
},
{
"code": null,
"e": 29851,
"s": 29844,
"text": "malikm"
},
{
"code": null,
"e": 29857,
"s": 29851,
"text": "Scala"
}
] |
URL Class in Java with Examples
|
18 Apr, 2022
URL known as Uniform Resource Locator is simply a string of text that identifies all the resources on the Internet, telling us the address of the resource, how to communicate with it, and retrieve something from it.
A URL can have many forms. The most general however follows a three-components system as proposed below:
Protocol: HTTP is the protocol hereHostname: Name of the machine on which the resource lives.File Name: The pathname to the file on the machine.Port Number: Port number to which to connect (typically optional).
Protocol: HTTP is the protocol here
Hostname: Name of the machine on which the resource lives.
File Name: The pathname to the file on the machine.
Port Number: Port number to which to connect (typically optional).
The URL class is the gateway to any of the resources available on the internet. A Class URL represents a Uniform Resource Locator, which is a pointer to a βresourceβ on the World Wide Web. A resource can point to a simple file or directory, or it can refer to a more complicated object, such as a query to a database or to a search engine.
URL(String address) throws MalformedURLException: It creates a URL object from the specified String.URL(String protocol, String host, String file): Creates a URL object from the specified protocol, host, and file name.URL(String protocol, String host, int port, String file): Creates a URL object from protocol, host, port, and file name.URL(URL context, String spec): Creates a URL object by parsing the given spec in the given context. URL(String protocol, String host, int port, String file, URLStreamHandler handler):Creates a URL object from the specified protocol, host, port number, file, and handler.URL(URL context, String spec, URLStreamHandler handler):Creates a URL by parsing the given spec with the specified handler within a specified context.
URL(String address) throws MalformedURLException: It creates a URL object from the specified String.
URL(String protocol, String host, String file): Creates a URL object from the specified protocol, host, and file name.
URL(String protocol, String host, int port, String file): Creates a URL object from protocol, host, port, and file name.
URL(URL context, String spec): Creates a URL object by parsing the given spec in the given context.
URL(String protocol, String host, int port, String file, URLStreamHandler handler):Creates a URL object from the specified protocol, host, port number, file, and handler.
URL(URL context, String spec, URLStreamHandler handler):Creates a URL by parsing the given spec with the specified handler within a specified context.
Example:
Java
// Java program to demonstrate working of URL // Importing required classesimport java.net.MalformedURLException;import java.net.URL; // Main class// URL classpublic class GFG { // Main driver method public static void main(String[] args) throws MalformedURLException { // Creating a URL with string representation URL url1 = new URL( "https://www.google.co.in/?gfe_rd=cr&ei=ptYq" + "WK26I4fT8gfth6CACg#q=geeks+for+geeks+java"); // Creating a URL with a protocol,hostname,and path URL url2 = new URL("http", "www.geeksforgeeks.org", "/jvm-works-jvm-architecture/"); URL url3 = new URL( "https://www.google.co.in/search?" + "q=gnu&rlz=1C1CHZL_enIN71" + "4IN715&oq=gnu&aqs=chrome..69i57j6" + "9i60l5.653j0j7&sourceid=chrome&ie=UTF" + "-8#q=geeks+for+geeks+java"); // Printing the string representation of the URL System.out.println(url1.toString()); System.out.println(url2.toString()); System.out.println(); System.out.println( "Different components of the URL3-"); // Retrieving the protocol for the URL System.out.println("Protocol:- " + url3.getProtocol()); // Retrieving the hostname of the url System.out.println("Hostname:- " + url3.getHost()); // Retrieving the default port System.out.println("Default port:- " + url3.getDefaultPort()); // Retrieving the query part of URL System.out.println("Query:- " + url3.getQuery()); // Retrieving the path of URL System.out.println("Path:- " + url3.getPath()); // Retrieving the file name System.out.println("File:- " + url3.getFile()); // Retrieving the reference System.out.println("Reference:- " + url3.getRef()); }}
Output:
https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java
https://www.geeksforgeeks.org/jvm-works-jvm-architecture/
Different components of the URL3-
Protocol:- https
Hostname:- www.google.co.in
Default port:- 443
Query:- q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8
Path:- /search
File:- /search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8
Reference:- q=geeks+for+geeks+java
This article is contributed by Rishabh Mahrsee. 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. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
akshaysingh98088
sumitgumber28
solankimayank
Java-Classes
Java-URL
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Apr, 2022"
},
{
"code": null,
"e": 268,
"s": 52,
"text": "URL known as Uniform Resource Locator is simply a string of text that identifies all the resources on the Internet, telling us the address of the resource, how to communicate with it, and retrieve something from it."
},
{
"code": null,
"e": 373,
"s": 268,
"text": "A URL can have many forms. The most general however follows a three-components system as proposed below:"
},
{
"code": null,
"e": 584,
"s": 373,
"text": "Protocol: HTTP is the protocol hereHostname: Name of the machine on which the resource lives.File Name: The pathname to the file on the machine.Port Number: Port number to which to connect (typically optional)."
},
{
"code": null,
"e": 620,
"s": 584,
"text": "Protocol: HTTP is the protocol here"
},
{
"code": null,
"e": 679,
"s": 620,
"text": "Hostname: Name of the machine on which the resource lives."
},
{
"code": null,
"e": 731,
"s": 679,
"text": "File Name: The pathname to the file on the machine."
},
{
"code": null,
"e": 798,
"s": 731,
"text": "Port Number: Port number to which to connect (typically optional)."
},
{
"code": null,
"e": 1138,
"s": 798,
"text": "The URL class is the gateway to any of the resources available on the internet. A Class URL represents a Uniform Resource Locator, which is a pointer to a βresourceβ on the World Wide Web. A resource can point to a simple file or directory, or it can refer to a more complicated object, such as a query to a database or to a search engine."
},
{
"code": null,
"e": 1897,
"s": 1138,
"text": "URL(String address) throws MalformedURLException: It creates a URL object from the specified String.URL(String protocol, String host, String file): Creates a URL object from the specified protocol, host, and file name.URL(String protocol, String host, int port, String file): Creates a URL object from protocol, host, port, and file name.URL(URL context, String spec): Creates a URL object by parsing the given spec in the given context. URL(String protocol, String host, int port, String file, URLStreamHandler handler):Creates a URL object from the specified protocol, host, port number, file, and handler.URL(URL context, String spec, URLStreamHandler handler):Creates a URL by parsing the given spec with the specified handler within a specified context."
},
{
"code": null,
"e": 1998,
"s": 1897,
"text": "URL(String address) throws MalformedURLException: It creates a URL object from the specified String."
},
{
"code": null,
"e": 2117,
"s": 1998,
"text": "URL(String protocol, String host, String file): Creates a URL object from the specified protocol, host, and file name."
},
{
"code": null,
"e": 2238,
"s": 2117,
"text": "URL(String protocol, String host, int port, String file): Creates a URL object from protocol, host, port, and file name."
},
{
"code": null,
"e": 2339,
"s": 2238,
"text": "URL(URL context, String spec): Creates a URL object by parsing the given spec in the given context. "
},
{
"code": null,
"e": 2510,
"s": 2339,
"text": "URL(String protocol, String host, int port, String file, URLStreamHandler handler):Creates a URL object from the specified protocol, host, port number, file, and handler."
},
{
"code": null,
"e": 2661,
"s": 2510,
"text": "URL(URL context, String spec, URLStreamHandler handler):Creates a URL by parsing the given spec with the specified handler within a specified context."
},
{
"code": null,
"e": 2670,
"s": 2661,
"text": "Example:"
},
{
"code": null,
"e": 2675,
"s": 2670,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of URL // Importing required classesimport java.net.MalformedURLException;import java.net.URL; // Main class// URL classpublic class GFG { // Main driver method public static void main(String[] args) throws MalformedURLException { // Creating a URL with string representation URL url1 = new URL( \"https://www.google.co.in/?gfe_rd=cr&ei=ptYq\" + \"WK26I4fT8gfth6CACg#q=geeks+for+geeks+java\"); // Creating a URL with a protocol,hostname,and path URL url2 = new URL(\"http\", \"www.geeksforgeeks.org\", \"/jvm-works-jvm-architecture/\"); URL url3 = new URL( \"https://www.google.co.in/search?\" + \"q=gnu&rlz=1C1CHZL_enIN71\" + \"4IN715&oq=gnu&aqs=chrome..69i57j6\" + \"9i60l5.653j0j7&sourceid=chrome&ie=UTF\" + \"-8#q=geeks+for+geeks+java\"); // Printing the string representation of the URL System.out.println(url1.toString()); System.out.println(url2.toString()); System.out.println(); System.out.println( \"Different components of the URL3-\"); // Retrieving the protocol for the URL System.out.println(\"Protocol:- \" + url3.getProtocol()); // Retrieving the hostname of the url System.out.println(\"Hostname:- \" + url3.getHost()); // Retrieving the default port System.out.println(\"Default port:- \" + url3.getDefaultPort()); // Retrieving the query part of URL System.out.println(\"Query:- \" + url3.getQuery()); // Retrieving the path of URL System.out.println(\"Path:- \" + url3.getPath()); // Retrieving the file name System.out.println(\"File:- \" + url3.getFile()); // Retrieving the reference System.out.println(\"Reference:- \" + url3.getRef()); }}",
"e": 4621,
"s": 2675,
"text": null
},
{
"code": null,
"e": 4631,
"s": 4621,
"text": "Output: "
},
{
"code": null,
"e": 5140,
"s": 4631,
"text": "https://www.google.co.in/?gfe_rd=cr&ei=ptYqWK26I4fT8gfth6CACg#q=geeks+for+geeks+java\nhttps://www.geeksforgeeks.org/jvm-works-jvm-architecture/\n\nDifferent components of the URL3-\nProtocol:- https\nHostname:- www.google.co.in\nDefault port:- 443\nQuery:- q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8\nPath:- /search\nFile:- /search?q=gnu&rlz=1C1CHZL_enIN714IN715&oq=gnu&aqs=chrome..69i57j69i60l5.653j0j7&sourceid=chrome&ie=UTF-8\nReference:- q=geeks+for+geeks+java"
},
{
"code": null,
"e": 5565,
"s": 5140,
"text": "This article is contributed by Rishabh Mahrsee. 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. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5578,
"s": 5565,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5595,
"s": 5578,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 5609,
"s": 5595,
"text": "sumitgumber28"
},
{
"code": null,
"e": 5623,
"s": 5609,
"text": "solankimayank"
},
{
"code": null,
"e": 5636,
"s": 5623,
"text": "Java-Classes"
},
{
"code": null,
"e": 5645,
"s": 5636,
"text": "Java-URL"
},
{
"code": null,
"e": 5650,
"s": 5645,
"text": "Java"
},
{
"code": null,
"e": 5655,
"s": 5650,
"text": "Java"
},
{
"code": null,
"e": 5753,
"s": 5655,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5804,
"s": 5753,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5835,
"s": 5804,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5854,
"s": 5835,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5884,
"s": 5854,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5899,
"s": 5884,
"text": "Stream In Java"
},
{
"code": null,
"e": 5917,
"s": 5899,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5937,
"s": 5917,
"text": "Collections in Java"
},
{
"code": null,
"e": 5961,
"s": 5937,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 5993,
"s": 5961,
"text": "Multidimensional Arrays in Java"
}
] |
Symmetric Binary Tree
|
21 Jun, 2021
Given a binary tree, check whether it is a mirror of itself.
Examples:
Input:
5
/ \
3 3
/ \ / \
8 9 9 8
Output: Symmetric
Input:
5
/ \
8 7
\ \
4 3
Output: Not Symmetric
Approach: The idea is to traverse the tree using Morris Traversal and Reverse Morris Traversal to traverse the given binary tree and at each step check that the data of the current node is equal in both the traversals. If at any step the data of the nodes are different. Then, the given tree is not Symmetric Binary Tree.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to check// if Tree is symmetric or not #include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; Node* left; Node* right; Node(int val) { data = val; left = right = NULL; }}; // Function to check if the given// binary tree is Symmetric or notbool isSymmetric(struct Node* root){ Node *curr1 = root, *curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != NULL && curr2 != NULL) { if (curr1->left == NULL && curr2->right == NULL) { if (curr1->data != curr2->data) return false; curr1 = curr1->right; curr2 = curr2->left; } else if (curr1->left != NULL && curr2->right != NULL) { Node* pre1 = curr1->left; Node* pre2 = curr2->right; while (pre1->right != NULL && pre1->right != curr1 && pre2->left != NULL && pre2->left != curr2) { pre1 = pre1->right; pre2 = pre2->left; } if (pre1->right == NULL && pre2->left == NULL) { // Here, we are threading the Node pre1->right = curr1; pre2->left = curr2; curr1 = curr1->left; curr2 = curr2->right; } else if (pre1->right == curr1 && pre2->left == curr2) { // Unthreading the nodes pre1->right = NULL; pre2->left = NULL; if (curr1->data != curr2->data) return false; curr1 = curr1->right; curr2 = curr2->left; } else return false; } else return false; } if (curr1 != curr2) return false; return true;} // Driver Codeint main(){ /* 5 / \ 3 3 / \ / \ 8 9 9 8 */ // Creation of Binary tree Node* root = new Node(5); root->left = new Node(3); root->right = new Node(3); root->left->left = new Node(8); root->left->right = new Node(9); root->right->left = new Node(9); root->right->right = new Node(8); if (isSymmetric(root)) cout << "Symmetric"; else cout << "Not Symmetric"; return 0;}
// Java implementation to check// if Tree is symmetric or notclass GFG{ // A Binary Tree Nodestatic class Node{ int data; Node left; Node right; Node(int val) { data = val; left = right = null; }}; // Function to check if the given// binary tree is Symmetric or notstatic boolean isSymmetric(Node root){ Node curr1 = root, curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != null && curr2 != null) { if (curr1.left == null && curr2.right == null) { if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else if (curr1.left != null && curr2.right != null) { Node pre1 = curr1.left; Node pre2 = curr2.right; while (pre1.right != null && pre1.right != curr1 && pre2.left != null && pre2.left != curr2) { pre1 = pre1.right; pre2 = pre2.left; } if (pre1.right == null && pre2.left == null) { // Here, we are threading the Node pre1.right = curr1; pre2.left = curr2; curr1 = curr1.left; curr2 = curr2.right; } else if (pre1.right == curr1 && pre2.left == curr2) { // Unthreading the nodes pre1.right = null; pre2.left = null; if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else return false; } else return false; } if (curr1 != curr2) return false; return true;} // Driver Codepublic static void main(String[] args){ /* 5 / \ 3 3 / \ / \ 8 9 9 8 */ // Creation of Binary tree Node root = new Node(5); root.left = new Node(3); root.right = new Node(3); root.left.left = new Node(8); root.left.right = new Node(9); root.right.left = new Node(9); root.right.right = new Node(8); if (isSymmetric(root)) System.out.print("Symmetric"); else System.out.print("Not Symmetric");}} // This code is contributed by Rajput-Ji
# Python3 implementation to check# if Tree is symmetric or not # A Binary Tree Nodeclass Node: def __init__(self, val): self.data = val self.left = self.right = None # Function to check if the given# binary tree is Symmetric or notdef isSymmetric(root): curr1 = root curr2 = root # Loop to traverse the tree in # Morris Traversal and # Reverse Morris Traversal while curr1 != None and curr2 != None: if (curr1.left == None and curr2.right == None): if curr1.data != curr2.data: return False curr1 = curr1.right curr2 = curr2.left elif curr1 != None and curr2 != None: pre1 = curr1.left pre2 = curr2.right while (pre1.right != None and pre1.right != curr1 and pre2.left != None and pre2.left != curr2): pre1 = pre1.right pre2 = pre2.left if pre1.right == None and pre2.left == None: # Here, we are threading the Node pre1.right = curr1 pre2.left = curr2 curr1 = curr1.left curr2 = curr2.right elif (pre1.right == curr1 and pre2.left == curr2): # Unthreading the nodes pre1.right = None pre2.left = None if curr1.data != curr2.data: return False curr1 = curr1.right curr2 = curr2.left else: return False else: return False if curr1 != curr2: return False return True # Driver codedef main(): # # 5 # / \ # 3 3 # / \ / \ #8 9 9 8 # Creation of Binary tree root = Node(5) root.left = Node(3) root.right = Node(3) root.left.left = Node(8) root.left.right = Node(9) root.right.left = Node(9) root.right.right = Node(8) if isSymmetric(root): print("Symmetric") else: print("Not Symmetric")main() # This code is contributed by Stuti Pathak
// C# implementation to check// if Tree is symmetric or notusing System; class GFG{ // A Binary Tree Nodeclass Node{ public int data; public Node left; public Node right; public Node(int val) { data = val; left = right = null; }}; // Function to check if the given// binary tree is Symmetric or notstatic bool isSymmetric(Node root){ Node curr1 = root, curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != null && curr2 != null) { if (curr1.left == null && curr2.right == null) { if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else if (curr1.left != null && curr2.right != null) { Node pre1 = curr1.left; Node pre2 = curr2.right; while (pre1.right != null && pre1.right != curr1 && pre2.left != null && pre2.left != curr2) { pre1 = pre1.right; pre2 = pre2.left; } if (pre1.right == null && pre2.left == null) { // Here, we are threading the Node pre1.right = curr1; pre2.left = curr2; curr1 = curr1.left; curr2 = curr2.right; } else if (pre1.right == curr1 && pre2.left == curr2) { // Unthreading the nodes pre1.right = null; pre2.left = null; if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else return false; } else return false; } if (curr1 != curr2) return false; return true;} // Driver Codepublic static void Main(String[] args){ /* 5 / \ 3 3 / \ / \ 8 9 9 8 */ // Creation of Binary tree Node root = new Node(5); root.left = new Node(3); root.right = new Node(3); root.left.left = new Node(8); root.left.right = new Node(9); root.right.left = new Node(9); root.right.right = new Node(8); if (isSymmetric(root)) Console.Write("Symmetric"); else Console.Write("Not Symmetric");}} // This code is contributed by Rajput-Ji
<script> // JavaScript implementation to check // if Tree is symmetric or not // A Binary Tree Node class Node { constructor(val) { this.left = null; this.right = null; this.data = val; } } // Function to check if the given // binary tree is Symmetric or not function isSymmetric(root) { let curr1 = root, curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != null && curr2 != null) { if (curr1.left == null && curr2.right == null) { if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else if (curr1.left != null && curr2.right != null) { let pre1 = curr1.left; let pre2 = curr2.right; while (pre1.right != null && pre1.right != curr1 && pre2.left != null && pre2.left != curr2) { pre1 = pre1.right; pre2 = pre2.left; } if (pre1.right == null && pre2.left == null) { // Here, we are threading the Node pre1.right = curr1; pre2.left = curr2; curr1 = curr1.left; curr2 = curr2.right; } else if (pre1.right == curr1 && pre2.left == curr2) { // Unthreading the nodes pre1.right = null; pre2.left = null; if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else return false; } else return false; } if (curr1 != curr2) return false; return true; } /* 5 / \ 3 3 / \ / \ 8 9 9 8 */ // Creation of Binary tree let root = new Node(5); root.left = new Node(3); root.right = new Node(3); root.left.left = new Node(8); root.left.right = new Node(9); root.right.left = new Node(9); root.right.right = new Node(8); if (isSymmetric(root)) document.write("Symmetric"); else document.write("Not Symmetric"); </script>
Output:
Symmetric
Time Complexity: Since every edge of the tree is traversed at most two times exactly as in the case of Morris traversal and in the worst case, the same number of extra edges (as input tree) are created and removed. Therefore, the time complexity of this approach is O(N).
Auxiliary Space: O(1)
stutipathak31jan
Rajput-Ji
rameshtravel07
Binary Tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
What is Data Structure: Types, Classifications and Applications
Diagonal Traversal of Binary Tree
Top 50 Tree Coding Problems for Interviews
Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
Iterative Preorder Traversal
Lowest Common Ancestor in a Binary Search Tree.
Write Code to Determine if Two Trees are Identical
Boundary Traversal of binary tree
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 114,
"s": 53,
"text": "Given a binary tree, check whether it is a mirror of itself."
},
{
"code": null,
"e": 124,
"s": 114,
"text": "Examples:"
},
{
"code": null,
"e": 287,
"s": 124,
"text": "Input:\n 5\n / \\\n 3 3\n / \\ / \\\n 8 9 9 8\n \nOutput: Symmetric\n\nInput:\n 5\n / \\\n 8 7\n \\ \\\n 4 3\nOutput: Not Symmetric "
},
{
"code": null,
"e": 609,
"s": 287,
"text": "Approach: The idea is to traverse the tree using Morris Traversal and Reverse Morris Traversal to traverse the given binary tree and at each step check that the data of the current node is equal in both the traversals. If at any step the data of the nodes are different. Then, the given tree is not Symmetric Binary Tree."
},
{
"code": null,
"e": 660,
"s": 609,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 664,
"s": 660,
"text": "C++"
},
{
"code": null,
"e": 669,
"s": 664,
"text": "Java"
},
{
"code": null,
"e": 677,
"s": 669,
"text": "Python3"
},
{
"code": null,
"e": 680,
"s": 677,
"text": "C#"
},
{
"code": null,
"e": 691,
"s": 680,
"text": "Javascript"
},
{
"code": "// C++ implementation to check// if Tree is symmetric or not #include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; Node* left; Node* right; Node(int val) { data = val; left = right = NULL; }}; // Function to check if the given// binary tree is Symmetric or notbool isSymmetric(struct Node* root){ Node *curr1 = root, *curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != NULL && curr2 != NULL) { if (curr1->left == NULL && curr2->right == NULL) { if (curr1->data != curr2->data) return false; curr1 = curr1->right; curr2 = curr2->left; } else if (curr1->left != NULL && curr2->right != NULL) { Node* pre1 = curr1->left; Node* pre2 = curr2->right; while (pre1->right != NULL && pre1->right != curr1 && pre2->left != NULL && pre2->left != curr2) { pre1 = pre1->right; pre2 = pre2->left; } if (pre1->right == NULL && pre2->left == NULL) { // Here, we are threading the Node pre1->right = curr1; pre2->left = curr2; curr1 = curr1->left; curr2 = curr2->right; } else if (pre1->right == curr1 && pre2->left == curr2) { // Unthreading the nodes pre1->right = NULL; pre2->left = NULL; if (curr1->data != curr2->data) return false; curr1 = curr1->right; curr2 = curr2->left; } else return false; } else return false; } if (curr1 != curr2) return false; return true;} // Driver Codeint main(){ /* 5 / \\ 3 3 / \\ / \\ 8 9 9 8 */ // Creation of Binary tree Node* root = new Node(5); root->left = new Node(3); root->right = new Node(3); root->left->left = new Node(8); root->left->right = new Node(9); root->right->left = new Node(9); root->right->right = new Node(8); if (isSymmetric(root)) cout << \"Symmetric\"; else cout << \"Not Symmetric\"; return 0;}",
"e": 3146,
"s": 691,
"text": null
},
{
"code": "// Java implementation to check// if Tree is symmetric or notclass GFG{ // A Binary Tree Nodestatic class Node{ int data; Node left; Node right; Node(int val) { data = val; left = right = null; }}; // Function to check if the given// binary tree is Symmetric or notstatic boolean isSymmetric(Node root){ Node curr1 = root, curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != null && curr2 != null) { if (curr1.left == null && curr2.right == null) { if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else if (curr1.left != null && curr2.right != null) { Node pre1 = curr1.left; Node pre2 = curr2.right; while (pre1.right != null && pre1.right != curr1 && pre2.left != null && pre2.left != curr2) { pre1 = pre1.right; pre2 = pre2.left; } if (pre1.right == null && pre2.left == null) { // Here, we are threading the Node pre1.right = curr1; pre2.left = curr2; curr1 = curr1.left; curr2 = curr2.right; } else if (pre1.right == curr1 && pre2.left == curr2) { // Unthreading the nodes pre1.right = null; pre2.left = null; if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else return false; } else return false; } if (curr1 != curr2) return false; return true;} // Driver Codepublic static void main(String[] args){ /* 5 / \\ 3 3 / \\ / \\ 8 9 9 8 */ // Creation of Binary tree Node root = new Node(5); root.left = new Node(3); root.right = new Node(3); root.left.left = new Node(8); root.left.right = new Node(9); root.right.left = new Node(9); root.right.right = new Node(8); if (isSymmetric(root)) System.out.print(\"Symmetric\"); else System.out.print(\"Not Symmetric\");}} // This code is contributed by Rajput-Ji",
"e": 5653,
"s": 3146,
"text": null
},
{
"code": "# Python3 implementation to check# if Tree is symmetric or not # A Binary Tree Nodeclass Node: def __init__(self, val): self.data = val self.left = self.right = None # Function to check if the given# binary tree is Symmetric or notdef isSymmetric(root): curr1 = root curr2 = root # Loop to traverse the tree in # Morris Traversal and # Reverse Morris Traversal while curr1 != None and curr2 != None: if (curr1.left == None and curr2.right == None): if curr1.data != curr2.data: return False curr1 = curr1.right curr2 = curr2.left elif curr1 != None and curr2 != None: pre1 = curr1.left pre2 = curr2.right while (pre1.right != None and pre1.right != curr1 and pre2.left != None and pre2.left != curr2): pre1 = pre1.right pre2 = pre2.left if pre1.right == None and pre2.left == None: # Here, we are threading the Node pre1.right = curr1 pre2.left = curr2 curr1 = curr1.left curr2 = curr2.right elif (pre1.right == curr1 and pre2.left == curr2): # Unthreading the nodes pre1.right = None pre2.left = None if curr1.data != curr2.data: return False curr1 = curr1.right curr2 = curr2.left else: return False else: return False if curr1 != curr2: return False return True # Driver codedef main(): # # 5 # / \\ # 3 3 # / \\ / \\ #8 9 9 8 # Creation of Binary tree root = Node(5) root.left = Node(3) root.right = Node(3) root.left.left = Node(8) root.left.right = Node(9) root.right.left = Node(9) root.right.right = Node(8) if isSymmetric(root): print(\"Symmetric\") else: print(\"Not Symmetric\")main() # This code is contributed by Stuti Pathak",
"e": 7999,
"s": 5653,
"text": null
},
{
"code": "// C# implementation to check// if Tree is symmetric or notusing System; class GFG{ // A Binary Tree Nodeclass Node{ public int data; public Node left; public Node right; public Node(int val) { data = val; left = right = null; }}; // Function to check if the given// binary tree is Symmetric or notstatic bool isSymmetric(Node root){ Node curr1 = root, curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != null && curr2 != null) { if (curr1.left == null && curr2.right == null) { if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else if (curr1.left != null && curr2.right != null) { Node pre1 = curr1.left; Node pre2 = curr2.right; while (pre1.right != null && pre1.right != curr1 && pre2.left != null && pre2.left != curr2) { pre1 = pre1.right; pre2 = pre2.left; } if (pre1.right == null && pre2.left == null) { // Here, we are threading the Node pre1.right = curr1; pre2.left = curr2; curr1 = curr1.left; curr2 = curr2.right; } else if (pre1.right == curr1 && pre2.left == curr2) { // Unthreading the nodes pre1.right = null; pre2.left = null; if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else return false; } else return false; } if (curr1 != curr2) return false; return true;} // Driver Codepublic static void Main(String[] args){ /* 5 / \\ 3 3 / \\ / \\ 8 9 9 8 */ // Creation of Binary tree Node root = new Node(5); root.left = new Node(3); root.right = new Node(3); root.left.left = new Node(8); root.left.right = new Node(9); root.right.left = new Node(9); root.right.right = new Node(8); if (isSymmetric(root)) Console.Write(\"Symmetric\"); else Console.Write(\"Not Symmetric\");}} // This code is contributed by Rajput-Ji",
"e": 10567,
"s": 7999,
"text": null
},
{
"code": "<script> // JavaScript implementation to check // if Tree is symmetric or not // A Binary Tree Node class Node { constructor(val) { this.left = null; this.right = null; this.data = val; } } // Function to check if the given // binary tree is Symmetric or not function isSymmetric(root) { let curr1 = root, curr2 = root; // Loop to traverse the tree in // Morris Traversal and // Reverse Morris Traversal while (curr1 != null && curr2 != null) { if (curr1.left == null && curr2.right == null) { if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else if (curr1.left != null && curr2.right != null) { let pre1 = curr1.left; let pre2 = curr2.right; while (pre1.right != null && pre1.right != curr1 && pre2.left != null && pre2.left != curr2) { pre1 = pre1.right; pre2 = pre2.left; } if (pre1.right == null && pre2.left == null) { // Here, we are threading the Node pre1.right = curr1; pre2.left = curr2; curr1 = curr1.left; curr2 = curr2.right; } else if (pre1.right == curr1 && pre2.left == curr2) { // Unthreading the nodes pre1.right = null; pre2.left = null; if (curr1.data != curr2.data) return false; curr1 = curr1.right; curr2 = curr2.left; } else return false; } else return false; } if (curr1 != curr2) return false; return true; } /* 5 / \\ 3 3 / \\ / \\ 8 9 9 8 */ // Creation of Binary tree let root = new Node(5); root.left = new Node(3); root.right = new Node(3); root.left.left = new Node(8); root.left.right = new Node(9); root.right.left = new Node(9); root.right.right = new Node(8); if (isSymmetric(root)) document.write(\"Symmetric\"); else document.write(\"Not Symmetric\"); </script>",
"e": 13227,
"s": 10567,
"text": null
},
{
"code": null,
"e": 13236,
"s": 13227,
"text": "Output: "
},
{
"code": null,
"e": 13246,
"s": 13236,
"text": "Symmetric"
},
{
"code": null,
"e": 13518,
"s": 13246,
"text": "Time Complexity: Since every edge of the tree is traversed at most two times exactly as in the case of Morris traversal and in the worst case, the same number of extra edges (as input tree) are created and removed. Therefore, the time complexity of this approach is O(N)."
},
{
"code": null,
"e": 13540,
"s": 13518,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13557,
"s": 13540,
"text": "stutipathak31jan"
},
{
"code": null,
"e": 13567,
"s": 13557,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13582,
"s": 13567,
"text": "rameshtravel07"
},
{
"code": null,
"e": 13594,
"s": 13582,
"text": "Binary Tree"
},
{
"code": null,
"e": 13599,
"s": 13594,
"text": "Tree"
},
{
"code": null,
"e": 13604,
"s": 13599,
"text": "Tree"
},
{
"code": null,
"e": 13702,
"s": 13604,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13734,
"s": 13702,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 13770,
"s": 13734,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 13834,
"s": 13770,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 13868,
"s": 13834,
"text": "Diagonal Traversal of Binary Tree"
},
{
"code": null,
"e": 13911,
"s": 13868,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 13981,
"s": 13911,
"text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)"
},
{
"code": null,
"e": 14010,
"s": 13981,
"text": "Iterative Preorder Traversal"
},
{
"code": null,
"e": 14058,
"s": 14010,
"text": "Lowest Common Ancestor in a Binary Search Tree."
},
{
"code": null,
"e": 14109,
"s": 14058,
"text": "Write Code to Determine if Two Trees are Identical"
}
] |
Sum of maximum elements of all subsets
|
06 Jul, 2022
Given an array of integer numbers, we need to find sum of maximum number of all possible subsets.
Examples:
Input : arr = {3, 2, 5}
Output : 28
Explanation :
Subsets and their maximum are,
{} maximum = 0
{3} maximum = 3
{2} maximum = 2
{5} maximum = 5
{3, 2} maximum = 3
{3, 5} maximum = 5
{2, 5} maximum = 5
{3, 2, 5} maximum = 5
Sum of maximum will be, 0 + 3 + 2 + 5 + 3 + 5 + 5 + 5 = 28,
which will be our answer.
A simple solution is to iterate through all subsets of array and finding maximum of all of them and then adding them in our answer, but this approach will lead us to exponential time complexity.
An efficient solution is based on one thing, how many subsets of array have a particular element as their maximum. As in above example, four subsets have 5 as their maximum, two subsets have 3 as their maximum and one subset has 2 as its maximum. The idea is to compute these frequencies corresponding to each element of array. Once we have frequencies, we can just multiply them with array values and sum them all, which will lead to our final result.
To find frequencies, first we sort the array in non-increasing order and when we are standing at a[i] we know, all element from a[i + 1] to a[N-1] are smaller than a[i], so any subset made by these element will choose a[i] as its maximum so count of such subsets corresponding to a[i] will be, 2^(N β i β 1) (total subset made by array elements from a[i + 1] to a[N]).
If same procedure is applied for all elements of array, we will get our final answer as, res = a[0]*2^(N-1) + a[1]*2^(N-2) ..... + a[i]*2^(N-i-1) + ..... + a[N-1]*2^(0) Now if we solve above equation as it is, calculating powers of 2 will take time at each index, instead we can reform the equation similar to hornerβs rule for simplification, res = a[N] + 2*(a[N-1] + 2*(a[N-2] + 2*( ...... 2*(a[2] + 2*a[1]).....)))) Total complexity of above solution will be O(N*log(N))
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C/C++ code to find sum of maximum of all subsets of array#include <bits/stdc++.h>using namespace std; // Method returns sum of maximum of all subsetsint sumOfMaximumOfSubsets(int arr[], int N){ // sorting array in decreasing order sort(arr, arr + N, greater<int>()); // initializing sum with first element int sum = arr[0]; for (int i = 1; i < N; i++) { // calculating evaluation similar to horner's rule sum = 2 * sum + arr[i]; } return sum;} // Driver code to test above methodsint main(){ int arr[] = {3, 2, 5}; int N = sizeof(arr) / sizeof(arr[0]); cout << sumOfMaximumOfSubsets(arr, N) << endl; return 0;}
import java.util.Arrays;import java.util.Collections; // Java code to find sum of// maximum of all subsets of arrayclass GFG{ // Method returns sum of maximum of all subsets static int sumOfMaximumOfSubsets(Integer arr[], int N) { // sorting array in decreasing order Arrays.sort(arr, Collections.reverseOrder()); // initializing sum with first element int sum = arr[0]; for (int i = 1; i < N; i++) { // calculating evaluation similar to horner's rule sum = 2 * sum + arr[i]; } return sum; } // Driver code public static void main(String[] args) { Integer arr[] = {3, 2, 5}; int N = arr.length; System.out.println(sumOfMaximumOfSubsets(arr, N)); }} /* This code contributed by PrinciRaj1992 */
# Python 3 code to find sum# of maximum of all subsets# of array # Method returns sum of# maximum of all subsetsdef sumOfMaximumOfSubsets(arr, N): # sorting array in # decreasing order arr.sort(reverse = True) # initializing sum # with first element sum = arr[0] for i in range(1, N): # calculating evaluation # similar to horner's rule sum = 2 * sum + arr[i] return sum # Driver codearr = [3, 2, 5]N = len(arr)print(sumOfMaximumOfSubsets(arr, N)) # This code is contributed# by Smitha
// C# code to find sum of// maximum of all subsets of arrayusing System; class GFG{ // Method returns sum of maximum of all subsets static int sumOfMaximumOfSubsets(int []arr, int N) { // sorting array in decreasing order Array.Sort(arr); Array.Reverse(arr); // initializing sum with first element int sum = arr[0]; for (int i = 1; i < N; i++) { // calculating evaluation // similar to horner's rule sum = 2 * sum + arr[i]; } return sum; } // Driver code public static void Main(String[] args) { int []arr = {3, 2, 5}; int N = arr.Length; Console.WriteLine(sumOfMaximumOfSubsets(arr, N)); }} // This code has been contributed by 29AjayKumar
<?php// PHP code to find sum of maximum of// all subsets of array // Method returns sum of maximum of all subsetsfunction sumOfMaximumOfSubsets($arr, $N){ // sorting array in decreasing order rsort($arr); // initializing sum with first element $sum = $arr[0]; for ( $i = 1; $i < $N; $i++) { // calculating evaluation similar // to horner's rule $sum = 2 * $sum + $arr[$i]; } return $sum;} // Driver Code$arr = array(3, 2, 5);$N = count($arr);echo sumOfMaximumOfSubsets($arr, $N); // This code is contributed by Rajput-Ji?>
<script> // JavaScript code to find sum of// maximum of all subsets of array // Method returns sum of maximum of all subsetsfunction sumOfMaximumOfSubsets(arr,N){ // sorting array in decreasing order arr.sort((a,b)=>a-b); arr.reverse(); // initializing sum with first element let sum = arr[0]; for (let i = 1; i < N; i++) { // calculating evaluation similar to horner's rule sum = 2 * sum + arr[i]; } return sum;} let arr= [3, 2, 5]; let N = arr.length; document.write(sumOfMaximumOfSubsets(arr, N)); </script>
28
This article is contributed by Utkarsh Trivedi. 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.
Smitha Dinesh Semwal
Rajput-Ji
princiraj1992
29AjayKumar
vaibhavrabadiya117
hardikkoriintern
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Subset Sum Problem | DP-25
Introduction to Data Structures
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Jul, 2022"
},
{
"code": null,
"e": 152,
"s": 54,
"text": "Given an array of integer numbers, we need to find sum of maximum number of all possible subsets."
},
{
"code": null,
"e": 163,
"s": 152,
"text": "Examples: "
},
{
"code": null,
"e": 559,
"s": 163,
"text": "Input : arr = {3, 2, 5}\nOutput : 28\nExplanation : \nSubsets and their maximum are,\n{} maximum = 0\n{3} maximum = 3\n{2} maximum = 2\n{5} maximum = 5\n{3, 2} maximum = 3\n{3, 5} maximum = 5\n{2, 5} maximum = 5\n{3, 2, 5} maximum = 5\nSum of maximum will be, 0 + 3 + 2 + 5 + 3 + 5 + 5 + 5 = 28,\nwhich will be our answer."
},
{
"code": null,
"e": 754,
"s": 559,
"text": "A simple solution is to iterate through all subsets of array and finding maximum of all of them and then adding them in our answer, but this approach will lead us to exponential time complexity."
},
{
"code": null,
"e": 1208,
"s": 754,
"text": "An efficient solution is based on one thing, how many subsets of array have a particular element as their maximum. As in above example, four subsets have 5 as their maximum, two subsets have 3 as their maximum and one subset has 2 as its maximum. The idea is to compute these frequencies corresponding to each element of array. Once we have frequencies, we can just multiply them with array values and sum them all, which will lead to our final result. "
},
{
"code": null,
"e": 1578,
"s": 1208,
"text": "To find frequencies, first we sort the array in non-increasing order and when we are standing at a[i] we know, all element from a[i + 1] to a[N-1] are smaller than a[i], so any subset made by these element will choose a[i] as its maximum so count of such subsets corresponding to a[i] will be, 2^(N β i β 1) (total subset made by array elements from a[i + 1] to a[N]). "
},
{
"code": null,
"e": 2053,
"s": 1578,
"text": "If same procedure is applied for all elements of array, we will get our final answer as, res = a[0]*2^(N-1) + a[1]*2^(N-2) ..... + a[i]*2^(N-i-1) + ..... + a[N-1]*2^(0) Now if we solve above equation as it is, calculating powers of 2 will take time at each index, instead we can reform the equation similar to hornerβs rule for simplification, res = a[N] + 2*(a[N-1] + 2*(a[N-2] + 2*( ...... 2*(a[2] + 2*a[1]).....)))) Total complexity of above solution will be O(N*log(N)) "
},
{
"code": null,
"e": 2069,
"s": 2053,
"text": "Implementation:"
},
{
"code": null,
"e": 2073,
"s": 2069,
"text": "C++"
},
{
"code": null,
"e": 2078,
"s": 2073,
"text": "Java"
},
{
"code": null,
"e": 2086,
"s": 2078,
"text": "Python3"
},
{
"code": null,
"e": 2089,
"s": 2086,
"text": "C#"
},
{
"code": null,
"e": 2093,
"s": 2089,
"text": "PHP"
},
{
"code": null,
"e": 2104,
"s": 2093,
"text": "Javascript"
},
{
"code": "// C/C++ code to find sum of maximum of all subsets of array#include <bits/stdc++.h>using namespace std; // Method returns sum of maximum of all subsetsint sumOfMaximumOfSubsets(int arr[], int N){ // sorting array in decreasing order sort(arr, arr + N, greater<int>()); // initializing sum with first element int sum = arr[0]; for (int i = 1; i < N; i++) { // calculating evaluation similar to horner's rule sum = 2 * sum + arr[i]; } return sum;} // Driver code to test above methodsint main(){ int arr[] = {3, 2, 5}; int N = sizeof(arr) / sizeof(arr[0]); cout << sumOfMaximumOfSubsets(arr, N) << endl; return 0;}",
"e": 2776,
"s": 2104,
"text": null
},
{
"code": "import java.util.Arrays;import java.util.Collections; // Java code to find sum of// maximum of all subsets of arrayclass GFG{ // Method returns sum of maximum of all subsets static int sumOfMaximumOfSubsets(Integer arr[], int N) { // sorting array in decreasing order Arrays.sort(arr, Collections.reverseOrder()); // initializing sum with first element int sum = arr[0]; for (int i = 1; i < N; i++) { // calculating evaluation similar to horner's rule sum = 2 * sum + arr[i]; } return sum; } // Driver code public static void main(String[] args) { Integer arr[] = {3, 2, 5}; int N = arr.length; System.out.println(sumOfMaximumOfSubsets(arr, N)); }} /* This code contributed by PrinciRaj1992 */",
"e": 3597,
"s": 2776,
"text": null
},
{
"code": "# Python 3 code to find sum# of maximum of all subsets# of array # Method returns sum of# maximum of all subsetsdef sumOfMaximumOfSubsets(arr, N): # sorting array in # decreasing order arr.sort(reverse = True) # initializing sum # with first element sum = arr[0] for i in range(1, N): # calculating evaluation # similar to horner's rule sum = 2 * sum + arr[i] return sum # Driver codearr = [3, 2, 5]N = len(arr)print(sumOfMaximumOfSubsets(arr, N)) # This code is contributed# by Smitha",
"e": 4136,
"s": 3597,
"text": null
},
{
"code": "// C# code to find sum of// maximum of all subsets of arrayusing System; class GFG{ // Method returns sum of maximum of all subsets static int sumOfMaximumOfSubsets(int []arr, int N) { // sorting array in decreasing order Array.Sort(arr); Array.Reverse(arr); // initializing sum with first element int sum = arr[0]; for (int i = 1; i < N; i++) { // calculating evaluation // similar to horner's rule sum = 2 * sum + arr[i]; } return sum; } // Driver code public static void Main(String[] args) { int []arr = {3, 2, 5}; int N = arr.Length; Console.WriteLine(sumOfMaximumOfSubsets(arr, N)); }} // This code has been contributed by 29AjayKumar",
"e": 4922,
"s": 4136,
"text": null
},
{
"code": "<?php// PHP code to find sum of maximum of// all subsets of array // Method returns sum of maximum of all subsetsfunction sumOfMaximumOfSubsets($arr, $N){ // sorting array in decreasing order rsort($arr); // initializing sum with first element $sum = $arr[0]; for ( $i = 1; $i < $N; $i++) { // calculating evaluation similar // to horner's rule $sum = 2 * $sum + $arr[$i]; } return $sum;} // Driver Code$arr = array(3, 2, 5);$N = count($arr);echo sumOfMaximumOfSubsets($arr, $N); // This code is contributed by Rajput-Ji?>",
"e": 5492,
"s": 4922,
"text": null
},
{
"code": "<script> // JavaScript code to find sum of// maximum of all subsets of array // Method returns sum of maximum of all subsetsfunction sumOfMaximumOfSubsets(arr,N){ // sorting array in decreasing order arr.sort((a,b)=>a-b); arr.reverse(); // initializing sum with first element let sum = arr[0]; for (let i = 1; i < N; i++) { // calculating evaluation similar to horner's rule sum = 2 * sum + arr[i]; } return sum;} let arr= [3, 2, 5]; let N = arr.length; document.write(sumOfMaximumOfSubsets(arr, N)); </script>",
"e": 6065,
"s": 5492,
"text": null
},
{
"code": null,
"e": 6068,
"s": 6065,
"text": "28"
},
{
"code": null,
"e": 6368,
"s": 6068,
"text": "This article is contributed by Utkarsh Trivedi. 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": 6389,
"s": 6368,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 6399,
"s": 6389,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6413,
"s": 6399,
"text": "princiraj1992"
},
{
"code": null,
"e": 6425,
"s": 6413,
"text": "29AjayKumar"
},
{
"code": null,
"e": 6444,
"s": 6425,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 6461,
"s": 6444,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 6468,
"s": 6461,
"text": "Arrays"
},
{
"code": null,
"e": 6475,
"s": 6468,
"text": "Arrays"
},
{
"code": null,
"e": 6573,
"s": 6475,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6641,
"s": 6573,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 6685,
"s": 6641,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 6717,
"s": 6685,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6765,
"s": 6717,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 6779,
"s": 6765,
"text": "Linear Search"
},
{
"code": null,
"e": 6864,
"s": 6779,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 6887,
"s": 6864,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 6943,
"s": 6887,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 6970,
"s": 6943,
"text": "Subset Sum Problem | DP-25"
}
] |
How to check whether a Button is clicked with JavaScript?
|
Following is the code for checking whether a button is clicked using JavaScript β
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;
}
.result {
font-size: 18px;
font-weight: 500;
color: blueviolet;
}
</style>
</head>
<body onbeforeunload="return pageUnload()">
<h1>Checking whether a Button is clicked using JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to check if the button is clicked</h3>
<script>
let BtnEle = document.querySelector(".Btn");
let resEle = document.querySelector(".result");
let clickCount = 0;
BtnEle.addEventListener("click", () => {
clickCount++;
resEle.innerHTML =
"The button has been clicked " + clickCount + " times ";
});
</script>
</body>
</html>
On clicking the button 5 times β
|
[
{
"code": null,
"e": 1269,
"s": 1187,
"text": "Following is the code for checking whether a button is clicked using JavaScript β"
},
{
"code": null,
"e": 1280,
"s": 1269,
"text": " Live Demo"
},
{
"code": null,
"e": 2206,
"s": 1280,
"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 .result {\n font-size: 18px;\n font-weight: 500;\n color: blueviolet;\n }\n</style>\n</head>\n<body onbeforeunload=\"return pageUnload()\">\n<h1>Checking whether a Button is clicked using JavaScript</h1>\n<div class=\"result\"></div>\n<br />\n<button class=\"Btn\">CLICK HERE</button>\n<h3>Click on the above button to check if the button is clicked</h3>\n<script>\n let BtnEle = document.querySelector(\".Btn\");\n let resEle = document.querySelector(\".result\");\n let clickCount = 0;\n BtnEle.addEventListener(\"click\", () => {\n clickCount++;\n resEle.innerHTML =\n \"The button has been clicked \" + clickCount + \" times \";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2239,
"s": 2206,
"text": "On clicking the button 5 times β"
}
] |
Program to print Arithmetic Progression series
|
11 Jul, 2022
Given first term (a), common difference (d) and a integer n of the Arithmetic Progression series, the task is to print the series. Examples :
Input : a = 5, d = 2, n = 10
Output : 5 7 9 11 13 15 17 19 21 23
Approach :
We know the Arithmetic Progression series is like = 2, 5, 8, 11, 14 .... ... In this series 2 is the stating term of the series . Common difference = 5 β 2 = 3 (Difference common in the series). so we can write the series as : t1 = a1 t2 = a1 + (2-1) * d t3 = a1 + (3-1) * d . . . tn = a1 + (n-1) * d
CPP
Java
Python3
C#
PHP
Javascript
// CPP Program to print an arithmetic// progression series#include <bits/stdc++.h>using namespace std; void printAP(int a, int d, int n){ // Printing AP by simply adding d// to previous term.int curr_term;curr_term=a;for (int i = 1; i <= n; i++){ cout << curr_term << " "; curr_term =curr_term + d; }} // Driver codeint main(){ // starting number int a = 2; // Common difference int d = 1; // N th term to be find int n = 5; printAP(a, d, n); return 0;}
// Java Program to print an arithmetic// progression seriesclass GFG{static void printAP(int a, int d, int n){ // Printing AP by simply adding d // to previous term. int curr_term;curr_term=a; for (int i = 1; i <= n; i++) { System.out.print(curr_term + " "); curr_term =curr_term + d; }} // Driver codepublic static void main(String[] args){// starting numberint a = 2; // Common differenceint d = 1; // N th term to be findint n = 5; printAP(a, d, n);}}// This code is contributed by Anant Agarwal.
# Python 3 Program to# print an arithmetic# progression seriesdef printAP(a,d,n): # Printing AP by simply adding d # to previous term. curr_termcurr_term=a for i in range(1,n+1):print(curr_term, end=' ') curr_term =curr_term + d # Driver codea = 2 # starting numberd = 1 # Common differencen = 5 # N th term to be find printAP(a, d, n) # This code is contributed# by Azkia Anam.
// C# Program to print an arithmetic// progression seriesusing System; class GFG{ static void printAP(int a, int d, int n) { // Printing AP by simply adding // d to previous term. int curr_term;curr_term=a; for (int i = 1; i <= n; i++) {Console.Write(curr_term + " "); curr_term += d; } } // Driver code public static void Main() { // starting number int a = 2; // Common difference int d = 1; // N th term to be find int n = 5; printAP(a, d, n); }}// This code is contributed by vgt_m.
<?php// PHP Program to print an arithmetic// progression series function printAP($a, $d, $n){ // Printing AP by simply adding d // to previous term. $curr_term;$curr_term=a; for ($i = 1; $i <= $n; $i++) { echo($curr_term . " "); $curr_term += $d; }} // Driver code // starting number$a = 2; // Common difference$d = 1; // N th term to be find$n = 5; printAP($a, $d, $n); // This code is contributed by Ajit.?>
<script> // JavaScript Program to print an arithmetic // progression series function printAP(a, d, n) { // Printing AP by simply adding d // to previous term. let curr_term; curr_term=a; for (let i = 1; i <= n; i++) { document.write(curr_term + " "); curr_term =curr_term + d; } } // Driver code // starting number let a = 2; // Common difference let d = 1; // N th term to be find let n = 5; printAP(a, d, n); // This code is contributed by Surbhi Tyagi </script>
2 3 4 5 6
Time compexity: O(n) where n is the total number of terms of a given A.P
Auxiliary Space: O(1)
jit_t
dey958042
Code_r
surbhityagi15
polymatir3j
arithmetic progression
series
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jul, 2022"
},
{
"code": null,
"e": 196,
"s": 52,
"text": "Given first term (a), common difference (d) and a integer n of the Arithmetic Progression series, the task is to print the series. Examples : "
},
{
"code": null,
"e": 261,
"s": 196,
"text": "Input : a = 5, d = 2, n = 10\nOutput : 5 7 9 11 13 15 17 19 21 23"
},
{
"code": null,
"e": 276,
"s": 263,
"text": "Approach : "
},
{
"code": null,
"e": 579,
"s": 276,
"text": "We know the Arithmetic Progression series is like = 2, 5, 8, 11, 14 .... ... In this series 2 is the stating term of the series . Common difference = 5 β 2 = 3 (Difference common in the series). so we can write the series as : t1 = a1 t2 = a1 + (2-1) * d t3 = a1 + (3-1) * d . . . tn = a1 + (n-1) * d "
},
{
"code": null,
"e": 585,
"s": 581,
"text": "CPP"
},
{
"code": null,
"e": 590,
"s": 585,
"text": "Java"
},
{
"code": null,
"e": 598,
"s": 590,
"text": "Python3"
},
{
"code": null,
"e": 601,
"s": 598,
"text": "C#"
},
{
"code": null,
"e": 605,
"s": 601,
"text": "PHP"
},
{
"code": null,
"e": 616,
"s": 605,
"text": "Javascript"
},
{
"code": "// CPP Program to print an arithmetic// progression series#include <bits/stdc++.h>using namespace std; void printAP(int a, int d, int n){ // Printing AP by simply adding d// to previous term.int curr_term;curr_term=a;for (int i = 1; i <= n; i++){ cout << curr_term << \" \"; curr_term =curr_term + d; }} // Driver codeint main(){ // starting number int a = 2; // Common difference int d = 1; // N th term to be find int n = 5; printAP(a, d, n); return 0;}",
"e": 1118,
"s": 616,
"text": null
},
{
"code": "// Java Program to print an arithmetic// progression seriesclass GFG{static void printAP(int a, int d, int n){ // Printing AP by simply adding d // to previous term. int curr_term;curr_term=a; for (int i = 1; i <= n; i++) { System.out.print(curr_term + \" \"); curr_term =curr_term + d; }} // Driver codepublic static void main(String[] args){// starting numberint a = 2; // Common differenceint d = 1; // N th term to be findint n = 5; printAP(a, d, n);}}// This code is contributed by Anant Agarwal.",
"e": 1644,
"s": 1118,
"text": null
},
{
"code": "# Python 3 Program to# print an arithmetic# progression seriesdef printAP(a,d,n): # Printing AP by simply adding d # to previous term. curr_termcurr_term=a for i in range(1,n+1):print(curr_term, end=' ') curr_term =curr_term + d # Driver codea = 2 # starting numberd = 1 # Common differencen = 5 # N th term to be find printAP(a, d, n) # This code is contributed# by Azkia Anam.",
"e": 2072,
"s": 1644,
"text": null
},
{
"code": "// C# Program to print an arithmetic// progression seriesusing System; class GFG{ static void printAP(int a, int d, int n) { // Printing AP by simply adding // d to previous term. int curr_term;curr_term=a; for (int i = 1; i <= n; i++) {Console.Write(curr_term + \" \"); curr_term += d; } } // Driver code public static void Main() { // starting number int a = 2; // Common difference int d = 1; // N th term to be find int n = 5; printAP(a, d, n); }}// This code is contributed by vgt_m.",
"e": 2725,
"s": 2072,
"text": null
},
{
"code": "<?php// PHP Program to print an arithmetic// progression series function printAP($a, $d, $n){ // Printing AP by simply adding d // to previous term. $curr_term;$curr_term=a; for ($i = 1; $i <= $n; $i++) { echo($curr_term . \" \"); $curr_term += $d; }} // Driver code // starting number$a = 2; // Common difference$d = 1; // N th term to be find$n = 5; printAP($a, $d, $n); // This code is contributed by Ajit.?>",
"e": 3169,
"s": 2725,
"text": null
},
{
"code": "<script> // JavaScript Program to print an arithmetic // progression series function printAP(a, d, n) { // Printing AP by simply adding d // to previous term. let curr_term; curr_term=a; for (let i = 1; i <= n; i++) { document.write(curr_term + \" \"); curr_term =curr_term + d; } } // Driver code // starting number let a = 2; // Common difference let d = 1; // N th term to be find let n = 5; printAP(a, d, n); // This code is contributed by Surbhi Tyagi </script>",
"e": 3772,
"s": 3169,
"text": null
},
{
"code": null,
"e": 3782,
"s": 3772,
"text": "2 3 4 5 6"
},
{
"code": null,
"e": 3857,
"s": 3784,
"text": "Time compexity: O(n) where n is the total number of terms of a given A.P"
},
{
"code": null,
"e": 3879,
"s": 3857,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3885,
"s": 3879,
"text": "jit_t"
},
{
"code": null,
"e": 3895,
"s": 3885,
"text": "dey958042"
},
{
"code": null,
"e": 3902,
"s": 3895,
"text": "Code_r"
},
{
"code": null,
"e": 3916,
"s": 3902,
"text": "surbhityagi15"
},
{
"code": null,
"e": 3928,
"s": 3916,
"text": "polymatir3j"
},
{
"code": null,
"e": 3951,
"s": 3928,
"text": "arithmetic progression"
},
{
"code": null,
"e": 3958,
"s": 3951,
"text": "series"
},
{
"code": null,
"e": 3971,
"s": 3958,
"text": "Mathematical"
},
{
"code": null,
"e": 3990,
"s": 3971,
"text": "School Programming"
},
{
"code": null,
"e": 4003,
"s": 3990,
"text": "Mathematical"
},
{
"code": null,
"e": 4010,
"s": 4003,
"text": "series"
}
] |
Perl push Function
|
This function pushes the values in LIST onto the end of the list ARRAY. Used with pop to implement stacks.
Following is the simple syntax for this function β
push ARRAY, LIST
This function returns number of elements in new array.
Following is the example code showing its basic usage β
#!/usr/bin/perl -w
$, = ",";
@array = ( 1, 2 );
print "Before pushing elements @array \n";
push(@array, (3, 4, 5));
print "After pushing elements @array \n";
When above code is executed, it produces the following result β
Before pushing elements 1 2
After pushing elements 1 2 3 4 5
|
[
{
"code": null,
"e": 2461,
"s": 2354,
"text": "This function pushes the values in LIST onto the end of the list ARRAY. Used with pop to implement stacks."
},
{
"code": null,
"e": 2512,
"s": 2461,
"text": "Following is the simple syntax for this function β"
},
{
"code": null,
"e": 2530,
"s": 2512,
"text": "push ARRAY, LIST\n"
},
{
"code": null,
"e": 2585,
"s": 2530,
"text": "This function returns number of elements in new array."
},
{
"code": null,
"e": 2641,
"s": 2585,
"text": "Following is the example code showing its basic usage β"
},
{
"code": null,
"e": 2802,
"s": 2641,
"text": "#!/usr/bin/perl -w\n\n$, = \",\";\n@array = ( 1, 2 );\nprint \"Before pushing elements @array \\n\";\npush(@array, (3, 4, 5));\nprint \"After pushing elements @array \\n\";"
},
{
"code": null,
"e": 2866,
"s": 2802,
"text": "When above code is executed, it produces the following result β"
}
] |
Java Program that Shows Use of Collection Interface
|
14 Sep, 2021
The Collection framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details.
Uses and advantages of Collection Framework:
This reduces the efforts of programmers by providing data structures and algorithms, so we do not have to write them.
This increases performance by providing a high-performance implementation of data structures and algorithms.
This provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth.
Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc collection APIs.
This provides static methods that perform useful functions on collections, such as sorting a list.
This provides Wrapper implementation which adds functionality, such as synchronization, to other implementations.
And many more advantages it provides for us to use and tackle the problems of development.
Usages: Examples of different types of Interfaces are given below:
List InterfaceLiked ListMap Interface Stacks
List Interface
Liked List
Map Interface
Stacks
Use Case 1: List Interface
Java
// Java Program that Shows Use of Collection Interface// ArrayList import java.util.*; class GFG { public static void main(String args[]) { ArrayList<String> list = new ArrayList<String>(); list.add("Geeks"); list.add("areyou"); list.add("working"); list.add("hard?"); Iterator itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}
Geeks
areyou
working
hard?
Use Case 2: Linked List
Java
// Java Program that Shows Use of Collection Interface// LinkedList import java.util.*; // Class testing java Collectionpublic class GFG { // Main driver method public static void main(String args[]) { // Creating a LinkedList LinkedList<String> al = new LinkedList<String>(); // Adding elements to above linked list al.add("Geeks"); al.add("areyou"); al.add("working"); al.add("hard?"); // Iterator Iterator<String> itr = al.iterator(); // Condition check over elements inside using // hasNext() method which holds true till there is // element inside list while (itr.hasNext()) { // Printing elements of LinkedList System.out.println(itr.next()); } }}
Geeks
areyou
working
hard?
Use Case 3: Map Interface
Java
// Java Program that Shows Use of Collection Interface// Hash-Map import java.util.*;public class GFG { // Main driver method public static void main(String[] args) { // Creating a Map Map<Integer, String> map = new HashMap<>(); // Adding elements to map map.put(1, "Geeks"); map.put(2, "are"); map.put(3, "you"); map.put(4, "working"); // Traversing Map // Converting to Set so that traversal is accessed Set set = map.entrySet(); // Iterator Iterator itr = set.iterator(); // Condition check over elements inside using // hasNext() method which holds true till there is // element inside list while (itr.hasNext()) { // Converting to Map.Entry so that we can get // key and value separately Map.Entry entry = (Map.Entry)itr.next(); // Printing elements inside HashMap System.out.println(entry.getKey() + " " + entry.getValue()); } }}
1 Geeks
2 are
3 you
4 working
Use Case 4: Stacks
Java
// Java Program that Shows Use of Collection Interface// Stack import java.util.*;public class GFG { // Main driver method public static void main(String args[]) { // Creating a stack in memory Stack<String> stack = new Stack<String>(); // Adding elements to stack stack.push("Geeks"); stack.push("are"); stack.push("you"); stack.push("working"); stack.push("hard?"); // pop() returns all elements of stack stack.pop(); //. iterator Iterator<String> itr = stack.iterator(); // Condition check over elements inside using // hasNext() method which holds true till there is // element inside list while (itr.hasNext()) { // Print all popped elements System.out.println(itr.next()); } }}
Geeks
are
you
working
surinderdawra388
sagartomar9927
simmytarika5
Java-Collections
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "The Collection framework is a unified architecture for representing and manipulating collections, enabling collections to be manipulated independently of implementation details."
},
{
"code": null,
"e": 251,
"s": 206,
"text": "Uses and advantages of Collection Framework:"
},
{
"code": null,
"e": 369,
"s": 251,
"text": "This reduces the efforts of programmers by providing data structures and algorithms, so we do not have to write them."
},
{
"code": null,
"e": 478,
"s": 369,
"text": "This increases performance by providing a high-performance implementation of data structures and algorithms."
},
{
"code": null,
"e": 602,
"s": 478,
"text": "This provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth."
},
{
"code": null,
"e": 703,
"s": 602,
"text": "Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc collection APIs."
},
{
"code": null,
"e": 802,
"s": 703,
"text": "This provides static methods that perform useful functions on collections, such as sorting a list."
},
{
"code": null,
"e": 916,
"s": 802,
"text": "This provides Wrapper implementation which adds functionality, such as synchronization, to other implementations."
},
{
"code": null,
"e": 1007,
"s": 916,
"text": "And many more advantages it provides for us to use and tackle the problems of development."
},
{
"code": null,
"e": 1074,
"s": 1007,
"text": "Usages: Examples of different types of Interfaces are given below:"
},
{
"code": null,
"e": 1119,
"s": 1074,
"text": "List InterfaceLiked ListMap Interface Stacks"
},
{
"code": null,
"e": 1134,
"s": 1119,
"text": "List Interface"
},
{
"code": null,
"e": 1145,
"s": 1134,
"text": "Liked List"
},
{
"code": null,
"e": 1160,
"s": 1145,
"text": "Map Interface "
},
{
"code": null,
"e": 1167,
"s": 1160,
"text": "Stacks"
},
{
"code": null,
"e": 1194,
"s": 1167,
"text": "Use Case 1: List Interface"
},
{
"code": null,
"e": 1199,
"s": 1194,
"text": "Java"
},
{
"code": "// Java Program that Shows Use of Collection Interface// ArrayList import java.util.*; class GFG { public static void main(String args[]) { ArrayList<String> list = new ArrayList<String>(); list.add(\"Geeks\"); list.add(\"areyou\"); list.add(\"working\"); list.add(\"hard?\"); Iterator itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next()); } }}",
"e": 1638,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1665,
"s": 1638,
"text": "Geeks\nareyou\nworking\nhard?"
},
{
"code": null,
"e": 1689,
"s": 1665,
"text": "Use Case 2: Linked List"
},
{
"code": null,
"e": 1694,
"s": 1689,
"text": "Java"
},
{
"code": "// Java Program that Shows Use of Collection Interface// LinkedList import java.util.*; // Class testing java Collectionpublic class GFG { // Main driver method public static void main(String args[]) { // Creating a LinkedList LinkedList<String> al = new LinkedList<String>(); // Adding elements to above linked list al.add(\"Geeks\"); al.add(\"areyou\"); al.add(\"working\"); al.add(\"hard?\"); // Iterator Iterator<String> itr = al.iterator(); // Condition check over elements inside using // hasNext() method which holds true till there is // element inside list while (itr.hasNext()) { // Printing elements of LinkedList System.out.println(itr.next()); } }}",
"e": 2485,
"s": 1694,
"text": null
},
{
"code": null,
"e": 2512,
"s": 2485,
"text": "Geeks\nareyou\nworking\nhard?"
},
{
"code": null,
"e": 2539,
"s": 2512,
"text": "Use Case 3: Map Interface "
},
{
"code": null,
"e": 2544,
"s": 2539,
"text": "Java"
},
{
"code": "// Java Program that Shows Use of Collection Interface// Hash-Map import java.util.*;public class GFG { // Main driver method public static void main(String[] args) { // Creating a Map Map<Integer, String> map = new HashMap<>(); // Adding elements to map map.put(1, \"Geeks\"); map.put(2, \"are\"); map.put(3, \"you\"); map.put(4, \"working\"); // Traversing Map // Converting to Set so that traversal is accessed Set set = map.entrySet(); // Iterator Iterator itr = set.iterator(); // Condition check over elements inside using // hasNext() method which holds true till there is // element inside list while (itr.hasNext()) { // Converting to Map.Entry so that we can get // key and value separately Map.Entry entry = (Map.Entry)itr.next(); // Printing elements inside HashMap System.out.println(entry.getKey() + \" \" + entry.getValue()); } }}",
"e": 3604,
"s": 2544,
"text": null
},
{
"code": null,
"e": 3634,
"s": 3604,
"text": "1 Geeks\n2 are\n3 you\n4 working"
},
{
"code": null,
"e": 3654,
"s": 3634,
"text": "Use Case 4: Stacks "
},
{
"code": null,
"e": 3659,
"s": 3654,
"text": "Java"
},
{
"code": "// Java Program that Shows Use of Collection Interface// Stack import java.util.*;public class GFG { // Main driver method public static void main(String args[]) { // Creating a stack in memory Stack<String> stack = new Stack<String>(); // Adding elements to stack stack.push(\"Geeks\"); stack.push(\"are\"); stack.push(\"you\"); stack.push(\"working\"); stack.push(\"hard?\"); // pop() returns all elements of stack stack.pop(); //. iterator Iterator<String> itr = stack.iterator(); // Condition check over elements inside using // hasNext() method which holds true till there is // element inside list while (itr.hasNext()) { // Print all popped elements System.out.println(itr.next()); } }}",
"e": 4502,
"s": 3659,
"text": null
},
{
"code": null,
"e": 4524,
"s": 4502,
"text": "Geeks\nare\nyou\nworking"
},
{
"code": null,
"e": 4541,
"s": 4524,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4556,
"s": 4541,
"text": "sagartomar9927"
},
{
"code": null,
"e": 4569,
"s": 4556,
"text": "simmytarika5"
},
{
"code": null,
"e": 4586,
"s": 4569,
"text": "Java-Collections"
},
{
"code": null,
"e": 4593,
"s": 4586,
"text": "Picked"
},
{
"code": null,
"e": 4598,
"s": 4593,
"text": "Java"
},
{
"code": null,
"e": 4612,
"s": 4598,
"text": "Java Programs"
},
{
"code": null,
"e": 4617,
"s": 4612,
"text": "Java"
},
{
"code": null,
"e": 4634,
"s": 4617,
"text": "Java-Collections"
}
] |
SimpleDateFormat toPattern() Method in Java with Examples
|
05 Feb, 2021
The toPattern() Method of SimpleDateFormat class is used to return the pattern of the date format.
Syntax:
public String toPattern()
Parameters: The method does not take any parameters.
Return Value: The method returns the pattern string describing this Date format.
Below programs illustrate the working of toPattern() Method of SimpleDateFormat:
Example 1:
Java
// Java code to illustrate toPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo { public static void main(String[] args) throws InterruptedException { SimpleDateFormat SDformat = new SimpleDateFormat(); // Initializing Calendar object Calendar cal = Calendar.getInstance(); // Getting the Current Date String Todaysdate = SDformat.format(cal.getTime()); // Displaying the date System.out.println("Current Date: " + Todaysdate); // Using toPattern() method // to Print the Date Pattern System.out.println("The Date Pattern- " + SDformat.toPattern()); }}
Current Date: 1/29/19 6:05 AM
The Date Pattern- M/d/yy h:mm a
arorakashish0911
Java-Functions
Java-SimpleDateFormat
Java-text package
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": "\n05 Feb, 2021"
},
{
"code": null,
"e": 127,
"s": 28,
"text": "The toPattern() Method of SimpleDateFormat class is used to return the pattern of the date format."
},
{
"code": null,
"e": 137,
"s": 127,
"text": "Syntax: "
},
{
"code": null,
"e": 163,
"s": 137,
"text": "public String toPattern()"
},
{
"code": null,
"e": 216,
"s": 163,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 297,
"s": 216,
"text": "Return Value: The method returns the pattern string describing this Date format."
},
{
"code": null,
"e": 378,
"s": 297,
"text": "Below programs illustrate the working of toPattern() Method of SimpleDateFormat:"
},
{
"code": null,
"e": 391,
"s": 378,
"text": "Example 1: "
},
{
"code": null,
"e": 396,
"s": 391,
"text": "Java"
},
{
"code": "// Java code to illustrate toPattern() method import java.text.*;import java.util.Calendar; public class SimpleDateFormat_Demo { public static void main(String[] args) throws InterruptedException { SimpleDateFormat SDformat = new SimpleDateFormat(); // Initializing Calendar object Calendar cal = Calendar.getInstance(); // Getting the Current Date String Todaysdate = SDformat.format(cal.getTime()); // Displaying the date System.out.println(\"Current Date: \" + Todaysdate); // Using toPattern() method // to Print the Date Pattern System.out.println(\"The Date Pattern- \" + SDformat.toPattern()); }}",
"e": 1160,
"s": 396,
"text": null
},
{
"code": null,
"e": 1222,
"s": 1160,
"text": "Current Date: 1/29/19 6:05 AM\nThe Date Pattern- M/d/yy h:mm a"
},
{
"code": null,
"e": 1241,
"s": 1224,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1256,
"s": 1241,
"text": "Java-Functions"
},
{
"code": null,
"e": 1278,
"s": 1256,
"text": "Java-SimpleDateFormat"
},
{
"code": null,
"e": 1296,
"s": 1278,
"text": "Java-text package"
},
{
"code": null,
"e": 1301,
"s": 1296,
"text": "Java"
},
{
"code": null,
"e": 1306,
"s": 1301,
"text": "Java"
},
{
"code": null,
"e": 1404,
"s": 1306,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1419,
"s": 1404,
"text": "Stream In Java"
},
{
"code": null,
"e": 1440,
"s": 1419,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1461,
"s": 1440,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1480,
"s": 1461,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1497,
"s": 1480,
"text": "Generics in Java"
},
{
"code": null,
"e": 1527,
"s": 1497,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 1553,
"s": 1527,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1569,
"s": 1553,
"text": "Strings in Java"
},
{
"code": null,
"e": 1606,
"s": 1569,
"text": "Differences between JDK, JRE and JVM"
}
] |
Find the missing number in Geometric Progression - GeeksforGeeks
|
19 Apr, 2021
Given an array that represents elements of geometric progression in order. One element is missing in the progression, find the missing number. It may be assumed that one term is always missing and the missing term is not first or last of series.Examples:
Input : arr[] = {1, 3 , 27, 81}
Output : 9
Input : arr[] = {4, 16, 64, 1024};
Output : 256
A Simple Solution is to linearly traverse the array and find the missing number. Time complexity of this solution is O(n).An efficient solution to solve this problem in O(Log n) time using Binary Search. The idea is to go to the middle element. Check if the ratio of middle and next to middle is equal to common ratio or not, if not then the missing element lies between mid and mid+1. If the middle element is equal to n/2th term in Geometric Series (Let n be the number of elements in input array), then missing element lies in right half. Else element lies in left half.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find missing number in// geometric progression#include <bits/stdc++.h>using namespace std; // It returns INT_MAX in case of errorint findMissingRec(int arr[], int low, int high, int ratio){ if (low >= high) return INT_MAX; int mid = low + (high - low)/2; // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio);} // Find ration and calls findMissingRecint findMissing(int arr[], int n){ // Finding ration assuming that the missing term is // not first or last term of series. int ratio = (float) pow(arr[n-1]/arr[0], 1.0/n); return findMissingRec(arr, 0, n-1, ratio);} // Driver codeint main(void){ int arr[] = {2, 4, 8, 32}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMissing(arr, n); return 0;}
// JAVA Code for Find the missing number// in Geometric Progressionclass GFG { // It returns INT_MAX in case of error public static int findMissingRec(int arr[], int low, int high, int ratio) { if (low >= high) return Integer.MAX_VALUE; int mid = low + (high - low)/2; // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (Math.pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio); } // Find ration and calls findMissingRec public static int findMissing(int arr[], int n) { // Finding ration assuming that the missing // term is not first or last term of series. int ratio =(int) Math.pow(arr[n-1]/arr[0], 1.0/n); return findMissingRec(arr, 0, n-1, ratio); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {2, 4, 8, 32}; int n = arr.length; System.out.print(findMissing(arr, n)); } }// This code is contributed by Arnav Kr. Mandal.
# Python3 program to find missing# number in geometric progression # It returns INT_MAX in case of errordef findMissingRec(arr, low, high, ratio): if (low >= high): return 2147483647 mid = low + (high - low) // 2 # If element next to mid is missing if (arr[mid + 1] // arr[mid] != ratio): return (arr[mid] * ratio) # If element previous to mid is missing if ((mid > 0) and (arr[mid] / arr[mid-1]) != ratio): return (arr[mid - 1] * ratio) # If missing element is in right half if (arr[mid] == arr[0] * (pow(ratio, mid)) ): return findMissingRec(arr, mid+1, high, ratio) return findMissingRec(arr, low, mid-1, ratio) # Find ration and calls findMissingRecdef findMissing(arr, n): # Finding ration assuming that # the missing term is not first # or last term of series. ratio = int(pow(arr[n-1] / arr[0], 1.0 / n)) return findMissingRec(arr, 0, n-1, ratio) # Driver codearr = [2, 4, 8, 32]n = len(arr)print(findMissing(arr, n)) # This code is contributed by Anant Agarwal.
// C# Code for Find the missing number// in Geometric Progressionusing System; class GFG { // It returns INT_MAX in case of error public static int findMissingRec(int []arr, int low, int high, int ratio) { if (low >= high) return int.MaxValue; int mid = low + (high - low)/2; // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (Math.Pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio); } // Find ration and calls findMissingRec public static int findMissing(int []arr, int n) { // Finding ration assuming that the missing // term is not first or last term of series. int ratio =(int) Math.Pow(arr[n-1]/arr[0], 1.0/n); return findMissingRec(arr, 0, n-1, ratio); } /* Driver program to test above function */ public static void Main() { int []arr = {2, 4, 8, 32}; int n = arr.Length; Console.Write(findMissing(arr, n)); }} // This code is contributed by nitin mittal.
<?php// PHP program to find missing number// in geometric progression // It returns INT_MAX in case of errorfunction findMissingRec(&$arr, $low, $high, $ratio){ if ($low >= $high) return PHP_INT_MAX; $mid = $low + intval(($high - $low) / 2); // If element next to mid is missing if ($arr[$mid+1]/$arr[$mid] != $ratio) return ($arr[$mid] * $ratio); // If element previous to mid is missing if (($mid > 0) && ($arr[$mid] / $arr[$mid - 1]) != $ratio) return ($arr[$mid - 1] * $ratio); // If missing element is in right half if ($arr[$mid] == $arr[0] * (pow($ratio, $mid))) return findMissingRec($arr, $mid + 1, $high, $ratio); return findMissingRec($arr, $low, $mid - 1, $ratio);} // Find ration and calls findMissingRecfunction findMissing(&$arr, $n){ // Finding ration assuming that the missing // term is not first or last term of series. $ratio = (float) pow($arr[$n - 1] / $arr[0], 1.0 / $n); return findMissingRec($arr, 0, $n - 1, $ratio);} // Driver code$arr = array(2, 4, 8, 32);$n = sizeof($arr);echo findMissing($arr, $n); // This code is contributed by ita_c?>
<script> // Javascript Code for Find the missing number// in Geometric Progression // It returns INT_MAX in case of error function findMissingRec(arr,low,high,ratio) { if (low >= high) return Integer.MAX_VALUE; let mid = Math.floor(low + (high - low)/2); // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (Math.pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio); } // Find ration and calls findMissingRec function findMissing(arr,n) { // Finding ration assuming that the missing // term is not first or last term of series. let ratio =Math.floor( Math.pow(arr[n-1]/arr[0], 1.0/n)); return findMissingRec(arr, 0, n-1, ratio); } /* Driver program to test above function */ let arr=[2, 4, 8, 32]; let n = arr.length; document.write(findMissing(arr, n)); // This code is contributed by rag2127 </script>
Output:
16
Note : Drawback withs this solution are : For larger values or for bigger array, it may cause overflow and/or may take more time to computer powers.This article is contributed by Yasin Zafar. 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
rag2127
Binary Search
Arrays
Arrays
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Bridge and Torch problem
Window Sliding Technique
Binary Tree (Array implementation)
Segment Tree | Set 1 (Sum of given range)
MSD( Most Significant Digit ) Radix Sort
Building Heap from Array
Maximum Subarray Sum using Divide and Conquer algorithm
Product of Array except itself
Find duplicates in O(n) time and O(1) extra space | Set 1
|
[
{
"code": null,
"e": 26067,
"s": 26039,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 26324,
"s": 26067,
"text": "Given an array that represents elements of geometric progression in order. One element is missing in the progression, find the missing number. It may be assumed that one term is always missing and the missing term is not first or last of series.Examples: "
},
{
"code": null,
"e": 26416,
"s": 26324,
"text": "Input : arr[] = {1, 3 , 27, 81}\nOutput : 9\n\nInput : arr[] = {4, 16, 64, 1024};\nOutput : 256"
},
{
"code": null,
"e": 26993,
"s": 26418,
"text": "A Simple Solution is to linearly traverse the array and find the missing number. Time complexity of this solution is O(n).An efficient solution to solve this problem in O(Log n) time using Binary Search. The idea is to go to the middle element. Check if the ratio of middle and next to middle is equal to common ratio or not, if not then the missing element lies between mid and mid+1. If the middle element is equal to n/2th term in Geometric Series (Let n be the number of elements in input array), then missing element lies in right half. Else element lies in left half. "
},
{
"code": null,
"e": 26997,
"s": 26993,
"text": "C++"
},
{
"code": null,
"e": 27002,
"s": 26997,
"text": "Java"
},
{
"code": null,
"e": 27010,
"s": 27002,
"text": "Python3"
},
{
"code": null,
"e": 27013,
"s": 27010,
"text": "C#"
},
{
"code": null,
"e": 27017,
"s": 27013,
"text": "PHP"
},
{
"code": null,
"e": 27028,
"s": 27017,
"text": "Javascript"
},
{
"code": "// C++ program to find missing number in// geometric progression#include <bits/stdc++.h>using namespace std; // It returns INT_MAX in case of errorint findMissingRec(int arr[], int low, int high, int ratio){ if (low >= high) return INT_MAX; int mid = low + (high - low)/2; // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio);} // Find ration and calls findMissingRecint findMissing(int arr[], int n){ // Finding ration assuming that the missing term is // not first or last term of series. int ratio = (float) pow(arr[n-1]/arr[0], 1.0/n); return findMissingRec(arr, 0, n-1, ratio);} // Driver codeint main(void){ int arr[] = {2, 4, 8, 32}; int n = sizeof(arr)/sizeof(arr[0]); cout << findMissing(arr, n); return 0;}",
"e": 28189,
"s": 27028,
"text": null
},
{
"code": "// JAVA Code for Find the missing number// in Geometric Progressionclass GFG { // It returns INT_MAX in case of error public static int findMissingRec(int arr[], int low, int high, int ratio) { if (low >= high) return Integer.MAX_VALUE; int mid = low + (high - low)/2; // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (Math.pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio); } // Find ration and calls findMissingRec public static int findMissing(int arr[], int n) { // Finding ration assuming that the missing // term is not first or last term of series. int ratio =(int) Math.pow(arr[n-1]/arr[0], 1.0/n); return findMissingRec(arr, 0, n-1, ratio); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {2, 4, 8, 32}; int n = arr.length; System.out.print(findMissing(arr, n)); } }// This code is contributed by Arnav Kr. Mandal.",
"e": 29633,
"s": 28189,
"text": null
},
{
"code": "# Python3 program to find missing# number in geometric progression # It returns INT_MAX in case of errordef findMissingRec(arr, low, high, ratio): if (low >= high): return 2147483647 mid = low + (high - low) // 2 # If element next to mid is missing if (arr[mid + 1] // arr[mid] != ratio): return (arr[mid] * ratio) # If element previous to mid is missing if ((mid > 0) and (arr[mid] / arr[mid-1]) != ratio): return (arr[mid - 1] * ratio) # If missing element is in right half if (arr[mid] == arr[0] * (pow(ratio, mid)) ): return findMissingRec(arr, mid+1, high, ratio) return findMissingRec(arr, low, mid-1, ratio) # Find ration and calls findMissingRecdef findMissing(arr, n): # Finding ration assuming that # the missing term is not first # or last term of series. ratio = int(pow(arr[n-1] / arr[0], 1.0 / n)) return findMissingRec(arr, 0, n-1, ratio) # Driver codearr = [2, 4, 8, 32]n = len(arr)print(findMissing(arr, n)) # This code is contributed by Anant Agarwal.",
"e": 30682,
"s": 29633,
"text": null
},
{
"code": "// C# Code for Find the missing number// in Geometric Progressionusing System; class GFG { // It returns INT_MAX in case of error public static int findMissingRec(int []arr, int low, int high, int ratio) { if (low >= high) return int.MaxValue; int mid = low + (high - low)/2; // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (Math.Pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio); } // Find ration and calls findMissingRec public static int findMissing(int []arr, int n) { // Finding ration assuming that the missing // term is not first or last term of series. int ratio =(int) Math.Pow(arr[n-1]/arr[0], 1.0/n); return findMissingRec(arr, 0, n-1, ratio); } /* Driver program to test above function */ public static void Main() { int []arr = {2, 4, 8, 32}; int n = arr.Length; Console.Write(findMissing(arr, n)); }} // This code is contributed by nitin mittal.",
"e": 32137,
"s": 30682,
"text": null
},
{
"code": "<?php// PHP program to find missing number// in geometric progression // It returns INT_MAX in case of errorfunction findMissingRec(&$arr, $low, $high, $ratio){ if ($low >= $high) return PHP_INT_MAX; $mid = $low + intval(($high - $low) / 2); // If element next to mid is missing if ($arr[$mid+1]/$arr[$mid] != $ratio) return ($arr[$mid] * $ratio); // If element previous to mid is missing if (($mid > 0) && ($arr[$mid] / $arr[$mid - 1]) != $ratio) return ($arr[$mid - 1] * $ratio); // If missing element is in right half if ($arr[$mid] == $arr[0] * (pow($ratio, $mid))) return findMissingRec($arr, $mid + 1, $high, $ratio); return findMissingRec($arr, $low, $mid - 1, $ratio);} // Find ration and calls findMissingRecfunction findMissing(&$arr, $n){ // Finding ration assuming that the missing // term is not first or last term of series. $ratio = (float) pow($arr[$n - 1] / $arr[0], 1.0 / $n); return findMissingRec($arr, 0, $n - 1, $ratio);} // Driver code$arr = array(2, 4, 8, 32);$n = sizeof($arr);echo findMissing($arr, $n); // This code is contributed by ita_c?>",
"e": 33402,
"s": 32137,
"text": null
},
{
"code": "<script> // Javascript Code for Find the missing number// in Geometric Progression // It returns INT_MAX in case of error function findMissingRec(arr,low,high,ratio) { if (low >= high) return Integer.MAX_VALUE; let mid = Math.floor(low + (high - low)/2); // If element next to mid is missing if (arr[mid+1]/arr[mid] != ratio) return (arr[mid] * ratio); // If element previous to mid is missing if ((mid > 0) && (arr[mid]/arr[mid-1]) != ratio) return (arr[mid-1] * ratio); // If missing element is in right half if (arr[mid] == arr[0] * (Math.pow(ratio, mid)) ) return findMissingRec(arr, mid+1, high, ratio); return findMissingRec(arr, low, mid-1, ratio); } // Find ration and calls findMissingRec function findMissing(arr,n) { // Finding ration assuming that the missing // term is not first or last term of series. let ratio =Math.floor( Math.pow(arr[n-1]/arr[0], 1.0/n)); return findMissingRec(arr, 0, n-1, ratio); } /* Driver program to test above function */ let arr=[2, 4, 8, 32]; let n = arr.length; document.write(findMissing(arr, n)); // This code is contributed by rag2127 </script>",
"e": 34734,
"s": 33402,
"text": null
},
{
"code": null,
"e": 34743,
"s": 34734,
"text": "Output: "
},
{
"code": null,
"e": 34746,
"s": 34743,
"text": "16"
},
{
"code": null,
"e": 35318,
"s": 34746,
"text": "Note : Drawback withs this solution are : For larger values or for bigger array, it may cause overflow and/or may take more time to computer powers.This article is contributed by Yasin Zafar. 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": 35331,
"s": 35318,
"text": "nitin mittal"
},
{
"code": null,
"e": 35337,
"s": 35331,
"text": "ukasp"
},
{
"code": null,
"e": 35345,
"s": 35337,
"text": "rag2127"
},
{
"code": null,
"e": 35359,
"s": 35345,
"text": "Binary Search"
},
{
"code": null,
"e": 35366,
"s": 35359,
"text": "Arrays"
},
{
"code": null,
"e": 35373,
"s": 35366,
"text": "Arrays"
},
{
"code": null,
"e": 35387,
"s": 35373,
"text": "Binary Search"
},
{
"code": null,
"e": 35485,
"s": 35387,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35522,
"s": 35485,
"text": "Program for Bridge and Torch problem"
},
{
"code": null,
"e": 35547,
"s": 35522,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 35582,
"s": 35547,
"text": "Binary Tree (Array implementation)"
},
{
"code": null,
"e": 35624,
"s": 35582,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 35665,
"s": 35624,
"text": "MSD( Most Significant Digit ) Radix Sort"
},
{
"code": null,
"e": 35690,
"s": 35665,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 35746,
"s": 35690,
"text": "Maximum Subarray Sum using Divide and Conquer algorithm"
},
{
"code": null,
"e": 35777,
"s": 35746,
"text": "Product of Array except itself"
}
] |
Bidirectional Search - GeeksforGeeks
|
CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses
For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more
School Guide
Python Programming
Learn To Make Apps
Explore more
All Courses
TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms
Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data ScienceMachine LearningData Science
Machine Learning
Data Science
CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software DesignsSoftware Design PatternsSystem Design Tutorial
Software Design Patterns
System Design Tutorial
School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
School Programming
MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
JobsApply for JobsPost a JobJOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri
Geeks Digest
Quizzes
Geeks Campus
Gblog Articles
IDE
Campus Mantri
Sign In
Sign In
Home
Saved Videos
Courses
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
School Learning
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
For Working Professionals
LIVE
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
DSA Live Classes
System Design
Java Backend Development
Full Stack LIVE
Explore More
Self-Paced
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
DSA- Self Paced
SDE Theory
Must-Do Coding Questions
Explore More
For Students
LIVE
Competitive Programming
Data Structures with C++
Data Science
Explore More
Competitive Programming
Data Structures with C++
Data Science
Explore More
Self-Paced
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
DSA- Self Paced
CIP
JAVA / Python / C++
Explore More
School Courses
School Guide
Python Programming
Learn To Make Apps
Explore more
School Guide
Python Programming
Learn To Make Apps
Explore more
Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Searching Algorithms
Sorting Algorithms
Graph Algorithms
Pattern Searching
Geometric Algorithms
Mathematical
Bitwise Algorithms
Randomized Algorithms
Greedy Algorithms
Dynamic Programming
Divide and Conquer
Backtracking
Branch and Bound
All Algorithms
Analysis of Algorithms
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Asymptotic Analysis
Worst, Average and Best Cases
Asymptotic Notations
Little o and little omega notations
Lower and Upper Bound Theory
Analysis of Loops
Solving Recurrences
Amortized Analysis
What does 'Space Complexity' mean ?
Pseudo-polynomial Algorithms
Polynomial Time Approximation Scheme
A Time Complexity Question
Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Arrays
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Hashing
Graph
Advanced Data Structure
Matrix
Strings
All Data Structures
Interview Corner
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Company Preparation
Top Topics
Practice Company Questions
Interview Experiences
Experienced Interviews
Internship Interviews
Competititve Programming
Design Patterns
System Design Tutorial
Multiple Choice Quizzes
Languages
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
C
C++
Java
Python
C#
JavaScript
jQuery
SQL
PHP
Scala
Perl
Go Language
HTML
CSS
Kotlin
ML & Data Science
Machine Learning
Data Science
Machine Learning
Data Science
CS Subjects
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
Mathematics
Operating System
DBMS
Computer Networks
Computer Organization and Architecture
Theory of Computation
Compiler Design
Digital Logic
Software Engineering
GATE
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
GATE Computer Science Notes
Last Minute Notes
GATE CS Solved Papers
GATE CS Original Papers and Official Keys
GATE 2021 Dates
GATE CS 2021 Syllabus
Important Topics for GATE CS
Web Technologies
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
HTML
CSS
JavaScript
AngularJS
ReactJS
NodeJS
Bootstrap
jQuery
PHP
Software Designs
Software Design Patterns
System Design Tutorial
Software Design Patterns
System Design Tutorial
School Learning
School Programming
School Programming
Mathematics
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Number System
Algebra
Trigonometry
Statistics
Probability
Geometry
Mensuration
Calculus
Maths Notes (Class 8-12)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 12 Notes
NCERT Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
RD Sharma Solutions
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Class 8 Maths Solution
Class 9 Maths Solution
Class 10 Maths Solution
Class 11 Maths Solution
Class 12 Maths Solution
Physics Notes (Class 8-11)
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
Class 8 Notes
Class 9 Notes
Class 10 Notes
Class 11 Notes
CS Exams/PSUs
ISRO
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
ISRO CS Original Papers and Official Keys
ISRO CS Solved Papers
ISRO CS Syllabus for Scientist/Engineer Exam
UGC NET
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
UGC NET CS Notes Paper II
UGC NET CS Notes Paper III
UGC NET CS Solved Papers
Student
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Campus Ambassador Program
School Ambassador Program
Project
Geek of the Month
Campus Geek of the Month
Placement Course
Competititve Programming
Testimonials
Student Chapter
Geek on the Top
Internship
Careers
Curated DSA Lists
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Top 50 Array Problems
Top 50 String Problems
Top 50 Tree Problems
Top 50 Graph Problems
Top 50 DP Problems
Tutorials
Jobs
Apply for Jobs
Post a Job
JOB-A-THON
Apply for Jobs
Post a Job
JOB-A-THON
Practice
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
All DSA Problems
Problem of the Day
Interview Series: Weekly Contests
Bi-Wizard Coding: School Contests
Contests and Events
Practice SDE Sheet
GBlog
Puzzles
What's New ?
Array
Matrix
Strings
Hashing
Linked List
Stack
Queue
Binary Tree
Binary Search Tree
Heap
Graph
Searching
Sorting
Divide & Conquer
Mathematical
Geometric
Bitwise
Greedy
Backtracking
Branch and Bound
Dynamic Programming
Pattern Searching
Randomized
Print all paths from a given source to a destination
Print all paths from a given source to a destination using BFS
Minimum number of edges between two vertices of a Graph
Count nodes within K-distance from all nodes in a set
Bidirectional Search
Minimum edge reversals to make a root
BFS for Disconnected Graph
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorffβs algorithm for Knightβs tour problem
The Knightβs tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Tree Traversals (Inorder, Preorder and Postorder)
Inorder Tree Traversal without Recursion
Inorder Tree Traversal without recursion and without stack!
Print Postorder traversal from given Inorder and Preorder traversals
Construct Tree from given Inorder and Preorder traversals
Dijkstra's shortest path algorithm | Greedy Algo-7
Graph and its representations
Primβs Minimum Spanning Tree (MST) | Greedy Algo-5
Print all paths from a given source to a destination
Print all paths from a given source to a destination using BFS
Minimum number of edges between two vertices of a Graph
Count nodes within K-distance from all nodes in a set
Bidirectional Search
Minimum edge reversals to make a root
BFS for Disconnected Graph
N Queen Problem | Backtracking-3
Printing all solutions in N-Queen Problem
Warnsdorffβs algorithm for Knightβs tour problem
The Knightβs tour problem | Backtracking-1
Rat in a Maze | Backtracking-2
Count number of ways to reach destination in a Maze
Count all possible paths from top left to bottom right of a mXn matrix
Print all possible paths from top left to bottom right of a mXn matrix
Unique paths in a Grid with Obstacles
Unique paths covering every non-obstacle block exactly once in a grid
Depth First Search or DFS for a Graph
Breadth First Search or BFS for a Graph
Level Order Binary Tree Traversal
Tree Traversals (Inorder, Preorder and Postorder)
Inorder Tree Traversal without Recursion
Inorder Tree Traversal without recursion and without stack!
Print Postorder traversal from given Inorder and Preorder traversals
Construct Tree from given Inorder and Preorder traversals
Dijkstra's shortest path algorithm | Greedy Algo-7
Graph and its representations
Primβs Minimum Spanning Tree (MST) | Greedy Algo-5
Difficulty Level :
Hard
Searching a graph is quite famous problem and have a lot of practical use. We have already discussed here how to search for a goal vertex starting from a source vertex using BFS. In normal graph search using BFS/DFS we begin our search in one direction usually from source vertex toward the goal vertex, but what if we start search from both direction simultaneously.Bidirectional search is a graph search algorithm which find smallest path from source to goal vertex. It runs two simultaneous search β
Forward search from source/initial vertex toward goal vertexBackward search from goal/target vertex toward source vertex
Forward search from source/initial vertex toward goal vertex
Backward search from goal/target vertex toward source vertex
Bidirectional search replaces single search graph(which is likely to grow exponentially) with two smaller sub graphs β one starting from initial vertex and other starting from goal vertex. The search terminates when two graphs intersect.Just like A* algorithm, bidirectional search can be guided by a heuristic estimate of remaining distance from source to goal and vice versa for finding shortest path possible.Consider following simple example-
Suppose we want to find if there exists a path from vertex 0 to vertex 14. Here we can execute two searches, one from vertex 0 and other from vertex 14. When both forward and backward search meet at vertex 7, we know that we have found a path from node 0 to 14 and search can be terminated now. We can clearly see that we have successfully avoided unnecessary exploration.
Why bidirectional approach?
Because in many cases it is faster, it dramatically reduce the amount of required exploration. Suppose if branching factor of tree is b and distance of goal vertex from source is d, then the normal BFS/DFS searching complexity would be O(bd). On the other hand, if we execute two search operation then the complexity would be O(bd/2) for each search and total complexity would be O(bd/2 +bd/2) which is far less than O(bd).
When to use bidirectional approach?
We can consider bidirectional approach when-
Both initial and goal states are unique and completely defined.The branching factor is exactly the same in both directions.
Both initial and goal states are unique and completely defined.
The branching factor is exactly the same in both directions.
Performance measures
Completeness : Bidirectional search is complete if BFS is used in both searches.
Optimality : It is optimal if BFS is used for search and paths have uniform cost.
Time and Space Complexity : Time and space complexity is O(bd/2).
Below is very simple implementation representing the concept of bidirectional search using BFS. This implementation considers undirected paths without any weight.
C++
Python3
// C++ program for Bidirectional BFS search// to check path between two vertices#include <bits/stdc++.h>using namespace std; // class representing undirected graph// using adjacency listclass Graph{ //number of nodes in graph int V; // Adjacency list list<int> *adj;public: Graph(int V); int isIntersecting(bool *s_visited, bool *t_visited); void addEdge(int u, int v); void printPath(int *s_parent, int *t_parent, int s, int t, int intersectNode); void BFS(list<int> *queue, bool *visited, int *parent); int biDirSearch(int s, int t);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];}; // Method for adding undirected edgevoid Graph::addEdge(int u, int v){ this->adj[u].push_back(v); this->adj[v].push_back(u);}; // Method for Breadth First Searchvoid Graph::BFS(list<int> *queue, bool *visited, int *parent){ int current = queue->front(); queue->pop_front(); list<int>::iterator i; for (i=adj[current].begin();i != adj[current].end();i++) { // If adjacent vertex is not visited earlier // mark it visited by assigning true value if (!visited[*i]) { // set current as parent of this vertex parent[*i] = current; // Mark this vertex visited visited[*i] = true; // Push to the end of queue queue->push_back(*i); } }}; // check for intersecting vertexint Graph::isIntersecting(bool *s_visited, bool *t_visited){ int intersectNode = -1; for(int i=0;i<V;i++) { // if a vertex is visited by both front // and back BFS search return that node // else return -1 if(s_visited[i] && t_visited[i]) return i; } return -1;}; // Print the path from source to targetvoid Graph::printPath(int *s_parent, int *t_parent, int s, int t, int intersectNode){ vector<int> path; path.push_back(intersectNode); int i = intersectNode; while (i != s) { path.push_back(s_parent[i]); i = s_parent[i]; } reverse(path.begin(), path.end()); i = intersectNode; while(i != t) { path.push_back(t_parent[i]); i = t_parent[i]; } vector<int>::iterator it; cout<<"*****Path*****\n"; for(it = path.begin();it != path.end();it++) cout<<*it<<" "; cout<<"\n";}; // Method for bidirectional searchingint Graph::biDirSearch(int s, int t){ // boolean array for BFS started from // source and target(front and backward BFS) // for keeping track on visited nodes bool s_visited[V], t_visited[V]; // Keep track on parents of nodes // for front and backward search int s_parent[V], t_parent[V]; // queue for front and backward search list<int> s_queue, t_queue; int intersectNode = -1; // necessary initialization for(int i=0; i<V; i++) { s_visited[i] = false; t_visited[i] = false; } s_queue.push_back(s); s_visited[s] = true; // parent of source is set to -1 s_parent[s]=-1; t_queue.push_back(t); t_visited[t] = true; // parent of target is set to -1 t_parent[t] = -1; while (!s_queue.empty() && !t_queue.empty()) { // Do BFS from source and target vertices BFS(&s_queue, s_visited, s_parent); BFS(&t_queue, t_visited, t_parent); // check for intersecting vertex intersectNode = isIntersecting(s_visited, t_visited); // If intersecting vertex is found // that means there exist a path if(intersectNode != -1) { cout << "Path exist between " << s << " and " << t << "\n"; cout << "Intersection at: " << intersectNode << "\n"; // print the path and exit the program printPath(s_parent, t_parent, s, t, intersectNode); exit(0); } } return -1;} // Driver codeint main(){ // no of vertices in graph int n=15; // source vertex int s=0; // target vertex int t=14; // create a graph given in above diagram Graph g(n); g.addEdge(0, 4); g.addEdge(1, 4); g.addEdge(2, 5); g.addEdge(3, 5); g.addEdge(4, 6); g.addEdge(5, 6); g.addEdge(6, 7); g.addEdge(7, 8); g.addEdge(8, 9); g.addEdge(8, 10); g.addEdge(9, 11); g.addEdge(9, 12); g.addEdge(10, 13); g.addEdge(10, 14); if (g.biDirSearch(s, t) == -1) cout << "Path don't exist between " << s << " and " << t << "\n"; return 0;}
# Python3 program for Bidirectional BFS# Search to check path between two vertices # Class definition for node to# be added to graphclass AdjacentNode: def __init__(self, vertex): self.vertex = vertex self.next = None # BidirectionalSearch implementationclass BidirectionalSearch: def __init__(self, vertices): # Initialize vertices and # graph with vertices self.vertices = vertices self.graph = [None] * self.vertices # Initializing queue for forward # and backward search self.src_queue = list() self.dest_queue = list() # Initializing source and # destination visited nodes as False self.src_visited = [False] * self.vertices self.dest_visited = [False] * self.vertices # Initializing source and destination # parent nodes self.src_parent = [None] * self.vertices self.dest_parent = [None] * self.vertices # Function for adding undirected edge def add_edge(self, src, dest): # Add edges to graph # Add source to destination node = AdjacentNode(dest) node.next = self.graph[src] self.graph[src] = node # Since graph is undirected add # destination to source node = AdjacentNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function for Breadth First Search def bfs(self, direction = 'forward'): if direction == 'forward': # BFS in forward direction current = self.src_queue.pop(0) connected_node = self.graph[current] while connected_node: vertex = connected_node.vertex if not self.src_visited[vertex]: self.src_queue.append(vertex) self.src_visited[vertex] = True self.src_parent[vertex] = current connected_node = connected_node.next else: # BFS in backward direction current = self.dest_queue.pop(0) connected_node = self.graph[current] while connected_node: vertex = connected_node.vertex if not self.dest_visited[vertex]: self.dest_queue.append(vertex) self.dest_visited[vertex] = True self.dest_parent[vertex] = current connected_node = connected_node.next # Check for intersecting vertex def is_intersecting(self): # Returns intersecting node # if present else -1 for i in range(self.vertices): if (self.src_visited[i] and self.dest_visited[i]): return i return -1 # Print the path from source to target def print_path(self, intersecting_node, src, dest): # Print final path from # source to destination path = list() path.append(intersecting_node) i = intersecting_node while i != src: path.append(self.src_parent[i]) i = self.src_parent[i] path = path[::-1] i = intersecting_node while i != dest: path.append(self.dest_parent[i]) i = self.dest_parent[i] print("*****Path*****") path = list(map(str, path)) print(' '.join(path)) # Function for bidirectional searching def bidirectional_search(self, src, dest): # Add source to queue and mark # visited as True and add its # parent as -1 self.src_queue.append(src) self.src_visited[src] = True self.src_parent[src] = -1 # Add destination to queue and # mark visited as True and add # its parent as -1 self.dest_queue.append(dest) self.dest_visited[dest] = True self.dest_parent[dest] = -1 while self.src_queue and self.dest_queue: # BFS in forward direction from # Source Vertex self.bfs(direction = 'forward') # BFS in reverse direction # from Destination Vertex self.bfs(direction = 'backward') # Check for intersecting vertex intersecting_node = self.is_intersecting() # If intersecting vertex exists # then path from source to # destination exists if intersecting_node != -1: print(f"Path exists between {src} and {dest}") print(f"Intersection at : {intersecting_node}") self.print_path(intersecting_node, src, dest) exit(0) return -1 # Driver codeif __name__ == '__main__': # Number of Vertices in graph n = 15 # Source Vertex src = 0 # Destination Vertex dest = 14 # Create a graph graph = BidirectionalSearch(n) graph.add_edge(0, 4) graph.add_edge(1, 4) graph.add_edge(2, 5) graph.add_edge(3, 5) graph.add_edge(4, 6) graph.add_edge(5, 6) graph.add_edge(6, 7) graph.add_edge(7, 8) graph.add_edge(8, 9) graph.add_edge(8, 10) graph.add_edge(9, 11) graph.add_edge(9, 12) graph.add_edge(10, 13) graph.add_edge(10, 14) out = graph.bidirectional_search(src, dest) if out == -1: print(f"Path does not exist between {src} and {dest}") # This code is contributed by Nirjhari Jankar
Output:
Path exist between 0 and 14
Intersection at: 7
*****Path*****
0 4 6 7 8 10 14
References
https://en.wikipedia.org/wiki/Bidirectional_search
This article is contributed by Atul Kumar. 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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
nirjhari jankar
prathibar03
BFS
Graph
Graph
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2
Topological Sorting
BellmanβFord Algorithm | DP-23
Detect Cycle in a Directed Graph
Floyd Warshall Algorithm | DP-16
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Ford-Fulkerson Algorithm for Maximum Flow Problem
Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)
Strongly Connected Components
Detect cycle in an undirected graph
|
[
{
"code": null,
"e": 419,
"s": 0,
"text": "CoursesFor Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore MoreFor StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore MoreSchool CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore moreAll Courses"
},
{
"code": null,
"e": 600,
"s": 419,
"text": "For Working ProfessionalsLIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore MoreSelf-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 685,
"s": 600,
"text": "LIVEDSA Live ClassesSystem DesignJava Backend DevelopmentFull Stack LIVEExplore More"
},
{
"code": null,
"e": 702,
"s": 685,
"text": "DSA Live Classes"
},
{
"code": null,
"e": 716,
"s": 702,
"text": "System Design"
},
{
"code": null,
"e": 741,
"s": 716,
"text": "Java Backend Development"
},
{
"code": null,
"e": 757,
"s": 741,
"text": "Full Stack LIVE"
},
{
"code": null,
"e": 770,
"s": 757,
"text": "Explore More"
},
{
"code": null,
"e": 842,
"s": 770,
"text": "Self-PacedDSA- Self PacedSDE TheoryMust-Do Coding QuestionsExplore More"
},
{
"code": null,
"e": 858,
"s": 842,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 869,
"s": 858,
"text": "SDE Theory"
},
{
"code": null,
"e": 894,
"s": 869,
"text": "Must-Do Coding Questions"
},
{
"code": null,
"e": 907,
"s": 894,
"text": "Explore More"
},
{
"code": null,
"e": 1054,
"s": 907,
"text": "For StudentsLIVECompetitive ProgrammingData Structures with C++Data ScienceExplore MoreSelf-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1130,
"s": 1054,
"text": "LIVECompetitive ProgrammingData Structures with C++Data ScienceExplore More"
},
{
"code": null,
"e": 1154,
"s": 1130,
"text": "Competitive Programming"
},
{
"code": null,
"e": 1179,
"s": 1154,
"text": "Data Structures with C++"
},
{
"code": null,
"e": 1192,
"s": 1179,
"text": "Data Science"
},
{
"code": null,
"e": 1205,
"s": 1192,
"text": "Explore More"
},
{
"code": null,
"e": 1265,
"s": 1205,
"text": "Self-PacedDSA- Self PacedCIPJAVA / Python / C++Explore More"
},
{
"code": null,
"e": 1281,
"s": 1265,
"text": "DSA- Self Paced"
},
{
"code": null,
"e": 1285,
"s": 1281,
"text": "CIP"
},
{
"code": null,
"e": 1305,
"s": 1285,
"text": "JAVA / Python / C++"
},
{
"code": null,
"e": 1318,
"s": 1305,
"text": "Explore More"
},
{
"code": null,
"e": 1393,
"s": 1318,
"text": "School CoursesSchool GuidePython ProgrammingLearn To Make AppsExplore more"
},
{
"code": null,
"e": 1406,
"s": 1393,
"text": "School Guide"
},
{
"code": null,
"e": 1425,
"s": 1406,
"text": "Python Programming"
},
{
"code": null,
"e": 1444,
"s": 1425,
"text": "Learn To Make Apps"
},
{
"code": null,
"e": 1457,
"s": 1444,
"text": "Explore more"
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "All Courses"
},
{
"code": null,
"e": 3985,
"s": 1469,
"text": "TutorialsAlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll AlgorithmsData StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data StructuresInterview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice QuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlinML & Data ScienceMachine LearningData ScienceCS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware EngineeringGATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CSWeb TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftware DesignsSoftware Design PatternsSystem Design TutorialSchool LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesCS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved PapersStudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 4566,
"s": 3985,
"text": "AlgorithmsAnalysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity QuestionSearching AlgorithmsSorting AlgorithmsGraph AlgorithmsPattern SearchingGeometric AlgorithmsMathematicalBitwise AlgorithmsRandomized AlgorithmsGreedy AlgorithmsDynamic ProgrammingDivide and ConquerBacktrackingBranch and BoundAll Algorithms"
},
{
"code": null,
"e": 4899,
"s": 4566,
"text": "Analysis of AlgorithmsAsymptotic AnalysisWorst, Average and Best CasesAsymptotic NotationsLittle o and little omega notationsLower and Upper Bound TheoryAnalysis of LoopsSolving RecurrencesAmortized AnalysisWhat does 'Space Complexity' mean ?Pseudo-polynomial AlgorithmsPolynomial Time Approximation SchemeA Time Complexity Question"
},
{
"code": null,
"e": 4919,
"s": 4899,
"text": "Asymptotic Analysis"
},
{
"code": null,
"e": 4949,
"s": 4919,
"text": "Worst, Average and Best Cases"
},
{
"code": null,
"e": 4970,
"s": 4949,
"text": "Asymptotic Notations"
},
{
"code": null,
"e": 5006,
"s": 4970,
"text": "Little o and little omega notations"
},
{
"code": null,
"e": 5035,
"s": 5006,
"text": "Lower and Upper Bound Theory"
},
{
"code": null,
"e": 5053,
"s": 5035,
"text": "Analysis of Loops"
},
{
"code": null,
"e": 5073,
"s": 5053,
"text": "Solving Recurrences"
},
{
"code": null,
"e": 5092,
"s": 5073,
"text": "Amortized Analysis"
},
{
"code": null,
"e": 5128,
"s": 5092,
"text": "What does 'Space Complexity' mean ?"
},
{
"code": null,
"e": 5157,
"s": 5128,
"text": "Pseudo-polynomial Algorithms"
},
{
"code": null,
"e": 5194,
"s": 5157,
"text": "Polynomial Time Approximation Scheme"
},
{
"code": null,
"e": 5221,
"s": 5194,
"text": "A Time Complexity Question"
},
{
"code": null,
"e": 5242,
"s": 5221,
"text": "Searching Algorithms"
},
{
"code": null,
"e": 5261,
"s": 5242,
"text": "Sorting Algorithms"
},
{
"code": null,
"e": 5278,
"s": 5261,
"text": "Graph Algorithms"
},
{
"code": null,
"e": 5296,
"s": 5278,
"text": "Pattern Searching"
},
{
"code": null,
"e": 5317,
"s": 5296,
"text": "Geometric Algorithms"
},
{
"code": null,
"e": 5330,
"s": 5317,
"text": "Mathematical"
},
{
"code": null,
"e": 5349,
"s": 5330,
"text": "Bitwise Algorithms"
},
{
"code": null,
"e": 5371,
"s": 5349,
"text": "Randomized Algorithms"
},
{
"code": null,
"e": 5389,
"s": 5371,
"text": "Greedy Algorithms"
},
{
"code": null,
"e": 5409,
"s": 5389,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 5428,
"s": 5409,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 5441,
"s": 5428,
"text": "Backtracking"
},
{
"code": null,
"e": 5458,
"s": 5441,
"text": "Branch and Bound"
},
{
"code": null,
"e": 5473,
"s": 5458,
"text": "All Algorithms"
},
{
"code": null,
"e": 5616,
"s": 5473,
"text": "Data StructuresArraysLinked ListStackQueueBinary TreeBinary Search TreeHeapHashingGraphAdvanced Data StructureMatrixStringsAll Data Structures"
},
{
"code": null,
"e": 5623,
"s": 5616,
"text": "Arrays"
},
{
"code": null,
"e": 5635,
"s": 5623,
"text": "Linked List"
},
{
"code": null,
"e": 5641,
"s": 5635,
"text": "Stack"
},
{
"code": null,
"e": 5647,
"s": 5641,
"text": "Queue"
},
{
"code": null,
"e": 5659,
"s": 5647,
"text": "Binary Tree"
},
{
"code": null,
"e": 5678,
"s": 5659,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 5683,
"s": 5678,
"text": "Heap"
},
{
"code": null,
"e": 5691,
"s": 5683,
"text": "Hashing"
},
{
"code": null,
"e": 5697,
"s": 5691,
"text": "Graph"
},
{
"code": null,
"e": 5721,
"s": 5697,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 5728,
"s": 5721,
"text": "Matrix"
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Strings"
},
{
"code": null,
"e": 5756,
"s": 5736,
"text": "All Data Structures"
},
{
"code": null,
"e": 5976,
"s": 5756,
"text": "Interview CornerCompany PreparationTop TopicsPractice Company QuestionsInterview ExperiencesExperienced InterviewsInternship InterviewsCompetititve ProgrammingDesign PatternsSystem Design TutorialMultiple Choice Quizzes"
},
{
"code": null,
"e": 5996,
"s": 5976,
"text": "Company Preparation"
},
{
"code": null,
"e": 6007,
"s": 5996,
"text": "Top Topics"
},
{
"code": null,
"e": 6034,
"s": 6007,
"text": "Practice Company Questions"
},
{
"code": null,
"e": 6056,
"s": 6034,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6079,
"s": 6056,
"text": "Experienced Interviews"
},
{
"code": null,
"e": 6101,
"s": 6079,
"text": "Internship Interviews"
},
{
"code": null,
"e": 6126,
"s": 6101,
"text": "Competititve Programming"
},
{
"code": null,
"e": 6142,
"s": 6126,
"text": "Design Patterns"
},
{
"code": null,
"e": 6165,
"s": 6142,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 6189,
"s": 6165,
"text": "Multiple Choice Quizzes"
},
{
"code": null,
"e": 6270,
"s": 6189,
"text": "LanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGo LanguageHTMLCSSKotlin"
},
{
"code": null,
"e": 6272,
"s": 6270,
"text": "C"
},
{
"code": null,
"e": 6276,
"s": 6272,
"text": "C++"
},
{
"code": null,
"e": 6281,
"s": 6276,
"text": "Java"
},
{
"code": null,
"e": 6288,
"s": 6281,
"text": "Python"
},
{
"code": null,
"e": 6291,
"s": 6288,
"text": "C#"
},
{
"code": null,
"e": 6302,
"s": 6291,
"text": "JavaScript"
},
{
"code": null,
"e": 6309,
"s": 6302,
"text": "jQuery"
},
{
"code": null,
"e": 6313,
"s": 6309,
"text": "SQL"
},
{
"code": null,
"e": 6317,
"s": 6313,
"text": "PHP"
},
{
"code": null,
"e": 6323,
"s": 6317,
"text": "Scala"
},
{
"code": null,
"e": 6328,
"s": 6323,
"text": "Perl"
},
{
"code": null,
"e": 6340,
"s": 6328,
"text": "Go Language"
},
{
"code": null,
"e": 6345,
"s": 6340,
"text": "HTML"
},
{
"code": null,
"e": 6349,
"s": 6345,
"text": "CSS"
},
{
"code": null,
"e": 6356,
"s": 6349,
"text": "Kotlin"
},
{
"code": null,
"e": 6402,
"s": 6356,
"text": "ML & Data ScienceMachine LearningData Science"
},
{
"code": null,
"e": 6419,
"s": 6402,
"text": "Machine Learning"
},
{
"code": null,
"e": 6432,
"s": 6419,
"text": "Data Science"
},
{
"code": null,
"e": 6599,
"s": 6432,
"text": "CS SubjectsMathematicsOperating SystemDBMSComputer NetworksComputer Organization and ArchitectureTheory of ComputationCompiler DesignDigital LogicSoftware Engineering"
},
{
"code": null,
"e": 6611,
"s": 6599,
"text": "Mathematics"
},
{
"code": null,
"e": 6628,
"s": 6611,
"text": "Operating System"
},
{
"code": null,
"e": 6633,
"s": 6628,
"text": "DBMS"
},
{
"code": null,
"e": 6651,
"s": 6633,
"text": "Computer Networks"
},
{
"code": null,
"e": 6690,
"s": 6651,
"text": "Computer Organization and Architecture"
},
{
"code": null,
"e": 6712,
"s": 6690,
"text": "Theory of Computation"
},
{
"code": null,
"e": 6728,
"s": 6712,
"text": "Compiler Design"
},
{
"code": null,
"e": 6742,
"s": 6728,
"text": "Digital Logic"
},
{
"code": null,
"e": 6763,
"s": 6742,
"text": "Software Engineering"
},
{
"code": null,
"e": 6938,
"s": 6763,
"text": "GATEGATE Computer Science NotesLast Minute NotesGATE CS Solved PapersGATE CS Original Papers and Official KeysGATE 2021 DatesGATE CS 2021 SyllabusImportant Topics for GATE CS"
},
{
"code": null,
"e": 6966,
"s": 6938,
"text": "GATE Computer Science Notes"
},
{
"code": null,
"e": 6984,
"s": 6966,
"text": "Last Minute Notes"
},
{
"code": null,
"e": 7006,
"s": 6984,
"text": "GATE CS Solved Papers"
},
{
"code": null,
"e": 7048,
"s": 7006,
"text": "GATE CS Original Papers and Official Keys"
},
{
"code": null,
"e": 7064,
"s": 7048,
"text": "GATE 2021 Dates"
},
{
"code": null,
"e": 7086,
"s": 7064,
"text": "GATE CS 2021 Syllabus"
},
{
"code": null,
"e": 7115,
"s": 7086,
"text": "Important Topics for GATE CS"
},
{
"code": null,
"e": 7189,
"s": 7115,
"text": "Web TechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHP"
},
{
"code": null,
"e": 7194,
"s": 7189,
"text": "HTML"
},
{
"code": null,
"e": 7198,
"s": 7194,
"text": "CSS"
},
{
"code": null,
"e": 7209,
"s": 7198,
"text": "JavaScript"
},
{
"code": null,
"e": 7219,
"s": 7209,
"text": "AngularJS"
},
{
"code": null,
"e": 7227,
"s": 7219,
"text": "ReactJS"
},
{
"code": null,
"e": 7234,
"s": 7227,
"text": "NodeJS"
},
{
"code": null,
"e": 7244,
"s": 7234,
"text": "Bootstrap"
},
{
"code": null,
"e": 7251,
"s": 7244,
"text": "jQuery"
},
{
"code": null,
"e": 7255,
"s": 7251,
"text": "PHP"
},
{
"code": null,
"e": 7318,
"s": 7255,
"text": "Software DesignsSoftware Design PatternsSystem Design Tutorial"
},
{
"code": null,
"e": 7343,
"s": 7318,
"text": "Software Design Patterns"
},
{
"code": null,
"e": 7366,
"s": 7343,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 7923,
"s": 7366,
"text": "School LearningSchool ProgrammingMathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMaths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 NotesNCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionRD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths SolutionPhysics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 7942,
"s": 7923,
"text": "School Programming"
},
{
"code": null,
"e": 8034,
"s": 7942,
"text": "MathematicsNumber SystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculus"
},
{
"code": null,
"e": 8048,
"s": 8034,
"text": "Number System"
},
{
"code": null,
"e": 8056,
"s": 8048,
"text": "Algebra"
},
{
"code": null,
"e": 8069,
"s": 8056,
"text": "Trigonometry"
},
{
"code": null,
"e": 8080,
"s": 8069,
"text": "Statistics"
},
{
"code": null,
"e": 8092,
"s": 8080,
"text": "Probability"
},
{
"code": null,
"e": 8101,
"s": 8092,
"text": "Geometry"
},
{
"code": null,
"e": 8113,
"s": 8101,
"text": "Mensuration"
},
{
"code": null,
"e": 8122,
"s": 8113,
"text": "Calculus"
},
{
"code": null,
"e": 8215,
"s": 8122,
"text": "Maths Notes (Class 8-12)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 NotesClass 12 Notes"
},
{
"code": null,
"e": 8229,
"s": 8215,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8243,
"s": 8229,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8258,
"s": 8243,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8273,
"s": 8258,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 8288,
"s": 8273,
"text": "Class 12 Notes"
},
{
"code": null,
"e": 8417,
"s": 8288,
"text": "NCERT SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8440,
"s": 8417,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8463,
"s": 8440,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8487,
"s": 8463,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8511,
"s": 8487,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8535,
"s": 8511,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8668,
"s": 8535,
"text": "RD Sharma SolutionsClass 8 Maths SolutionClass 9 Maths SolutionClass 10 Maths SolutionClass 11 Maths SolutionClass 12 Maths Solution"
},
{
"code": null,
"e": 8691,
"s": 8668,
"text": "Class 8 Maths Solution"
},
{
"code": null,
"e": 8714,
"s": 8691,
"text": "Class 9 Maths Solution"
},
{
"code": null,
"e": 8738,
"s": 8714,
"text": "Class 10 Maths Solution"
},
{
"code": null,
"e": 8762,
"s": 8738,
"text": "Class 11 Maths Solution"
},
{
"code": null,
"e": 8786,
"s": 8762,
"text": "Class 12 Maths Solution"
},
{
"code": null,
"e": 8867,
"s": 8786,
"text": "Physics Notes (Class 8-11)Class 8 NotesClass 9 NotesClass 10 NotesClass 11 Notes"
},
{
"code": null,
"e": 8881,
"s": 8867,
"text": "Class 8 Notes"
},
{
"code": null,
"e": 8895,
"s": 8881,
"text": "Class 9 Notes"
},
{
"code": null,
"e": 8910,
"s": 8895,
"text": "Class 10 Notes"
},
{
"code": null,
"e": 8925,
"s": 8910,
"text": "Class 11 Notes"
},
{
"code": null,
"e": 9131,
"s": 8925,
"text": "CS Exams/PSUsISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer ExamUGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9242,
"s": 9131,
"text": "ISROISRO CS Original Papers and Official KeysISRO CS Solved PapersISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9284,
"s": 9242,
"text": "ISRO CS Original Papers and Official Keys"
},
{
"code": null,
"e": 9306,
"s": 9284,
"text": "ISRO CS Solved Papers"
},
{
"code": null,
"e": 9351,
"s": 9306,
"text": "ISRO CS Syllabus for Scientist/Engineer Exam"
},
{
"code": null,
"e": 9434,
"s": 9351,
"text": "UGC NETUGC NET CS Notes Paper IIUGC NET CS Notes Paper IIIUGC NET CS Solved Papers"
},
{
"code": null,
"e": 9460,
"s": 9434,
"text": "UGC NET CS Notes Paper II"
},
{
"code": null,
"e": 9487,
"s": 9460,
"text": "UGC NET CS Notes Paper III"
},
{
"code": null,
"e": 9512,
"s": 9487,
"text": "UGC NET CS Solved Papers"
},
{
"code": null,
"e": 9717,
"s": 9512,
"text": "StudentCampus Ambassador ProgramSchool Ambassador ProgramProjectGeek of the MonthCampus Geek of the MonthPlacement CourseCompetititve ProgrammingTestimonialsStudent ChapterGeek on the TopInternshipCareers"
},
{
"code": null,
"e": 9743,
"s": 9717,
"text": "Campus Ambassador Program"
},
{
"code": null,
"e": 9769,
"s": 9743,
"text": "School Ambassador Program"
},
{
"code": null,
"e": 9777,
"s": 9769,
"text": "Project"
},
{
"code": null,
"e": 9795,
"s": 9777,
"text": "Geek of the Month"
},
{
"code": null,
"e": 9820,
"s": 9795,
"text": "Campus Geek of the Month"
},
{
"code": null,
"e": 9837,
"s": 9820,
"text": "Placement Course"
},
{
"code": null,
"e": 9862,
"s": 9837,
"text": "Competititve Programming"
},
{
"code": null,
"e": 9875,
"s": 9862,
"text": "Testimonials"
},
{
"code": null,
"e": 9891,
"s": 9875,
"text": "Student Chapter"
},
{
"code": null,
"e": 9907,
"s": 9891,
"text": "Geek on the Top"
},
{
"code": null,
"e": 9918,
"s": 9907,
"text": "Internship"
},
{
"code": null,
"e": 9926,
"s": 9918,
"text": "Careers"
},
{
"code": null,
"e": 9965,
"s": 9926,
"text": "JobsApply for JobsPost a JobJOB-A-THON"
},
{
"code": null,
"e": 9980,
"s": 9965,
"text": "Apply for Jobs"
},
{
"code": null,
"e": 9991,
"s": 9980,
"text": "Post a Job"
},
{
"code": null,
"e": 10002,
"s": 9991,
"text": "JOB-A-THON"
},
{
"code": null,
"e": 10267,
"s": 10002,
"text": "PracticeAll DSA ProblemsProblem of the DayInterview Series: Weekly ContestsBi-Wizard Coding: School ContestsContests and EventsPractice SDE SheetCurated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10284,
"s": 10267,
"text": "All DSA Problems"
},
{
"code": null,
"e": 10303,
"s": 10284,
"text": "Problem of the Day"
},
{
"code": null,
"e": 10337,
"s": 10303,
"text": "Interview Series: Weekly Contests"
},
{
"code": null,
"e": 10371,
"s": 10337,
"text": "Bi-Wizard Coding: School Contests"
},
{
"code": null,
"e": 10391,
"s": 10371,
"text": "Contests and Events"
},
{
"code": null,
"e": 10410,
"s": 10391,
"text": "Practice SDE Sheet"
},
{
"code": null,
"e": 10530,
"s": 10410,
"text": "Curated DSA ListsTop 50 Array ProblemsTop 50 String ProblemsTop 50 Tree ProblemsTop 50 Graph ProblemsTop 50 DP Problems"
},
{
"code": null,
"e": 10552,
"s": 10530,
"text": "Top 50 Array Problems"
},
{
"code": null,
"e": 10575,
"s": 10552,
"text": "Top 50 String Problems"
},
{
"code": null,
"e": 10596,
"s": 10575,
"text": "Top 50 Tree Problems"
},
{
"code": null,
"e": 10618,
"s": 10596,
"text": "Top 50 Graph Problems"
},
{
"code": null,
"e": 10637,
"s": 10618,
"text": "Top 50 DP Problems"
},
{
"code": null,
"e": 10908,
"s": 10641,
"text": "WriteCome write articles for us and get featuredPracticeLearn and code with the best industry expertsPremiumGet access to ad-free content, doubt assistance and more!JobsCome and find your dream job with usGeeks DigestQuizzesGeeks CampusGblog ArticlesIDECampus Mantri"
},
{
"code": null,
"e": 10921,
"s": 10908,
"text": "Geeks Digest"
},
{
"code": null,
"e": 10929,
"s": 10921,
"text": "Quizzes"
},
{
"code": null,
"e": 10942,
"s": 10929,
"text": "Geeks Campus"
},
{
"code": null,
"e": 10957,
"s": 10942,
"text": "Gblog Articles"
},
{
"code": null,
"e": 10961,
"s": 10957,
"text": "IDE"
},
{
"code": null,
"e": 10975,
"s": 10961,
"text": "Campus Mantri"
},
{
"code": null,
"e": 10983,
"s": 10975,
"text": "Sign In"
},
{
"code": null,
"e": 10991,
"s": 10983,
"text": "Sign In"
},
{
"code": null,
"e": 10996,
"s": 10991,
"text": "Home"
},
{
"code": null,
"e": 11009,
"s": 10996,
"text": "Saved Videos"
},
{
"code": null,
"e": 11017,
"s": 11009,
"text": "Courses"
},
{
"code": null,
"e": 15482,
"s": 11017,
"text": "\n\nFor Working Professionals\n \n\n\n\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n\n\nFor Students\n \n\n\n\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n\n\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n\n\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n\n\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n\n\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n\n\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n\n\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n\n\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n\n\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n\n\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n\n\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n\n\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n\n\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n\n\nSchool Learning\n \n\n\nSchool Programming\n\n\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n\n\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n\n\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n\n\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\n\nCS Exams/PSUs\n \n\n\n\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n\n\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n\n\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n\n\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n\n\nTutorials\n \n\n\n\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n\n\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 15536,
"s": 15482,
"text": "\nFor Working Professionals\n \n\n"
},
{
"code": null,
"e": 15659,
"s": 15536,
"text": "\nLIVE\n \n\n\nDSA Live Classes\n\nSystem Design\n\nJava Backend Development\n\nFull Stack LIVE\n\nExplore More\n"
},
{
"code": null,
"e": 15678,
"s": 15659,
"text": "\nDSA Live Classes\n"
},
{
"code": null,
"e": 15694,
"s": 15678,
"text": "\nSystem Design\n"
},
{
"code": null,
"e": 15721,
"s": 15694,
"text": "\nJava Backend Development\n"
},
{
"code": null,
"e": 15739,
"s": 15721,
"text": "\nFull Stack LIVE\n"
},
{
"code": null,
"e": 15754,
"s": 15739,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15862,
"s": 15754,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nSDE Theory\n\nMust-Do Coding Questions\n\nExplore More\n"
},
{
"code": null,
"e": 15880,
"s": 15862,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 15893,
"s": 15880,
"text": "\nSDE Theory\n"
},
{
"code": null,
"e": 15920,
"s": 15893,
"text": "\nMust-Do Coding Questions\n"
},
{
"code": null,
"e": 15935,
"s": 15920,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 15976,
"s": 15935,
"text": "\nFor Students\n \n\n"
},
{
"code": null,
"e": 16088,
"s": 15976,
"text": "\nLIVE\n \n\n\nCompetitive Programming\n\nData Structures with C++\n\nData Science\n\nExplore More\n"
},
{
"code": null,
"e": 16114,
"s": 16088,
"text": "\nCompetitive Programming\n"
},
{
"code": null,
"e": 16141,
"s": 16114,
"text": "\nData Structures with C++\n"
},
{
"code": null,
"e": 16156,
"s": 16141,
"text": "\nData Science\n"
},
{
"code": null,
"e": 16171,
"s": 16156,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16267,
"s": 16171,
"text": "\nSelf-Paced\n \n\n\nDSA- Self Paced\n\nCIP\n\nJAVA / Python / C++\n\nExplore More\n"
},
{
"code": null,
"e": 16285,
"s": 16267,
"text": "\nDSA- Self Paced\n"
},
{
"code": null,
"e": 16291,
"s": 16285,
"text": "\nCIP\n"
},
{
"code": null,
"e": 16313,
"s": 16291,
"text": "\nJAVA / Python / C++\n"
},
{
"code": null,
"e": 16328,
"s": 16313,
"text": "\nExplore More\n"
},
{
"code": null,
"e": 16439,
"s": 16328,
"text": "\nSchool Courses\n \n\n\nSchool Guide\n\nPython Programming\n\nLearn To Make Apps\n\nExplore more\n"
},
{
"code": null,
"e": 16454,
"s": 16439,
"text": "\nSchool Guide\n"
},
{
"code": null,
"e": 16475,
"s": 16454,
"text": "\nPython Programming\n"
},
{
"code": null,
"e": 16496,
"s": 16475,
"text": "\nLearn To Make Apps\n"
},
{
"code": null,
"e": 16511,
"s": 16496,
"text": "\nExplore more\n"
},
{
"code": null,
"e": 16816,
"s": 16511,
"text": "\nAlgorithms\n \n\n\nSearching Algorithms\n\nSorting Algorithms\n\nGraph Algorithms\n\nPattern Searching\n\nGeometric Algorithms\n\nMathematical\n\nBitwise Algorithms\n\nRandomized Algorithms\n\nGreedy Algorithms\n\nDynamic Programming\n\nDivide and Conquer\n\nBacktracking\n\nBranch and Bound\n\nAll Algorithms\n"
},
{
"code": null,
"e": 16839,
"s": 16816,
"text": "\nSearching Algorithms\n"
},
{
"code": null,
"e": 16860,
"s": 16839,
"text": "\nSorting Algorithms\n"
},
{
"code": null,
"e": 16879,
"s": 16860,
"text": "\nGraph Algorithms\n"
},
{
"code": null,
"e": 16899,
"s": 16879,
"text": "\nPattern Searching\n"
},
{
"code": null,
"e": 16922,
"s": 16899,
"text": "\nGeometric Algorithms\n"
},
{
"code": null,
"e": 16937,
"s": 16922,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 16958,
"s": 16937,
"text": "\nBitwise Algorithms\n"
},
{
"code": null,
"e": 16982,
"s": 16958,
"text": "\nRandomized Algorithms\n"
},
{
"code": null,
"e": 17002,
"s": 16982,
"text": "\nGreedy Algorithms\n"
},
{
"code": null,
"e": 17024,
"s": 17002,
"text": "\nDynamic Programming\n"
},
{
"code": null,
"e": 17045,
"s": 17024,
"text": "\nDivide and Conquer\n"
},
{
"code": null,
"e": 17060,
"s": 17045,
"text": "\nBacktracking\n"
},
{
"code": null,
"e": 17079,
"s": 17060,
"text": "\nBranch and Bound\n"
},
{
"code": null,
"e": 17096,
"s": 17079,
"text": "\nAll Algorithms\n"
},
{
"code": null,
"e": 17481,
"s": 17096,
"text": "\nAnalysis of Algorithms\n \n\n\nAsymptotic Analysis\n\nWorst, Average and Best Cases\n\nAsymptotic Notations\n\nLittle o and little omega notations\n\nLower and Upper Bound Theory\n\nAnalysis of Loops\n\nSolving Recurrences\n\nAmortized Analysis\n\nWhat does 'Space Complexity' mean ?\n\nPseudo-polynomial Algorithms\n\nPolynomial Time Approximation Scheme\n\nA Time Complexity Question\n"
},
{
"code": null,
"e": 17503,
"s": 17481,
"text": "\nAsymptotic Analysis\n"
},
{
"code": null,
"e": 17535,
"s": 17503,
"text": "\nWorst, Average and Best Cases\n"
},
{
"code": null,
"e": 17558,
"s": 17535,
"text": "\nAsymptotic Notations\n"
},
{
"code": null,
"e": 17596,
"s": 17558,
"text": "\nLittle o and little omega notations\n"
},
{
"code": null,
"e": 17627,
"s": 17596,
"text": "\nLower and Upper Bound Theory\n"
},
{
"code": null,
"e": 17647,
"s": 17627,
"text": "\nAnalysis of Loops\n"
},
{
"code": null,
"e": 17669,
"s": 17647,
"text": "\nSolving Recurrences\n"
},
{
"code": null,
"e": 17690,
"s": 17669,
"text": "\nAmortized Analysis\n"
},
{
"code": null,
"e": 17728,
"s": 17690,
"text": "\nWhat does 'Space Complexity' mean ?\n"
},
{
"code": null,
"e": 17759,
"s": 17728,
"text": "\nPseudo-polynomial Algorithms\n"
},
{
"code": null,
"e": 17798,
"s": 17759,
"text": "\nPolynomial Time Approximation Scheme\n"
},
{
"code": null,
"e": 17827,
"s": 17798,
"text": "\nA Time Complexity Question\n"
},
{
"code": null,
"e": 18024,
"s": 17827,
"text": "\nData Structures\n \n\n\nArrays\n\nLinked List\n\nStack\n\nQueue\n\nBinary Tree\n\nBinary Search Tree\n\nHeap\n\nHashing\n\nGraph\n\nAdvanced Data Structure\n\nMatrix\n\nStrings\n\nAll Data Structures\n"
},
{
"code": null,
"e": 18033,
"s": 18024,
"text": "\nArrays\n"
},
{
"code": null,
"e": 18047,
"s": 18033,
"text": "\nLinked List\n"
},
{
"code": null,
"e": 18055,
"s": 18047,
"text": "\nStack\n"
},
{
"code": null,
"e": 18063,
"s": 18055,
"text": "\nQueue\n"
},
{
"code": null,
"e": 18077,
"s": 18063,
"text": "\nBinary Tree\n"
},
{
"code": null,
"e": 18098,
"s": 18077,
"text": "\nBinary Search Tree\n"
},
{
"code": null,
"e": 18105,
"s": 18098,
"text": "\nHeap\n"
},
{
"code": null,
"e": 18115,
"s": 18105,
"text": "\nHashing\n"
},
{
"code": null,
"e": 18123,
"s": 18115,
"text": "\nGraph\n"
},
{
"code": null,
"e": 18149,
"s": 18123,
"text": "\nAdvanced Data Structure\n"
},
{
"code": null,
"e": 18158,
"s": 18149,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 18168,
"s": 18158,
"text": "\nStrings\n"
},
{
"code": null,
"e": 18190,
"s": 18168,
"text": "\nAll Data Structures\n"
},
{
"code": null,
"e": 18458,
"s": 18190,
"text": "\nInterview Corner\n \n\n\nCompany Preparation\n\nTop Topics\n\nPractice Company Questions\n\nInterview Experiences\n\nExperienced Interviews\n\nInternship Interviews\n\nCompetititve Programming\n\nDesign Patterns\n\nSystem Design Tutorial\n\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18480,
"s": 18458,
"text": "\nCompany Preparation\n"
},
{
"code": null,
"e": 18493,
"s": 18480,
"text": "\nTop Topics\n"
},
{
"code": null,
"e": 18522,
"s": 18493,
"text": "\nPractice Company Questions\n"
},
{
"code": null,
"e": 18546,
"s": 18522,
"text": "\nInterview Experiences\n"
},
{
"code": null,
"e": 18571,
"s": 18546,
"text": "\nExperienced Interviews\n"
},
{
"code": null,
"e": 18595,
"s": 18571,
"text": "\nInternship Interviews\n"
},
{
"code": null,
"e": 18622,
"s": 18595,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 18640,
"s": 18622,
"text": "\nDesign Patterns\n"
},
{
"code": null,
"e": 18665,
"s": 18640,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 18691,
"s": 18665,
"text": "\nMultiple Choice Quizzes\n"
},
{
"code": null,
"e": 18830,
"s": 18691,
"text": "\nLanguages\n \n\n\nC\n\nC++\n\nJava\n\nPython\n\nC#\n\nJavaScript\n\njQuery\n\nSQL\n\nPHP\n\nScala\n\nPerl\n\nGo Language\n\nHTML\n\nCSS\n\nKotlin\n"
},
{
"code": null,
"e": 18834,
"s": 18830,
"text": "\nC\n"
},
{
"code": null,
"e": 18840,
"s": 18834,
"text": "\nC++\n"
},
{
"code": null,
"e": 18847,
"s": 18840,
"text": "\nJava\n"
},
{
"code": null,
"e": 18856,
"s": 18847,
"text": "\nPython\n"
},
{
"code": null,
"e": 18861,
"s": 18856,
"text": "\nC#\n"
},
{
"code": null,
"e": 18874,
"s": 18861,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 18883,
"s": 18874,
"text": "\njQuery\n"
},
{
"code": null,
"e": 18889,
"s": 18883,
"text": "\nSQL\n"
},
{
"code": null,
"e": 18895,
"s": 18889,
"text": "\nPHP\n"
},
{
"code": null,
"e": 18903,
"s": 18895,
"text": "\nScala\n"
},
{
"code": null,
"e": 18910,
"s": 18903,
"text": "\nPerl\n"
},
{
"code": null,
"e": 18924,
"s": 18910,
"text": "\nGo Language\n"
},
{
"code": null,
"e": 18931,
"s": 18924,
"text": "\nHTML\n"
},
{
"code": null,
"e": 18937,
"s": 18931,
"text": "\nCSS\n"
},
{
"code": null,
"e": 18946,
"s": 18937,
"text": "\nKotlin\n"
},
{
"code": null,
"e": 19024,
"s": 18946,
"text": "\nML & Data Science\n \n\n\nMachine Learning\n\nData Science\n"
},
{
"code": null,
"e": 19043,
"s": 19024,
"text": "\nMachine Learning\n"
},
{
"code": null,
"e": 19058,
"s": 19043,
"text": "\nData Science\n"
},
{
"code": null,
"e": 19271,
"s": 19058,
"text": "\nCS Subjects\n \n\n\nMathematics\n\nOperating System\n\nDBMS\n\nComputer Networks\n\nComputer Organization and Architecture\n\nTheory of Computation\n\nCompiler Design\n\nDigital Logic\n\nSoftware Engineering\n"
},
{
"code": null,
"e": 19285,
"s": 19271,
"text": "\nMathematics\n"
},
{
"code": null,
"e": 19304,
"s": 19285,
"text": "\nOperating System\n"
},
{
"code": null,
"e": 19311,
"s": 19304,
"text": "\nDBMS\n"
},
{
"code": null,
"e": 19331,
"s": 19311,
"text": "\nComputer Networks\n"
},
{
"code": null,
"e": 19372,
"s": 19331,
"text": "\nComputer Organization and Architecture\n"
},
{
"code": null,
"e": 19396,
"s": 19372,
"text": "\nTheory of Computation\n"
},
{
"code": null,
"e": 19414,
"s": 19396,
"text": "\nCompiler Design\n"
},
{
"code": null,
"e": 19430,
"s": 19414,
"text": "\nDigital Logic\n"
},
{
"code": null,
"e": 19453,
"s": 19430,
"text": "\nSoftware Engineering\n"
},
{
"code": null,
"e": 19670,
"s": 19453,
"text": "\nGATE\n \n\n\nGATE Computer Science Notes\n\nLast Minute Notes\n\nGATE CS Solved Papers\n\nGATE CS Original Papers and Official Keys\n\nGATE 2021 Dates\n\nGATE CS 2021 Syllabus\n\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19700,
"s": 19670,
"text": "\nGATE Computer Science Notes\n"
},
{
"code": null,
"e": 19720,
"s": 19700,
"text": "\nLast Minute Notes\n"
},
{
"code": null,
"e": 19744,
"s": 19720,
"text": "\nGATE CS Solved Papers\n"
},
{
"code": null,
"e": 19788,
"s": 19744,
"text": "\nGATE CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 19806,
"s": 19788,
"text": "\nGATE 2021 Dates\n"
},
{
"code": null,
"e": 19830,
"s": 19806,
"text": "\nGATE CS 2021 Syllabus\n"
},
{
"code": null,
"e": 19861,
"s": 19830,
"text": "\nImportant Topics for GATE CS\n"
},
{
"code": null,
"e": 19981,
"s": 19861,
"text": "\nWeb Technologies\n \n\n\nHTML\n\nCSS\n\nJavaScript\n\nAngularJS\n\nReactJS\n\nNodeJS\n\nBootstrap\n\njQuery\n\nPHP\n"
},
{
"code": null,
"e": 19988,
"s": 19981,
"text": "\nHTML\n"
},
{
"code": null,
"e": 19994,
"s": 19988,
"text": "\nCSS\n"
},
{
"code": null,
"e": 20007,
"s": 19994,
"text": "\nJavaScript\n"
},
{
"code": null,
"e": 20019,
"s": 20007,
"text": "\nAngularJS\n"
},
{
"code": null,
"e": 20029,
"s": 20019,
"text": "\nReactJS\n"
},
{
"code": null,
"e": 20038,
"s": 20029,
"text": "\nNodeJS\n"
},
{
"code": null,
"e": 20050,
"s": 20038,
"text": "\nBootstrap\n"
},
{
"code": null,
"e": 20059,
"s": 20050,
"text": "\njQuery\n"
},
{
"code": null,
"e": 20065,
"s": 20059,
"text": "\nPHP\n"
},
{
"code": null,
"e": 20160,
"s": 20065,
"text": "\nSoftware Designs\n \n\n\nSoftware Design Patterns\n\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20187,
"s": 20160,
"text": "\nSoftware Design Patterns\n"
},
{
"code": null,
"e": 20212,
"s": 20187,
"text": "\nSystem Design Tutorial\n"
},
{
"code": null,
"e": 20276,
"s": 20212,
"text": "\nSchool Learning\n \n\n\nSchool Programming\n"
},
{
"code": null,
"e": 20297,
"s": 20276,
"text": "\nSchool Programming\n"
},
{
"code": null,
"e": 20433,
"s": 20297,
"text": "\nMathematics\n \n\n\nNumber System\n\nAlgebra\n\nTrigonometry\n\nStatistics\n\nProbability\n\nGeometry\n\nMensuration\n\nCalculus\n"
},
{
"code": null,
"e": 20449,
"s": 20433,
"text": "\nNumber System\n"
},
{
"code": null,
"e": 20459,
"s": 20449,
"text": "\nAlgebra\n"
},
{
"code": null,
"e": 20474,
"s": 20459,
"text": "\nTrigonometry\n"
},
{
"code": null,
"e": 20487,
"s": 20474,
"text": "\nStatistics\n"
},
{
"code": null,
"e": 20501,
"s": 20487,
"text": "\nProbability\n"
},
{
"code": null,
"e": 20512,
"s": 20501,
"text": "\nGeometry\n"
},
{
"code": null,
"e": 20526,
"s": 20512,
"text": "\nMensuration\n"
},
{
"code": null,
"e": 20537,
"s": 20526,
"text": "\nCalculus\n"
},
{
"code": null,
"e": 20668,
"s": 20537,
"text": "\nMaths Notes (Class 8-12)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n\nClass 12 Notes\n"
},
{
"code": null,
"e": 20684,
"s": 20668,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 20700,
"s": 20684,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 20717,
"s": 20700,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 20734,
"s": 20717,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 20751,
"s": 20734,
"text": "\nClass 12 Notes\n"
},
{
"code": null,
"e": 20918,
"s": 20751,
"text": "\nNCERT Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 20943,
"s": 20918,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 20968,
"s": 20943,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 20994,
"s": 20968,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21020,
"s": 20994,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21046,
"s": 21020,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21217,
"s": 21046,
"text": "\nRD Sharma Solutions\n \n\n\nClass 8 Maths Solution\n\nClass 9 Maths Solution\n\nClass 10 Maths Solution\n\nClass 11 Maths Solution\n\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21242,
"s": 21217,
"text": "\nClass 8 Maths Solution\n"
},
{
"code": null,
"e": 21267,
"s": 21242,
"text": "\nClass 9 Maths Solution\n"
},
{
"code": null,
"e": 21293,
"s": 21267,
"text": "\nClass 10 Maths Solution\n"
},
{
"code": null,
"e": 21319,
"s": 21293,
"text": "\nClass 11 Maths Solution\n"
},
{
"code": null,
"e": 21345,
"s": 21319,
"text": "\nClass 12 Maths Solution\n"
},
{
"code": null,
"e": 21462,
"s": 21345,
"text": "\nPhysics Notes (Class 8-11)\n \n\n\nClass 8 Notes\n\nClass 9 Notes\n\nClass 10 Notes\n\nClass 11 Notes\n"
},
{
"code": null,
"e": 21478,
"s": 21462,
"text": "\nClass 8 Notes\n"
},
{
"code": null,
"e": 21494,
"s": 21478,
"text": "\nClass 9 Notes\n"
},
{
"code": null,
"e": 21511,
"s": 21494,
"text": "\nClass 10 Notes\n"
},
{
"code": null,
"e": 21528,
"s": 21511,
"text": "\nClass 11 Notes\n"
},
{
"code": null,
"e": 21570,
"s": 21528,
"text": "\nCS Exams/PSUs\n \n\n"
},
{
"code": null,
"e": 21715,
"s": 21570,
"text": "\nISRO\n \n\n\nISRO CS Original Papers and Official Keys\n\nISRO CS Solved Papers\n\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21759,
"s": 21715,
"text": "\nISRO CS Original Papers and Official Keys\n"
},
{
"code": null,
"e": 21783,
"s": 21759,
"text": "\nISRO CS Solved Papers\n"
},
{
"code": null,
"e": 21830,
"s": 21783,
"text": "\nISRO CS Syllabus for Scientist/Engineer Exam\n"
},
{
"code": null,
"e": 21947,
"s": 21830,
"text": "\nUGC NET\n \n\n\nUGC NET CS Notes Paper II\n\nUGC NET CS Notes Paper III\n\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 21975,
"s": 21947,
"text": "\nUGC NET CS Notes Paper II\n"
},
{
"code": null,
"e": 22004,
"s": 21975,
"text": "\nUGC NET CS Notes Paper III\n"
},
{
"code": null,
"e": 22031,
"s": 22004,
"text": "\nUGC NET CS Solved Papers\n"
},
{
"code": null,
"e": 22288,
"s": 22031,
"text": "\nStudent\n \n\n\nCampus Ambassador Program\n\nSchool Ambassador Program\n\nProject\n\nGeek of the Month\n\nCampus Geek of the Month\n\nPlacement Course\n\nCompetititve Programming\n\nTestimonials\n\nStudent Chapter\n\nGeek on the Top\n\nInternship\n\nCareers\n"
},
{
"code": null,
"e": 22316,
"s": 22288,
"text": "\nCampus Ambassador Program\n"
},
{
"code": null,
"e": 22344,
"s": 22316,
"text": "\nSchool Ambassador Program\n"
},
{
"code": null,
"e": 22354,
"s": 22344,
"text": "\nProject\n"
},
{
"code": null,
"e": 22374,
"s": 22354,
"text": "\nGeek of the Month\n"
},
{
"code": null,
"e": 22401,
"s": 22374,
"text": "\nCampus Geek of the Month\n"
},
{
"code": null,
"e": 22420,
"s": 22401,
"text": "\nPlacement Course\n"
},
{
"code": null,
"e": 22447,
"s": 22420,
"text": "\nCompetititve Programming\n"
},
{
"code": null,
"e": 22462,
"s": 22447,
"text": "\nTestimonials\n"
},
{
"code": null,
"e": 22480,
"s": 22462,
"text": "\nStudent Chapter\n"
},
{
"code": null,
"e": 22498,
"s": 22480,
"text": "\nGeek on the Top\n"
},
{
"code": null,
"e": 22511,
"s": 22498,
"text": "\nInternship\n"
},
{
"code": null,
"e": 22521,
"s": 22511,
"text": "\nCareers\n"
},
{
"code": null,
"e": 22679,
"s": 22521,
"text": "\nCurated DSA Lists\n \n\n\nTop 50 Array Problems\n\nTop 50 String Problems\n\nTop 50 Tree Problems\n\nTop 50 Graph Problems\n\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22703,
"s": 22679,
"text": "\nTop 50 Array Problems\n"
},
{
"code": null,
"e": 22728,
"s": 22703,
"text": "\nTop 50 String Problems\n"
},
{
"code": null,
"e": 22751,
"s": 22728,
"text": "\nTop 50 Tree Problems\n"
},
{
"code": null,
"e": 22775,
"s": 22751,
"text": "\nTop 50 Graph Problems\n"
},
{
"code": null,
"e": 22796,
"s": 22775,
"text": "\nTop 50 DP Problems\n"
},
{
"code": null,
"e": 22834,
"s": 22796,
"text": "\nTutorials\n \n\n"
},
{
"code": null,
"e": 22907,
"s": 22834,
"text": "\nJobs\n \n\n\nApply for Jobs\n\nPost a Job\n\nJOB-A-THON\n"
},
{
"code": null,
"e": 22924,
"s": 22907,
"text": "\nApply for Jobs\n"
},
{
"code": null,
"e": 22937,
"s": 22924,
"text": "\nPost a Job\n"
},
{
"code": null,
"e": 22950,
"s": 22937,
"text": "\nJOB-A-THON\n"
},
{
"code": null,
"e": 23136,
"s": 22950,
"text": "\nPractice\n \n\n\nAll DSA Problems\n\nProblem of the Day\n\nInterview Series: Weekly Contests\n\nBi-Wizard Coding: School Contests\n\nContests and Events\n\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23155,
"s": 23136,
"text": "\nAll DSA Problems\n"
},
{
"code": null,
"e": 23176,
"s": 23155,
"text": "\nProblem of the Day\n"
},
{
"code": null,
"e": 23212,
"s": 23176,
"text": "\nInterview Series: Weekly Contests\n"
},
{
"code": null,
"e": 23248,
"s": 23212,
"text": "\nBi-Wizard Coding: School Contests\n"
},
{
"code": null,
"e": 23270,
"s": 23248,
"text": "\nContests and Events\n"
},
{
"code": null,
"e": 23291,
"s": 23270,
"text": "\nPractice SDE Sheet\n"
},
{
"code": null,
"e": 23297,
"s": 23291,
"text": "GBlog"
},
{
"code": null,
"e": 23305,
"s": 23297,
"text": "Puzzles"
},
{
"code": null,
"e": 23318,
"s": 23305,
"text": "What's New ?"
},
{
"code": null,
"e": 23324,
"s": 23318,
"text": "Array"
},
{
"code": null,
"e": 23331,
"s": 23324,
"text": "Matrix"
},
{
"code": null,
"e": 23339,
"s": 23331,
"text": "Strings"
},
{
"code": null,
"e": 23347,
"s": 23339,
"text": "Hashing"
},
{
"code": null,
"e": 23359,
"s": 23347,
"text": "Linked List"
},
{
"code": null,
"e": 23365,
"s": 23359,
"text": "Stack"
},
{
"code": null,
"e": 23371,
"s": 23365,
"text": "Queue"
},
{
"code": null,
"e": 23383,
"s": 23371,
"text": "Binary Tree"
},
{
"code": null,
"e": 23402,
"s": 23383,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 23407,
"s": 23402,
"text": "Heap"
},
{
"code": null,
"e": 23413,
"s": 23407,
"text": "Graph"
},
{
"code": null,
"e": 23423,
"s": 23413,
"text": "Searching"
},
{
"code": null,
"e": 23431,
"s": 23423,
"text": "Sorting"
},
{
"code": null,
"e": 23448,
"s": 23431,
"text": "Divide & Conquer"
},
{
"code": null,
"e": 23461,
"s": 23448,
"text": "Mathematical"
},
{
"code": null,
"e": 23471,
"s": 23461,
"text": "Geometric"
},
{
"code": null,
"e": 23479,
"s": 23471,
"text": "Bitwise"
},
{
"code": null,
"e": 23486,
"s": 23479,
"text": "Greedy"
},
{
"code": null,
"e": 23499,
"s": 23486,
"text": "Backtracking"
},
{
"code": null,
"e": 23516,
"s": 23499,
"text": "Branch and Bound"
},
{
"code": null,
"e": 23536,
"s": 23516,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 23554,
"s": 23536,
"text": "Pattern Searching"
},
{
"code": null,
"e": 23565,
"s": 23554,
"text": "Randomized"
},
{
"code": null,
"e": 23618,
"s": 23565,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 23681,
"s": 23618,
"text": "Print all paths from a given source to a destination using BFS"
},
{
"code": null,
"e": 23737,
"s": 23681,
"text": "Minimum number of edges between two vertices of a Graph"
},
{
"code": null,
"e": 23791,
"s": 23737,
"text": "Count nodes within K-distance from all nodes in a set"
},
{
"code": null,
"e": 23812,
"s": 23791,
"text": "Bidirectional Search"
},
{
"code": null,
"e": 23850,
"s": 23812,
"text": "Minimum edge reversals to make a root"
},
{
"code": null,
"e": 23877,
"s": 23850,
"text": "BFS for Disconnected Graph"
},
{
"code": null,
"e": 23910,
"s": 23877,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 23952,
"s": 23910,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 24001,
"s": 23952,
"text": "Warnsdorffβs algorithm for Knightβs tour problem"
},
{
"code": null,
"e": 24044,
"s": 24001,
"text": "The Knightβs tour problem | Backtracking-1"
},
{
"code": null,
"e": 24075,
"s": 24044,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 24127,
"s": 24075,
"text": "Count number of ways to reach destination in a Maze"
},
{
"code": null,
"e": 24198,
"s": 24127,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 24269,
"s": 24198,
"text": "Print all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 24307,
"s": 24269,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 24377,
"s": 24307,
"text": "Unique paths covering every non-obstacle block exactly once in a grid"
},
{
"code": null,
"e": 24415,
"s": 24377,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 24455,
"s": 24415,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 24489,
"s": 24455,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 24539,
"s": 24489,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 24580,
"s": 24539,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 24640,
"s": 24580,
"text": "Inorder Tree Traversal without recursion and without stack!"
},
{
"code": null,
"e": 24709,
"s": 24640,
"text": "Print Postorder traversal from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 24767,
"s": 24709,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 24818,
"s": 24767,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 24848,
"s": 24818,
"text": "Graph and its representations"
},
{
"code": null,
"e": 24899,
"s": 24848,
"text": "Primβs Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 24952,
"s": 24899,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 25015,
"s": 24952,
"text": "Print all paths from a given source to a destination using BFS"
},
{
"code": null,
"e": 25071,
"s": 25015,
"text": "Minimum number of edges between two vertices of a Graph"
},
{
"code": null,
"e": 25125,
"s": 25071,
"text": "Count nodes within K-distance from all nodes in a set"
},
{
"code": null,
"e": 25146,
"s": 25125,
"text": "Bidirectional Search"
},
{
"code": null,
"e": 25184,
"s": 25146,
"text": "Minimum edge reversals to make a root"
},
{
"code": null,
"e": 25211,
"s": 25184,
"text": "BFS for Disconnected Graph"
},
{
"code": null,
"e": 25244,
"s": 25211,
"text": "N Queen Problem | Backtracking-3"
},
{
"code": null,
"e": 25286,
"s": 25244,
"text": "Printing all solutions in N-Queen Problem"
},
{
"code": null,
"e": 25335,
"s": 25286,
"text": "Warnsdorffβs algorithm for Knightβs tour problem"
},
{
"code": null,
"e": 25378,
"s": 25335,
"text": "The Knightβs tour problem | Backtracking-1"
},
{
"code": null,
"e": 25409,
"s": 25378,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 25461,
"s": 25409,
"text": "Count number of ways to reach destination in a Maze"
},
{
"code": null,
"e": 25532,
"s": 25461,
"text": "Count all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 25603,
"s": 25532,
"text": "Print all possible paths from top left to bottom right of a mXn matrix"
},
{
"code": null,
"e": 25641,
"s": 25603,
"text": "Unique paths in a Grid with Obstacles"
},
{
"code": null,
"e": 25711,
"s": 25641,
"text": "Unique paths covering every non-obstacle block exactly once in a grid"
},
{
"code": null,
"e": 25749,
"s": 25711,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 25789,
"s": 25749,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 25823,
"s": 25789,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 25873,
"s": 25823,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 25914,
"s": 25873,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 25974,
"s": 25914,
"text": "Inorder Tree Traversal without recursion and without stack!"
},
{
"code": null,
"e": 26043,
"s": 25974,
"text": "Print Postorder traversal from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 26101,
"s": 26043,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 26152,
"s": 26101,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 26182,
"s": 26152,
"text": "Graph and its representations"
},
{
"code": null,
"e": 26233,
"s": 26182,
"text": "Primβs Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 26257,
"s": 26233,
"text": "Difficulty Level :\nHard"
},
{
"code": null,
"e": 26761,
"s": 26257,
"text": "Searching a graph is quite famous problem and have a lot of practical use. We have already discussed here how to search for a goal vertex starting from a source vertex using BFS. In normal graph search using BFS/DFS we begin our search in one direction usually from source vertex toward the goal vertex, but what if we start search from both direction simultaneously.Bidirectional search is a graph search algorithm which find smallest path from source to goal vertex. It runs two simultaneous search β "
},
{
"code": null,
"e": 26882,
"s": 26761,
"text": "Forward search from source/initial vertex toward goal vertexBackward search from goal/target vertex toward source vertex"
},
{
"code": null,
"e": 26943,
"s": 26882,
"text": "Forward search from source/initial vertex toward goal vertex"
},
{
"code": null,
"e": 27004,
"s": 26943,
"text": "Backward search from goal/target vertex toward source vertex"
},
{
"code": null,
"e": 27453,
"s": 27004,
"text": "Bidirectional search replaces single search graph(which is likely to grow exponentially) with two smaller sub graphs β one starting from initial vertex and other starting from goal vertex. The search terminates when two graphs intersect.Just like A* algorithm, bidirectional search can be guided by a heuristic estimate of remaining distance from source to goal and vice versa for finding shortest path possible.Consider following simple example- "
},
{
"code": null,
"e": 27828,
"s": 27453,
"text": "Suppose we want to find if there exists a path from vertex 0 to vertex 14. Here we can execute two searches, one from vertex 0 and other from vertex 14. When both forward and backward search meet at vertex 7, we know that we have found a path from node 0 to 14 and search can be terminated now. We can clearly see that we have successfully avoided unnecessary exploration. "
},
{
"code": null,
"e": 27856,
"s": 27828,
"text": "Why bidirectional approach?"
},
{
"code": null,
"e": 28280,
"s": 27856,
"text": "Because in many cases it is faster, it dramatically reduce the amount of required exploration. Suppose if branching factor of tree is b and distance of goal vertex from source is d, then the normal BFS/DFS searching complexity would be O(bd). On the other hand, if we execute two search operation then the complexity would be O(bd/2) for each search and total complexity would be O(bd/2 +bd/2) which is far less than O(bd)."
},
{
"code": null,
"e": 28316,
"s": 28280,
"text": "When to use bidirectional approach?"
},
{
"code": null,
"e": 28362,
"s": 28316,
"text": "We can consider bidirectional approach when- "
},
{
"code": null,
"e": 28486,
"s": 28362,
"text": "Both initial and goal states are unique and completely defined.The branching factor is exactly the same in both directions."
},
{
"code": null,
"e": 28550,
"s": 28486,
"text": "Both initial and goal states are unique and completely defined."
},
{
"code": null,
"e": 28611,
"s": 28550,
"text": "The branching factor is exactly the same in both directions."
},
{
"code": null,
"e": 28632,
"s": 28611,
"text": "Performance measures"
},
{
"code": null,
"e": 28713,
"s": 28632,
"text": "Completeness : Bidirectional search is complete if BFS is used in both searches."
},
{
"code": null,
"e": 28795,
"s": 28713,
"text": "Optimality : It is optimal if BFS is used for search and paths have uniform cost."
},
{
"code": null,
"e": 28861,
"s": 28795,
"text": "Time and Space Complexity : Time and space complexity is O(bd/2)."
},
{
"code": null,
"e": 29025,
"s": 28861,
"text": "Below is very simple implementation representing the concept of bidirectional search using BFS. This implementation considers undirected paths without any weight. "
},
{
"code": null,
"e": 29029,
"s": 29025,
"text": "C++"
},
{
"code": null,
"e": 29037,
"s": 29029,
"text": "Python3"
},
{
"code": "// C++ program for Bidirectional BFS search// to check path between two vertices#include <bits/stdc++.h>using namespace std; // class representing undirected graph// using adjacency listclass Graph{ //number of nodes in graph int V; // Adjacency list list<int> *adj;public: Graph(int V); int isIntersecting(bool *s_visited, bool *t_visited); void addEdge(int u, int v); void printPath(int *s_parent, int *t_parent, int s, int t, int intersectNode); void BFS(list<int> *queue, bool *visited, int *parent); int biDirSearch(int s, int t);}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];}; // Method for adding undirected edgevoid Graph::addEdge(int u, int v){ this->adj[u].push_back(v); this->adj[v].push_back(u);}; // Method for Breadth First Searchvoid Graph::BFS(list<int> *queue, bool *visited, int *parent){ int current = queue->front(); queue->pop_front(); list<int>::iterator i; for (i=adj[current].begin();i != adj[current].end();i++) { // If adjacent vertex is not visited earlier // mark it visited by assigning true value if (!visited[*i]) { // set current as parent of this vertex parent[*i] = current; // Mark this vertex visited visited[*i] = true; // Push to the end of queue queue->push_back(*i); } }}; // check for intersecting vertexint Graph::isIntersecting(bool *s_visited, bool *t_visited){ int intersectNode = -1; for(int i=0;i<V;i++) { // if a vertex is visited by both front // and back BFS search return that node // else return -1 if(s_visited[i] && t_visited[i]) return i; } return -1;}; // Print the path from source to targetvoid Graph::printPath(int *s_parent, int *t_parent, int s, int t, int intersectNode){ vector<int> path; path.push_back(intersectNode); int i = intersectNode; while (i != s) { path.push_back(s_parent[i]); i = s_parent[i]; } reverse(path.begin(), path.end()); i = intersectNode; while(i != t) { path.push_back(t_parent[i]); i = t_parent[i]; } vector<int>::iterator it; cout<<\"*****Path*****\\n\"; for(it = path.begin();it != path.end();it++) cout<<*it<<\" \"; cout<<\"\\n\";}; // Method for bidirectional searchingint Graph::biDirSearch(int s, int t){ // boolean array for BFS started from // source and target(front and backward BFS) // for keeping track on visited nodes bool s_visited[V], t_visited[V]; // Keep track on parents of nodes // for front and backward search int s_parent[V], t_parent[V]; // queue for front and backward search list<int> s_queue, t_queue; int intersectNode = -1; // necessary initialization for(int i=0; i<V; i++) { s_visited[i] = false; t_visited[i] = false; } s_queue.push_back(s); s_visited[s] = true; // parent of source is set to -1 s_parent[s]=-1; t_queue.push_back(t); t_visited[t] = true; // parent of target is set to -1 t_parent[t] = -1; while (!s_queue.empty() && !t_queue.empty()) { // Do BFS from source and target vertices BFS(&s_queue, s_visited, s_parent); BFS(&t_queue, t_visited, t_parent); // check for intersecting vertex intersectNode = isIntersecting(s_visited, t_visited); // If intersecting vertex is found // that means there exist a path if(intersectNode != -1) { cout << \"Path exist between \" << s << \" and \" << t << \"\\n\"; cout << \"Intersection at: \" << intersectNode << \"\\n\"; // print the path and exit the program printPath(s_parent, t_parent, s, t, intersectNode); exit(0); } } return -1;} // Driver codeint main(){ // no of vertices in graph int n=15; // source vertex int s=0; // target vertex int t=14; // create a graph given in above diagram Graph g(n); g.addEdge(0, 4); g.addEdge(1, 4); g.addEdge(2, 5); g.addEdge(3, 5); g.addEdge(4, 6); g.addEdge(5, 6); g.addEdge(6, 7); g.addEdge(7, 8); g.addEdge(8, 9); g.addEdge(8, 10); g.addEdge(9, 11); g.addEdge(9, 12); g.addEdge(10, 13); g.addEdge(10, 14); if (g.biDirSearch(s, t) == -1) cout << \"Path don't exist between \" << s << \" and \" << t << \"\\n\"; return 0;}",
"e": 33583,
"s": 29037,
"text": null
},
{
"code": "# Python3 program for Bidirectional BFS# Search to check path between two vertices # Class definition for node to# be added to graphclass AdjacentNode: def __init__(self, vertex): self.vertex = vertex self.next = None # BidirectionalSearch implementationclass BidirectionalSearch: def __init__(self, vertices): # Initialize vertices and # graph with vertices self.vertices = vertices self.graph = [None] * self.vertices # Initializing queue for forward # and backward search self.src_queue = list() self.dest_queue = list() # Initializing source and # destination visited nodes as False self.src_visited = [False] * self.vertices self.dest_visited = [False] * self.vertices # Initializing source and destination # parent nodes self.src_parent = [None] * self.vertices self.dest_parent = [None] * self.vertices # Function for adding undirected edge def add_edge(self, src, dest): # Add edges to graph # Add source to destination node = AdjacentNode(dest) node.next = self.graph[src] self.graph[src] = node # Since graph is undirected add # destination to source node = AdjacentNode(src) node.next = self.graph[dest] self.graph[dest] = node # Function for Breadth First Search def bfs(self, direction = 'forward'): if direction == 'forward': # BFS in forward direction current = self.src_queue.pop(0) connected_node = self.graph[current] while connected_node: vertex = connected_node.vertex if not self.src_visited[vertex]: self.src_queue.append(vertex) self.src_visited[vertex] = True self.src_parent[vertex] = current connected_node = connected_node.next else: # BFS in backward direction current = self.dest_queue.pop(0) connected_node = self.graph[current] while connected_node: vertex = connected_node.vertex if not self.dest_visited[vertex]: self.dest_queue.append(vertex) self.dest_visited[vertex] = True self.dest_parent[vertex] = current connected_node = connected_node.next # Check for intersecting vertex def is_intersecting(self): # Returns intersecting node # if present else -1 for i in range(self.vertices): if (self.src_visited[i] and self.dest_visited[i]): return i return -1 # Print the path from source to target def print_path(self, intersecting_node, src, dest): # Print final path from # source to destination path = list() path.append(intersecting_node) i = intersecting_node while i != src: path.append(self.src_parent[i]) i = self.src_parent[i] path = path[::-1] i = intersecting_node while i != dest: path.append(self.dest_parent[i]) i = self.dest_parent[i] print(\"*****Path*****\") path = list(map(str, path)) print(' '.join(path)) # Function for bidirectional searching def bidirectional_search(self, src, dest): # Add source to queue and mark # visited as True and add its # parent as -1 self.src_queue.append(src) self.src_visited[src] = True self.src_parent[src] = -1 # Add destination to queue and # mark visited as True and add # its parent as -1 self.dest_queue.append(dest) self.dest_visited[dest] = True self.dest_parent[dest] = -1 while self.src_queue and self.dest_queue: # BFS in forward direction from # Source Vertex self.bfs(direction = 'forward') # BFS in reverse direction # from Destination Vertex self.bfs(direction = 'backward') # Check for intersecting vertex intersecting_node = self.is_intersecting() # If intersecting vertex exists # then path from source to # destination exists if intersecting_node != -1: print(f\"Path exists between {src} and {dest}\") print(f\"Intersection at : {intersecting_node}\") self.print_path(intersecting_node, src, dest) exit(0) return -1 # Driver codeif __name__ == '__main__': # Number of Vertices in graph n = 15 # Source Vertex src = 0 # Destination Vertex dest = 14 # Create a graph graph = BidirectionalSearch(n) graph.add_edge(0, 4) graph.add_edge(1, 4) graph.add_edge(2, 5) graph.add_edge(3, 5) graph.add_edge(4, 6) graph.add_edge(5, 6) graph.add_edge(6, 7) graph.add_edge(7, 8) graph.add_edge(8, 9) graph.add_edge(8, 10) graph.add_edge(9, 11) graph.add_edge(9, 12) graph.add_edge(10, 13) graph.add_edge(10, 14) out = graph.bidirectional_search(src, dest) if out == -1: print(f\"Path does not exist between {src} and {dest}\") # This code is contributed by Nirjhari Jankar",
"e": 39347,
"s": 33583,
"text": null
},
{
"code": null,
"e": 39356,
"s": 39347,
"text": "Output: "
},
{
"code": null,
"e": 39435,
"s": 39356,
"text": "Path exist between 0 and 14\nIntersection at: 7\n*****Path*****\n0 4 6 7 8 10 14 "
},
{
"code": null,
"e": 39447,
"s": 39435,
"text": "References "
},
{
"code": null,
"e": 39498,
"s": 39447,
"text": "https://en.wikipedia.org/wiki/Bidirectional_search"
},
{
"code": null,
"e": 39917,
"s": 39498,
"text": "This article is contributed by Atul Kumar. 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.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 39933,
"s": 39917,
"text": "nirjhari jankar"
},
{
"code": null,
"e": 39945,
"s": 39933,
"text": "prathibar03"
},
{
"code": null,
"e": 39949,
"s": 39945,
"text": "BFS"
},
{
"code": null,
"e": 39955,
"s": 39949,
"text": "Graph"
},
{
"code": null,
"e": 39961,
"s": 39955,
"text": "Graph"
},
{
"code": null,
"e": 39965,
"s": 39961,
"text": "BFS"
},
{
"code": null,
"e": 40063,
"s": 39965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40121,
"s": 40063,
"text": "Kruskalβs Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 40141,
"s": 40121,
"text": "Topological Sorting"
},
{
"code": null,
"e": 40172,
"s": 40141,
"text": "BellmanβFord Algorithm | DP-23"
},
{
"code": null,
"e": 40205,
"s": 40172,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 40238,
"s": 40205,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 40306,
"s": 40238,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 40356,
"s": 40306,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 40431,
"s": 40356,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 40461,
"s": 40431,
"text": "Strongly Connected Components"
}
] |
Replacing Element in Java Vector - GeeksforGeeks
|
11 Dec, 2020
To replace an element in Java Vector, set() method of java.util.Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of a Vector is zero-based. So, to replace the first element, 0 should be the index passed as parameter.
Declaration:
public Object set(int index, Object element)
Return Value:
The element which is at the specified index
Exception Throws:
IndexOutOfBoundsException
when the index is out of range
i.e, index < 0 or index >= size()
Implementation:
Java
// Replacing Element in Java Vectorimport java.util.Vector;public class Sias { public static void main(String args[]) { try { // create a instance vector Vector<Integer> vector = new Vector<>(); // insert the values in vector vector.add(1); vector.add(2); vector.add(3); vector.add(4); vector.add(5); // display the vector System.out.println("original vector : " + vector); // call set() and replace 2 index value vector.set(2, 10); // display vector after replacing value System.out.println("after replace the value : " + vector); // call set() and replace 9th index value // which is exception as arrayoutofbound vector.set(9, 91); // display vector after replacing value System.out.println("after replace the value : " + vector); } catch (Exception e) { System.out.println(e); } }}
original vector : [1, 2, 3, 4, 5]
after replace the value : [1, 2, 10, 4, 5]
java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9
Time Complexity: O(n), where n is the length of the vector
Java-Vector
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25535,
"s": 25507,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 25850,
"s": 25535,
"text": "To replace an element in Java Vector, set() method of java.util.Vector class can be used. The set() method takes two parameters-the indexes of the element which has to be replaced and the new element. The index of a Vector is zero-based. So, to replace the first element, 0 should be the index passed as parameter."
},
{
"code": null,
"e": 25863,
"s": 25850,
"text": "Declaration:"
},
{
"code": null,
"e": 25909,
"s": 25863,
"text": " public Object set(int index, Object element)"
},
{
"code": null,
"e": 25924,
"s": 25909,
"text": "Return Value: "
},
{
"code": null,
"e": 25968,
"s": 25924,
"text": "The element which is at the specified index"
},
{
"code": null,
"e": 25986,
"s": 25968,
"text": "Exception Throws:"
},
{
"code": null,
"e": 26079,
"s": 25986,
"text": "IndexOutOfBoundsException \nwhen the index is out of range \ni.e, index < 0 or index >= size()"
},
{
"code": null,
"e": 26095,
"s": 26079,
"text": "Implementation:"
},
{
"code": null,
"e": 26100,
"s": 26095,
"text": "Java"
},
{
"code": "// Replacing Element in Java Vectorimport java.util.Vector;public class Sias { public static void main(String args[]) { try { // create a instance vector Vector<Integer> vector = new Vector<>(); // insert the values in vector vector.add(1); vector.add(2); vector.add(3); vector.add(4); vector.add(5); // display the vector System.out.println(\"original vector : \" + vector); // call set() and replace 2 index value vector.set(2, 10); // display vector after replacing value System.out.println(\"after replace the value : \" + vector); // call set() and replace 9th index value // which is exception as arrayoutofbound vector.set(9, 91); // display vector after replacing value System.out.println(\"after replace the value : \" + vector); } catch (Exception e) { System.out.println(e); } }}",
"e": 27244,
"s": 26100,
"text": null
},
{
"code": null,
"e": 27392,
"s": 27244,
"text": "original vector : [1, 2, 3, 4, 5]\nafter replace the value : [1, 2, 10, 4, 5]\njava.lang.ArrayIndexOutOfBoundsException: Array index out of range: 9\n"
},
{
"code": null,
"e": 27451,
"s": 27392,
"text": "Time Complexity: O(n), where n is the length of the vector"
},
{
"code": null,
"e": 27463,
"s": 27451,
"text": "Java-Vector"
},
{
"code": null,
"e": 27470,
"s": 27463,
"text": "Picked"
},
{
"code": null,
"e": 27475,
"s": 27470,
"text": "Java"
},
{
"code": null,
"e": 27489,
"s": 27475,
"text": "Java Programs"
},
{
"code": null,
"e": 27494,
"s": 27489,
"text": "Java"
},
{
"code": null,
"e": 27592,
"s": 27494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27607,
"s": 27592,
"text": "Stream In Java"
},
{
"code": null,
"e": 27626,
"s": 27607,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27644,
"s": 27626,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27676,
"s": 27644,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27696,
"s": 27676,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27724,
"s": 27696,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 27768,
"s": 27724,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 27794,
"s": 27768,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 27828,
"s": 27794,
"text": "Convert Double to Integer in Java"
}
] |
Microsoft Azure - CPU and Memory Utilization of Azure VMs in a Single Table Chart - GeeksforGeeks
|
16 Dec, 2021
In this article, you will see that how you can analyze your azure virtual machineβs performance of both CPU Utilization and Memory Utilization at once using azure log queries. These KQL queries will help you to understand all the Azure VMs Performance in the form of a table chart and this will also allow you to export the data in the CSV file.
With this data, you can easily analyze, which servers need to be resized for scaling up (increasing the size) or scaling down (decreasing the size).
You can analyze the VMs in Seconds.
Easy to filter the VMs
Easy to filter log data by using the conditions.
Easy to Analyse the performance between time range (Example like 7 Days, 15 Days, 2 Months, 2 Hours, 12 Hours,...etc)
Allows us to Export the data in CSV for future reference for past performance.
Step 1: Login to Azure Portal.
Step 2: Go to Log Analytics Workspace >> Navigate to General Section from left menu >> Select Logs
Paste the below following KQL Query to get the Consolidated CPU and Memory Utilization in a Single Table Chart
VM CPU Utilization and MEMORY Utilization β across all the computers by OS Type equals βWindows/Linuxβ from the select scope
Perf
| where ObjectName == "Processor" and CounterName == "% Processor Time" and InstanceName == "_Total"
| where Computer in ((Heartbeat | where OSType == "Linux" or OSType == "Windows" | distinct Computer))
| summarize MIN_CPU = min(CounterValue), AVG_CPU = avg(CounterValue), MAX_CPU = max(CounterValue) by Computer
| join
(
Perf
| where ObjectName == "Memory"
| where CounterName == "% Used Memory" or CounterName == "% Committed Bytes In Use"
| summarize MIN_MEM = min(CounterValue), AVG_MEM = avg(CounterValue), MAX_MEM = max(CounterValue) by Computer
) on Computer
| project Computer, MIN_CPU, AVG_CPU, MAX_CPU, MIN_MEM, AVG_MEM, MAX_MEM
Output:
Note: You can download the table data in the form of CSV by clicking on Export
Example 1: To filter the solution based on Average CPU Utilization greater than 50%
Perf
| where ObjectName == "Processor" and CounterName == "% Processor Time" and InstanceName == "_Total"
| where Computer in ((Heartbeat | where OSType == "Linux" or OSType == "Windows" | distinct Computer))
| summarize MIN_CPU = min(CounterValue), AVG_CPU = avg(CounterValue), MAX_CPU = max(CounterValue) by Computer
| join
(
Perf
| where ObjectName == "Memory"
| where CounterName == "% Used Memory" or CounterName == "% Committed Bytes In Use"
| summarize MIN_MEM = min(CounterValue), AVG_MEM = avg(CounterValue), MAX_MEM = max(CounterValue) by Computer
) on Computer
| project Computer, MIN_CPU, AVG_CPU, MAX_CPU, MIN_MEM, AVG_MEM, MAX_MEM
| where AVG_CPU > 50
Output:
Example 2: To filter the solution based on Average CPU Utilization greater than 50% and Average Memory Utilization greater than 50 %. While we are using and in the query, the condition should satisfy both the conditions.
Perf
| where ObjectName == "Processor" and CounterName == "% Processor Time" and InstanceName == "_Total"
| where Computer in ((Heartbeat | where OSType == "Linux" or OSType == "Windows" | distinct Computer))
| summarize MIN_CPU = min(CounterValue), AVG_CPU = avg(CounterValue), MAX_CPU = max(CounterValue) by Computer
| join
(
Perf
| where ObjectName == "Memory"
| where CounterName == "% Used Memory" or CounterName == "% Committed Bytes In Use"
| summarize MIN_MEM = min(CounterValue), AVG_MEM = avg(CounterValue), MAX_MEM = max(CounterValue) by Computer
) on Computer
| project Computer, MIN_CPU, AVG_CPU, MAX_CPU, MIN_MEM, AVG_MEM, MAX_MEM
| where AVG_CPU > 50 and AVG_MEM > 50
Output:
azure-virtual-machine
Cloud-Computing
Microsoft Azure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Microsoft Azure - Azure Firewall Flow Logs From Select Source IP
Microsoft Azure - KQL Query to Get the VM Computer Properties
Microsoft Azure - Check Status of Azure VM using Azure PowerShell
Defense in Depth Strategy in Microsoft Azure
Microsoft Azure - Graph Query to Get Properties of Azure VM Resource
Microsoft Azure - Resource Tagging and Best Practices
Microsoft Azure - Find and Delete Orphaned Public IP addresses in Azure Portal
Microsoft Azure - Query System Event Log Data Using Azure KQL
Microsoft Azure - Rebooting an Application Gateway
Microsoft Azure - Get Azure VM Properties using Azure PowerShell
|
[
{
"code": null,
"e": 26939,
"s": 26911,
"text": "\n16 Dec, 2021"
},
{
"code": null,
"e": 27286,
"s": 26939,
"text": "In this article, you will see that how you can analyze your azure virtual machineβs performance of both CPU Utilization and Memory Utilization at once using azure log queries. These KQL queries will help you to understand all the Azure VMs Performance in the form of a table chart and this will also allow you to export the data in the CSV file. "
},
{
"code": null,
"e": 27435,
"s": 27286,
"text": "With this data, you can easily analyze, which servers need to be resized for scaling up (increasing the size) or scaling down (decreasing the size)."
},
{
"code": null,
"e": 27471,
"s": 27435,
"text": "You can analyze the VMs in Seconds."
},
{
"code": null,
"e": 27494,
"s": 27471,
"text": "Easy to filter the VMs"
},
{
"code": null,
"e": 27543,
"s": 27494,
"text": "Easy to filter log data by using the conditions."
},
{
"code": null,
"e": 27661,
"s": 27543,
"text": "Easy to Analyse the performance between time range (Example like 7 Days, 15 Days, 2 Months, 2 Hours, 12 Hours,...etc)"
},
{
"code": null,
"e": 27740,
"s": 27661,
"text": "Allows us to Export the data in CSV for future reference for past performance."
},
{
"code": null,
"e": 27771,
"s": 27740,
"text": "Step 1: Login to Azure Portal."
},
{
"code": null,
"e": 27870,
"s": 27771,
"text": "Step 2: Go to Log Analytics Workspace >> Navigate to General Section from left menu >> Select Logs"
},
{
"code": null,
"e": 27981,
"s": 27870,
"text": "Paste the below following KQL Query to get the Consolidated CPU and Memory Utilization in a Single Table Chart"
},
{
"code": null,
"e": 28106,
"s": 27981,
"text": "VM CPU Utilization and MEMORY Utilization β across all the computers by OS Type equals βWindows/Linuxβ from the select scope"
},
{
"code": null,
"e": 28754,
"s": 28106,
"text": "Perf\n| where ObjectName == \"Processor\" and CounterName == \"% Processor Time\" and InstanceName == \"_Total\"\n| where Computer in ((Heartbeat | where OSType == \"Linux\" or OSType == \"Windows\" | distinct Computer))\n| summarize MIN_CPU = min(CounterValue), AVG_CPU = avg(CounterValue), MAX_CPU = max(CounterValue) by Computer\n| join \n( \nPerf \n| where ObjectName == \"Memory\"\n| where CounterName == \"% Used Memory\" or CounterName == \"% Committed Bytes In Use\"\n| summarize MIN_MEM = min(CounterValue), AVG_MEM = avg(CounterValue), MAX_MEM = max(CounterValue) by Computer\n) on Computer\n| project Computer, MIN_CPU, AVG_CPU, MAX_CPU, MIN_MEM, AVG_MEM, MAX_MEM"
},
{
"code": null,
"e": 28762,
"s": 28754,
"text": "Output:"
},
{
"code": null,
"e": 28842,
"s": 28762,
"text": "Note: You can download the table data in the form of CSV by clicking on Export "
},
{
"code": null,
"e": 28926,
"s": 28842,
"text": "Example 1: To filter the solution based on Average CPU Utilization greater than 50%"
},
{
"code": null,
"e": 29595,
"s": 28926,
"text": "Perf\n| where ObjectName == \"Processor\" and CounterName == \"% Processor Time\" and InstanceName == \"_Total\"\n| where Computer in ((Heartbeat | where OSType == \"Linux\" or OSType == \"Windows\" | distinct Computer))\n| summarize MIN_CPU = min(CounterValue), AVG_CPU = avg(CounterValue), MAX_CPU = max(CounterValue) by Computer\n| join \n( \nPerf \n| where ObjectName == \"Memory\"\n| where CounterName == \"% Used Memory\" or CounterName == \"% Committed Bytes In Use\"\n| summarize MIN_MEM = min(CounterValue), AVG_MEM = avg(CounterValue), MAX_MEM = max(CounterValue) by Computer\n) on Computer\n| project Computer, MIN_CPU, AVG_CPU, MAX_CPU, MIN_MEM, AVG_MEM, MAX_MEM\n| where AVG_CPU > 50"
},
{
"code": null,
"e": 29603,
"s": 29595,
"text": "Output:"
},
{
"code": null,
"e": 29825,
"s": 29603,
"text": "Example 2: To filter the solution based on Average CPU Utilization greater than 50% and Average Memory Utilization greater than 50 %. While we are using and in the query, the condition should satisfy both the conditions."
},
{
"code": null,
"e": 30511,
"s": 29825,
"text": "Perf\n| where ObjectName == \"Processor\" and CounterName == \"% Processor Time\" and InstanceName == \"_Total\"\n| where Computer in ((Heartbeat | where OSType == \"Linux\" or OSType == \"Windows\" | distinct Computer))\n| summarize MIN_CPU = min(CounterValue), AVG_CPU = avg(CounterValue), MAX_CPU = max(CounterValue) by Computer\n| join \n( \nPerf \n| where ObjectName == \"Memory\"\n| where CounterName == \"% Used Memory\" or CounterName == \"% Committed Bytes In Use\"\n| summarize MIN_MEM = min(CounterValue), AVG_MEM = avg(CounterValue), MAX_MEM = max(CounterValue) by Computer\n) on Computer\n| project Computer, MIN_CPU, AVG_CPU, MAX_CPU, MIN_MEM, AVG_MEM, MAX_MEM\n| where AVG_CPU > 50 and AVG_MEM > 50"
},
{
"code": null,
"e": 30519,
"s": 30511,
"text": "Output:"
},
{
"code": null,
"e": 30541,
"s": 30519,
"text": "azure-virtual-machine"
},
{
"code": null,
"e": 30557,
"s": 30541,
"text": "Cloud-Computing"
},
{
"code": null,
"e": 30573,
"s": 30557,
"text": "Microsoft Azure"
},
{
"code": null,
"e": 30671,
"s": 30573,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30736,
"s": 30671,
"text": "Microsoft Azure - Azure Firewall Flow Logs From Select Source IP"
},
{
"code": null,
"e": 30798,
"s": 30736,
"text": "Microsoft Azure - KQL Query to Get the VM Computer Properties"
},
{
"code": null,
"e": 30864,
"s": 30798,
"text": "Microsoft Azure - Check Status of Azure VM using Azure PowerShell"
},
{
"code": null,
"e": 30909,
"s": 30864,
"text": "Defense in Depth Strategy in Microsoft Azure"
},
{
"code": null,
"e": 30978,
"s": 30909,
"text": "Microsoft Azure - Graph Query to Get Properties of Azure VM Resource"
},
{
"code": null,
"e": 31032,
"s": 30978,
"text": "Microsoft Azure - Resource Tagging and Best Practices"
},
{
"code": null,
"e": 31111,
"s": 31032,
"text": "Microsoft Azure - Find and Delete Orphaned Public IP addresses in Azure Portal"
},
{
"code": null,
"e": 31173,
"s": 31111,
"text": "Microsoft Azure - Query System Event Log Data Using Azure KQL"
},
{
"code": null,
"e": 31224,
"s": 31173,
"text": "Microsoft Azure - Rebooting an Application Gateway"
}
] |
A Problem in Many Binary Search Implementations - GeeksforGeeks
|
15 Dec, 2016
Consider the following C implementation of Binary Search function, is there anything wrong in this?
// A iterative binary search function. It returns location of x in// given array arr[l..r] if present, otherwise -1int binarySearch(int arr[], int l, int r, int x){ while (l <= r) { // find index of middle element int m = (l+r)/2; // Check if x is present at mid if (arr[m] == x) return m; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } // if we reach here, then element was not present return -1;}
The above looks fine except one subtle thing, the expression βm = (l+r)/2β. It fails for large values of l and r. Specifically, it fails if the sum of low and high is greater than the maximum positive int value (231 β 1). The sum overflows to a negative value, and the value stays negative when divided by two. In C this causes an array index out of bounds with unpredictable results.
What is the way to resolve this problem?Following is one way:
int mid = low + ((high - low) / 2);
Probably faster, and arguably as clear is (works only in Java, refer this):
int mid = (low + high) >>> 1;
In C and C++ (where you donβt have the >>> operator), you can do this:
mid = ((unsigned int)low + (unsigned int)high)) >> 1
The similar problem appears in Merge Sort as well.
The above content is taken from google reasearch blog.
Please refer this as well, it points out that the above solutions may not always work.
The above problem occurs when array length is 230 or greater and the search repeatedly moves to second half of the array. This much size of array is not likely to appear most of the time. For example, when we try the below program with 32 bit Code Blocks compiler, we get compiler error.
int main(){ int arr[1<<30]; return 0;}
Output:
error: size of array 'arr' is too large
Even when we try boolean array, the program compiles fine, but crashes when run in Windows 7.0 and Code Blocks 32 bit compiler
#include <stdbool.h>int main(){ bool arr[1<<30]; return 0;}
Output: No compiler error, but crashes at run time.
Sources:http://googleresearch.blogspot.in/2006/06/extra-extra-read-all-about-it-nearly.htmlhttp://locklessinc.com/articles/binary_search/
This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Binary Search
Searching
Searching
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Search an element in a sorted and rotated array
Given an array of size n and a number k, find all elements that appear more than n/k times
k largest(or smallest) elements in an array
Median of two sorted arrays of different sizes
Find the index of an array element in Java
Two Pointers Technique
Count number of occurrences (or frequency) in a sorted array
Most frequent element in an array
Best First Search (Informed Search)
|
[
{
"code": null,
"e": 25999,
"s": 25971,
"text": "\n15 Dec, 2016"
},
{
"code": null,
"e": 26099,
"s": 25999,
"text": "Consider the following C implementation of Binary Search function, is there anything wrong in this?"
},
{
"code": "// A iterative binary search function. It returns location of x in// given array arr[l..r] if present, otherwise -1int binarySearch(int arr[], int l, int r, int x){ while (l <= r) { // find index of middle element int m = (l+r)/2; // Check if x is present at mid if (arr[m] == x) return m; // If x greater, ignore left half if (arr[m] < x) l = m + 1; // If x is smaller, ignore right half else r = m - 1; } // if we reach here, then element was not present return -1;}",
"e": 26647,
"s": 26099,
"text": null
},
{
"code": null,
"e": 27032,
"s": 26647,
"text": "The above looks fine except one subtle thing, the expression βm = (l+r)/2β. It fails for large values of l and r. Specifically, it fails if the sum of low and high is greater than the maximum positive int value (231 β 1). The sum overflows to a negative value, and the value stays negative when divided by two. In C this causes an array index out of bounds with unpredictable results."
},
{
"code": null,
"e": 27094,
"s": 27032,
"text": "What is the way to resolve this problem?Following is one way:"
},
{
"code": null,
"e": 27139,
"s": 27094,
"text": " int mid = low + ((high - low) / 2); "
},
{
"code": null,
"e": 27215,
"s": 27139,
"text": "Probably faster, and arguably as clear is (works only in Java, refer this):"
},
{
"code": null,
"e": 27254,
"s": 27215,
"text": " int mid = (low + high) >>> 1; "
},
{
"code": null,
"e": 27325,
"s": 27254,
"text": "In C and C++ (where you donβt have the >>> operator), you can do this:"
},
{
"code": null,
"e": 27387,
"s": 27325,
"text": " mid = ((unsigned int)low + (unsigned int)high)) >> 1 "
},
{
"code": null,
"e": 27438,
"s": 27387,
"text": "The similar problem appears in Merge Sort as well."
},
{
"code": null,
"e": 27493,
"s": 27438,
"text": "The above content is taken from google reasearch blog."
},
{
"code": null,
"e": 27580,
"s": 27493,
"text": "Please refer this as well, it points out that the above solutions may not always work."
},
{
"code": null,
"e": 27868,
"s": 27580,
"text": "The above problem occurs when array length is 230 or greater and the search repeatedly moves to second half of the array. This much size of array is not likely to appear most of the time. For example, when we try the below program with 32 bit Code Blocks compiler, we get compiler error."
},
{
"code": "int main(){ int arr[1<<30]; return 0;}",
"e": 27913,
"s": 27868,
"text": null
},
{
"code": null,
"e": 27921,
"s": 27913,
"text": "Output:"
},
{
"code": null,
"e": 27961,
"s": 27921,
"text": "error: size of array 'arr' is too large"
},
{
"code": null,
"e": 28088,
"s": 27961,
"text": "Even when we try boolean array, the program compiles fine, but crashes when run in Windows 7.0 and Code Blocks 32 bit compiler"
},
{
"code": "#include <stdbool.h>int main(){ bool arr[1<<30]; return 0;}",
"e": 28154,
"s": 28088,
"text": null
},
{
"code": null,
"e": 28206,
"s": 28154,
"text": "Output: No compiler error, but crashes at run time."
},
{
"code": null,
"e": 28344,
"s": 28206,
"text": "Sources:http://googleresearch.blogspot.in/2006/06/extra-extra-read-all-about-it-nearly.htmlhttp://locklessinc.com/articles/binary_search/"
},
{
"code": null,
"e": 28512,
"s": 28344,
"text": "This article is contributed by Abhay Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 28526,
"s": 28512,
"text": "Binary Search"
},
{
"code": null,
"e": 28536,
"s": 28526,
"text": "Searching"
},
{
"code": null,
"e": 28546,
"s": 28536,
"text": "Searching"
},
{
"code": null,
"e": 28560,
"s": 28546,
"text": "Binary Search"
},
{
"code": null,
"e": 28658,
"s": 28560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28706,
"s": 28658,
"text": "Search an element in a sorted and rotated array"
},
{
"code": null,
"e": 28797,
"s": 28706,
"text": "Given an array of size n and a number k, find all elements that appear more than n/k times"
},
{
"code": null,
"e": 28841,
"s": 28797,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 28888,
"s": 28841,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 28931,
"s": 28888,
"text": "Find the index of an array element in Java"
},
{
"code": null,
"e": 28954,
"s": 28931,
"text": "Two Pointers Technique"
},
{
"code": null,
"e": 29015,
"s": 28954,
"text": "Count number of occurrences (or frequency) in a sorted array"
},
{
"code": null,
"e": 29049,
"s": 29015,
"text": "Most frequent element in an array"
}
] |
ByteBuffer getChar() method in Java with Examples - GeeksforGeeks
|
22 Jul, 2019
The getChar() method of java.nio.ByteBuffer class is used to get method for reading a char value
Reads the next two bytes at this bufferβs current position, composing them into a char value according to the current byte order, and then increments the position by two.
Syntax:
public abstract char getChar()
Return Value: This method returns the char value at the bufferβs current position
Throws: This method throws BufferUnderflowException β If the bufferβs current position is not smaller than its limit, then this exception is thrown.
Below are the examples to illustrate the getChar() method:
Examples 1:
// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 50; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put("Geeks"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.println("Original ByteBuffer: "); while ((c = bb.getChar()) != 0) System.out.print(c + " "); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's current position // using getChar() method char value = bb.getChar(); // print the char value System.out.println("\n\nByte Value: " + value); // Reads the char at this buffer's next position // using getChar() method char value1 = bb.getChar(); // print the char value System.out.print("\nNext Byte Value: " + value1); } catch (IllegalArgumentException e) { System.out.println("\nException Thrown: " + e); } catch (ReadOnlyBufferException e) { System.out.println("\nException Thrown: " + e); } catch (BufferUnderflowException e) { System.out.println("\nException Thrown: " + e); } }}
Original ByteBuffer:
G e e k s
Byte Value: G
Next Byte Value: e
Examples 2:
// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put("abc"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.print("Original ByteBuffer: "); while ((c = bb.getChar()) != 0) System.out.print(c + " "); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's current position // using getChar() method char value = bb.getChar(); // print the char value System.out.println("\n\nFirst char Value: " + value); // Reads the char at this buffer's next position // using getChar() method char value1 = bb.getChar(); // print the char value System.out.println("\nSecond char Value: " + value1); // Reads the char at this buffer's next position // using getChar() method char value2 = bb.getChar(); // print the char value System.out.println("\nThird char Value: " + value2); // Reads the char at this buffer's next position // using getChar() method System.out.print("\nsince the buffer current position is incremented"); System.out.print(" to greater than its limit "); char value3 = bb.getChar(); char value4 = bb.getChar(); } catch (BufferOverflowException e) { System.out.println("\nException Thrown: " + e); } catch (ReadOnlyBufferException e) { System.out.println("\nException Thrown: " + e); } catch (BufferUnderflowException e) { System.out.println("\nException Thrown: " + e); } }}
Original ByteBuffer: a b c
First char Value: a
Second char Value: b
Third char Value: c
since the buffer current position is incremented to greater than its limit
Exception Thrown: java.nio.BufferUnderflowException
The get(int index) method of ByteBuffer is used to reads two bytes at the given index, composing them into a char value according to the current byte order.
Syntax:
public abstract char getChar(int index)
Parameters: This method takes index (The index from which the Byte will be read) as a parameter.
Return Value: This method returns the char value at the given index.
Exception: This method throws IndexOutOfBoundsException. If index is negative or not smaller than the bufferβs limit this exception is thrown.
Below are the examples to illustrate the get(int index) method:
Examples 1:
// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 50; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put("abc"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.print("Original ByteBuffer: "); while ((c = bb.getChar()) != 0) System.out.print(c + " "); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's at index 0 // using getChar() method char value0 = bb.getChar(0); // print the char value System.out.println("\n\nchar Value at index 0: " + value0); // Reads the char at this buffer's at index 2 // using getChar() method char value1 = bb.getChar(2); // print the char value System.out.println("\nchar Value at index 2: " + value1); // Reads the char at this buffer's at index 4 // using getChar() method char value2 = bb.getChar(4); // print the char value System.out.println("\nchar Value at index 4: " + value2); } catch (IllegalArgumentException e) { System.out.println("\nException Thrown: " + e); } catch (ReadOnlyBufferException e) { System.out.println("\nException Thrown: " + e); } catch (BufferUnderflowException e) { System.out.println("\nException Thrown: " + e); } }}
Original ByteBuffer: a b c
char Value at index 0: a
char Value at index 2: b
char Value at index 4: c
Examples 2:
// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 50; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put("abc"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.print("Original ByteBuffer: "); while ((c = bb.getChar()) != 0) System.out.print(c + " "); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's at index 0 // using getChar() method char value0 = bb.getChar(0); // print the char value System.out.println("\n\nchar Value at index 0: " + value0); // Reads the char at this buffer's at index 2 // using getChar() method char value1 = bb.getChar(2); // print the char value System.out.println("\nchar Value at index 2: " + value1); // Reads the char at this buffer's at index 4 // using getChar() method System.out.println("\nTrying to get the char" + " at negative index "); char value2 = bb.getChar(-4); } catch (IndexOutOfBoundsException e) { System.out.println("\nException Thrown: " + e); } catch (ReadOnlyBufferException e) { System.out.println("\nException Thrown: " + e); } catch (BufferUnderflowException e) { System.out.println("\nException Thrown: " + e); } }}
Original ByteBuffer: a b c
char Value at index 0: a
char Value at index 2: b
Trying to get the char at a negative index
Exception Thrown: java.lang.IndexOutOfBoundsException
Reference:
https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getCharβ
https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getChar-int-
Vijay Sirra
Java-ByteBuffer
Java-Functions
Java-NIO package
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Introduction to Parallel Computing
|
[
{
"code": null,
"e": 25893,
"s": 25865,
"text": "\n22 Jul, 2019"
},
{
"code": null,
"e": 25990,
"s": 25893,
"text": "The getChar() method of java.nio.ByteBuffer class is used to get method for reading a char value"
},
{
"code": null,
"e": 26161,
"s": 25990,
"text": "Reads the next two bytes at this bufferβs current position, composing them into a char value according to the current byte order, and then increments the position by two."
},
{
"code": null,
"e": 26169,
"s": 26161,
"text": "Syntax:"
},
{
"code": null,
"e": 26200,
"s": 26169,
"text": "public abstract char getChar()"
},
{
"code": null,
"e": 26282,
"s": 26200,
"text": "Return Value: This method returns the char value at the bufferβs current position"
},
{
"code": null,
"e": 26431,
"s": 26282,
"text": "Throws: This method throws BufferUnderflowException β If the bufferβs current position is not smaller than its limit, then this exception is thrown."
},
{
"code": null,
"e": 26490,
"s": 26431,
"text": "Below are the examples to illustrate the getChar() method:"
},
{
"code": null,
"e": 26502,
"s": 26490,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 50; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put(\"Geeks\"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.println(\"Original ByteBuffer: \"); while ((c = bb.getChar()) != 0) System.out.print(c + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's current position // using getChar() method char value = bb.getChar(); // print the char value System.out.println(\"\\n\\nByte Value: \" + value); // Reads the char at this buffer's next position // using getChar() method char value1 = bb.getChar(); // print the char value System.out.print(\"\\nNext Byte Value: \" + value1); } catch (IllegalArgumentException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (BufferUnderflowException e) { System.out.println(\"\\nException Thrown: \" + e); } }}",
"e": 28226,
"s": 26502,
"text": null
},
{
"code": null,
"e": 28295,
"s": 28226,
"text": "Original ByteBuffer: \nG e e k s \n\nByte Value: G\n\nNext Byte Value: e\n"
},
{
"code": null,
"e": 28307,
"s": 28295,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put(\"abc\"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.print(\"Original ByteBuffer: \"); while ((c = bb.getChar()) != 0) System.out.print(c + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's current position // using getChar() method char value = bb.getChar(); // print the char value System.out.println(\"\\n\\nFirst char Value: \" + value); // Reads the char at this buffer's next position // using getChar() method char value1 = bb.getChar(); // print the char value System.out.println(\"\\nSecond char Value: \" + value1); // Reads the char at this buffer's next position // using getChar() method char value2 = bb.getChar(); // print the char value System.out.println(\"\\nThird char Value: \" + value2); // Reads the char at this buffer's next position // using getChar() method System.out.print(\"\\nsince the buffer current position is incremented\"); System.out.print(\" to greater than its limit \"); char value3 = bb.getChar(); char value4 = bb.getChar(); } catch (BufferOverflowException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (BufferUnderflowException e) { System.out.println(\"\\nException Thrown: \" + e); } }}",
"e": 30596,
"s": 28307,
"text": null
},
{
"code": null,
"e": 30818,
"s": 30596,
"text": "Original ByteBuffer: a b c \n\nFirst char Value: a\n\nSecond char Value: b\n\nThird char Value: c\n\nsince the buffer current position is incremented to greater than its limit \nException Thrown: java.nio.BufferUnderflowException\n"
},
{
"code": null,
"e": 30975,
"s": 30818,
"text": "The get(int index) method of ByteBuffer is used to reads two bytes at the given index, composing them into a char value according to the current byte order."
},
{
"code": null,
"e": 30983,
"s": 30975,
"text": "Syntax:"
},
{
"code": null,
"e": 31023,
"s": 30983,
"text": "public abstract char getChar(int index)"
},
{
"code": null,
"e": 31120,
"s": 31023,
"text": "Parameters: This method takes index (The index from which the Byte will be read) as a parameter."
},
{
"code": null,
"e": 31189,
"s": 31120,
"text": "Return Value: This method returns the char value at the given index."
},
{
"code": null,
"e": 31332,
"s": 31189,
"text": "Exception: This method throws IndexOutOfBoundsException. If index is negative or not smaller than the bufferβs limit this exception is thrown."
},
{
"code": null,
"e": 31396,
"s": 31332,
"text": "Below are the examples to illustrate the get(int index) method:"
},
{
"code": null,
"e": 31408,
"s": 31396,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 50; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put(\"abc\"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.print(\"Original ByteBuffer: \"); while ((c = bb.getChar()) != 0) System.out.print(c + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's at index 0 // using getChar() method char value0 = bb.getChar(0); // print the char value System.out.println(\"\\n\\nchar Value at index 0: \" + value0); // Reads the char at this buffer's at index 2 // using getChar() method char value1 = bb.getChar(2); // print the char value System.out.println(\"\\nchar Value at index 2: \" + value1); // Reads the char at this buffer's at index 4 // using getChar() method char value2 = bb.getChar(4); // print the char value System.out.println(\"\\nchar Value at index 4: \" + value2); } catch (IllegalArgumentException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (BufferUnderflowException e) { System.out.println(\"\\nException Thrown: \" + e); } }}",
"e": 33475,
"s": 31408,
"text": null
},
{
"code": null,
"e": 33582,
"s": 33475,
"text": "Original ByteBuffer: a b c \n\nchar Value at index 0: a\n\nchar Value at index 2: b\n\nchar Value at index 4: c\n"
},
{
"code": null,
"e": 33594,
"s": 33582,
"text": "Examples 2:"
},
{
"code": "// Java program to demonstrate// getChar() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 50; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the string in the bytebuffer bb.asCharBuffer().put(\"abc\"); // rewind the Bytebuffer bb.rewind(); // Declaring the variable char c; // print the ByteBuffer System.out.print(\"Original ByteBuffer: \"); while ((c = bb.getChar()) != 0) System.out.print(c + \" \"); // rewind the Bytebuffer bb.rewind(); // Reads the char at this buffer's at index 0 // using getChar() method char value0 = bb.getChar(0); // print the char value System.out.println(\"\\n\\nchar Value at index 0: \" + value0); // Reads the char at this buffer's at index 2 // using getChar() method char value1 = bb.getChar(2); // print the char value System.out.println(\"\\nchar Value at index 2: \" + value1); // Reads the char at this buffer's at index 4 // using getChar() method System.out.println(\"\\nTrying to get the char\" + \" at negative index \"); char value2 = bb.getChar(-4); } catch (IndexOutOfBoundsException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"\\nException Thrown: \" + e); } catch (BufferUnderflowException e) { System.out.println(\"\\nException Thrown: \" + e); } }}",
"e": 35730,
"s": 33594,
"text": null
},
{
"code": null,
"e": 35911,
"s": 35730,
"text": "Original ByteBuffer: a b c \n\nchar Value at index 0: a\n\nchar Value at index 2: b\n\nTrying to get the char at a negative index \n\nException Thrown: java.lang.IndexOutOfBoundsException\n"
},
{
"code": null,
"e": 35922,
"s": 35911,
"text": "Reference:"
},
{
"code": null,
"e": 35998,
"s": 35922,
"text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getCharβ"
},
{
"code": null,
"e": 36078,
"s": 35998,
"text": "https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getChar-int-"
},
{
"code": null,
"e": 36090,
"s": 36078,
"text": "Vijay Sirra"
},
{
"code": null,
"e": 36106,
"s": 36090,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 36121,
"s": 36106,
"text": "Java-Functions"
},
{
"code": null,
"e": 36138,
"s": 36121,
"text": "Java-NIO package"
},
{
"code": null,
"e": 36143,
"s": 36138,
"text": "Misc"
},
{
"code": null,
"e": 36148,
"s": 36143,
"text": "Misc"
},
{
"code": null,
"e": 36153,
"s": 36148,
"text": "Misc"
},
{
"code": null,
"e": 36251,
"s": 36153,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36272,
"s": 36251,
"text": "Activation Functions"
},
{
"code": null,
"e": 36310,
"s": 36272,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 36346,
"s": 36310,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 36381,
"s": 36346,
"text": "Sensors in Internet of Things(IoT)"
},
{
"code": null,
"e": 36420,
"s": 36381,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 36466,
"s": 36420,
"text": "Election algorithm and distributed processing"
},
{
"code": null,
"e": 36515,
"s": 36466,
"text": "Introduction to Internet of Things (IoT) | Set 1"
},
{
"code": null,
"e": 36547,
"s": 36515,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 36597,
"s": 36547,
"text": "Communication Models in IoT (Internet of Things )"
}
] |
Count number of triplets with product equal to given number with duplicates allowed | Set-2 - GeeksforGeeks
|
12 Nov, 2021
Given an array of positive integers(may contain duplicates) and a number βmβ, find the number of unordered triplets ((Ai, Aj, Ak) and (Aj, Ai, Ak) and other permutations are counted as one only) with product equal to βmβ.
Examples:
Input: arr[] = { 1, 4, 6, 2, 3, 8}, M = 24 Output: 3 The triplets are {1, 4, 6} {1, 3, 8} {4, 2, 3}
Input: arr[] = { 0, 4, 6, 2, 3, 8}, M = 18 Output: 0 There are no triplets in this case
A solution with O(N2) has been discussed in the previous post. In this post a better approach with lesser complexity has been discussed.
Approach: The below algorithm is followed to solve the above problem.
Use a hash-map to count the frequency of every element in the given array.
Declare a set which can store triplets, so that only unordered triplets are taken to count.
Iterate from 1 to sqrt(m) in a loop(let variable be i), since the maximum number by which M is divisible is sqrt(M) leaving out M.
Check if M is divisible by i or not and i is present in the array of integers or not, if it is, then again loop from 1 to M/i.(let the loop variable be j).
Again Check if M is divisible by j or not and j is present in the array of integers or not, if it is then check if the remaining number that is ( (M / i) / j) is present or not.
If it is present, then a triplet has been formed. To avoid duplicate triplets, insert them in the set in sorted order.
Check if the set the size increases after the insertion of triplet if it does then use combinatorics to find the number of triplets.
To find the number of triplets, the following conditions will be there. If all of the Ai, Aj and Ak are unique, then number of combinations will be the product of their frequencies.If all of them are same, then we can only choose three of them, hence the formula stands at .If any of the two are same(let Ai and Aj), the count will be * frequency[Ak]
If all of the Ai, Aj and Ak are unique, then number of combinations will be the product of their frequencies.If all of them are same, then we can only choose three of them, hence the formula stands at .If any of the two are same(let Ai and Aj), the count will be * frequency[Ak]
If all of the Ai, Aj and Ak are unique, then number of combinations will be the product of their frequencies.
If all of them are same, then we can only choose three of them, hence the formula stands at .
If any of the two are same(let Ai and Aj), the count will be * frequency[Ak]
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find the// number of triplets in array// whose product is equal to M#include <bits/stdc++.h>using namespace std; // Function to count the tripletsint countTriplets(int a[], int m, int n){ // hash-map to store the frequency of every number unordered_map<int, int> frequency; // set to store the unique triplets set<pair<int, pair<int, int> > > st; // count the number of times // every element appears in a map for (int i = 0; i < n; i++) { frequency[a[i]] += 1; } // stores the answer int ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (int i = 1; i * i <= m; i++) { // if divisible and present if (m % i == 0 and frequency[i]) { // remaining number after division int num1 = m / i; // iterate for the second number of the triplet for (int j = 1; j * j <= num1; j++) { // if divisible and present if (num1 % j == 0 and frequency[j]) { // remaining number after division int num2 = num1 / j; // if the third number is present in array if (frequency[num2]) { // a temp array to store the triplet int temp[] = { num2, i, j }; // sort the triplets sort(temp, temp + 3); // get the size of set int setsize = st.size(); // insert the triplet in ascending order st.insert({ temp[0], { temp[1], temp[2] } }); // if the set size increases after insertion, // it means a new triplet is found if (setsize != st.size()) { // if all the number in triplets are unique if (i != j and j != num2) ans += frequency[i] * frequency[j] * frequency[num2]; // if Ai and Aj are same among triplets else if (i == j && j != num2) ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[num2]; // if Aj and Ak are same among triplets else if (j == num2 && j != i) ans += (frequency[j] * (frequency[j] - 1) / 2) * frequency[i]; // if three of them are // same among triplets else if (i == j and j == num2) ans += (frequency[i] * (frequency[i] - 1) * (frequency[i] - 2) / 6); // if Ai and Ak are same among triplets else ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[j]; } } } } } } return ans;} // Driver Codeint main(){ int a[] = { 1, 4, 6, 2, 3, 8 }; int m = 24; int n = sizeof(a) / sizeof(a[0]); cout << countTriplets(a, m, n); return 0;}
// Java program to find the// number of triplets in array// whose product is equal to Mimport java.util.*; class GFG{ // Function to count the tripletsstatic int countTriplets(int a[], int m, int n){ // hash-map to store // the frequency of every number HashMap<Integer, Integer> frequency = new HashMap<>(); // put to store the unique triplets Set<String> st = new HashSet<String>(); // count the number of times // every element appears in a map for (int i = 0; i < n; i++) { frequency.put(a[i],(frequency.get(a[i]) == null ? 1:(frequency.get(a[i]) + 1))); } // stores the answer int ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (int i = 1; i * i <= m; i++) { // if divisible && present if (m % i == 0 && frequency.get(i)!=null) { // remaining number after division int num1 = m / i; // iterate for the second number of the triplet for (int j = 1; j * j <= num1; j++) { // if divisible && present if (num1 % j == 0 && frequency.get(j) != null) { // remaining number after division int num2 = num1 / j; // if the third number is present in array if (frequency.get(num2) != null) { // a temp array to store the triplet int temp[] = { num2, i, j }; // sort the triplets Arrays.sort(temp); // get the size of put int setsize = st.size(); // add the triplet in ascending order st.add(temp[0]+" "+ temp[1]+" " +temp[2] ); // if the put size increases after addition, // it means a new triplet is found if (setsize != st.size()) { // if all the number in triplets are unique if (i != j && j != num2) ans += frequency.get(i) * frequency.get(j) * frequency.get(num2); // if Ai && Aj are same among triplets else if (i == j && j != num2) ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(num2); // if Aj && Ak are same among triplets else if (j == num2 && j != i) ans += (frequency.get(j) * (frequency.get(j) - 1) / 2) * frequency.get(i); // if three of them are // same among triplets else if (i == j && j == num2) ans += (frequency.get(i) * (frequency.get(i) - 1) * (frequency.get(i) - 2) / 6); // if Ai && Ak are same among triplets else ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(j); } } } } } } return ans;} // Driver Codepublic static void main(String args[]){ int a[] = { 1, 4, 6, 2, 3, 8 }; int m = 24; int n = a.length; System.out.println(countTriplets(a, m, n));}} // This code is contributed by Arnab Kundu
# Python3 program to find the# number of triplets in array# whose product is equal to Mimport math # Function to count the tripletsdef countTriplets(a, m, n): # hash-map to store # the frequency of every number frequency = {} # put to store the unique triplets st = set({}) # count the number of times # every element appears in a map for i in range(n): if a[i] in frequency: frequency[a[i]] += 1 else: frequency[a[i]] = 1 # stores the answer ans = 0 # iterate till sqrt(m) since tnum2t is the # maximum number tnum2t can divide M except itself i = 1 while i * i <= m: # if divisible && present if (m % i == 0 and i in frequency): # remaining number after division num1 = int(m / i) # iterate for the second number of the triplet j = 1 while j * j <= num1: # if divisible && present if (num1 % j == 0 and j in frequency): # remaining number after division num2 = math.floor(num1 / j) # if the third number is present in array if num2 in frequency: # a temp array to store the triplet temp = [ num2, i, j ] # sort the triplets temp.sort() # get the size of put setsize = len(st) # add the triplet in ascending order st.add(str(temp[0])+" "+ str(temp[1])+" " +str(temp[2])) # if the put size increases after addition, # it means a new triplet is found if setsize != len(st): # if all the number in # triplets are unique if (i != j and j != num2): ans += frequency[i] * frequency[j] * frequency[num2] # if Ai && Aj are same among triplets elif (i == j and j != num2): ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[num2] # if Aj && Ak are same among triplets elif (j == num2 and j != i): ans += (frequency[j] * (frequency[j] - 1) / 2) * frequency[i] # if three of them are # same among triplets elif (i == j and j == num2): ans += (frequency[i] * (frequency[i] - 1) * (frequency[i] - 2) / 6) # if Ai && Ak are same among triplets else: ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[j] j += 1 i += 1 return int(ans) a=[1, 4, 6, 2, 3, 8 ]m = 24;n = len(a)print(countTriplets(a, m, n)) # This code is contributed by rameshtravel07.
// C# program to find the// number of triplets in array// whose product is equal to Musing System;using System.Collections.Generic;class GFG { // Function to count the triplets static int countTriplets(int[] a, int m, int n) { // hash-map to store // the frequency of every number Dictionary<int, int> frequency = new Dictionary<int, int>(); // put to store the unique triplets HashSet<string> st = new HashSet<string>(); // count the number of times // every element appears in a map for (int i = 0; i < n; i++) { if(frequency.ContainsKey(a[i])) { frequency[a[i]] += 1; } else{ frequency[a[i]] = 1; } } // stores the answer int ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (int i = 1; i * i <= m; i++) { // if divisible && present if (m % i == 0 && frequency.ContainsKey(i)) { // remaining number after division int num1 = m / i; // iterate for the second number of the triplet for (int j = 1; j * j <= num1; j++) { // if divisible && present if (num1 % j == 0 && frequency.ContainsKey(j)) { // remaining number after division int num2 = num1 / j; // if the third number is present in array if (frequency.ContainsKey(num2)) { // a temp array to store the triplet int[] temp = { num2, i, j }; // sort the triplets Array.Sort(temp); // get the size of put int setsize = st.Count; // add the triplet in ascending order st.Add(temp[0].ToString()+" "+ temp[1].ToString()+" " +temp[2].ToString()); // if the put size increases after addition, // it means a new triplet is found if (setsize != st.Count) { // if all the number in triplets are unique if (i != j && j != num2) ans += frequency[i] * frequency[j] * frequency[num2]; // if Ai && Aj are same among triplets else if (i == j && j != num2) ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[num2]; // if Aj && Ak are same among triplets else if (j == num2 && j != i) ans += (frequency[j] * (frequency[j] - 1) / 2) * frequency[i]; // if three of them are // same among triplets else if (i == j && j == num2) ans += (frequency[i] * (frequency[i] - 1) * (frequency[i] - 2) / 6); // if Ai && Ak are same among triplets else ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[j]; } } } } } } return ans; } // Driver code static void Main() { int[] a = { 1, 4, 6, 2, 3, 8 }; int m = 24; int n = a.Length; Console.Write(countTriplets(a, m, n)); }} // This code is contributed by decode2207.
<script> // JavaScript program to find the// number of triplets in array// whose product is equal to M // Function to count the tripletsfunction countTriplets(a,m,n){ // hash-map to store // the frequency of every number let frequency = new Map(); // put to store the unique triplets let st = new Set(); // count the number of times // every element appears in a map for (let i = 0; i < n; i++) { frequency.set(a[i],(frequency.get(a[i]) == null ? 1:(frequency.get(a[i]) + 1))); } // stores the answer let ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (let i = 1; i * i <= m; i++) { // if divisible && present if (m % i == 0 && frequency.get(i)!=null) { // remaining number after division let num1 = m / i; // iterate for the second number of the triplet for (let j = 1; j * j <= num1; j++) { // if divisible && present if (num1 % j == 0 && frequency.get(j) != null) { // remaining number after division let num2 = Math.floor(num1 / j); // if the third number is present in array if (frequency.get(num2) != null) { // a temp array to store the triplet let temp = [ num2, i, j ]; // sort the triplets temp.sort(function(a,b){return a-b;}); // get the size of put let setsize = st.size; // add the triplet in ascending order st.add(temp[0]+" "+ temp[1]+" " +temp[2] ); // if the put size increases after addition, // it means a new triplet is found if (setsize != st.size) { // if all the number in // triplets are unique if (i != j && j != num2) ans += frequency.get(i) * frequency.get(j) * frequency.get(num2); // if Ai && Aj are same among triplets else if (i == j && j != num2) ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(num2); // if Aj && Ak are same among triplets else if (j == num2 && j != i) ans += (frequency.get(j) * (frequency.get(j) - 1) / 2) * frequency.get(i); // if three of them are // same among triplets else if (i == j && j == num2) ans += (frequency.get(i) * (frequency.get(i) - 1) * (frequency.get(i) - 2) / 6); // if Ai && Ak are same among triplets else ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(j); } } } } } } return ans;} // Driver Codelet a=[1, 4, 6, 2, 3, 8 ];let m = 24;let n = a.length;document.write(countTriplets(a, m, n)); // This code is contributed by avanitrachhadiya2155 </script>
3
Time Complexity: O(N * log N)
Akanksha_Rai
samagragupta
andrew1234
avanitrachhadiya2155
sagartomar9927
decode2207
rameshtravel07
kashishsoda
surindertarika1234
Codenation
cpp-pair
cpp-set
cpp-unordered_map
frequency-counting
Combinatorial
Codenation
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinational Sum
Print all possible strings of length k that can be formed from a set of n characters
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Print all distinct permutations of a given string with duplicates
Heap's Algorithm for generating permutations
Distinct permutations of the string | Set 2
Make all combinations of size k
Count Derangements (Permutation such that no element appears in its original position)
Print all subsets of given size of a set
|
[
{
"code": null,
"e": 26943,
"s": 26915,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 27166,
"s": 26943,
"text": "Given an array of positive integers(may contain duplicates) and a number βmβ, find the number of unordered triplets ((Ai, Aj, Ak) and (Aj, Ai, Ak) and other permutations are counted as one only) with product equal to βmβ. "
},
{
"code": null,
"e": 27177,
"s": 27166,
"text": "Examples: "
},
{
"code": null,
"e": 27277,
"s": 27177,
"text": "Input: arr[] = { 1, 4, 6, 2, 3, 8}, M = 24 Output: 3 The triplets are {1, 4, 6} {1, 3, 8} {4, 2, 3}"
},
{
"code": null,
"e": 27366,
"s": 27277,
"text": "Input: arr[] = { 0, 4, 6, 2, 3, 8}, M = 18 Output: 0 There are no triplets in this case "
},
{
"code": null,
"e": 27504,
"s": 27366,
"text": "A solution with O(N2) has been discussed in the previous post. In this post a better approach with lesser complexity has been discussed. "
},
{
"code": null,
"e": 27576,
"s": 27504,
"text": "Approach: The below algorithm is followed to solve the above problem. "
},
{
"code": null,
"e": 27651,
"s": 27576,
"text": "Use a hash-map to count the frequency of every element in the given array."
},
{
"code": null,
"e": 27743,
"s": 27651,
"text": "Declare a set which can store triplets, so that only unordered triplets are taken to count."
},
{
"code": null,
"e": 27874,
"s": 27743,
"text": "Iterate from 1 to sqrt(m) in a loop(let variable be i), since the maximum number by which M is divisible is sqrt(M) leaving out M."
},
{
"code": null,
"e": 28030,
"s": 27874,
"text": "Check if M is divisible by i or not and i is present in the array of integers or not, if it is, then again loop from 1 to M/i.(let the loop variable be j)."
},
{
"code": null,
"e": 28208,
"s": 28030,
"text": "Again Check if M is divisible by j or not and j is present in the array of integers or not, if it is then check if the remaining number that is ( (M / i) / j) is present or not."
},
{
"code": null,
"e": 28327,
"s": 28208,
"text": "If it is present, then a triplet has been formed. To avoid duplicate triplets, insert them in the set in sorted order."
},
{
"code": null,
"e": 28460,
"s": 28327,
"text": "Check if the set the size increases after the insertion of triplet if it does then use combinatorics to find the number of triplets."
},
{
"code": null,
"e": 28811,
"s": 28460,
"text": "To find the number of triplets, the following conditions will be there. If all of the Ai, Aj and Ak are unique, then number of combinations will be the product of their frequencies.If all of them are same, then we can only choose three of them, hence the formula stands at .If any of the two are same(let Ai and Aj), the count will be * frequency[Ak]"
},
{
"code": null,
"e": 29090,
"s": 28811,
"text": "If all of the Ai, Aj and Ak are unique, then number of combinations will be the product of their frequencies.If all of them are same, then we can only choose three of them, hence the formula stands at .If any of the two are same(let Ai and Aj), the count will be * frequency[Ak]"
},
{
"code": null,
"e": 29200,
"s": 29090,
"text": "If all of the Ai, Aj and Ak are unique, then number of combinations will be the product of their frequencies."
},
{
"code": null,
"e": 29294,
"s": 29200,
"text": "If all of them are same, then we can only choose three of them, hence the formula stands at ."
},
{
"code": null,
"e": 29371,
"s": 29294,
"text": "If any of the two are same(let Ai and Aj), the count will be * frequency[Ak]"
},
{
"code": null,
"e": 29424,
"s": 29371,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 29428,
"s": 29424,
"text": "C++"
},
{
"code": null,
"e": 29433,
"s": 29428,
"text": "Java"
},
{
"code": null,
"e": 29441,
"s": 29433,
"text": "Python3"
},
{
"code": null,
"e": 29444,
"s": 29441,
"text": "C#"
},
{
"code": null,
"e": 29455,
"s": 29444,
"text": "Javascript"
},
{
"code": "// C++ program to find the// number of triplets in array// whose product is equal to M#include <bits/stdc++.h>using namespace std; // Function to count the tripletsint countTriplets(int a[], int m, int n){ // hash-map to store the frequency of every number unordered_map<int, int> frequency; // set to store the unique triplets set<pair<int, pair<int, int> > > st; // count the number of times // every element appears in a map for (int i = 0; i < n; i++) { frequency[a[i]] += 1; } // stores the answer int ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (int i = 1; i * i <= m; i++) { // if divisible and present if (m % i == 0 and frequency[i]) { // remaining number after division int num1 = m / i; // iterate for the second number of the triplet for (int j = 1; j * j <= num1; j++) { // if divisible and present if (num1 % j == 0 and frequency[j]) { // remaining number after division int num2 = num1 / j; // if the third number is present in array if (frequency[num2]) { // a temp array to store the triplet int temp[] = { num2, i, j }; // sort the triplets sort(temp, temp + 3); // get the size of set int setsize = st.size(); // insert the triplet in ascending order st.insert({ temp[0], { temp[1], temp[2] } }); // if the set size increases after insertion, // it means a new triplet is found if (setsize != st.size()) { // if all the number in triplets are unique if (i != j and j != num2) ans += frequency[i] * frequency[j] * frequency[num2]; // if Ai and Aj are same among triplets else if (i == j && j != num2) ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[num2]; // if Aj and Ak are same among triplets else if (j == num2 && j != i) ans += (frequency[j] * (frequency[j] - 1) / 2) * frequency[i]; // if three of them are // same among triplets else if (i == j and j == num2) ans += (frequency[i] * (frequency[i] - 1) * (frequency[i] - 2) / 6); // if Ai and Ak are same among triplets else ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[j]; } } } } } } return ans;} // Driver Codeint main(){ int a[] = { 1, 4, 6, 2, 3, 8 }; int m = 24; int n = sizeof(a) / sizeof(a[0]); cout << countTriplets(a, m, n); return 0;}",
"e": 32815,
"s": 29455,
"text": null
},
{
"code": "// Java program to find the// number of triplets in array// whose product is equal to Mimport java.util.*; class GFG{ // Function to count the tripletsstatic int countTriplets(int a[], int m, int n){ // hash-map to store // the frequency of every number HashMap<Integer, Integer> frequency = new HashMap<>(); // put to store the unique triplets Set<String> st = new HashSet<String>(); // count the number of times // every element appears in a map for (int i = 0; i < n; i++) { frequency.put(a[i],(frequency.get(a[i]) == null ? 1:(frequency.get(a[i]) + 1))); } // stores the answer int ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (int i = 1; i * i <= m; i++) { // if divisible && present if (m % i == 0 && frequency.get(i)!=null) { // remaining number after division int num1 = m / i; // iterate for the second number of the triplet for (int j = 1; j * j <= num1; j++) { // if divisible && present if (num1 % j == 0 && frequency.get(j) != null) { // remaining number after division int num2 = num1 / j; // if the third number is present in array if (frequency.get(num2) != null) { // a temp array to store the triplet int temp[] = { num2, i, j }; // sort the triplets Arrays.sort(temp); // get the size of put int setsize = st.size(); // add the triplet in ascending order st.add(temp[0]+\" \"+ temp[1]+\" \" +temp[2] ); // if the put size increases after addition, // it means a new triplet is found if (setsize != st.size()) { // if all the number in triplets are unique if (i != j && j != num2) ans += frequency.get(i) * frequency.get(j) * frequency.get(num2); // if Ai && Aj are same among triplets else if (i == j && j != num2) ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(num2); // if Aj && Ak are same among triplets else if (j == num2 && j != i) ans += (frequency.get(j) * (frequency.get(j) - 1) / 2) * frequency.get(i); // if three of them are // same among triplets else if (i == j && j == num2) ans += (frequency.get(i) * (frequency.get(i) - 1) * (frequency.get(i) - 2) / 6); // if Ai && Ak are same among triplets else ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(j); } } } } } } return ans;} // Driver Codepublic static void main(String args[]){ int a[] = { 1, 4, 6, 2, 3, 8 }; int m = 24; int n = a.length; System.out.println(countTriplets(a, m, n));}} // This code is contributed by Arnab Kundu",
"e": 36769,
"s": 32815,
"text": null
},
{
"code": "# Python3 program to find the# number of triplets in array# whose product is equal to Mimport math # Function to count the tripletsdef countTriplets(a, m, n): # hash-map to store # the frequency of every number frequency = {} # put to store the unique triplets st = set({}) # count the number of times # every element appears in a map for i in range(n): if a[i] in frequency: frequency[a[i]] += 1 else: frequency[a[i]] = 1 # stores the answer ans = 0 # iterate till sqrt(m) since tnum2t is the # maximum number tnum2t can divide M except itself i = 1 while i * i <= m: # if divisible && present if (m % i == 0 and i in frequency): # remaining number after division num1 = int(m / i) # iterate for the second number of the triplet j = 1 while j * j <= num1: # if divisible && present if (num1 % j == 0 and j in frequency): # remaining number after division num2 = math.floor(num1 / j) # if the third number is present in array if num2 in frequency: # a temp array to store the triplet temp = [ num2, i, j ] # sort the triplets temp.sort() # get the size of put setsize = len(st) # add the triplet in ascending order st.add(str(temp[0])+\" \"+ str(temp[1])+\" \" +str(temp[2])) # if the put size increases after addition, # it means a new triplet is found if setsize != len(st): # if all the number in # triplets are unique if (i != j and j != num2): ans += frequency[i] * frequency[j] * frequency[num2] # if Ai && Aj are same among triplets elif (i == j and j != num2): ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[num2] # if Aj && Ak are same among triplets elif (j == num2 and j != i): ans += (frequency[j] * (frequency[j] - 1) / 2) * frequency[i] # if three of them are # same among triplets elif (i == j and j == num2): ans += (frequency[i] * (frequency[i] - 1) * (frequency[i] - 2) / 6) # if Ai && Ak are same among triplets else: ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[j] j += 1 i += 1 return int(ans) a=[1, 4, 6, 2, 3, 8 ]m = 24;n = len(a)print(countTriplets(a, m, n)) # This code is contributed by rameshtravel07.",
"e": 39907,
"s": 36769,
"text": null
},
{
"code": "// C# program to find the// number of triplets in array// whose product is equal to Musing System;using System.Collections.Generic;class GFG { // Function to count the triplets static int countTriplets(int[] a, int m, int n) { // hash-map to store // the frequency of every number Dictionary<int, int> frequency = new Dictionary<int, int>(); // put to store the unique triplets HashSet<string> st = new HashSet<string>(); // count the number of times // every element appears in a map for (int i = 0; i < n; i++) { if(frequency.ContainsKey(a[i])) { frequency[a[i]] += 1; } else{ frequency[a[i]] = 1; } } // stores the answer int ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (int i = 1; i * i <= m; i++) { // if divisible && present if (m % i == 0 && frequency.ContainsKey(i)) { // remaining number after division int num1 = m / i; // iterate for the second number of the triplet for (int j = 1; j * j <= num1; j++) { // if divisible && present if (num1 % j == 0 && frequency.ContainsKey(j)) { // remaining number after division int num2 = num1 / j; // if the third number is present in array if (frequency.ContainsKey(num2)) { // a temp array to store the triplet int[] temp = { num2, i, j }; // sort the triplets Array.Sort(temp); // get the size of put int setsize = st.Count; // add the triplet in ascending order st.Add(temp[0].ToString()+\" \"+ temp[1].ToString()+\" \" +temp[2].ToString()); // if the put size increases after addition, // it means a new triplet is found if (setsize != st.Count) { // if all the number in triplets are unique if (i != j && j != num2) ans += frequency[i] * frequency[j] * frequency[num2]; // if Ai && Aj are same among triplets else if (i == j && j != num2) ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[num2]; // if Aj && Ak are same among triplets else if (j == num2 && j != i) ans += (frequency[j] * (frequency[j] - 1) / 2) * frequency[i]; // if three of them are // same among triplets else if (i == j && j == num2) ans += (frequency[i] * (frequency[i] - 1) * (frequency[i] - 2) / 6); // if Ai && Ak are same among triplets else ans += (frequency[i] * (frequency[i] - 1) / 2) * frequency[j]; } } } } } } return ans; } // Driver code static void Main() { int[] a = { 1, 4, 6, 2, 3, 8 }; int m = 24; int n = a.Length; Console.Write(countTriplets(a, m, n)); }} // This code is contributed by decode2207.",
"e": 44340,
"s": 39907,
"text": null
},
{
"code": "<script> // JavaScript program to find the// number of triplets in array// whose product is equal to M // Function to count the tripletsfunction countTriplets(a,m,n){ // hash-map to store // the frequency of every number let frequency = new Map(); // put to store the unique triplets let st = new Set(); // count the number of times // every element appears in a map for (let i = 0; i < n; i++) { frequency.set(a[i],(frequency.get(a[i]) == null ? 1:(frequency.get(a[i]) + 1))); } // stores the answer let ans = 0; // iterate till sqrt(m) since tnum2t is the // maximum number tnum2t can divide M except itself for (let i = 1; i * i <= m; i++) { // if divisible && present if (m % i == 0 && frequency.get(i)!=null) { // remaining number after division let num1 = m / i; // iterate for the second number of the triplet for (let j = 1; j * j <= num1; j++) { // if divisible && present if (num1 % j == 0 && frequency.get(j) != null) { // remaining number after division let num2 = Math.floor(num1 / j); // if the third number is present in array if (frequency.get(num2) != null) { // a temp array to store the triplet let temp = [ num2, i, j ]; // sort the triplets temp.sort(function(a,b){return a-b;}); // get the size of put let setsize = st.size; // add the triplet in ascending order st.add(temp[0]+\" \"+ temp[1]+\" \" +temp[2] ); // if the put size increases after addition, // it means a new triplet is found if (setsize != st.size) { // if all the number in // triplets are unique if (i != j && j != num2) ans += frequency.get(i) * frequency.get(j) * frequency.get(num2); // if Ai && Aj are same among triplets else if (i == j && j != num2) ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(num2); // if Aj && Ak are same among triplets else if (j == num2 && j != i) ans += (frequency.get(j) * (frequency.get(j) - 1) / 2) * frequency.get(i); // if three of them are // same among triplets else if (i == j && j == num2) ans += (frequency.get(i) * (frequency.get(i) - 1) * (frequency.get(i) - 2) / 6); // if Ai && Ak are same among triplets else ans += (frequency.get(i) * (frequency.get(i) - 1) / 2) * frequency.get(j); } } } } } } return ans;} // Driver Codelet a=[1, 4, 6, 2, 3, 8 ];let m = 24;let n = a.length;document.write(countTriplets(a, m, n)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 48248,
"s": 44340,
"text": null
},
{
"code": null,
"e": 48250,
"s": 48248,
"text": "3"
},
{
"code": null,
"e": 48283,
"s": 48252,
"text": "Time Complexity: O(N * log N) "
},
{
"code": null,
"e": 48296,
"s": 48283,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 48309,
"s": 48296,
"text": "samagragupta"
},
{
"code": null,
"e": 48320,
"s": 48309,
"text": "andrew1234"
},
{
"code": null,
"e": 48341,
"s": 48320,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 48356,
"s": 48341,
"text": "sagartomar9927"
},
{
"code": null,
"e": 48367,
"s": 48356,
"text": "decode2207"
},
{
"code": null,
"e": 48382,
"s": 48367,
"text": "rameshtravel07"
},
{
"code": null,
"e": 48394,
"s": 48382,
"text": "kashishsoda"
},
{
"code": null,
"e": 48413,
"s": 48394,
"text": "surindertarika1234"
},
{
"code": null,
"e": 48424,
"s": 48413,
"text": "Codenation"
},
{
"code": null,
"e": 48433,
"s": 48424,
"text": "cpp-pair"
},
{
"code": null,
"e": 48441,
"s": 48433,
"text": "cpp-set"
},
{
"code": null,
"e": 48459,
"s": 48441,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 48478,
"s": 48459,
"text": "frequency-counting"
},
{
"code": null,
"e": 48492,
"s": 48478,
"text": "Combinatorial"
},
{
"code": null,
"e": 48503,
"s": 48492,
"text": "Codenation"
},
{
"code": null,
"e": 48517,
"s": 48503,
"text": "Combinatorial"
},
{
"code": null,
"e": 48615,
"s": 48517,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48633,
"s": 48615,
"text": "Combinational Sum"
},
{
"code": null,
"e": 48718,
"s": 48633,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
},
{
"code": null,
"e": 48755,
"s": 48718,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 48812,
"s": 48755,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 48878,
"s": 48812,
"text": "Print all distinct permutations of a given string with duplicates"
},
{
"code": null,
"e": 48923,
"s": 48878,
"text": "Heap's Algorithm for generating permutations"
},
{
"code": null,
"e": 48967,
"s": 48923,
"text": "Distinct permutations of the string | Set 2"
},
{
"code": null,
"e": 48999,
"s": 48967,
"text": "Make all combinations of size k"
},
{
"code": null,
"e": 49086,
"s": 48999,
"text": "Count Derangements (Permutation such that no element appears in its original position)"
}
] |
How to plot all the columns of a dataframe in R ? - GeeksforGeeks
|
10 Sep, 2021
In this article, we will learn how to plot all columns of the DataFrame in R programming language.
Dataset in use:
x y1 y2 y3
1 1 0.08475635 0.4543649 0
2 2 0.22646034 0.6492529 1
3 3 0.43255650 0.1537271 0
4 4 0.55806524 0.6492887 3
5 5 0.05975527 0.3832137 1
6 6 0.08475635 0.4543649 0
7 7 0.22646034 0.6492529 1
8 8 0.43255650 0.1537271 0
9 9 0.55806524 0.6492887 3
10 10 0.05975527 0.3832137 1
We just have to pass our dataframe in the plot.ts() function, and it will plot all the dataframe columns in a time series plot. In the Y-axis we can see the names of the columns of our dataframe.
Syntax: plot.ts(df)
Parameters:
df: DataFrame object
Example:
R
set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1))plot.ts(df)
Output:
The zoo() function is present in the zoo package, so it has to be imported by placing require(zoo) function on the first line of the code. This function converts the dataframe in such a format(βzooβ series) that it can be plotted easily in a form of a time series plot.
Since y is NULL in our case, a time series plot of x is produced. But if both x and y were a uni-variate βzooβ series then a scatter plot of y vs x wouldβve been produced.
Syntax: plot(zoo(df))
Parameters:
df: DataFrame object
Example:
R
require(zoo)set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) df <- zoo(df)plot(df)
Output:
In this approach, we will plot a line chart showing multiple columns of a data frame using the basic plot() function. The plot() function is defined as a generic function for plotting in R Language. It can be used to create basic plots of a different type.
Syntax: plot(X, Y, type = βlβ, col = 1, ylim = c(0, 3))
Parameters:
X: X-axis. ->
Y: Y-axis ->
type: specifies the type of plot
col: specifies colour
ylim: specifies limit for y-axis
In the code below first dataframe column is X-axis, and the rest columns are y-axis, and they are plotted against the first column in form of a line chart. The value of col should be different for different lines such that different line has a different color, and finally we have specified ylim which limits the value of y-axis.
We can also plot different types of plots by specifying different values for type parameters. For example, type=βhβ, would have plotted a histogram.
Example:
R
require(zoo)set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) plot(df$x, df$y1, type = "o", col = 1, ylim = c(0, 3))lines(df$x, df$y2, type = "o", col = 2)lines(df$x, df$y3, type = "o", col = 3)
Output:
For this the data has to be reshaped to be in the form where it can be plotted.
Example:
R
library(ggplot2) set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) # Reshape data framedf_reshaped <- data.frame(x = df$x, y = c(df$y1, df$y2, df$y3), group = c(rep("y1", nrow(df)), rep("y2", nrow(df)), rep("y3", nrow(df))))head(df_reshaped,10)
Output:
x y group
1 1 0.08475635 y1
2 2 0.22646034 y1
3 3 0.43255650 y1
4 4 0.55806524 y1
5 5 0.05975527 y1
6 6 0.08475635 y1
7 7 0.22646034 y1
8 8 0.43255650 y1
9 9 0.55806524 y1
10 10 0.05975527 y1
Plotting multiple variables in the same panel
In this method, we plot a line graph for each column of the dataframe in the same panel. This can be useful when comparing columns that store same type of data but differ in some nature. After reshaping the data, let us see how line plots of the various column will appear.
Syntax:
ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()
Example:
R
library(ggplot2) set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) # Reshape data framedf_reshaped <- data.frame(x = df$x, y = c(df$y1, df$y2, df$y3), group = c(rep("y1", nrow(df)), rep("y2", nrow(df)), rep("y3", nrow(df)))) ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()
Output:
Plotting multiple variables in the different panels
In this method, we plot a line graph for each column of the dataframe in the different panel of a same plot. We can achieve this task by adding facet_grid() function. facet_grid() function produces a layout panel defined by rows and columns.
Syntax:
ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()+ facet_grid(group ~ .)
Example:
R
library(ggplot2) set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) # Reshape data framedf_reshaped <- data.frame(x = df$x, y = c(df$y1, df$y2, df$y3), group = c(rep("y1", nrow(df)), rep("y2", nrow(df)), rep("y3", nrow(df)))) ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()+ facet_grid(group ~ .)
Output:
adnanirshad158
Picked
R-Charts
R-DataFrame
R-Graphs
R-plots
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?
K-Means Clustering in R Programming
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
R - if statement
How to import an Excel File into R ?
Plot mean and standard deviation using ggplot2 in R
|
[
{
"code": null,
"e": 26357,
"s": 26329,
"text": "\n10 Sep, 2021"
},
{
"code": null,
"e": 26456,
"s": 26357,
"text": "In this article, we will learn how to plot all columns of the DataFrame in R programming language."
},
{
"code": null,
"e": 26472,
"s": 26456,
"text": "Dataset in use:"
},
{
"code": null,
"e": 26799,
"s": 26472,
"text": " x y1 y2 y3\n1 1 0.08475635 0.4543649 0\n2 2 0.22646034 0.6492529 1\n3 3 0.43255650 0.1537271 0\n4 4 0.55806524 0.6492887 3\n5 5 0.05975527 0.3832137 1\n6 6 0.08475635 0.4543649 0\n7 7 0.22646034 0.6492529 1\n8 8 0.43255650 0.1537271 0\n9 9 0.55806524 0.6492887 3\n10 10 0.05975527 0.3832137 1"
},
{
"code": null,
"e": 26995,
"s": 26799,
"text": "We just have to pass our dataframe in the plot.ts() function, and it will plot all the dataframe columns in a time series plot. In the Y-axis we can see the names of the columns of our dataframe."
},
{
"code": null,
"e": 27015,
"s": 26995,
"text": "Syntax: plot.ts(df)"
},
{
"code": null,
"e": 27028,
"s": 27015,
"text": "Parameters: "
},
{
"code": null,
"e": 27049,
"s": 27028,
"text": "df: DataFrame object"
},
{
"code": null,
"e": 27058,
"s": 27049,
"text": "Example:"
},
{
"code": null,
"e": 27060,
"s": 27058,
"text": "R"
},
{
"code": "set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1))plot.ts(df)",
"e": 27258,
"s": 27060,
"text": null
},
{
"code": null,
"e": 27270,
"s": 27262,
"text": "Output:"
},
{
"code": null,
"e": 27544,
"s": 27274,
"text": "The zoo() function is present in the zoo package, so it has to be imported by placing require(zoo) function on the first line of the code. This function converts the dataframe in such a format(βzooβ series) that it can be plotted easily in a form of a time series plot."
},
{
"code": null,
"e": 27718,
"s": 27546,
"text": "Since y is NULL in our case, a time series plot of x is produced. But if both x and y were a uni-variate βzooβ series then a scatter plot of y vs x wouldβve been produced."
},
{
"code": null,
"e": 27742,
"s": 27720,
"text": "Syntax: plot(zoo(df))"
},
{
"code": null,
"e": 27755,
"s": 27742,
"text": "Parameters: "
},
{
"code": null,
"e": 27776,
"s": 27755,
"text": "df: DataFrame object"
},
{
"code": null,
"e": 27787,
"s": 27778,
"text": "Example:"
},
{
"code": null,
"e": 27791,
"s": 27789,
"text": "R"
},
{
"code": "require(zoo)set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) df <- zoo(df)plot(df)",
"e": 28012,
"s": 27791,
"text": null
},
{
"code": null,
"e": 28024,
"s": 28016,
"text": "Output:"
},
{
"code": null,
"e": 28285,
"s": 28028,
"text": "In this approach, we will plot a line chart showing multiple columns of a data frame using the basic plot() function. The plot() function is defined as a generic function for plotting in R Language. It can be used to create basic plots of a different type."
},
{
"code": null,
"e": 28343,
"s": 28287,
"text": "Syntax: plot(X, Y, type = βlβ, col = 1, ylim = c(0, 3))"
},
{
"code": null,
"e": 28356,
"s": 28343,
"text": "Parameters: "
},
{
"code": null,
"e": 28370,
"s": 28356,
"text": "X: X-axis. ->"
},
{
"code": null,
"e": 28383,
"s": 28370,
"text": "Y: Y-axis ->"
},
{
"code": null,
"e": 28416,
"s": 28383,
"text": "type: specifies the type of plot"
},
{
"code": null,
"e": 28438,
"s": 28416,
"text": "col: specifies colour"
},
{
"code": null,
"e": 28471,
"s": 28438,
"text": "ylim: specifies limit for y-axis"
},
{
"code": null,
"e": 28803,
"s": 28473,
"text": "In the code below first dataframe column is X-axis, and the rest columns are y-axis, and they are plotted against the first column in form of a line chart. The value of col should be different for different lines such that different line has a different color, and finally we have specified ylim which limits the value of y-axis."
},
{
"code": null,
"e": 28955,
"s": 28805,
"text": "We can also plot different types of plots by specifying different values for type parameters. For example, type=βhβ, would have plotted a histogram. "
},
{
"code": null,
"e": 28966,
"s": 28957,
"text": "Example:"
},
{
"code": null,
"e": 28970,
"s": 28968,
"text": "R"
},
{
"code": "require(zoo)set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) plot(df$x, df$y1, type = \"o\", col = 1, ylim = c(0, 3))lines(df$x, df$y2, type = \"o\", col = 2)lines(df$x, df$y3, type = \"o\", col = 3)",
"e": 29301,
"s": 28970,
"text": null
},
{
"code": null,
"e": 29313,
"s": 29305,
"text": "Output:"
},
{
"code": null,
"e": 29397,
"s": 29317,
"text": "For this the data has to be reshaped to be in the form where it can be plotted."
},
{
"code": null,
"e": 29408,
"s": 29399,
"text": "Example:"
},
{
"code": null,
"e": 29412,
"s": 29410,
"text": "R"
},
{
"code": "library(ggplot2) set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) # Reshape data framedf_reshaped <- data.frame(x = df$x, y = c(df$y1, df$y2, df$y3), group = c(rep(\"y1\", nrow(df)), rep(\"y2\", nrow(df)), rep(\"y3\", nrow(df))))head(df_reshaped,10)",
"e": 29928,
"s": 29412,
"text": null
},
{
"code": null,
"e": 29936,
"s": 29928,
"text": "Output:"
},
{
"code": null,
"e": 30187,
"s": 29936,
"text": " x y group\n1 1 0.08475635 y1\n2 2 0.22646034 y1\n3 3 0.43255650 y1\n4 4 0.55806524 y1\n5 5 0.05975527 y1\n6 6 0.08475635 y1\n7 7 0.22646034 y1\n8 8 0.43255650 y1\n9 9 0.55806524 y1\n10 10 0.05975527 y1"
},
{
"code": null,
"e": 30233,
"s": 30187,
"text": "Plotting multiple variables in the same panel"
},
{
"code": null,
"e": 30507,
"s": 30233,
"text": "In this method, we plot a line graph for each column of the dataframe in the same panel. This can be useful when comparing columns that store same type of data but differ in some nature. After reshaping the data, let us see how line plots of the various column will appear."
},
{
"code": null,
"e": 30515,
"s": 30507,
"text": "Syntax:"
},
{
"code": null,
"e": 30574,
"s": 30515,
"text": "ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()"
},
{
"code": null,
"e": 30583,
"s": 30574,
"text": "Example:"
},
{
"code": null,
"e": 30585,
"s": 30583,
"text": "R"
},
{
"code": "library(ggplot2) set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) # Reshape data framedf_reshaped <- data.frame(x = df$x, y = c(df$y1, df$y2, df$y3), group = c(rep(\"y1\", nrow(df)), rep(\"y2\", nrow(df)), rep(\"y3\", nrow(df)))) ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()",
"e": 31140,
"s": 30585,
"text": null
},
{
"code": null,
"e": 31152,
"s": 31144,
"text": "Output:"
},
{
"code": null,
"e": 31208,
"s": 31156,
"text": "Plotting multiple variables in the different panels"
},
{
"code": null,
"e": 31452,
"s": 31210,
"text": "In this method, we plot a line graph for each column of the dataframe in the different panel of a same plot. We can achieve this task by adding facet_grid() function. facet_grid() function produces a layout panel defined by rows and columns."
},
{
"code": null,
"e": 31464,
"s": 31454,
"text": "Syntax: "
},
{
"code": null,
"e": 31549,
"s": 31466,
"text": "ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()+ facet_grid(group ~ .) "
},
{
"code": null,
"e": 31560,
"s": 31551,
"text": "Example:"
},
{
"code": null,
"e": 31564,
"s": 31562,
"text": "R"
},
{
"code": "library(ggplot2) set.seed(200) df <- data.frame(x = 1:10, y1 = rnorm(5), y2 = runif(5), y3 = rpois(5, 1)) # Reshape data framedf_reshaped <- data.frame(x = df$x, y = c(df$y1, df$y2, df$y3), group = c(rep(\"y1\", nrow(df)), rep(\"y2\", nrow(df)), rep(\"y3\", nrow(df)))) ggplot(df_reshaped, aes(x, y, col = group)) + geom_line()+ facet_grid(group ~ .)",
"e": 32142,
"s": 31564,
"text": null
},
{
"code": null,
"e": 32150,
"s": 32142,
"text": "Output:"
},
{
"code": null,
"e": 32165,
"s": 32150,
"text": "adnanirshad158"
},
{
"code": null,
"e": 32172,
"s": 32165,
"text": "Picked"
},
{
"code": null,
"e": 32181,
"s": 32172,
"text": "R-Charts"
},
{
"code": null,
"e": 32193,
"s": 32181,
"text": "R-DataFrame"
},
{
"code": null,
"e": 32202,
"s": 32193,
"text": "R-Graphs"
},
{
"code": null,
"e": 32210,
"s": 32202,
"text": "R-plots"
},
{
"code": null,
"e": 32221,
"s": 32210,
"text": "R Language"
},
{
"code": null,
"e": 32319,
"s": 32221,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32371,
"s": 32319,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 32406,
"s": 32371,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 32444,
"s": 32406,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 32502,
"s": 32444,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 32538,
"s": 32502,
"text": "K-Means Clustering in R Programming"
},
{
"code": null,
"e": 32581,
"s": 32538,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 32630,
"s": 32581,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 32647,
"s": 32630,
"text": "R - if statement"
},
{
"code": null,
"e": 32684,
"s": 32647,
"text": "How to import an Excel File into R ?"
}
] |
Find the numbers from 1 to N that contains exactly k non-zero digits - GeeksforGeeks
|
24 Nov, 2021
Prerequisites: Dynamic Programming, DigitDPGiven two integers N and K. The task is to find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten.
Examples:
Input: N = 100, K = 1 Output: 19 Explanation: The digits with exactly 1 non zero digits between 1 and 100 are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100
Input: N = 25, K = 2 Output: 14 Explanation: The digits with exactly 2 non zero digits between 1 and 25 are: 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25
Approach: It is enough to consider the integers of N digits, by filling the higher digits with 0 if necessary. This problem can be solved by applying the method called digit DP.
dp[i][0][j] = The higher i digits have already been decided, and there are j non-zero digits, and it has already been determined that it is less than N.
dp[i][1][j] = The higher i digits have already been decided, and there are j non-zero digits, and it has not yet been determined that it is less than N.
After computing the above dp, the desired answer is dp[L][0][K] + dp[L][1][K], where L is the number of digits of N.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find number less than N// having k non-zero digitsint k_nonzero_numbers(string s, int n, int k){ // Store the memorised values int dp[n + 1][2][k + 1]; // Initialise for (int i = 0; i <= n; i++) for (int j = 0; j < 2; j++) for (int x = 0; x <= k; x++) dp[i][j][x] = 0; // Base dp[0][0][0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for (int i = 0; i < n; ++i) { int sm = 0; while (sm < 2) { for (int j = 0; j < k + 1; ++j) { int x = 0; while (x <= (sm ? 9 : s[i] - '0')) { dp[i + 1][sm || x < (s[i] - '0')][j + (x > 0)] += dp[i][sm][j]; ++x; } } ++sm; } } // Return the required answer return dp[n][0][k] + dp[n][1][k];} // Driver codeint main(){ string s = "25"; int k = 2; int n = s.size(); // Function call cout << k_nonzero_numbers(s, n, k); return 0;}
// Java implementation of the above approachclass Geeks{ // Function to find number less than N// having k non-zero digitsstatic int k_nonzero_numbers(String s, int n, int k){ // Store the memorised values int dp[][][] = new int[n + 1][2][k + 1]; // Initialise for(int i = 0; i <= n; i++) for(int j = 0; j < 2; j++) for(int x = 0; x <= k; x++) dp[i][j][x] = 0; // Base dp[0][0][0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for(int i = 0; i < n; ++i) { int sm = 0; while (sm < 2) { for(int j = 0; j < k + 1; ++j) { int x = 0; while (x <= (sm != 0 ? 9 :s.charAt(i) - '0')) { if (j + (x > 0 ? 1 : 0) < k + 1) { dp[i + 1][(sm != 0 || x < (s.charAt(i) - '0')) ? 1 : 0][j + (x > 0 ? 1 : 0)] += dp[i][sm][j]; } ++x; } } ++sm; } } // Return the required answer return dp[n][0][k] + dp[n][1][k];} // Driver codepublic static void main(String[] args){ String s = "25"; int k = 2; int n = s.length(); // Function call System.out.println(k_nonzero_numbers(s, n, k));}} // This code is contributed by Rajnis09
# Python3 implementation of the above approach # Function to find number less than N# having k non-zero digitsdef k_nonzero_numbers(s, n, k): # Store the memorised values dp = [[[ 0 for i in range(k + 2)] for i in range(2)] for i in range(n + 2)] # Initialise for i in range(n + 1): for j in range(2): for x in range(k + 1): dp[i][j][x] = 0 # Base dp[0][0][0] = 1 # Calculate all states # For every state, from numbers 1 to N, # the count of numbers which contain # exactly j non zero digits is being # computed and updated in the dp array. for i in range(n): sm = 0 while (sm < 2): for j in range(k + 1): x = 0 y = 0 if sm: y = 9 else: y = ord(s[i]) - ord('0') while (x <= y): dp[i + 1][(sm or x < ( ord(s[i]) - ord('0')))][j + (x > 0)] += dp[i][sm][j] x += 1 sm += 1 # Return the required answer return dp[n][0][k] + dp[n][1][k] # Driver codeif __name__ == '__main__': s = "25" k = 2 n = len(s) # Function call print(k_nonzero_numbers(s, n, k)) # This code is contributed by mohit kumar 29
// C# implementation of the above approachusing System;using System.Collections; class GFG{ // Function to find number less than N// having k non-zero digitsstatic int k_nonzero_numbers(string s, int n, int k){ // Store the memorised values int [,,]dp = new int[n + 1, 2, k + 1]; // Initialise for(int i = 0; i <= n; i++) for(int j = 0; j < 2; j++) for(int x = 0; x <= k; x++) dp[i, j, x] = 0; // Base dp[0, 0, 0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for(int i = 0; i < n; ++i) { int sm = 0; while (sm < 2) { for(int j = 0; j < k + 1; ++j) { int x = 0; while (x <= (sm != 0 ? 9 : s[i]- '0')) { if (j + (x > 0 ? 1 : 0) < k + 1) { dp[i + 1, ((sm != 0 || x < (s[i] - '0')) ? 1 : 0), j + (x > 0 ? 1 : 0)] += dp[i, sm, j]; } ++x; } } ++sm; } } // Return the required answer return dp[n, 0, k] + dp[n, 1, k];} // Driver codepublic static void Main(string[] args){ string s = "25"; int k = 2; int n = s.Length; // Function call Console.Write(k_nonzero_numbers(s, n, k));}} // This code is contributed by rutvik_56
<script> // Javascript implementation of the above approach // Function to find number less than N// having k non-zero digitsfunction k_nonzero_numbers(s,n,k){ // Store the memorised values let dp = new Array(n + 1); // Initialise for(let i = 0; i <= n; i++) { dp[i]=new Array(2); for(let j = 0; j < 2; j++) { dp[i][j] = new Array(k+1); for(let x = 0; x <= k; x++) dp[i][j][x] = 0; } } // Base dp[0][0][0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for(let i = 0; i < n; ++i) { let sm = 0; while (sm < 2) { for(let j = 0; j < k + 1; ++j) { let x = 0; while (x <= (sm != 0 ? 9 :s[i].charCodeAt(0) - '0'.charCodeAt(0))) { if (j + (x > 0 ? 1 : 0) < k + 1) { dp[i + 1][(sm != 0 || x < (s[i].charCodeAt(0) - '0'.charCodeAt(0))) ? 1 : 0][j + (x > 0 ? 1 : 0)] += dp[i][sm][j]; } ++x; } } ++sm; } } // Return the required answer return dp[n][0][k] + dp[n][1][k];} // Driver codelet s = "25"; let k = 2;let n = s.length; // Function calldocument.write(k_nonzero_numbers(s, n, k)); // This code is contributed by unknown2108</script>
14
Time Complexity: O(LK) where L is the number of digits in N.
Auxiliary Space: O(N * K * 2)Note: The two for loops used to calculate the state which from [0, 1] and [0, 9] respectively are considered as a constant multiplication.
Rajnis09
rutvik_56
mohit kumar 29
unknown2108
rishavmahato348
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
BellmanβFord Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
Merge two sorted arrays
|
[
{
"code": null,
"e": 26669,
"s": 26641,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 26877,
"s": 26669,
"text": "Prerequisites: Dynamic Programming, DigitDPGiven two integers N and K. The task is to find the number of integers between 1 and N (inclusive) that contains exactly K non-zero digits when written in base ten."
},
{
"code": null,
"e": 26889,
"s": 26877,
"text": "Examples: "
},
{
"code": null,
"e": 27067,
"s": 26889,
"text": "Input: N = 100, K = 1 Output: 19 Explanation: The digits with exactly 1 non zero digits between 1 and 100 are: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100"
},
{
"code": null,
"e": 27232,
"s": 27067,
"text": "Input: N = 25, K = 2 Output: 14 Explanation: The digits with exactly 2 non zero digits between 1 and 25 are: 11, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25 "
},
{
"code": null,
"e": 27411,
"s": 27232,
"text": "Approach: It is enough to consider the integers of N digits, by filling the higher digits with 0 if necessary. This problem can be solved by applying the method called digit DP. "
},
{
"code": null,
"e": 27564,
"s": 27411,
"text": "dp[i][0][j] = The higher i digits have already been decided, and there are j non-zero digits, and it has already been determined that it is less than N."
},
{
"code": null,
"e": 27717,
"s": 27564,
"text": "dp[i][1][j] = The higher i digits have already been decided, and there are j non-zero digits, and it has not yet been determined that it is less than N."
},
{
"code": null,
"e": 27835,
"s": 27717,
"text": "After computing the above dp, the desired answer is dp[L][0][K] + dp[L][1][K], where L is the number of digits of N. "
},
{
"code": null,
"e": 27887,
"s": 27835,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27891,
"s": 27887,
"text": "C++"
},
{
"code": null,
"e": 27896,
"s": 27891,
"text": "Java"
},
{
"code": null,
"e": 27904,
"s": 27896,
"text": "Python3"
},
{
"code": null,
"e": 27907,
"s": 27904,
"text": "C#"
},
{
"code": null,
"e": 27918,
"s": 27907,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find number less than N// having k non-zero digitsint k_nonzero_numbers(string s, int n, int k){ // Store the memorised values int dp[n + 1][2][k + 1]; // Initialise for (int i = 0; i <= n; i++) for (int j = 0; j < 2; j++) for (int x = 0; x <= k; x++) dp[i][j][x] = 0; // Base dp[0][0][0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for (int i = 0; i < n; ++i) { int sm = 0; while (sm < 2) { for (int j = 0; j < k + 1; ++j) { int x = 0; while (x <= (sm ? 9 : s[i] - '0')) { dp[i + 1][sm || x < (s[i] - '0')][j + (x > 0)] += dp[i][sm][j]; ++x; } } ++sm; } } // Return the required answer return dp[n][0][k] + dp[n][1][k];} // Driver codeint main(){ string s = \"25\"; int k = 2; int n = s.size(); // Function call cout << k_nonzero_numbers(s, n, k); return 0;}",
"e": 29186,
"s": 27918,
"text": null
},
{
"code": "// Java implementation of the above approachclass Geeks{ // Function to find number less than N// having k non-zero digitsstatic int k_nonzero_numbers(String s, int n, int k){ // Store the memorised values int dp[][][] = new int[n + 1][2][k + 1]; // Initialise for(int i = 0; i <= n; i++) for(int j = 0; j < 2; j++) for(int x = 0; x <= k; x++) dp[i][j][x] = 0; // Base dp[0][0][0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for(int i = 0; i < n; ++i) { int sm = 0; while (sm < 2) { for(int j = 0; j < k + 1; ++j) { int x = 0; while (x <= (sm != 0 ? 9 :s.charAt(i) - '0')) { if (j + (x > 0 ? 1 : 0) < k + 1) { dp[i + 1][(sm != 0 || x < (s.charAt(i) - '0')) ? 1 : 0][j + (x > 0 ? 1 : 0)] += dp[i][sm][j]; } ++x; } } ++sm; } } // Return the required answer return dp[n][0][k] + dp[n][1][k];} // Driver codepublic static void main(String[] args){ String s = \"25\"; int k = 2; int n = s.length(); // Function call System.out.println(k_nonzero_numbers(s, n, k));}} // This code is contributed by Rajnis09",
"e": 30790,
"s": 29186,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to find number less than N# having k non-zero digitsdef k_nonzero_numbers(s, n, k): # Store the memorised values dp = [[[ 0 for i in range(k + 2)] for i in range(2)] for i in range(n + 2)] # Initialise for i in range(n + 1): for j in range(2): for x in range(k + 1): dp[i][j][x] = 0 # Base dp[0][0][0] = 1 # Calculate all states # For every state, from numbers 1 to N, # the count of numbers which contain # exactly j non zero digits is being # computed and updated in the dp array. for i in range(n): sm = 0 while (sm < 2): for j in range(k + 1): x = 0 y = 0 if sm: y = 9 else: y = ord(s[i]) - ord('0') while (x <= y): dp[i + 1][(sm or x < ( ord(s[i]) - ord('0')))][j + (x > 0)] += dp[i][sm][j] x += 1 sm += 1 # Return the required answer return dp[n][0][k] + dp[n][1][k] # Driver codeif __name__ == '__main__': s = \"25\" k = 2 n = len(s) # Function call print(k_nonzero_numbers(s, n, k)) # This code is contributed by mohit kumar 29",
"e": 32174,
"s": 30790,
"text": null
},
{
"code": "// C# implementation of the above approachusing System;using System.Collections; class GFG{ // Function to find number less than N// having k non-zero digitsstatic int k_nonzero_numbers(string s, int n, int k){ // Store the memorised values int [,,]dp = new int[n + 1, 2, k + 1]; // Initialise for(int i = 0; i <= n; i++) for(int j = 0; j < 2; j++) for(int x = 0; x <= k; x++) dp[i, j, x] = 0; // Base dp[0, 0, 0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for(int i = 0; i < n; ++i) { int sm = 0; while (sm < 2) { for(int j = 0; j < k + 1; ++j) { int x = 0; while (x <= (sm != 0 ? 9 : s[i]- '0')) { if (j + (x > 0 ? 1 : 0) < k + 1) { dp[i + 1, ((sm != 0 || x < (s[i] - '0')) ? 1 : 0), j + (x > 0 ? 1 : 0)] += dp[i, sm, j]; } ++x; } } ++sm; } } // Return the required answer return dp[n, 0, k] + dp[n, 1, k];} // Driver codepublic static void Main(string[] args){ string s = \"25\"; int k = 2; int n = s.Length; // Function call Console.Write(k_nonzero_numbers(s, n, k));}} // This code is contributed by rutvik_56",
"e": 33801,
"s": 32174,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Function to find number less than N// having k non-zero digitsfunction k_nonzero_numbers(s,n,k){ // Store the memorised values let dp = new Array(n + 1); // Initialise for(let i = 0; i <= n; i++) { dp[i]=new Array(2); for(let j = 0; j < 2; j++) { dp[i][j] = new Array(k+1); for(let x = 0; x <= k; x++) dp[i][j][x] = 0; } } // Base dp[0][0][0] = 1; // Calculate all states // For every state, from numbers 1 to N, // the count of numbers which contain exactly j // non zero digits is being computed and updated // in the dp array. for(let i = 0; i < n; ++i) { let sm = 0; while (sm < 2) { for(let j = 0; j < k + 1; ++j) { let x = 0; while (x <= (sm != 0 ? 9 :s[i].charCodeAt(0) - '0'.charCodeAt(0))) { if (j + (x > 0 ? 1 : 0) < k + 1) { dp[i + 1][(sm != 0 || x < (s[i].charCodeAt(0) - '0'.charCodeAt(0))) ? 1 : 0][j + (x > 0 ? 1 : 0)] += dp[i][sm][j]; } ++x; } } ++sm; } } // Return the required answer return dp[n][0][k] + dp[n][1][k];} // Driver codelet s = \"25\"; let k = 2;let n = s.length; // Function calldocument.write(k_nonzero_numbers(s, n, k)); // This code is contributed by unknown2108</script>",
"e": 35450,
"s": 33801,
"text": null
},
{
"code": null,
"e": 35453,
"s": 35450,
"text": "14"
},
{
"code": null,
"e": 35517,
"s": 35455,
"text": "Time Complexity: O(LK) where L is the number of digits in N. "
},
{
"code": null,
"e": 35686,
"s": 35517,
"text": "Auxiliary Space: O(N * K * 2)Note: The two for loops used to calculate the state which from [0, 1] and [0, 9] respectively are considered as a constant multiplication. "
},
{
"code": null,
"e": 35695,
"s": 35686,
"text": "Rajnis09"
},
{
"code": null,
"e": 35705,
"s": 35695,
"text": "rutvik_56"
},
{
"code": null,
"e": 35720,
"s": 35705,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 35732,
"s": 35720,
"text": "unknown2108"
},
{
"code": null,
"e": 35748,
"s": 35732,
"text": "rishavmahato348"
},
{
"code": null,
"e": 35768,
"s": 35748,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35781,
"s": 35768,
"text": "Mathematical"
},
{
"code": null,
"e": 35801,
"s": 35781,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 35814,
"s": 35801,
"text": "Mathematical"
},
{
"code": null,
"e": 35912,
"s": 35814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35943,
"s": 35912,
"text": "BellmanβFord Algorithm | DP-23"
},
{
"code": null,
"e": 35976,
"s": 35943,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 36003,
"s": 35976,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 36022,
"s": 36003,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 36057,
"s": 36022,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 36117,
"s": 36057,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 36132,
"s": 36117,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36175,
"s": 36132,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 36194,
"s": 36175,
"text": "Coin Change | DP-7"
}
] |
Command Pattern - GeeksforGeeks
|
01 Sep, 2021
Like previous articles, let us take up a design problem to understand command pattern. Suppose you are building a home automation system. There is a programmable remote which can be used to turn on and off various items in your home like lights, stereo, AC etc. It looks something like this.
You can do it with simple if-else statements like
if (buttonPressed == button1)
lights.on()
But we need to keep in mind that turning on some devices like stereo comprises of many steps like setting cd, volume etc. Also we can reassign a button to do something else. By using simple if-else we are coding to implementation rather than interface. Also there is tight coupling.
So what we want to achieve is a design that provides loose coupling and remote control should not have much information about a particular device. The command pattern helps us do that.
Definition: The command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations.
The definition is a bit confusing at first but letβs step through it. In analogy to our problem above remote control is the client and stereo, lights etc. are the receivers. In command pattern there is a Command object that encapsulates a request by binding together a set of actions on a specific receiver. It does so by exposing just one method execute() that causes some actions to be invoked on the receiver.
Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on stereo or maybe open the garage door.
queue or log requests, and support undoable operations means that Commandβs Execute operation can store state for reversing its effects in the Command itself. The Command may have an added unExecute operation that reverses the effects of a previous call to execute.It may also support logging changes so that they can be reapplied in case of a system crash.
Below is the Java implementation of above mentioned remote control example:
// A simple Java program to demonstrate// implementation of Command Pattern using// a remote control example. // An interface for commandinterface Command{ public void execute();} // Light class and its corresponding command// classesclass Light{ public void on() { System.out.println("Light is on"); } public void off() { System.out.println("Light is off"); }}class LightOnCommand implements Command{ Light light; // The constructor is passed the light it // is going to control. public LightOnCommand(Light light) { this.light = light; } public void execute() { light.on(); }}class LightOffCommand implements Command{ Light light; public LightOffCommand(Light light) { this.light = light; } public void execute() { light.off(); }} // Stereo and its command classesclass Stereo{ public void on() { System.out.println("Stereo is on"); } public void off() { System.out.println("Stereo is off"); } public void setCD() { System.out.println("Stereo is set " + "for CD input"); } public void setDVD() { System.out.println("Stereo is set"+ " for DVD input"); } public void setRadio() { System.out.println("Stereo is set" + " for Radio"); } public void setVolume(int volume) { // code to set the volume System.out.println("Stereo volume set" + " to " + volume); }}class StereoOffCommand implements Command{ Stereo stereo; public StereoOffCommand(Stereo stereo) { this.stereo = stereo; } public void execute() { stereo.off(); }}class StereoOnWithCDCommand implements Command{ Stereo stereo; public StereoOnWithCDCommand(Stereo stereo) { this.stereo = stereo; } public void execute() { stereo.on(); stereo.setCD(); stereo.setVolume(11); }} // A Simple remote control with one buttonclass SimpleRemoteControl{ Command slot; // only one button public SimpleRemoteControl() { } public void setCommand(Command command) { // set the command the remote will // execute slot = command; } public void buttonWasPressed() { slot.execute(); }} // Driver classclass RemoteControlTest{ public static void main(String[] args) { SimpleRemoteControl remote = new SimpleRemoteControl(); Light light = new Light(); Stereo stereo = new Stereo(); // we can change command dynamically remote.setCommand(new LightOnCommand(light)); remote.buttonWasPressed(); remote.setCommand(new StereoOnWithCDCommand(stereo)); remote.buttonWasPressed(); remote.setCommand(new StereoOffCommand(stereo)); remote.buttonWasPressed(); } }
Output:
Light is on
Stereo is on
Stereo is set for CD input
Stereo volume set to 11
Stereo is off
Notice that the remote control doesnβt know anything about turning on the stereo. That information is contained in a separate command object. This reduces the coupling between them.
Advantages:
Makes our code extensible as we can add new commands without changing existing code.
Reduces coupling the invoker and receiver of a command.
Disadvantages:
Increase in the number of classes for each individual command
Further Read β Command Method in Python
References:
Head First Design Patterns (book)
https://github.com/bethrobson/Head-First-Design-Patterns/tree/master/src/headfirst/designpatterns/command
If This article is contributed by Sulabh Kumar. 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
Design Pattern
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Unified Modeling Language (UML) | An Introduction
Unified Modeling Language (UML) | State Diagrams
Abstract Factory Pattern
Composite Design Pattern
Observer Pattern | Set 1 (Introduction)
Monolithic vs Microservices architecture
Unified Modeling Language (UML) | Class Diagrams
Singleton Design Pattern | Introduction
How to design a parking lot using object-oriented principles?
Chain of Responsibility Design Pattern
|
[
{
"code": null,
"e": 25803,
"s": 25775,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 26095,
"s": 25803,
"text": "Like previous articles, let us take up a design problem to understand command pattern. Suppose you are building a home automation system. There is a programmable remote which can be used to turn on and off various items in your home like lights, stereo, AC etc. It looks something like this."
},
{
"code": null,
"e": 26147,
"s": 26097,
"text": "You can do it with simple if-else statements like"
},
{
"code": null,
"e": 26195,
"s": 26147,
"text": "if (buttonPressed == button1)\n lights.on()\n"
},
{
"code": null,
"e": 26478,
"s": 26195,
"text": "But we need to keep in mind that turning on some devices like stereo comprises of many steps like setting cd, volume etc. Also we can reassign a button to do something else. By using simple if-else we are coding to implementation rather than interface. Also there is tight coupling."
},
{
"code": null,
"e": 26663,
"s": 26478,
"text": "So what we want to achieve is a design that provides loose coupling and remote control should not have much information about a particular device. The command pattern helps us do that."
},
{
"code": null,
"e": 26859,
"s": 26663,
"text": "Definition: The command pattern encapsulates a request as an object, thereby letting us parameterize other objects with different requests, queue or log requests, and support undoable operations."
},
{
"code": null,
"e": 27272,
"s": 26859,
"text": "The definition is a bit confusing at first but letβs step through it. In analogy to our problem above remote control is the client and stereo, lights etc. are the receivers. In command pattern there is a Command object that encapsulates a request by binding together a set of actions on a specific receiver. It does so by exposing just one method execute() that causes some actions to be invoked on the receiver."
},
{
"code": null,
"e": 27456,
"s": 27272,
"text": "Parameterizing other objects with different requests in our analogy means that the button used to turn on the lights can later be used to turn on stereo or maybe open the garage door."
},
{
"code": null,
"e": 27814,
"s": 27456,
"text": "queue or log requests, and support undoable operations means that Commandβs Execute operation can store state for reversing its effects in the Command itself. The Command may have an added unExecute operation that reverses the effects of a previous call to execute.It may also support logging changes so that they can be reapplied in case of a system crash."
},
{
"code": null,
"e": 27890,
"s": 27814,
"text": "Below is the Java implementation of above mentioned remote control example:"
},
{
"code": "// A simple Java program to demonstrate// implementation of Command Pattern using// a remote control example. // An interface for commandinterface Command{ public void execute();} // Light class and its corresponding command// classesclass Light{ public void on() { System.out.println(\"Light is on\"); } public void off() { System.out.println(\"Light is off\"); }}class LightOnCommand implements Command{ Light light; // The constructor is passed the light it // is going to control. public LightOnCommand(Light light) { this.light = light; } public void execute() { light.on(); }}class LightOffCommand implements Command{ Light light; public LightOffCommand(Light light) { this.light = light; } public void execute() { light.off(); }} // Stereo and its command classesclass Stereo{ public void on() { System.out.println(\"Stereo is on\"); } public void off() { System.out.println(\"Stereo is off\"); } public void setCD() { System.out.println(\"Stereo is set \" + \"for CD input\"); } public void setDVD() { System.out.println(\"Stereo is set\"+ \" for DVD input\"); } public void setRadio() { System.out.println(\"Stereo is set\" + \" for Radio\"); } public void setVolume(int volume) { // code to set the volume System.out.println(\"Stereo volume set\" + \" to \" + volume); }}class StereoOffCommand implements Command{ Stereo stereo; public StereoOffCommand(Stereo stereo) { this.stereo = stereo; } public void execute() { stereo.off(); }}class StereoOnWithCDCommand implements Command{ Stereo stereo; public StereoOnWithCDCommand(Stereo stereo) { this.stereo = stereo; } public void execute() { stereo.on(); stereo.setCD(); stereo.setVolume(11); }} // A Simple remote control with one buttonclass SimpleRemoteControl{ Command slot; // only one button public SimpleRemoteControl() { } public void setCommand(Command command) { // set the command the remote will // execute slot = command; } public void buttonWasPressed() { slot.execute(); }} // Driver classclass RemoteControlTest{ public static void main(String[] args) { SimpleRemoteControl remote = new SimpleRemoteControl(); Light light = new Light(); Stereo stereo = new Stereo(); // we can change command dynamically remote.setCommand(new LightOnCommand(light)); remote.buttonWasPressed(); remote.setCommand(new StereoOnWithCDCommand(stereo)); remote.buttonWasPressed(); remote.setCommand(new StereoOffCommand(stereo)); remote.buttonWasPressed(); } }",
"e": 30909,
"s": 27890,
"text": null
},
{
"code": null,
"e": 30917,
"s": 30909,
"text": "Output:"
},
{
"code": null,
"e": 31007,
"s": 30917,
"text": "Light is on\nStereo is on\nStereo is set for CD input\nStereo volume set to 11\nStereo is off"
},
{
"code": null,
"e": 31189,
"s": 31007,
"text": "Notice that the remote control doesnβt know anything about turning on the stereo. That information is contained in a separate command object. This reduces the coupling between them."
},
{
"code": null,
"e": 31201,
"s": 31189,
"text": "Advantages:"
},
{
"code": null,
"e": 31286,
"s": 31201,
"text": "Makes our code extensible as we can add new commands without changing existing code."
},
{
"code": null,
"e": 31342,
"s": 31286,
"text": "Reduces coupling the invoker and receiver of a command."
},
{
"code": null,
"e": 31357,
"s": 31342,
"text": "Disadvantages:"
},
{
"code": null,
"e": 31419,
"s": 31357,
"text": "Increase in the number of classes for each individual command"
},
{
"code": null,
"e": 31459,
"s": 31419,
"text": "Further Read β Command Method in Python"
},
{
"code": null,
"e": 31471,
"s": 31459,
"text": "References:"
},
{
"code": null,
"e": 31505,
"s": 31471,
"text": "Head First Design Patterns (book)"
},
{
"code": null,
"e": 31611,
"s": 31505,
"text": "https://github.com/bethrobson/Head-First-Design-Patterns/tree/master/src/headfirst/designpatterns/command"
},
{
"code": null,
"e": 31878,
"s": 31611,
"text": "If This article is contributed by Sulabh Kumar. 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": 32002,
"s": 31878,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 32017,
"s": 32002,
"text": "Design Pattern"
},
{
"code": null,
"e": 32115,
"s": 32017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32165,
"s": 32115,
"text": "Unified Modeling Language (UML) | An Introduction"
},
{
"code": null,
"e": 32214,
"s": 32165,
"text": "Unified Modeling Language (UML) | State Diagrams"
},
{
"code": null,
"e": 32239,
"s": 32214,
"text": "Abstract Factory Pattern"
},
{
"code": null,
"e": 32264,
"s": 32239,
"text": "Composite Design Pattern"
},
{
"code": null,
"e": 32304,
"s": 32264,
"text": "Observer Pattern | Set 1 (Introduction)"
},
{
"code": null,
"e": 32345,
"s": 32304,
"text": "Monolithic vs Microservices architecture"
},
{
"code": null,
"e": 32394,
"s": 32345,
"text": "Unified Modeling Language (UML) | Class Diagrams"
},
{
"code": null,
"e": 32434,
"s": 32394,
"text": "Singleton Design Pattern | Introduction"
},
{
"code": null,
"e": 32496,
"s": 32434,
"text": "How to design a parking lot using object-oriented principles?"
}
] |
How to use Python Pexpect to Automate Linux Commands? - GeeksforGeeks
|
13 Dec, 2021
Pexpect is a Python library for spawning child processes and controlling them automatically. Pexpect can be used to automate interactive applications such as SSH, FTP, password, telnet, etc. Pexpect works by spawning child processes and responding to expected patterns.
Pexpect can be installed by using the following command.
pip3 install pexpect
It can be done in different ways:
Using run() method
Using spawn class
Using sendline() method
After the installation letβs see how to automate the Linux commands.
Method 1: Using run() method
The pexpect.run() method can be called to execute a command and return its output. This function can be used as a replacement for os.system.
Example:
Python3
import pexpect print(pexpect.run('echo hello'))
fig 1
Method 2: Using spawn class
Spawn class is the main interface to start a new child process and control it. The string inside spawn can be replaced by the shell command that needs to be executed.
Syntax: pexpect.spawn(βrm ./devβ)
The important methods of pexpect.spawn class are expect().
Syntax: expect(pattern, timeout=-1, searchwindowsize=-1, async_= False)
This method waits for the child process to return a given string. The pattern specified in the except method will be matched all through the string. The timeout is used to raise pexpect.TIMEOUT. The searchwindowsize parameter is used to set the maxread attribute of the class. Set async_ = True when creating a non-blocking application.
Example:
Python3
import pexpect # start a child process with spawn# It just echos geeksforgeekschild = pexpect.spawn("echo geeksforgeeks") # prints he matched index of string.print(child.expect(["hai", "welcome", "geeksforgeeks"]))
Output:
fig 2
The example prints the index that matches the child process.
Method 3: Using sendline(s = β β)
This method writes the string to the child process and also returns the number of bytes written. It appears to the child process as someone is typing from the terminal.
Example:
Python3
import pexpect # Start a child process with spawn# This process waits for the input# form userchild = pexpect.spawn("cat") # The input to the cat process is sent# by the sendline()child.sendline("hai geek") # prints the index of matched string# expressing with child processprint(child.expect(["hello", "hai geek"]))
Output:
fig 3
Letβs see a complex example for better understanding. Here where will use the FTP client to login into ftp.us.debian.org and download welcome.msg file and print the file. Here we are going to use an FTP client to login and download files from a remote machine and then print.
Approach:
Import pexpect.
spawn a child with pexpect.spawn(βftp ftp.us.debian.orβ).
FTP client asks for the user name. Match the pattern with expect(βName .*: β)
Send the username to the child process with sendline method.
Then the FTP client asks for the password. Match the pattern with expect(βPassword: β)
Then the serve logged in. Then you can download files.
Detect whether you can send the command to the FTP server by the presence of βftp> β.
Then send the command by sendline(βget welcome.msgβ), this just downloads the file to the local machine.
Then close the FTP client by using the βbyeβ command.
Finally, print all the interactions with the child process with the child.before. It returns a byte string, decodes it before printing it.
Use pexpect.run to print the content of the downloaded file from the FTP server.
Python3
import pexpect def main(): # spawn a child process. child = pexpect.spawn('ftp ftp.us.debian.org') # search for the Name pattern. child.expect('Name .*: ') # send the username with sendline child.sendline('anonymous') # search for the Password pattern child.expect('Password:') # send the password to the childprocess # by sendline child.sendline('anonymous@') # detect ftp accepts command from user # by 'ftp> ' pattern child.expect('ftp> ') # If it accepts command then download the # welcome.msg file from the ftp server child.sendline('get welcome.msg') # again check wheather ftp client accepts # command from user by 'ftp> ' pattern child.expect('ftp> ') # close the ftp client. child.sendline('bye') # print the interactions with the child # process. print(child.before.decode()) child.interact() # print the downloaded file by executing cat # command with pexpect.run method print(pexpect.run('cat ./welcome.msg').decode()) if __name__ == '__main__': main()
Output:
Fig 4
varshagumber28
sagar0719kumar
sweetyty
gabaa406
Rajvijay
Picked
python-modules
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": "\n13 Dec, 2021"
},
{
"code": null,
"e": 25807,
"s": 25537,
"text": "Pexpect is a Python library for spawning child processes and controlling them automatically. Pexpect can be used to automate interactive applications such as SSH, FTP, password, telnet, etc. Pexpect works by spawning child processes and responding to expected patterns."
},
{
"code": null,
"e": 25864,
"s": 25807,
"text": "Pexpect can be installed by using the following command."
},
{
"code": null,
"e": 25885,
"s": 25864,
"text": "pip3 install pexpect"
},
{
"code": null,
"e": 25919,
"s": 25885,
"text": "It can be done in different ways:"
},
{
"code": null,
"e": 25938,
"s": 25919,
"text": "Using run() method"
},
{
"code": null,
"e": 25956,
"s": 25938,
"text": "Using spawn class"
},
{
"code": null,
"e": 25980,
"s": 25956,
"text": "Using sendline() method"
},
{
"code": null,
"e": 26049,
"s": 25980,
"text": "After the installation letβs see how to automate the Linux commands."
},
{
"code": null,
"e": 26078,
"s": 26049,
"text": "Method 1: Using run() method"
},
{
"code": null,
"e": 26219,
"s": 26078,
"text": "The pexpect.run() method can be called to execute a command and return its output. This function can be used as a replacement for os.system."
},
{
"code": null,
"e": 26228,
"s": 26219,
"text": "Example:"
},
{
"code": null,
"e": 26236,
"s": 26228,
"text": "Python3"
},
{
"code": "import pexpect print(pexpect.run('echo hello'))",
"e": 26284,
"s": 26236,
"text": null
},
{
"code": null,
"e": 26290,
"s": 26284,
"text": "fig 1"
},
{
"code": null,
"e": 26318,
"s": 26290,
"text": "Method 2: Using spawn class"
},
{
"code": null,
"e": 26485,
"s": 26318,
"text": "Spawn class is the main interface to start a new child process and control it. The string inside spawn can be replaced by the shell command that needs to be executed."
},
{
"code": null,
"e": 26519,
"s": 26485,
"text": "Syntax: pexpect.spawn(βrm ./devβ)"
},
{
"code": null,
"e": 26578,
"s": 26519,
"text": "The important methods of pexpect.spawn class are expect()."
},
{
"code": null,
"e": 26650,
"s": 26578,
"text": "Syntax: expect(pattern, timeout=-1, searchwindowsize=-1, async_= False)"
},
{
"code": null,
"e": 26989,
"s": 26650,
"text": "This method waits for the child process to return a given string. The pattern specified in the except method will be matched all through the string. The timeout is used to raise pexpect.TIMEOUT. The searchwindowsize parameter is used to set the maxread attribute of the class. Set async_ = True when creating a non-blocking application."
},
{
"code": null,
"e": 26998,
"s": 26989,
"text": "Example:"
},
{
"code": null,
"e": 27006,
"s": 26998,
"text": "Python3"
},
{
"code": "import pexpect # start a child process with spawn# It just echos geeksforgeekschild = pexpect.spawn(\"echo geeksforgeeks\") # prints he matched index of string.print(child.expect([\"hai\", \"welcome\", \"geeksforgeeks\"]))",
"e": 27223,
"s": 27006,
"text": null
},
{
"code": null,
"e": 27231,
"s": 27223,
"text": "Output:"
},
{
"code": null,
"e": 27237,
"s": 27231,
"text": "fig 2"
},
{
"code": null,
"e": 27298,
"s": 27237,
"text": "The example prints the index that matches the child process."
},
{
"code": null,
"e": 27332,
"s": 27298,
"text": "Method 3: Using sendline(s = β β)"
},
{
"code": null,
"e": 27502,
"s": 27332,
"text": "This method writes the string to the child process and also returns the number of bytes written. It appears to the child process as someone is typing from the terminal. "
},
{
"code": null,
"e": 27511,
"s": 27502,
"text": "Example:"
},
{
"code": null,
"e": 27519,
"s": 27511,
"text": "Python3"
},
{
"code": "import pexpect # Start a child process with spawn# This process waits for the input# form userchild = pexpect.spawn(\"cat\") # The input to the cat process is sent# by the sendline()child.sendline(\"hai geek\") # prints the index of matched string# expressing with child processprint(child.expect([\"hello\", \"hai geek\"]))",
"e": 27837,
"s": 27519,
"text": null
},
{
"code": null,
"e": 27845,
"s": 27837,
"text": "Output:"
},
{
"code": null,
"e": 27851,
"s": 27845,
"text": "fig 3"
},
{
"code": null,
"e": 28128,
"s": 27851,
"text": "Letβs see a complex example for better understanding. Here where will use the FTP client to login into ftp.us.debian.org and download welcome.msg file and print the file. Here we are going to use an FTP client to login and download files from a remote machine and then print."
},
{
"code": null,
"e": 28138,
"s": 28128,
"text": "Approach:"
},
{
"code": null,
"e": 28154,
"s": 28138,
"text": "Import pexpect."
},
{
"code": null,
"e": 28212,
"s": 28154,
"text": "spawn a child with pexpect.spawn(βftp ftp.us.debian.orβ)."
},
{
"code": null,
"e": 28291,
"s": 28212,
"text": "FTP client asks for the user name. Match the pattern with expect(βName .*: β)"
},
{
"code": null,
"e": 28352,
"s": 28291,
"text": "Send the username to the child process with sendline method."
},
{
"code": null,
"e": 28440,
"s": 28352,
"text": "Then the FTP client asks for the password. Match the pattern with expect(βPassword: β)"
},
{
"code": null,
"e": 28495,
"s": 28440,
"text": "Then the serve logged in. Then you can download files."
},
{
"code": null,
"e": 28582,
"s": 28495,
"text": "Detect whether you can send the command to the FTP server by the presence of βftp> β."
},
{
"code": null,
"e": 28687,
"s": 28582,
"text": "Then send the command by sendline(βget welcome.msgβ), this just downloads the file to the local machine."
},
{
"code": null,
"e": 28741,
"s": 28687,
"text": "Then close the FTP client by using the βbyeβ command."
},
{
"code": null,
"e": 28880,
"s": 28741,
"text": "Finally, print all the interactions with the child process with the child.before. It returns a byte string, decodes it before printing it."
},
{
"code": null,
"e": 28961,
"s": 28880,
"text": "Use pexpect.run to print the content of the downloaded file from the FTP server."
},
{
"code": null,
"e": 28969,
"s": 28961,
"text": "Python3"
},
{
"code": "import pexpect def main(): # spawn a child process. child = pexpect.spawn('ftp ftp.us.debian.org') # search for the Name pattern. child.expect('Name .*: ') # send the username with sendline child.sendline('anonymous') # search for the Password pattern child.expect('Password:') # send the password to the childprocess # by sendline child.sendline('anonymous@') # detect ftp accepts command from user # by 'ftp> ' pattern child.expect('ftp> ') # If it accepts command then download the # welcome.msg file from the ftp server child.sendline('get welcome.msg') # again check wheather ftp client accepts # command from user by 'ftp> ' pattern child.expect('ftp> ') # close the ftp client. child.sendline('bye') # print the interactions with the child # process. print(child.before.decode()) child.interact() # print the downloaded file by executing cat # command with pexpect.run method print(pexpect.run('cat ./welcome.msg').decode()) if __name__ == '__main__': main()",
"e": 30040,
"s": 28969,
"text": null
},
{
"code": null,
"e": 30048,
"s": 30040,
"text": "Output:"
},
{
"code": null,
"e": 30055,
"s": 30048,
"text": "Fig 4"
},
{
"code": null,
"e": 30070,
"s": 30055,
"text": "varshagumber28"
},
{
"code": null,
"e": 30085,
"s": 30070,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 30094,
"s": 30085,
"text": "sweetyty"
},
{
"code": null,
"e": 30103,
"s": 30094,
"text": "gabaa406"
},
{
"code": null,
"e": 30112,
"s": 30103,
"text": "Rajvijay"
},
{
"code": null,
"e": 30119,
"s": 30112,
"text": "Picked"
},
{
"code": null,
"e": 30134,
"s": 30119,
"text": "python-modules"
},
{
"code": null,
"e": 30141,
"s": 30134,
"text": "Python"
},
{
"code": null,
"e": 30239,
"s": 30141,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30271,
"s": 30239,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30313,
"s": 30271,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30355,
"s": 30313,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30382,
"s": 30355,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30438,
"s": 30382,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30460,
"s": 30438,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30499,
"s": 30460,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30530,
"s": 30499,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30559,
"s": 30530,
"text": "Create a directory in Python"
}
] |
Draw Diamond shape using Turtle graphics in Python - GeeksforGeeks
|
11 Jun, 2021
In this article, we are going to learn how to draw the shape of a Diamond using turtle graphics in Python.
Turtle graphics:
forward(length): moves the pen in the forward direction by x unit.
right(angle): rotate the pen in the clockwise direction by an angle x.
left(angle): rotate the pen in the anticlockwise direction by an angle x.
Approach:
Import the turtle modules.
Define an instance for the turtle.
First, make the bigger triangle
Then make three lines inside the bigger triangle
Then make 4 small triangles
Then make one line above these four triangles
Below is the Python implementation of the above approach:
Python3
# python program# import for turtle moduleimport turtle # defining instance of turtlepen = turtle.Turtle()wn = turtle.Screen() # this is for bigger trianglepen.left(60)pen.forward(200)pen.left(120)pen.forward(200)pen.left(120)pen.forward(200)pen.left(150) # this for making three lines# inside the bigger trianglepen.forward(174)pen.backward(174)pen.left(16.5)pen.forward(180)pen.backward(180)pen.right(31.5)pen.forward(180)pen.right(75) # this is for making upper triangle1pen.forward(53)pen.left(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle2pen.right(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle3 pen.right(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle1pen.right(120)pen.forward(50)pen.left(120)pen.forward(50)pen.left(180)pen.forward(50) # this is for making line above all 4 small trianglepen.left(300)pen.forward(160)
Output:
ruhelaa48
Python-turtle
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": 25561,
"s": 25533,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 25668,
"s": 25561,
"text": "In this article, we are going to learn how to draw the shape of a Diamond using turtle graphics in Python."
},
{
"code": null,
"e": 25685,
"s": 25668,
"text": "Turtle graphics:"
},
{
"code": null,
"e": 25752,
"s": 25685,
"text": "forward(length): moves the pen in the forward direction by x unit."
},
{
"code": null,
"e": 25823,
"s": 25752,
"text": "right(angle): rotate the pen in the clockwise direction by an angle x."
},
{
"code": null,
"e": 25897,
"s": 25823,
"text": "left(angle): rotate the pen in the anticlockwise direction by an angle x."
},
{
"code": null,
"e": 25907,
"s": 25897,
"text": "Approach:"
},
{
"code": null,
"e": 25934,
"s": 25907,
"text": "Import the turtle modules."
},
{
"code": null,
"e": 25969,
"s": 25934,
"text": "Define an instance for the turtle."
},
{
"code": null,
"e": 26001,
"s": 25969,
"text": "First, make the bigger triangle"
},
{
"code": null,
"e": 26050,
"s": 26001,
"text": "Then make three lines inside the bigger triangle"
},
{
"code": null,
"e": 26078,
"s": 26050,
"text": "Then make 4 small triangles"
},
{
"code": null,
"e": 26124,
"s": 26078,
"text": "Then make one line above these four triangles"
},
{
"code": null,
"e": 26182,
"s": 26124,
"text": "Below is the Python implementation of the above approach:"
},
{
"code": null,
"e": 26190,
"s": 26182,
"text": "Python3"
},
{
"code": "# python program# import for turtle moduleimport turtle # defining instance of turtlepen = turtle.Turtle()wn = turtle.Screen() # this is for bigger trianglepen.left(60)pen.forward(200)pen.left(120)pen.forward(200)pen.left(120)pen.forward(200)pen.left(150) # this for making three lines# inside the bigger trianglepen.forward(174)pen.backward(174)pen.left(16.5)pen.forward(180)pen.backward(180)pen.right(31.5)pen.forward(180)pen.right(75) # this is for making upper triangle1pen.forward(53)pen.left(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle2pen.right(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle3 pen.right(120)pen.forward(50)pen.left(120)pen.forward(50) # this is for making upper triangle1pen.right(120)pen.forward(50)pen.left(120)pen.forward(50)pen.left(180)pen.forward(50) # this is for making line above all 4 small trianglepen.left(300)pen.forward(160)",
"e": 27147,
"s": 26190,
"text": null
},
{
"code": null,
"e": 27155,
"s": 27147,
"text": "Output:"
},
{
"code": null,
"e": 27165,
"s": 27155,
"text": "ruhelaa48"
},
{
"code": null,
"e": 27179,
"s": 27165,
"text": "Python-turtle"
},
{
"code": null,
"e": 27186,
"s": 27179,
"text": "Python"
},
{
"code": null,
"e": 27284,
"s": 27186,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27316,
"s": 27284,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27358,
"s": 27316,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27400,
"s": 27358,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27427,
"s": 27400,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27483,
"s": 27427,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27505,
"s": 27483,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27544,
"s": 27505,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27575,
"s": 27544,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27604,
"s": 27575,
"text": "Create a directory in Python"
}
] |
Lodash _.isString() Method - GeeksforGeeks
|
05 Sep, 2020
The _.isString() method is used to find whether the given value is a string object or not. It returns True if the given value is a string. Otherwise, it returns false.
Syntax:
_.isString(value)
Parameters: This method accepts a single parameter as mentioned above and described below:
value: This parameter holds the value to check.
Return Value: This method returns true if the value is a string, else false.
Example 1: Here, const _ = require(βlodashβ) is used to import the lodash library into the file.
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isString() method console.log(_.isString('GeeksforGeeks')); console.log(_.isString(true));
Output:
true
false
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.isString() method console.log(_.isString('123')); console.log(_.isString(123)); console.log(_.isString("0.123"));
Output:
true
false
true
Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Remove elements from a JavaScript Array
Installation of Node.js on Linux
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?
|
[
{
"code": null,
"e": 26307,
"s": 26279,
"text": "\n05 Sep, 2020"
},
{
"code": null,
"e": 26477,
"s": 26307,
"text": "The _.isString() method is used to find whether the given value is a string object or not. It returns True if the given value is a string. Otherwise, it returns false. "
},
{
"code": null,
"e": 26485,
"s": 26477,
"text": "Syntax:"
},
{
"code": null,
"e": 26504,
"s": 26485,
"text": "_.isString(value)\n"
},
{
"code": null,
"e": 26595,
"s": 26504,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 26643,
"s": 26595,
"text": "value: This parameter holds the value to check."
},
{
"code": null,
"e": 26720,
"s": 26643,
"text": "Return Value: This method returns true if the value is a string, else false."
},
{
"code": null,
"e": 26817,
"s": 26720,
"text": "Example 1: Here, const _ = require(βlodashβ) is used to import the lodash library into the file."
},
{
"code": null,
"e": 26828,
"s": 26817,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isString() method console.log(_.isString('GeeksforGeeks')); console.log(_.isString(true)); ",
"e": 27001,
"s": 26828,
"text": null
},
{
"code": null,
"e": 27009,
"s": 27001,
"text": "Output:"
},
{
"code": null,
"e": 27021,
"s": 27009,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 27034,
"s": 27021,
"text": "Example 2: "
},
{
"code": null,
"e": 27045,
"s": 27034,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.isString() method console.log(_.isString('123')); console.log(_.isString(123)); console.log(_.isString(\"0.123\")); ",
"e": 27241,
"s": 27045,
"text": null
},
{
"code": null,
"e": 27250,
"s": 27241,
"text": " Output:"
},
{
"code": null,
"e": 27267,
"s": 27250,
"text": "true\nfalse\ntrue\n"
},
{
"code": null,
"e": 27374,
"s": 27267,
"text": "Note: This code will not work in normal JavaScript because it requires the library lodash to be installed."
},
{
"code": null,
"e": 27392,
"s": 27374,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 27403,
"s": 27392,
"text": "JavaScript"
},
{
"code": null,
"e": 27420,
"s": 27403,
"text": "Web Technologies"
},
{
"code": null,
"e": 27518,
"s": 27420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27558,
"s": 27518,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27603,
"s": 27558,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27664,
"s": 27603,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27736,
"s": 27664,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27777,
"s": 27736,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27817,
"s": 27777,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27850,
"s": 27817,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27895,
"s": 27850,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27938,
"s": 27895,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HTML Entities - GeeksforGeeks
|
14 Dec, 2021
In this article, we will know HTML Entities, along with understanding their implementation through the examples. HTML provides some method to display reserved characters. Reserved characters are those characters that are either reserved for HTML or those which are not present in the basic keyboard. For instance, β<β is reserved in HTML language. Sometimes this character needs to display on the web page which creates ambiguity in code. Along with these are the characters which are normally not present in basic keyboard ( Β£, Β₯, β¬, Β© ), etc. HTML provides some Entity names and Entity numbers to use these symbols. Entity names are case-sensitive. Entity number is easy to learn.
Syntax:
&entity_name; or &#entity_number;
Some useful Symbols with their Entity name and Entity numbers are listed below:
Example: In this example, we have represented different entity symbols in HTML.
HTML
<!DOCTYPE html><html><body> <h2>GeeksforGeeks</h2> <div class="container"> <h3>Different entity symbol representation</h3> <ul style="list-style-type:none;"> <li> <h4>Indian currency: βΉ</h4> </li> <li> <h4>Euro: β¬</h4> </li> <li> <h4>Pound: Β£</h4> </li> <li> <h4>Yen: Β₯</h4> </li> <li> <h4>Dollar: $</h4> </li> </ul> </div></body></html>
Output:
HTML Entities
Reserved Characters: These characters are either reserved for HTML or those which are not present in the basic keyboard & canβt use them directly.
Example: Here, a few of the reserved characters are discussed:
Other Characters: Some characters that arenβt available directly on our keyboard, therefore such an entity can be used to represent it by using their entity number.
Example: These keywords are directly not available to type, we need to specify their entity number. Here #x before the numbers represents the hexadecimal representation.
β₯
β₯ β₯ ≥
Β©
© Β©
β¬
€ β¬
β
β β ∃
Example: This example illustrates the use of the special characters that are directly not available to type from the keyboard.
HTML
<!DOCTYPE html><html> <head> <title>HTML Entities</title></head> <body> <p>Showing euro β¬</p> <p>Showing cent Β’</p> <p>Showing Copyright Β©</p> <p>Showing BLACK DIAMOND SUIT β¦</p> <p>Showing TRADEMARK TM</p> </body> </html>
Output:
Special Character
Advantage of HTML Entity:
Entity names can be easy to remember.
Disadvantages:
Browsers might not support all the entity names, instead, they can support the use of entity numbers.
Non-breaking Space: It is used to provide the space that will not break into a new line. This HTML entity is represented by that will separate the 2 words & will stick together without breaking it into a new line. We can also use the non-breaking space for preventing the browsers from truncating spaces in HTML pages. The non-breaking hyphen (β) is used to define a hyphen character (β) that does not break into a new line.
Example:
12:00 PM256 km/h
12:00 PM
256 km/h
If we use to write 10 spaces in our text, then the browser will remove 9 of them. In order to add real spaces in our text, we can use the character entity.
Diacritical Marks: A diacritical mark is a βglyphβ added to a letter. Diacritical marks like grave ( ` Μ) and acute ( Μ ) are called accents. It can appear both above and below a letter, inside a letter, and between two letters. Diacritical marks can be used in combination with alphanumeric characters to generate a character that is not present in the character set (encoding) used on the page. Here is the list of some diacritical marks.
Μ
a
aΜ
aΜ
Μ
a
aΜ
aΜ
Μ
a
aΜ
aΜ
Μ
a
aΜ
aΜ
Μ
O
OΜ
OΜ
Μ
O
OΜ
OΜ
Μ
O
OΜ
OΜ
Μ
O
OΜ
OΜ
Supported Browser:
Google Chrome
Microsoft Edge
Firefox
Opera
Safari
Attention reader! Donβt stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
MohdArsalan
ysachin2314
bhaskargeeksforgeeks
sagartomar9927
HTML-Basics
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
|
[
{
"code": null,
"e": 31646,
"s": 31618,
"text": "\n14 Dec, 2021"
},
{
"code": null,
"e": 32330,
"s": 31646,
"text": "In this article, we will know HTML Entities, along with understanding their implementation through the examples. HTML provides some method to display reserved characters. Reserved characters are those characters that are either reserved for HTML or those which are not present in the basic keyboard. For instance, β<β is reserved in HTML language. Sometimes this character needs to display on the web page which creates ambiguity in code. Along with these are the characters which are normally not present in basic keyboard ( Β£, Β₯, β¬, Β© ), etc. HTML provides some Entity names and Entity numbers to use these symbols. Entity names are case-sensitive. Entity number is easy to learn. "
},
{
"code": null,
"e": 32338,
"s": 32330,
"text": "Syntax:"
},
{
"code": null,
"e": 32372,
"s": 32338,
"text": "&entity_name; or &#entity_number;"
},
{
"code": null,
"e": 32452,
"s": 32372,
"text": "Some useful Symbols with their Entity name and Entity numbers are listed below:"
},
{
"code": null,
"e": 32532,
"s": 32452,
"text": "Example: In this example, we have represented different entity symbols in HTML."
},
{
"code": null,
"e": 32537,
"s": 32532,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><body> <h2>GeeksforGeeks</h2> <div class=\"container\"> <h3>Different entity symbol representation</h3> <ul style=\"list-style-type:none;\"> <li> <h4>Indian currency: βΉ</h4> </li> <li> <h4>Euro: β¬</h4> </li> <li> <h4>Pound: Β£</h4> </li> <li> <h4>Yen: Β₯</h4> </li> <li> <h4>Dollar: $</h4> </li> </ul> </div></body></html>",
"e": 33090,
"s": 32537,
"text": null
},
{
"code": null,
"e": 33098,
"s": 33090,
"text": "Output:"
},
{
"code": null,
"e": 33112,
"s": 33098,
"text": "HTML Entities"
},
{
"code": null,
"e": 33259,
"s": 33112,
"text": "Reserved Characters: These characters are either reserved for HTML or those which are not present in the basic keyboard & canβt use them directly."
},
{
"code": null,
"e": 33322,
"s": 33259,
"text": "Example: Here, a few of the reserved characters are discussed:"
},
{
"code": null,
"e": 33488,
"s": 33322,
"text": "Other Characters: Some characters that arenβt available directly on our keyboard, therefore such an entity can be used to represent it by using their entity number. "
},
{
"code": null,
"e": 33658,
"s": 33488,
"text": "Example: These keywords are directly not available to type, we need to specify their entity number. Here #x before the numbers represents the hexadecimal representation."
},
{
"code": null,
"e": 33660,
"s": 33658,
"text": "β₯"
},
{
"code": null,
"e": 33679,
"s": 33660,
"text": "β₯ β₯ ≥"
},
{
"code": null,
"e": 33681,
"s": 33679,
"text": "Β©"
},
{
"code": null,
"e": 33690,
"s": 33681,
"text": "© Β©"
},
{
"code": null,
"e": 33692,
"s": 33690,
"text": "β¬"
},
{
"code": null,
"e": 33702,
"s": 33692,
"text": "€ β¬"
},
{
"code": null,
"e": 33704,
"s": 33702,
"text": "β"
},
{
"code": null,
"e": 33716,
"s": 33704,
"text": "β β ∃"
},
{
"code": null,
"e": 33843,
"s": 33716,
"text": "Example: This example illustrates the use of the special characters that are directly not available to type from the keyboard."
},
{
"code": null,
"e": 33848,
"s": 33843,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML Entities</title></head> <body> <p>Showing euro β¬</p> <p>Showing cent Β’</p> <p>Showing Copyright Β©</p> <p>Showing BLACK DIAMOND SUIT β¦</p> <p>Showing TRADEMARK TM</p> </body> </html>",
"e": 34098,
"s": 33848,
"text": null
},
{
"code": null,
"e": 34106,
"s": 34098,
"text": "Output:"
},
{
"code": null,
"e": 34124,
"s": 34106,
"text": "Special Character"
},
{
"code": null,
"e": 34150,
"s": 34124,
"text": "Advantage of HTML Entity:"
},
{
"code": null,
"e": 34188,
"s": 34150,
"text": "Entity names can be easy to remember."
},
{
"code": null,
"e": 34203,
"s": 34188,
"text": "Disadvantages:"
},
{
"code": null,
"e": 34305,
"s": 34203,
"text": "Browsers might not support all the entity names, instead, they can support the use of entity numbers."
},
{
"code": null,
"e": 34737,
"s": 34305,
"text": "Non-breaking Space: It is used to provide the space that will not break into a new line. This HTML entity is represented by that will separate the 2 words & will stick together without breaking it into a new line. We can also use the non-breaking space for preventing the browsers from truncating spaces in HTML pages. The non-breaking hyphen (β) is used to define a hyphen character (β) that does not break into a new line."
},
{
"code": null,
"e": 34746,
"s": 34737,
"text": "Example:"
},
{
"code": null,
"e": 34763,
"s": 34746,
"text": "12:00 PM256 km/h"
},
{
"code": null,
"e": 34772,
"s": 34763,
"text": "12:00 PM"
},
{
"code": null,
"e": 34781,
"s": 34772,
"text": "256 km/h"
},
{
"code": null,
"e": 34937,
"s": 34781,
"text": "If we use to write 10 spaces in our text, then the browser will remove 9 of them. In order to add real spaces in our text, we can use the character entity."
},
{
"code": null,
"e": 35378,
"s": 34937,
"text": "Diacritical Marks: A diacritical mark is a βglyphβ added to a letter. Diacritical marks like grave ( ` Μ) and acute ( Μ ) are called accents. It can appear both above and below a letter, inside a letter, and between two letters. Diacritical marks can be used in combination with alphanumeric characters to generate a character that is not present in the character set (encoding) used on the page. Here is the list of some diacritical marks."
},
{
"code": null,
"e": 35381,
"s": 35378,
"text": " Μ"
},
{
"code": null,
"e": 35383,
"s": 35381,
"text": "a"
},
{
"code": null,
"e": 35386,
"s": 35383,
"text": "aΜ"
},
{
"code": null,
"e": 35389,
"s": 35386,
"text": "aΜ"
},
{
"code": null,
"e": 35392,
"s": 35389,
"text": " Μ"
},
{
"code": null,
"e": 35394,
"s": 35392,
"text": "a"
},
{
"code": null,
"e": 35397,
"s": 35394,
"text": "aΜ"
},
{
"code": null,
"e": 35400,
"s": 35397,
"text": "aΜ"
},
{
"code": null,
"e": 35402,
"s": 35400,
"text": "Μ"
},
{
"code": null,
"e": 35404,
"s": 35402,
"text": "a"
},
{
"code": null,
"e": 35407,
"s": 35404,
"text": "aΜ"
},
{
"code": null,
"e": 35410,
"s": 35407,
"text": "aΜ"
},
{
"code": null,
"e": 35413,
"s": 35410,
"text": " Μ"
},
{
"code": null,
"e": 35415,
"s": 35413,
"text": "a"
},
{
"code": null,
"e": 35418,
"s": 35415,
"text": "aΜ"
},
{
"code": null,
"e": 35421,
"s": 35418,
"text": "aΜ"
},
{
"code": null,
"e": 35424,
"s": 35421,
"text": " Μ"
},
{
"code": null,
"e": 35426,
"s": 35424,
"text": "O"
},
{
"code": null,
"e": 35429,
"s": 35426,
"text": "OΜ"
},
{
"code": null,
"e": 35432,
"s": 35429,
"text": "OΜ"
},
{
"code": null,
"e": 35435,
"s": 35432,
"text": " Μ"
},
{
"code": null,
"e": 35437,
"s": 35435,
"text": "O"
},
{
"code": null,
"e": 35440,
"s": 35437,
"text": "OΜ"
},
{
"code": null,
"e": 35443,
"s": 35440,
"text": "OΜ"
},
{
"code": null,
"e": 35445,
"s": 35443,
"text": "Μ"
},
{
"code": null,
"e": 35447,
"s": 35445,
"text": "O"
},
{
"code": null,
"e": 35450,
"s": 35447,
"text": "OΜ"
},
{
"code": null,
"e": 35453,
"s": 35450,
"text": "OΜ"
},
{
"code": null,
"e": 35456,
"s": 35453,
"text": " Μ"
},
{
"code": null,
"e": 35458,
"s": 35456,
"text": "O"
},
{
"code": null,
"e": 35461,
"s": 35458,
"text": "OΜ"
},
{
"code": null,
"e": 35464,
"s": 35461,
"text": "OΜ"
},
{
"code": null,
"e": 35483,
"s": 35464,
"text": "Supported Browser:"
},
{
"code": null,
"e": 35497,
"s": 35483,
"text": "Google Chrome"
},
{
"code": null,
"e": 35512,
"s": 35497,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 35520,
"s": 35512,
"text": "Firefox"
},
{
"code": null,
"e": 35526,
"s": 35520,
"text": "Opera"
},
{
"code": null,
"e": 35533,
"s": 35526,
"text": "Safari"
},
{
"code": null,
"e": 35670,
"s": 35533,
"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": 35682,
"s": 35670,
"text": "MohdArsalan"
},
{
"code": null,
"e": 35694,
"s": 35682,
"text": "ysachin2314"
},
{
"code": null,
"e": 35715,
"s": 35694,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 35730,
"s": 35715,
"text": "sagartomar9927"
},
{
"code": null,
"e": 35742,
"s": 35730,
"text": "HTML-Basics"
},
{
"code": null,
"e": 35747,
"s": 35742,
"text": "HTML"
},
{
"code": null,
"e": 35764,
"s": 35747,
"text": "Web Technologies"
},
{
"code": null,
"e": 35769,
"s": 35764,
"text": "HTML"
},
{
"code": null,
"e": 35867,
"s": 35769,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35929,
"s": 35867,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35979,
"s": 35929,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 36027,
"s": 35979,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 36087,
"s": 36027,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 36140,
"s": 36087,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 36180,
"s": 36140,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 36213,
"s": 36180,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36258,
"s": 36213,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 36301,
"s": 36258,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to get the length of a string in bytes in JavaScript ? - GeeksforGeeks
|
01 Apr, 2021
Task: To find the size of the given string in bytes.
Example:
Input: "GeeksForGeeks"
Output: 13 bytes
Input: 20β¬
Output: 5 bytes
Input: "????"
Output: 4 bytes
To achieve this we have two ways the first one is using the Blob API and the second is Buffer API, the first one works with the browser, and the second works with the Node.js environment. blob object is simply a group of bytes that holds the data stored in a file. To read the bytes of a string using blog we create a new instance of Blob object then we pass the string inside it and by using the size property we can get the bytes of a string.
Example 1: Using Blob API.
Javascript
<script>const len = (str) => { // Creating new Blob object and passing string into it // inside square brackets and then // by using size property storin the size // inside the size variable let size = new Blob([str]).size; return size;} console.log(len("Geeksforgeeks"))console.log(len("true"))console.log(len("false"))console.log(len("12345"))console.log(len("20β¬"))console.log(len("????"))</script>
Output:
13
4
5
5
5
4
Example 2: Using Buffer API. Now there is another way to achieve this in NodeJS using Buffer. So first create the Buffer object and then pass the string inside it and using the length property you can get the size of the string
Javascript
<script>const len = (str) => { let size = Buffer.from(str).length; return size;} console.log(len("Geeksforgeeks"))console.log(len("true"))console.log(len("false"))console.log(len("12345"))console.log(len("20β¬"))console.log(len("????"))</script>
Output:
13
4
5
5
5
4
JavaScript-Questions
NodeJS-Questions
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
Node.js fs.readFile() Method
|
[
{
"code": null,
"e": 26805,
"s": 26777,
"text": "\n01 Apr, 2021"
},
{
"code": null,
"e": 26858,
"s": 26805,
"text": "Task: To find the size of the given string in bytes."
},
{
"code": null,
"e": 26867,
"s": 26858,
"text": "Example:"
},
{
"code": null,
"e": 26966,
"s": 26867,
"text": "Input: \"GeeksForGeeks\"\nOutput: 13 bytes\n\nInput: 20β¬\nOutput: 5 bytes\n\nInput: \"????\"\nOutput: 4 bytes"
},
{
"code": null,
"e": 27411,
"s": 26966,
"text": "To achieve this we have two ways the first one is using the Blob API and the second is Buffer API, the first one works with the browser, and the second works with the Node.js environment. blob object is simply a group of bytes that holds the data stored in a file. To read the bytes of a string using blog we create a new instance of Blob object then we pass the string inside it and by using the size property we can get the bytes of a string."
},
{
"code": null,
"e": 27438,
"s": 27411,
"text": "Example 1: Using Blob API."
},
{
"code": null,
"e": 27449,
"s": 27438,
"text": "Javascript"
},
{
"code": "<script>const len = (str) => { // Creating new Blob object and passing string into it // inside square brackets and then // by using size property storin the size // inside the size variable let size = new Blob([str]).size; return size;} console.log(len(\"Geeksforgeeks\"))console.log(len(\"true\"))console.log(len(\"false\"))console.log(len(\"12345\"))console.log(len(\"20β¬\"))console.log(len(\"????\"))</script>",
"e": 27864,
"s": 27449,
"text": null
},
{
"code": null,
"e": 27872,
"s": 27864,
"text": "Output:"
},
{
"code": null,
"e": 27885,
"s": 27872,
"text": "13\n4\n5\n5\n5\n4"
},
{
"code": null,
"e": 28113,
"s": 27885,
"text": "Example 2: Using Buffer API. Now there is another way to achieve this in NodeJS using Buffer. So first create the Buffer object and then pass the string inside it and using the length property you can get the size of the string"
},
{
"code": null,
"e": 28124,
"s": 28113,
"text": "Javascript"
},
{
"code": "<script>const len = (str) => { let size = Buffer.from(str).length; return size;} console.log(len(\"Geeksforgeeks\"))console.log(len(\"true\"))console.log(len(\"false\"))console.log(len(\"12345\"))console.log(len(\"20β¬\"))console.log(len(\"????\"))</script>",
"e": 28373,
"s": 28124,
"text": null
},
{
"code": null,
"e": 28381,
"s": 28373,
"text": "Output:"
},
{
"code": null,
"e": 28394,
"s": 28381,
"text": "13\n4\n5\n5\n5\n4"
},
{
"code": null,
"e": 28415,
"s": 28394,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 28432,
"s": 28415,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 28443,
"s": 28432,
"text": "JavaScript"
},
{
"code": null,
"e": 28451,
"s": 28443,
"text": "Node.js"
},
{
"code": null,
"e": 28468,
"s": 28451,
"text": "Web Technologies"
},
{
"code": null,
"e": 28566,
"s": 28468,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28606,
"s": 28566,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28667,
"s": 28606,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28708,
"s": 28667,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28730,
"s": 28708,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28784,
"s": 28730,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28817,
"s": 28784,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28865,
"s": 28817,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 28898,
"s": 28865,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 28928,
"s": 28898,
"text": "Node.js fs.writeFile() Method"
}
] |
Array Index with same count of even or odd numbers on both sides - GeeksforGeeks
|
12 May, 2022
Given an array of N integers. We need to find an index such that Frequency of Even numbers on its left side is equal to the frequency of even numbers on its right sides Or frequency of odd numbers on its left side is equal to the frequency of Odd numbers on its right sides. If No such index exist in an array print -1 Else print required index. Note-(If more than one index exist then return index that comes first)
Examples:
Input : arr[] = {4, 3, 2, 1, 2, 4}
Output : index = 2
Explanation: At index 2, there is one
odd number on its left and one odd on
its right.
Input :arr[] = { 1, 2, 4, 5, 8, 3, 12}
Output : index = 3
Method 1 : (Simple Approach) Run two loops. For every element, count evens and odds on its left and right sides.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.#include <iostream>using namespace std; // Function to find indexint findIndex(int arr[], int n) { for (int i = 0; i < n; i++) { int odd_left = 0, even_left = 0; int odd_right = 0, even_right = 0; // To count Even and Odd numbers of left side for (int j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd numbers of right side for (int k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both sides are equal or not if (even_right == even_left || odd_right == odd_left) return i; } return -1;} // Driver's Functionint main() { int arr[] = {4, 3, 2, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); int index = findIndex(arr, n); ((index == -1) ? cout << "-1" : cout << "index = " << index); return 0;}
// Java program to find// an index which has// same number of even// elements on left and// right, Or same number// of odd elements on// left and right. class GFG{ // Function to find indexstatic int findIndex(int arr[], int n) { for (int i = 0; i < n; i++) { int odd_left = 0, even_left = 0; int odd_right = 0, even_right = 0; // To count Even and Odd // numbers of left side for (int j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd // numbers of right side for (int k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both // sides are equal or not if (even_right == even_left || odd_right == odd_left) return i;} return -1; } // Driver's Functionpublic static void main(String[] args) { int arr[] = {4, 3, 2, 1, 2};int n = arr.length;int index = findIndex(arr, n); if (index == -1) System.out.println("-1");else{ System.out.print("index = "); System.out.print(index);}}} // This code is contributed by// Smitha Dinesh Semwal
'''Python program to find an index which has same number of even elements on left and right, Or same number of odd elements on left and right.''' # Function to find indexdef findIndex(arr,n): for i in range(n): odd_left = 0 even_left = 0 odd_right = 0 even_right = 0 # To count Even and Odd # numbers of left side for j in range(i): if (arr[j] % 2 == 0): even_left=even_left+1 else: odd_left=odd_left+1 # To count Even and Odd # numbers of right side for k in range(n - 1, i, -1): if (arr[k] % 2 == 0): even_right=even_right+1 else: odd_right=odd_right+1 # To check Even Or Odd of Both # sides are equal or not if (even_right == even_left and odd_right == odd_left): return i return -1 # Driver's Function arr = [4, 3, 2, 1, 2]n = len(arr)index = findIndex(arr, n) if (index == -1): print("-1")else: print("index = ", index) # This code is contributed# by Anant Agarwal.
// C# program to find an index which has// same number of even elements on left// and right, Or same number of odd// elements on left and right.using System; class GFG{ // Function to find index static int findIndex(int []arr, int n) { for (int i = 0; i < n; i++) { int odd_left = 0, even_left = 0; int odd_right = 0, even_right = 0; // To count Even and Odd // numbers of left side for (int j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd // numbers of right side for (int k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both // sides are equal or not if (even_right == even_left || odd_right == odd_left) return i; } return -1; } // Driver's Function public static void Main() { int []arr = {4, 3, 2, 1, 2}; int n = arr.Length; int index = findIndex(arr, n); if (index == -1) Console.Write("-1"); else{ Console.Write("index = "); Console.Write(index); } }} // This code is contributed by vt_m.
<?php// PHP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right. // Function to find indexfunction findIndex($arr, $n){ for ($i = 0; $i < $n; $i++) { $odd_left = 0; $even_left = 0; $odd_right = 0; $even_right = 0; // To count Even and Odd // numbers of left side for ($j = 0; $j < $i; $j++) { if ($arr[$j] % 2 == 0) $even_left++; else $odd_left++; } // To count Even and Odd // numbers of right side for ($k = $n - 1; $k > $i; $k--) { if ($arr[$k] % 2 == 0) $even_right++; else $odd_right++; } // To check Even Or Odd of // Both sides are equal or not if ($even_right == $even_left || $odd_right == $odd_left) return $i; } return -1;} // Drivers Code{ $arr = array(4, 3, 2, 1, 2); $n = sizeof($arr) / sizeof($arr[0]); $index = findIndex($arr, $n); if($index == -1) echo "-1"; else echo ("index = $index" ); return 0;} // This code is contributed by nitin mittal.?>
<script> // Javascript program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right. // Function to find indexfunction findIndex(arr, n) { for (let i = 0; i < n; i++) { let odd_left = 0, even_left = 0; let odd_right = 0, even_right = 0; // To count Even and Odd numbers of left side for (let j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd numbers of right side for (let k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both sides are equal or not if (even_right == even_left || odd_right == odd_left) return i;} return -1;} // Driver's Function let arr = [4, 3, 2, 1, 2];let n = arr.length;let index = findIndex(arr, n); if (index == -1) document.write("-1"); else{ document.write("index = "); document.write(index); } //This code is contributed by Mayank Tyagi</script>
index = 2
Time Complexity : O(n*n) Auxiliary Space : O(1)
Method 2:(Efficient solution) 1- Create two vectors of pair types i.e v_left and v_right 2- v_left[i] stores the frequency of odd and even numbers of its left sides 3- v_right[i] stores the frequency of odd and even numbers of its right sides 4- Now check (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) if True return i 5- At last if no such index exist return -1
C++
Java
Python3
C#
Javascript
// CPP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.#include <bits/stdc++.h>#include <iostream>using namespace std; // Function to Find indexint Find_Index(int n, int arr[]) { int odd = 0, even = 0; // Create two vectors of pair type vector<pair<int, int>> v_left, v_right; v_left.push_back(make_pair(odd, even)); for (int i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) even++; else odd++; v_left.push_back(make_pair(odd, even)); } odd = 0, even = 0; v_right.push_back(make_pair(odd, even)); for (int i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) even++; else odd++; v_right.push_back(make_pair(odd, even)); } reverse(v_right.begin(), v_right.end()); for (int i = 0; i < v_left.size(); i++) { // To check even or odd of Both sides are // equal or not if (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) return i; } return -1;} // Driver's Functionint main() { int arr[] = {4, 3, 2, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); int index = Find_Index(n, arr); ((index == -1) ? cout << "-1" : cout << "index = " << index); return 0;}
// Java program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.import java.util.*; class GFG{ public static class pair { int first, second; pair(int f, int s) { first = f; second = s; } }; // Function to Find index static int Find_Index(int n, int arr[]) { int odd = 0, even = 0; // Create two vectors of pair type Vector<pair> v_left = new Vector<>();; Vector<pair> v_right = new Vector<>(); v_left.add(new pair(odd, even)); for (int i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_left.add(new pair(odd, even)); } odd = 0; even = 0; v_right.add(new pair(odd, even)); for (int i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_right.add(new pair(odd, even)); } Collections.reverse(v_right); for (int i = 0; i < v_left.size(); i++) { // To check even or odd of Both sides are // equal or not if (v_left.get(i).first == v_right.get(i).first || v_left.get(i).second == v_right.get(i).second) { return i; } } return -1; } // Driver code public static void main(String[] args) { int arr[] = {4, 3, 2, 1, 2}; int n = arr.length; int index = Find_Index(n, arr); if (index == -1) { System.out.println("-1"); } else { System.out.println("index = " + index); } }} /* This code contributed by PrinciRaj1992 */
# Python program to find an index which has# same number of even elements on left and# right, Or same number of odd elements on# left and right.class pair: def __init__(self, f, s): self.first = f self.second = s # Function to Find indexdef Find_Index(n, arr): odd, even = 0, 0 # Create two vectors of pair type v_left = [] v_right = [] v_left.append(pair(odd, even)) for i in range(n-1): if (arr[i] % 2 == 0): even += 1 else: odd += 1 v_left.append(pair(odd, even)) odd = 0 even = 0 v_right.append(pair(odd, even)) for i in range(n-1,0,-1): if (arr[i] % 2 == 0): even += 1 else: odd += 1 v_right.append(pair(odd, even)) v_right = v_right[::-1] for i in range(len(v_left)): # To check even or odd of Both sides are # equal or not if (v_left[i].first == v_right[i].first or v_left[i].second == v_right[i].second): return i return -1 # Driver codearr = [4, 3, 2, 1, 2]n = len(arr)index = Find_Index(n, arr)if (index == -1): print("-1")else: print("index = " + str(index)) # This code is contributed by shinjanpatra
// C# program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.using System;using System.Collections.Generic; class GFG{ public class pair { public int first, second; public pair(int f, int s) { first = f; second = s; } }; // Function to Find index static int Find_Index(int n, int []arr) { int odd = 0, even = 0; // Create two vectors of pair type List<pair> v_left = new List<pair>();; List<pair> v_right = new List<pair>(); v_left.Add(new pair(odd, even)); for (int i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_left.Add(new pair(odd, even)); } odd = 0; even = 0; v_right.Add(new pair(odd, even)); for (int i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_right.Add(new pair(odd, even)); } v_right.Reverse(); for (int i = 0; i < v_left.Count; i++) { // To check even or odd of Both sides are // equal or not if (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) { return i; } } return -1; } // Driver code public static void Main(String[] args) { int []arr = {4, 3, 2, 1, 2}; int n = arr.Length; int index = Find_Index(n, arr); if (index == -1) { Console.WriteLine("-1"); } else { Console.WriteLine("index = " + index); } }} // This code is contributed by 29AjayKumar
<script>// Javascript program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.class pair{ constructor(f,s) { this.first = f; this.second = s; }} // Function to Find indexfunction Find_Index(n,arr){ let odd = 0, even = 0; // Create two vectors of pair type let v_left = []; let v_right = []; v_left.push(new pair(odd, even)); for (let i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_left.push(new pair(odd, even)); } odd = 0; even = 0; v_right.push(new pair(odd, even)); for (let i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_right.push(new pair(odd, even)); } v_right.reverse(); for (let i = 0; i < v_left.length; i++) { // To check even or odd of Both sides are // equal or not if (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) { return i; } } return -1;} // Driver codelet arr = [4, 3, 2, 1, 2];let n = arr.length;let index = Find_Index(n, arr);if (index == -1){ document.write("-1");}else{ document.write("index = " + index);} // This code is contributed by rag2127</script>
index = 2
Time Complexity : O(n) Auxiliary Space : O(n) Further optimization : We can optimize the space used in the program. Instead of making vectors of pairs, we can make vectors of integers. We can use the fact that number of odd elements is equal total elements minus total number of even elements. Similarly, number of even elements is equal total elements minus total number of odd elements.
nitin mittal
princiraj1992
29AjayKumar
mayanktyagi1709
rag2127
shinjanpatra
frequency-counting
prefix-sum
Arrays
prefix-sum
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Count pairs with given sum
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Find a triplet that sum to a given value
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Find duplicates in O(n) time and O(1) extra space | Set 1
Remove duplicates from sorted array
Move all negative numbers to beginning and positive to end with constant extra space
|
[
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n12 May, 2022"
},
{
"code": null,
"e": 26482,
"s": 26065,
"text": "Given an array of N integers. We need to find an index such that Frequency of Even numbers on its left side is equal to the frequency of even numbers on its right sides Or frequency of odd numbers on its left side is equal to the frequency of Odd numbers on its right sides. If No such index exist in an array print -1 Else print required index. Note-(If more than one index exist then return index that comes first)"
},
{
"code": null,
"e": 26494,
"s": 26482,
"text": "Examples: "
},
{
"code": null,
"e": 26697,
"s": 26494,
"text": "Input : arr[] = {4, 3, 2, 1, 2, 4} \nOutput : index = 2\nExplanation: At index 2, there is one\nodd number on its left and one odd on\nits right.\n\nInput :arr[] = { 1, 2, 4, 5, 8, 3, 12}\nOutput : index = 3 "
},
{
"code": null,
"e": 26812,
"s": 26697,
"text": "Method 1 : (Simple Approach) Run two loops. For every element, count evens and odds on its left and right sides. "
},
{
"code": null,
"e": 26816,
"s": 26812,
"text": "C++"
},
{
"code": null,
"e": 26821,
"s": 26816,
"text": "Java"
},
{
"code": null,
"e": 26829,
"s": 26821,
"text": "Python3"
},
{
"code": null,
"e": 26832,
"s": 26829,
"text": "C#"
},
{
"code": null,
"e": 26836,
"s": 26832,
"text": "PHP"
},
{
"code": null,
"e": 26847,
"s": 26836,
"text": "Javascript"
},
{
"code": "// CPP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.#include <iostream>using namespace std; // Function to find indexint findIndex(int arr[], int n) { for (int i = 0; i < n; i++) { int odd_left = 0, even_left = 0; int odd_right = 0, even_right = 0; // To count Even and Odd numbers of left side for (int j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd numbers of right side for (int k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both sides are equal or not if (even_right == even_left || odd_right == odd_left) return i; } return -1;} // Driver's Functionint main() { int arr[] = {4, 3, 2, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); int index = findIndex(arr, n); ((index == -1) ? cout << \"-1\" : cout << \"index = \" << index); return 0;}",
"e": 27897,
"s": 26847,
"text": null
},
{
"code": "// Java program to find// an index which has// same number of even// elements on left and// right, Or same number// of odd elements on// left and right. class GFG{ // Function to find indexstatic int findIndex(int arr[], int n) { for (int i = 0; i < n; i++) { int odd_left = 0, even_left = 0; int odd_right = 0, even_right = 0; // To count Even and Odd // numbers of left side for (int j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd // numbers of right side for (int k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both // sides are equal or not if (even_right == even_left || odd_right == odd_left) return i;} return -1; } // Driver's Functionpublic static void main(String[] args) { int arr[] = {4, 3, 2, 1, 2};int n = arr.length;int index = findIndex(arr, n); if (index == -1) System.out.println(\"-1\");else{ System.out.print(\"index = \"); System.out.print(index);}}} // This code is contributed by// Smitha Dinesh Semwal",
"e": 29038,
"s": 27897,
"text": null
},
{
"code": "'''Python program to find an index which has same number of even elements on left and right, Or same number of odd elements on left and right.''' # Function to find indexdef findIndex(arr,n): for i in range(n): odd_left = 0 even_left = 0 odd_right = 0 even_right = 0 # To count Even and Odd # numbers of left side for j in range(i): if (arr[j] % 2 == 0): even_left=even_left+1 else: odd_left=odd_left+1 # To count Even and Odd # numbers of right side for k in range(n - 1, i, -1): if (arr[k] % 2 == 0): even_right=even_right+1 else: odd_right=odd_right+1 # To check Even Or Odd of Both # sides are equal or not if (even_right == even_left and odd_right == odd_left): return i return -1 # Driver's Function arr = [4, 3, 2, 1, 2]n = len(arr)index = findIndex(arr, n) if (index == -1): print(\"-1\")else: print(\"index = \", index) # This code is contributed# by Anant Agarwal.",
"e": 30171,
"s": 29038,
"text": null
},
{
"code": "// C# program to find an index which has// same number of even elements on left// and right, Or same number of odd// elements on left and right.using System; class GFG{ // Function to find index static int findIndex(int []arr, int n) { for (int i = 0; i < n; i++) { int odd_left = 0, even_left = 0; int odd_right = 0, even_right = 0; // To count Even and Odd // numbers of left side for (int j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd // numbers of right side for (int k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both // sides are equal or not if (even_right == even_left || odd_right == odd_left) return i; } return -1; } // Driver's Function public static void Main() { int []arr = {4, 3, 2, 1, 2}; int n = arr.Length; int index = findIndex(arr, n); if (index == -1) Console.Write(\"-1\"); else{ Console.Write(\"index = \"); Console.Write(index); } }} // This code is contributed by vt_m.",
"e": 31687,
"s": 30171,
"text": null
},
{
"code": "<?php// PHP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right. // Function to find indexfunction findIndex($arr, $n){ for ($i = 0; $i < $n; $i++) { $odd_left = 0; $even_left = 0; $odd_right = 0; $even_right = 0; // To count Even and Odd // numbers of left side for ($j = 0; $j < $i; $j++) { if ($arr[$j] % 2 == 0) $even_left++; else $odd_left++; } // To count Even and Odd // numbers of right side for ($k = $n - 1; $k > $i; $k--) { if ($arr[$k] % 2 == 0) $even_right++; else $odd_right++; } // To check Even Or Odd of // Both sides are equal or not if ($even_right == $even_left || $odd_right == $odd_left) return $i; } return -1;} // Drivers Code{ $arr = array(4, 3, 2, 1, 2); $n = sizeof($arr) / sizeof($arr[0]); $index = findIndex($arr, $n); if($index == -1) echo \"-1\"; else echo (\"index = $index\" ); return 0;} // This code is contributed by nitin mittal.?>",
"e": 32965,
"s": 31687,
"text": null
},
{
"code": "<script> // Javascript program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right. // Function to find indexfunction findIndex(arr, n) { for (let i = 0; i < n; i++) { let odd_left = 0, even_left = 0; let odd_right = 0, even_right = 0; // To count Even and Odd numbers of left side for (let j = 0; j < i; j++) { if (arr[j] % 2 == 0) even_left++; else odd_left++; } // To count Even and Odd numbers of right side for (let k = n - 1; k > i; k--) { if (arr[k] % 2 == 0) even_right++; else odd_right++; } // To check Even Or Odd of Both sides are equal or not if (even_right == even_left || odd_right == odd_left) return i;} return -1;} // Driver's Function let arr = [4, 3, 2, 1, 2];let n = arr.length;let index = findIndex(arr, n); if (index == -1) document.write(\"-1\"); else{ document.write(\"index = \"); document.write(index); } //This code is contributed by Mayank Tyagi</script>",
"e": 34048,
"s": 32965,
"text": null
},
{
"code": null,
"e": 34058,
"s": 34048,
"text": "index = 2"
},
{
"code": null,
"e": 34109,
"s": 34060,
"text": "Time Complexity : O(n*n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 34507,
"s": 34109,
"text": "Method 2:(Efficient solution) 1- Create two vectors of pair types i.e v_left and v_right 2- v_left[i] stores the frequency of odd and even numbers of its left sides 3- v_right[i] stores the frequency of odd and even numbers of its right sides 4- Now check (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) if True return i 5- At last if no such index exist return -1 "
},
{
"code": null,
"e": 34511,
"s": 34507,
"text": "C++"
},
{
"code": null,
"e": 34516,
"s": 34511,
"text": "Java"
},
{
"code": null,
"e": 34524,
"s": 34516,
"text": "Python3"
},
{
"code": null,
"e": 34527,
"s": 34524,
"text": "C#"
},
{
"code": null,
"e": 34538,
"s": 34527,
"text": "Javascript"
},
{
"code": "// CPP program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.#include <bits/stdc++.h>#include <iostream>using namespace std; // Function to Find indexint Find_Index(int n, int arr[]) { int odd = 0, even = 0; // Create two vectors of pair type vector<pair<int, int>> v_left, v_right; v_left.push_back(make_pair(odd, even)); for (int i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) even++; else odd++; v_left.push_back(make_pair(odd, even)); } odd = 0, even = 0; v_right.push_back(make_pair(odd, even)); for (int i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) even++; else odd++; v_right.push_back(make_pair(odd, even)); } reverse(v_right.begin(), v_right.end()); for (int i = 0; i < v_left.size(); i++) { // To check even or odd of Both sides are // equal or not if (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) return i; } return -1;} // Driver's Functionint main() { int arr[] = {4, 3, 2, 1, 2}; int n = sizeof(arr) / sizeof(arr[0]); int index = Find_Index(n, arr); ((index == -1) ? cout << \"-1\" : cout << \"index = \" << index); return 0;}",
"e": 35779,
"s": 34538,
"text": null
},
{
"code": "// Java program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.import java.util.*; class GFG{ public static class pair { int first, second; pair(int f, int s) { first = f; second = s; } }; // Function to Find index static int Find_Index(int n, int arr[]) { int odd = 0, even = 0; // Create two vectors of pair type Vector<pair> v_left = new Vector<>();; Vector<pair> v_right = new Vector<>(); v_left.add(new pair(odd, even)); for (int i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_left.add(new pair(odd, even)); } odd = 0; even = 0; v_right.add(new pair(odd, even)); for (int i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_right.add(new pair(odd, even)); } Collections.reverse(v_right); for (int i = 0; i < v_left.size(); i++) { // To check even or odd of Both sides are // equal or not if (v_left.get(i).first == v_right.get(i).first || v_left.get(i).second == v_right.get(i).second) { return i; } } return -1; } // Driver code public static void main(String[] args) { int arr[] = {4, 3, 2, 1, 2}; int n = arr.length; int index = Find_Index(n, arr); if (index == -1) { System.out.println(\"-1\"); } else { System.out.println(\"index = \" + index); } }} /* This code contributed by PrinciRaj1992 */",
"e": 37733,
"s": 35779,
"text": null
},
{
"code": "# Python program to find an index which has# same number of even elements on left and# right, Or same number of odd elements on# left and right.class pair: def __init__(self, f, s): self.first = f self.second = s # Function to Find indexdef Find_Index(n, arr): odd, even = 0, 0 # Create two vectors of pair type v_left = [] v_right = [] v_left.append(pair(odd, even)) for i in range(n-1): if (arr[i] % 2 == 0): even += 1 else: odd += 1 v_left.append(pair(odd, even)) odd = 0 even = 0 v_right.append(pair(odd, even)) for i in range(n-1,0,-1): if (arr[i] % 2 == 0): even += 1 else: odd += 1 v_right.append(pair(odd, even)) v_right = v_right[::-1] for i in range(len(v_left)): # To check even or odd of Both sides are # equal or not if (v_left[i].first == v_right[i].first or v_left[i].second == v_right[i].second): return i return -1 # Driver codearr = [4, 3, 2, 1, 2]n = len(arr)index = Find_Index(n, arr)if (index == -1): print(\"-1\")else: print(\"index = \" + str(index)) # This code is contributed by shinjanpatra",
"e": 38966,
"s": 37733,
"text": null
},
{
"code": "// C# program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.using System;using System.Collections.Generic; class GFG{ public class pair { public int first, second; public pair(int f, int s) { first = f; second = s; } }; // Function to Find index static int Find_Index(int n, int []arr) { int odd = 0, even = 0; // Create two vectors of pair type List<pair> v_left = new List<pair>();; List<pair> v_right = new List<pair>(); v_left.Add(new pair(odd, even)); for (int i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_left.Add(new pair(odd, even)); } odd = 0; even = 0; v_right.Add(new pair(odd, even)); for (int i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_right.Add(new pair(odd, even)); } v_right.Reverse(); for (int i = 0; i < v_left.Count; i++) { // To check even or odd of Both sides are // equal or not if (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) { return i; } } return -1; } // Driver code public static void Main(String[] args) { int []arr = {4, 3, 2, 1, 2}; int n = arr.Length; int index = Find_Index(n, arr); if (index == -1) { Console.WriteLine(\"-1\"); } else { Console.WriteLine(\"index = \" + index); } }} // This code is contributed by 29AjayKumar",
"e": 40913,
"s": 38966,
"text": null
},
{
"code": "<script>// Javascript program to find an index which has// same number of even elements on left and// right, Or same number of odd elements on// left and right.class pair{ constructor(f,s) { this.first = f; this.second = s; }} // Function to Find indexfunction Find_Index(n,arr){ let odd = 0, even = 0; // Create two vectors of pair type let v_left = []; let v_right = []; v_left.push(new pair(odd, even)); for (let i = 0; i < n - 1; i++) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_left.push(new pair(odd, even)); } odd = 0; even = 0; v_right.push(new pair(odd, even)); for (let i = n - 1; i > 0; i--) { if (arr[i] % 2 == 0) { even++; } else { odd++; } v_right.push(new pair(odd, even)); } v_right.reverse(); for (let i = 0; i < v_left.length; i++) { // To check even or odd of Both sides are // equal or not if (v_left[i].first == v_right[i].first || v_left[i].second == v_right[i].second) { return i; } } return -1;} // Driver codelet arr = [4, 3, 2, 1, 2];let n = arr.length;let index = Find_Index(n, arr);if (index == -1){ document.write(\"-1\");}else{ document.write(\"index = \" + index);} // This code is contributed by rag2127</script>",
"e": 42538,
"s": 40913,
"text": null
},
{
"code": null,
"e": 42548,
"s": 42538,
"text": "index = 2"
},
{
"code": null,
"e": 42941,
"s": 42550,
"text": "Time Complexity : O(n) Auxiliary Space : O(n) Further optimization : We can optimize the space used in the program. Instead of making vectors of pairs, we can make vectors of integers. We can use the fact that number of odd elements is equal total elements minus total number of even elements. Similarly, number of even elements is equal total elements minus total number of odd elements. "
},
{
"code": null,
"e": 42954,
"s": 42941,
"text": "nitin mittal"
},
{
"code": null,
"e": 42968,
"s": 42954,
"text": "princiraj1992"
},
{
"code": null,
"e": 42980,
"s": 42968,
"text": "29AjayKumar"
},
{
"code": null,
"e": 42996,
"s": 42980,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 43004,
"s": 42996,
"text": "rag2127"
},
{
"code": null,
"e": 43017,
"s": 43004,
"text": "shinjanpatra"
},
{
"code": null,
"e": 43036,
"s": 43017,
"text": "frequency-counting"
},
{
"code": null,
"e": 43047,
"s": 43036,
"text": "prefix-sum"
},
{
"code": null,
"e": 43054,
"s": 43047,
"text": "Arrays"
},
{
"code": null,
"e": 43065,
"s": 43054,
"text": "prefix-sum"
},
{
"code": null,
"e": 43072,
"s": 43065,
"text": "Arrays"
},
{
"code": null,
"e": 43170,
"s": 43072,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43201,
"s": 43170,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 43228,
"s": 43201,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 43253,
"s": 43228,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 43291,
"s": 43253,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 43312,
"s": 43291,
"text": "Next Greater Element"
},
{
"code": null,
"e": 43353,
"s": 43312,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 43412,
"s": 43353,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 43470,
"s": 43412,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 43506,
"s": 43470,
"text": "Remove duplicates from sorted array"
}
] |
Python | Convert tuple to float value - GeeksforGeeks
|
11 Nov, 2019
Sometimes, while working with tuple, we can have a problem in which, we need to convert a tuple to floating-point number in which first element represents integer part and next element represents a decimal part. Letβs discuss certain way in which this can be achieved.
Method : Using join() + float() + str() + generator expression
The combination of above functionalities can solve this problem. In this, we 1st convert the tuple elements into a string, then join them and convert them to desired integer.
# Python3 code to demonstrate working of# Convert tuple to float# using join() + float() + str() + generator expression # initialize tupletest_tup = (4, 56) # printing original tuple print("The original tuple : " + str(test_tup)) # Convert tuple to float# using join() + float() + str() + generator expressionres = float('.'.join(str(ele) for ele in test_tup)) # printing resultprint("The float after conversion from tuple is : " + str(res))
The original tuple : (4, 56)
The float after conversion from tuple is : 4.56
Python tuple-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 25841,
"s": 25813,
"text": "\n11 Nov, 2019"
},
{
"code": null,
"e": 26110,
"s": 25841,
"text": "Sometimes, while working with tuple, we can have a problem in which, we need to convert a tuple to floating-point number in which first element represents integer part and next element represents a decimal part. Letβs discuss certain way in which this can be achieved."
},
{
"code": null,
"e": 26173,
"s": 26110,
"text": "Method : Using join() + float() + str() + generator expression"
},
{
"code": null,
"e": 26348,
"s": 26173,
"text": "The combination of above functionalities can solve this problem. In this, we 1st convert the tuple elements into a string, then join them and convert them to desired integer."
},
{
"code": "# Python3 code to demonstrate working of# Convert tuple to float# using join() + float() + str() + generator expression # initialize tupletest_tup = (4, 56) # printing original tuple print(\"The original tuple : \" + str(test_tup)) # Convert tuple to float# using join() + float() + str() + generator expressionres = float('.'.join(str(ele) for ele in test_tup)) # printing resultprint(\"The float after conversion from tuple is : \" + str(res))",
"e": 26794,
"s": 26348,
"text": null
},
{
"code": null,
"e": 26872,
"s": 26794,
"text": "The original tuple : (4, 56)\nThe float after conversion from tuple is : 4.56\n"
},
{
"code": null,
"e": 26894,
"s": 26872,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 26901,
"s": 26894,
"text": "Python"
},
{
"code": null,
"e": 26917,
"s": 26901,
"text": "Python Programs"
},
{
"code": null,
"e": 27015,
"s": 26917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27033,
"s": 27015,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27065,
"s": 27033,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27087,
"s": 27065,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27129,
"s": 27087,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27159,
"s": 27129,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27181,
"s": 27159,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27220,
"s": 27181,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27258,
"s": 27220,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 27298,
"s": 27258,
"text": "How to print without newline in Python?"
}
] |
How to rotate a text canvas using Fabric.js ? - GeeksforGeeks
|
04 Sep, 2021
In this article, we are going to see how to rotate a text canvas using FabricJS. The canvas means text written is movable and can be stretched according to requirement. Further, the text itself cannot be edited like a textbox.Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our text. After this, we will initialize instances of Canvas and Text provided by FabricJS and use the angle property to rotate the text to the required angle and render the Canvas on the Text as given in the example below.
Syntax:
fabric.Text(text, angle: Number);
Parameters: This function accepts two parameters as mentioned above and described below:
text: It specifies the text to be written.
options: It specifies the additional options to be applied and we are using the angle option for this example.
Program: This example uses FabricJS to create simple editable text canvas.
html
<!DOCTYPE html><html> <head> <title> How to rotate a text canvas using Fabric.js? </title> <!-- Loading the FabricJS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js"> </script></head> <body> <canvas id="canvas" width="600" height="200" style="border:1px solid #000000;"> </canvas> <script> // Create a new instance of Canvas var canvas = new fabric.Canvas("canvas"); // Create a new Textbox instance var text = new fabric.Text('GeeksforGeeks', { angle: 10 }); // Render the Textbox on Canvas canvas.add(text); </script></body> </html>
Output:
sagartomar9927
Fabric.js
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to Open URL in New Tab using JavaScript ?
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": 26217,
"s": 26189,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 26861,
"s": 26217,
"text": "In this article, we are going to see how to rotate a text canvas using FabricJS. The canvas means text written is movable and can be stretched according to requirement. Further, the text itself cannot be edited like a textbox.Approach: To make it possible, we are going to use a JavaScript library called FabricJS. After importing the library using CDN, we will create a canvas block in the body tag which will contain our text. After this, we will initialize instances of Canvas and Text provided by FabricJS and use the angle property to rotate the text to the required angle and render the Canvas on the Text as given in the example below. "
},
{
"code": null,
"e": 26871,
"s": 26861,
"text": "Syntax: "
},
{
"code": null,
"e": 26906,
"s": 26871,
"text": "fabric.Text(text, angle: Number); "
},
{
"code": null,
"e": 26997,
"s": 26906,
"text": "Parameters: This function accepts two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 27040,
"s": 26997,
"text": "text: It specifies the text to be written."
},
{
"code": null,
"e": 27151,
"s": 27040,
"text": "options: It specifies the additional options to be applied and we are using the angle option for this example."
},
{
"code": null,
"e": 27227,
"s": 27151,
"text": "Program: This example uses FabricJS to create simple editable text canvas. "
},
{
"code": null,
"e": 27232,
"s": 27227,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to rotate a text canvas using Fabric.js? </title> <!-- Loading the FabricJS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.6.2/fabric.min.js\"> </script></head> <body> <canvas id=\"canvas\" width=\"600\" height=\"200\" style=\"border:1px solid #000000;\"> </canvas> <script> // Create a new instance of Canvas var canvas = new fabric.Canvas(\"canvas\"); // Create a new Textbox instance var text = new fabric.Text('GeeksforGeeks', { angle: 10 }); // Render the Textbox on Canvas canvas.add(text); </script></body> </html>",
"e": 27924,
"s": 27232,
"text": null
},
{
"code": null,
"e": 27933,
"s": 27924,
"text": "Output: "
},
{
"code": null,
"e": 27948,
"s": 27933,
"text": "sagartomar9927"
},
{
"code": null,
"e": 27958,
"s": 27948,
"text": "Fabric.js"
},
{
"code": null,
"e": 27974,
"s": 27958,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27985,
"s": 27974,
"text": "JavaScript"
},
{
"code": null,
"e": 28002,
"s": 27985,
"text": "Web Technologies"
},
{
"code": null,
"e": 28100,
"s": 28002,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28140,
"s": 28100,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28185,
"s": 28140,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28246,
"s": 28185,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28318,
"s": 28246,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28364,
"s": 28318,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 28404,
"s": 28364,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28449,
"s": 28404,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28492,
"s": 28449,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28542,
"s": 28492,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
MySQL update datetime column values and add 10 years 3 months 22 days and 10 hours, 30 minutes to existing data?
|
For this, you can use INTERVAL in MySQL. Let us first create a table β
mysql> create table DemoTable1509
-> (
-> ArrivalTime datetime
-> );
Query OK, 0 rows affected (0.51 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable1509 values('2018-01-21 10:20:30');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1509 values('2019-04-01 11:00:00');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1509 values('2015-12-12 05:45:20');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement β
mysql> select * from DemoTable1509;
This will produce the following output β
+---------------------+
| ArrivalTime |
+---------------------+
| 2018-01-21 10:20:30 |
| 2019-04-01 11:00:00 |
| 2015-12-12 05:45:20 |
+---------------------+
3 rows in set (0.00 sec)
Here is the query to MySQL update datetime column and add 10 years 3 months 22 days and 10 hours, 30 minutes to existing data β
mysql> update DemoTable1509
-> set ArrivalTime=ArrivalTime+interval 10 year + interval 3 month +interval 22 day+interval 10 hour+interval 30 minute;
Query OK, 3 rows affected (0.17 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check the table records once again β
mysql> select * from DemoTable1509;
This will produce the following output β
+---------------------+
| ArrivalTime |
+---------------------+
| 2028-05-13 20:50:30 |
| 2029-07-23 21:30:00 |
| 2026-04-03 16:15:20 |
+---------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1133,
"s": 1062,
"text": "For this, you can use INTERVAL in MySQL. Let us first create a table β"
},
{
"code": null,
"e": 1248,
"s": 1133,
"text": "mysql> create table DemoTable1509\n -> (\n -> ArrivalTime datetime\n -> );\nQuery OK, 0 rows affected (0.51 sec)"
},
{
"code": null,
"e": 1304,
"s": 1248,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1604,
"s": 1304,
"text": "mysql> insert into DemoTable1509 values('2018-01-21 10:20:30');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1509 values('2019-04-01 11:00:00');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable1509 values('2015-12-12 05:45:20');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 1664,
"s": 1604,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1700,
"s": 1664,
"text": "mysql> select * from DemoTable1509;"
},
{
"code": null,
"e": 1741,
"s": 1700,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1934,
"s": 1741,
"text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2018-01-21 10:20:30 |\n| 2019-04-01 11:00:00 |\n| 2015-12-12 05:45:20 |\n+---------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2062,
"s": 1934,
"text": "Here is the query to MySQL update datetime column and add 10 years 3 months 22 days and 10 hours, 30 minutes to existing data β"
},
{
"code": null,
"e": 2292,
"s": 2062,
"text": "mysql> update DemoTable1509\n -> set ArrivalTime=ArrivalTime+interval 10 year + interval 3 month +interval 22 day+interval 10 hour+interval 30 minute;\nQuery OK, 3 rows affected (0.17 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 2336,
"s": 2292,
"text": "Let us check the table records once again β"
},
{
"code": null,
"e": 2372,
"s": 2336,
"text": "mysql> select * from DemoTable1509;"
},
{
"code": null,
"e": 2413,
"s": 2372,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2606,
"s": 2413,
"text": "+---------------------+\n| ArrivalTime |\n+---------------------+\n| 2028-05-13 20:50:30 |\n| 2029-07-23 21:30:00 |\n| 2026-04-03 16:15:20 |\n+---------------------+\n3 rows in set (0.00 sec)"
}
] |
Find duplicate column values in MySQL and display them
|
For this, use GROUP BY HAVING clause. Let us first create a table β
mysql> create table DemoTable1858
(
ModelNumber varchar(50)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command β
mysql> insert into DemoTable1858 values('Audi A4');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi A6');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi A4');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi Q5');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi R8');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1858 values('Audi Q5');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement β
mysql> select * from DemoTable1858;
This will produce the following output β
+-------------+
| ModelNumber |
+-------------+
| Audi A4 |
| Audi A6 |
| Audi A4 |
| Audi Q5 |
| Audi R8 |
| Audi Q5 |
+-------------+
6 rows in set (0.00 sec)
Here is the query to find duplicate column value in MySQL β
mysql> select ModelNumber from DemoTable1858
group by ModelNumber
having count(ModelNumber) >=2;
This will produce the following output β
+-------------+
| ModelNumber |
+-------------+
| Audi A4 |
| Audi Q5 |
+-------------+
2 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1130,
"s": 1062,
"text": "For this, use GROUP BY HAVING clause. Let us first create a table β"
},
{
"code": null,
"e": 1245,
"s": 1130,
"text": "mysql> create table DemoTable1858\n (\n ModelNumber varchar(50)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1301,
"s": 1245,
"text": "Insert some records in the table using insert command β"
},
{
"code": null,
"e": 1829,
"s": 1301,
"text": "mysql> insert into DemoTable1858 values('Audi A4');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1858 values('Audi A6');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1858 values('Audi A4');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1858 values('Audi Q5');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1858 values('Audi R8');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1858 values('Audi Q5');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1889,
"s": 1829,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1925,
"s": 1889,
"text": "mysql> select * from DemoTable1858;"
},
{
"code": null,
"e": 1966,
"s": 1925,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2151,
"s": 1966,
"text": "+-------------+\n| ModelNumber |\n+-------------+\n| Audi A4 |\n| Audi A6 |\n| Audi A4 |\n| Audi Q5 |\n| Audi R8 |\n| Audi Q5 |\n+-------------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2211,
"s": 2151,
"text": "Here is the query to find duplicate column value in MySQL β"
},
{
"code": null,
"e": 2318,
"s": 2211,
"text": "mysql> select ModelNumber from DemoTable1858\n group by ModelNumber\n having count(ModelNumber) >=2;"
},
{
"code": null,
"e": 2359,
"s": 2318,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2480,
"s": 2359,
"text": "+-------------+\n| ModelNumber |\n+-------------+\n| Audi A4 |\n| Audi Q5 |\n+-------------+\n2 rows in set (0.00 sec)"
}
] |
PyTorch β How to convert an image to grayscale?
|
To convert an image to grayscale, we apply Grayscale() transformation. It's one of the transforms provided by the torchvision.transforms module. This module contains many important transformations that can be used to perform different types manipulations on the image data.
Grayscale() transformation accepts both PIL and tensor images or a batch of tensor images. A tensor image is a PyTorch Tensor with shape [3, H, W], where H is the image height and W is the image width. A batch of tensor images is also a torch tensor with [B, 3, H, W]. B is the number of images in the batch.
torchvision.transforms.Grayscale()(img)
It returns a grayscale image.
We could use the following steps to convert an image to grayscale β
Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them.
Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them.
import torch
import torchvision
import torchvision.transforms as transforms
from PIL import Image
Read the input image. The input image is a PIL image or a torch tensor.
Read the input image. The input image is a PIL image or a torch tensor.
img = Image.open('laptop.jpg')
Define a transform to convert the original input image to grayscale.
Define a transform to convert the original input image to grayscale.
transform = transforms.Grayscale()
Apply the above defined transform on the input image convert it to grayscale.
Apply the above defined transform on the input image convert it to grayscale.
img = transform(img)
Visualize the grayscaled image.
Visualize the grayscaled image.
img.show()
The following image is used as the input in both the examples.
The following Python3 program converts the input PIL image to grayscale.
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image
# Read the image
img = Image.open('laptop.jpg')
# define a transform to convert the image to grayscale
transform = transforms.Grayscale()
# apply the above transform on the image
img = transform(img)
# dispaly the image
img.show()
# num of output channels = 1
print(img.mode)
It will produce the following output β
Note that the mode of the grayscale image is L. The grayscale image has a single
channel.
The following Python3 program shows how to convert an input image to grayscale.
# Python program to convert an image to grayscale
# import required libraries
import torch
import torchvision.transforms as transforms
from PIL import Image
# Read the image
img = Image.open('laptop.jpg')
# define a transform to convert the image to grayscale
transform = transforms.Grayscale(3)
# apply the above transform on the image
img = transform(img)
# display the image
img.show()
# the num of output channels =3, R=G=B, but Gray image
print(img.mode)
It will produce the following output β
Note that the mode of output gray image is RGB. It has three channels, Red, Green, and Blue, but it's a grayscale image.
|
[
{
"code": null,
"e": 1336,
"s": 1062,
"text": "To convert an image to grayscale, we apply Grayscale() transformation. It's one of the transforms provided by the torchvision.transforms module. This module contains many important transformations that can be used to perform different types manipulations on the image data."
},
{
"code": null,
"e": 1645,
"s": 1336,
"text": "Grayscale() transformation accepts both PIL and tensor images or a batch of tensor images. A tensor image is a PyTorch Tensor with shape [3, H, W], where H is the image height and W is the image width. A batch of tensor images is also a torch tensor with [B, 3, H, W]. B is the number of images in the batch."
},
{
"code": null,
"e": 1685,
"s": 1645,
"text": "torchvision.transforms.Grayscale()(img)"
},
{
"code": null,
"e": 1715,
"s": 1685,
"text": "It returns a grayscale image."
},
{
"code": null,
"e": 1783,
"s": 1715,
"text": "We could use the following steps to convert an image to grayscale β"
},
{
"code": null,
"e": 1954,
"s": 1783,
"text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them."
},
{
"code": null,
"e": 2125,
"s": 1954,
"text": "Import the required libraries. In all the following examples, the required Python libraries are torch, Pillow, and torchvision. Make sure you have already installed them."
},
{
"code": null,
"e": 2223,
"s": 2125,
"text": "import torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom PIL import Image"
},
{
"code": null,
"e": 2295,
"s": 2223,
"text": "Read the input image. The input image is a PIL image or a torch tensor."
},
{
"code": null,
"e": 2367,
"s": 2295,
"text": "Read the input image. The input image is a PIL image or a torch tensor."
},
{
"code": null,
"e": 2398,
"s": 2367,
"text": "img = Image.open('laptop.jpg')"
},
{
"code": null,
"e": 2467,
"s": 2398,
"text": "Define a transform to convert the original input image to grayscale."
},
{
"code": null,
"e": 2536,
"s": 2467,
"text": "Define a transform to convert the original input image to grayscale."
},
{
"code": null,
"e": 2571,
"s": 2536,
"text": "transform = transforms.Grayscale()"
},
{
"code": null,
"e": 2649,
"s": 2571,
"text": "Apply the above defined transform on the input image convert it to grayscale."
},
{
"code": null,
"e": 2727,
"s": 2649,
"text": "Apply the above defined transform on the input image convert it to grayscale."
},
{
"code": null,
"e": 2748,
"s": 2727,
"text": "img = transform(img)"
},
{
"code": null,
"e": 2780,
"s": 2748,
"text": "Visualize the grayscaled image."
},
{
"code": null,
"e": 2812,
"s": 2780,
"text": "Visualize the grayscaled image."
},
{
"code": null,
"e": 2823,
"s": 2812,
"text": "img.show()"
},
{
"code": null,
"e": 2886,
"s": 2823,
"text": "The following image is used as the input in both the examples."
},
{
"code": null,
"e": 2959,
"s": 2886,
"text": "The following Python3 program converts the input PIL image to grayscale."
},
{
"code": null,
"e": 3347,
"s": 2959,
"text": "# import required libraries\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\n\n# Read the image\nimg = Image.open('laptop.jpg')\n\n# define a transform to convert the image to grayscale\ntransform = transforms.Grayscale()\n\n# apply the above transform on the image\nimg = transform(img)\n\n# dispaly the image\nimg.show()\n\n# num of output channels = 1\nprint(img.mode)"
},
{
"code": null,
"e": 3386,
"s": 3347,
"text": "It will produce the following output β"
},
{
"code": null,
"e": 3476,
"s": 3386,
"text": "Note that the mode of the grayscale image is L. The grayscale image has a single\nchannel."
},
{
"code": null,
"e": 3556,
"s": 3476,
"text": "The following Python3 program shows how to convert an input image to grayscale."
},
{
"code": null,
"e": 4021,
"s": 3556,
"text": "# Python program to convert an image to grayscale\n# import required libraries\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\n\n# Read the image\nimg = Image.open('laptop.jpg')\n\n# define a transform to convert the image to grayscale\ntransform = transforms.Grayscale(3)\n\n# apply the above transform on the image\nimg = transform(img)\n\n# display the image\nimg.show()\n\n# the num of output channels =3, R=G=B, but Gray image\nprint(img.mode)"
},
{
"code": null,
"e": 4060,
"s": 4021,
"text": "It will produce the following output β"
},
{
"code": null,
"e": 4181,
"s": 4060,
"text": "Note that the mode of output gray image is RGB. It has three channels, Red, Green, and Blue, but it's a grayscale image."
}
] |
Convert MySQL date format from yyyy-mm-ddThh:mm:ss.sssZ to yyyy-mm-dd hh:mm:ss ?
|
Let us first create a table β
mysql> create table DemoTable668(JoiningDate varchar(200));
Query OK, 0 rows affected (0.97 sec)
Insert some records in the table using insert command. We have inserted date in the format yyyy-mm-ddThh:mm:ss.sssZ β
mysql> insert into DemoTable668 values('2001-01-10T06:20:00.000Z');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable668 values('2019-07-20T04:00:00.000Z');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable668 values('2016-02-12T05:10:50.000Z');
Query OK, 1 row affected (0.17 sec)
Display all records from the table using select statement β
mysql> select *from DemoTable668;
This will produce the following output β
+--------------------------+
| JoiningDate |
+--------------------------+
| 2001-01-10T06:20:00.000Z |
| 2019-07-20T04:00:00.000Z |
| 2016-02-12T05:10:50.000Z |
+--------------------------+
3 rows in set (0.00 sec)
Following is the query to convert the date format from yyyy-mm-ddThh:mm:ss.sssZ to yyyy-mm-dd hh:mm:ss β
mysql> update DemoTable668
SET JoiningDate = DATE_FORMAT(STR_TO_DATE(JoiningDate,'%Y-%m-%dT%H:%i:%s.000Z'),'%Y-%m-%d %H:%i:%s');
Query OK, 3 rows affected (0.11 sec)
Rows matched: 3 Changed: 3 Warnings: 0
Let us check table records once again β
mysql> select *from DemoTable668;
This will produce the following output β
+---------------------+
| JoiningDate |
+---------------------+
| 2001-01-10 06:20:00 |
| 2019-07-20 04:00:00 |
| 2016-02-12 05:10:50 |
+---------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table β"
},
{
"code": null,
"e": 1189,
"s": 1092,
"text": "mysql> create table DemoTable668(JoiningDate varchar(200));\nQuery OK, 0 rows affected (0.97 sec)"
},
{
"code": null,
"e": 1307,
"s": 1189,
"text": "Insert some records in the table using insert command. We have inserted date in the format yyyy-mm-ddThh:mm:ss.sssZ β"
},
{
"code": null,
"e": 1619,
"s": 1307,
"text": "mysql> insert into DemoTable668 values('2001-01-10T06:20:00.000Z');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable668 values('2019-07-20T04:00:00.000Z');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into DemoTable668 values('2016-02-12T05:10:50.000Z');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1679,
"s": 1619,
"text": "Display all records from the table using select statement β"
},
{
"code": null,
"e": 1713,
"s": 1679,
"text": "mysql> select *from DemoTable668;"
},
{
"code": null,
"e": 1754,
"s": 1713,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 1982,
"s": 1754,
"text": "+--------------------------+\n| JoiningDate |\n+--------------------------+\n| 2001-01-10T06:20:00.000Z |\n| 2019-07-20T04:00:00.000Z |\n| 2016-02-12T05:10:50.000Z |\n+--------------------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2087,
"s": 1982,
"text": "Following is the query to convert the date format from yyyy-mm-ddThh:mm:ss.sssZ to yyyy-mm-dd hh:mm:ss β"
},
{
"code": null,
"e": 2295,
"s": 2087,
"text": "mysql> update DemoTable668\n SET JoiningDate = DATE_FORMAT(STR_TO_DATE(JoiningDate,'%Y-%m-%dT%H:%i:%s.000Z'),'%Y-%m-%d %H:%i:%s');\nQuery OK, 3 rows affected (0.11 sec)\nRows matched: 3 Changed: 3 Warnings: 0"
},
{
"code": null,
"e": 2335,
"s": 2295,
"text": "Let us check table records once again β"
},
{
"code": null,
"e": 2369,
"s": 2335,
"text": "mysql> select *from DemoTable668;"
},
{
"code": null,
"e": 2410,
"s": 2369,
"text": "This will produce the following output β"
},
{
"code": null,
"e": 2603,
"s": 2410,
"text": "+---------------------+\n| JoiningDate |\n+---------------------+\n| 2001-01-10 06:20:00 |\n| 2019-07-20 04:00:00 |\n| 2016-02-12 05:10:50 |\n+---------------------+\n3 rows in set (0.00 sec)"
}
] |
Data Structures | Misc | Question 6 - GeeksforGeeks
|
28 Jun, 2021
The most appropriate matching for the following pairs
X: depth first search 1: heap
Y: breadth-first search 2: queue
Z: sorting 3: stack
is (GATE CS 2000):
(A) Xβ1 Yβ2 Z-3(B) Xβ3 Yβ1 Z-2(C) Xβ3 Yβ2 Z-1(D) Xβ2 Yβ3 Z-1Answer: (C)Explanation: Stack is used for Depth first SearchQueue is used for Breadth First SearchHeap is used for sortingQuiz of this Question
Data Structures
Data Structures-Misc
Misc
Data Structures
Misc
Data Structures
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Advantages and Disadvantages of Linked List
C program to implement Adjacency Matrix of a given Graph
Difference between Singly linked list and Doubly linked list
FIFO vs LIFO approach in Programming
Bit manipulation | Swap Endianness of a number
Data Structures | Queue | Question 11
Data Structures | Stack | Question 4
Advantages of vector over array in C++
Program to create Custom Vector Class in C++
Multilevel Linked List
|
[
{
"code": null,
"e": 25020,
"s": 24992,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25074,
"s": 25020,
"text": "The most appropriate matching for the following pairs"
},
{
"code": null,
"e": 25199,
"s": 25074,
"text": "X: depth first search 1: heap\nY: breadth-first search 2: queue\nZ: sorting 3: stack"
},
{
"code": null,
"e": 25218,
"s": 25199,
"text": "is (GATE CS 2000):"
},
{
"code": null,
"e": 25422,
"s": 25218,
"text": "(A) Xβ1 Yβ2 Z-3(B) Xβ3 Yβ1 Z-2(C) Xβ3 Yβ2 Z-1(D) Xβ2 Yβ3 Z-1Answer: (C)Explanation: Stack is used for Depth first SearchQueue is used for Breadth First SearchHeap is used for sortingQuiz of this Question"
},
{
"code": null,
"e": 25438,
"s": 25422,
"text": "Data Structures"
},
{
"code": null,
"e": 25459,
"s": 25438,
"text": "Data Structures-Misc"
},
{
"code": null,
"e": 25464,
"s": 25459,
"text": "Misc"
},
{
"code": null,
"e": 25480,
"s": 25464,
"text": "Data Structures"
},
{
"code": null,
"e": 25485,
"s": 25480,
"text": "Misc"
},
{
"code": null,
"e": 25501,
"s": 25485,
"text": "Data Structures"
},
{
"code": null,
"e": 25506,
"s": 25501,
"text": "Misc"
},
{
"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": 25648,
"s": 25604,
"text": "Advantages and Disadvantages of Linked List"
},
{
"code": null,
"e": 25705,
"s": 25648,
"text": "C program to implement Adjacency Matrix of a given Graph"
},
{
"code": null,
"e": 25766,
"s": 25705,
"text": "Difference between Singly linked list and Doubly linked list"
},
{
"code": null,
"e": 25803,
"s": 25766,
"text": "FIFO vs LIFO approach in Programming"
},
{
"code": null,
"e": 25850,
"s": 25803,
"text": "Bit manipulation | Swap Endianness of a number"
},
{
"code": null,
"e": 25888,
"s": 25850,
"text": "Data Structures | Queue | Question 11"
},
{
"code": null,
"e": 25925,
"s": 25888,
"text": "Data Structures | Stack | Question 4"
},
{
"code": null,
"e": 25964,
"s": 25925,
"text": "Advantages of vector over array in C++"
},
{
"code": null,
"e": 26009,
"s": 25964,
"text": "Program to create Custom Vector Class in C++"
}
] |
5 Methods to Check for NaN values in in Python | by Abhijith Chandradas | Towards Data Science
|
NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float.
NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results.
Finding and dealing with NaN within an array, series or dataframe is easy. However, identifying a stand alone NaN value is tricky. In this article I explain five methods to deal with NaN in python. The first three methods involves in-built functions from libraries. The last two relies on properties of NaN for finding NaN values.
isna() in pandas library can be used to check if the value is null/NaN. It will return True if the value is NaN/null.
import pandas as pdx = float("nan")print(f"It's pd.isna : {pd.isna(x)}")OutputIt's pd.isna : True
isnan() in numpy library can be used to check if the value is null/NaN. It is similar to isna() in pandas.
import numpy as npx = float("nan")print(f"It's np.isnan : {np.isnan(x)}")OutputIt's np.isnan : True
Math library provides has built-in mathematical functions. The library is applicable to all real numbers. cmath library can be used if dealing with complex numbers.Math library has built in function isnan() to check null/NaN values.
import mathx = float("nan")print(f"It's math.isnan : {math.isnan(x)}")OutputIt's math.isnan : True
When I started my career working with big IT company, I had to undergo a training for the first month. The trainer, when introducing the concept of NaN values mentioned that they are like aliens we know nothing about. These aliens are constantly shapeshifting, and hence we cannot compare NaN value against itself.The most common method to check for NaN values is to check if the variable is equal to itself. If it is not, then it must be NaN value.
def isNaN(num): return num!= numx=float("nan")isNaN(x)OutputTrue
Another property of NaN which can be used to check for NaN is the range. All floating point values fall within the range of minus infinity to infinity.
infinity < any number< infinity
However, NaN values does not come within this range. Hence, NaN can be identified if the value does not fall within the range from minus infinity to infinity.
This can be implemented as below:
def isNaN(num): if float('-inf') < float(num) < float('inf'): return False else: return Truex=float("nan")isNaN(x)OutputTrue
I hope you have found the above article helpful. I am sure there would be many other techniques to check for NaN values based on various other logics. Please share the other methods you have come across to check for NaN/ Null values.
Cheers!
I hope you like the article, I would highly recommend signing up for Medium Membership to read more articles by me or stories by thousands of other authors on variety of topics. Your membership fee directly supports me and other writers you read. Youβll also get full access to every story on Medium.
|
[
{
"code": null,
"e": 365,
"s": 172,
"text": "NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float."
},
{
"code": null,
"e": 497,
"s": 365,
"text": "NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results."
},
{
"code": null,
"e": 828,
"s": 497,
"text": "Finding and dealing with NaN within an array, series or dataframe is easy. However, identifying a stand alone NaN value is tricky. In this article I explain five methods to deal with NaN in python. The first three methods involves in-built functions from libraries. The last two relies on properties of NaN for finding NaN values."
},
{
"code": null,
"e": 946,
"s": 828,
"text": "isna() in pandas library can be used to check if the value is null/NaN. It will return True if the value is NaN/null."
},
{
"code": null,
"e": 1046,
"s": 946,
"text": "import pandas as pdx = float(\"nan\")print(f\"It's pd.isna : {pd.isna(x)}\")OutputIt's pd.isna : True"
},
{
"code": null,
"e": 1153,
"s": 1046,
"text": "isnan() in numpy library can be used to check if the value is null/NaN. It is similar to isna() in pandas."
},
{
"code": null,
"e": 1255,
"s": 1153,
"text": "import numpy as npx = float(\"nan\")print(f\"It's np.isnan : {np.isnan(x)}\")OutputIt's np.isnan : True"
},
{
"code": null,
"e": 1488,
"s": 1255,
"text": "Math library provides has built-in mathematical functions. The library is applicable to all real numbers. cmath library can be used if dealing with complex numbers.Math library has built in function isnan() to check null/NaN values."
},
{
"code": null,
"e": 1588,
"s": 1488,
"text": "import mathx = float(\"nan\")print(f\"It's math.isnan : {math.isnan(x)}\")OutputIt's math.isnan : True"
},
{
"code": null,
"e": 2038,
"s": 1588,
"text": "When I started my career working with big IT company, I had to undergo a training for the first month. The trainer, when introducing the concept of NaN values mentioned that they are like aliens we know nothing about. These aliens are constantly shapeshifting, and hence we cannot compare NaN value against itself.The most common method to check for NaN values is to check if the variable is equal to itself. If it is not, then it must be NaN value."
},
{
"code": null,
"e": 2106,
"s": 2038,
"text": "def isNaN(num): return num!= numx=float(\"nan\")isNaN(x)OutputTrue"
},
{
"code": null,
"e": 2258,
"s": 2106,
"text": "Another property of NaN which can be used to check for NaN is the range. All floating point values fall within the range of minus infinity to infinity."
},
{
"code": null,
"e": 2290,
"s": 2258,
"text": "infinity < any number< infinity"
},
{
"code": null,
"e": 2449,
"s": 2290,
"text": "However, NaN values does not come within this range. Hence, NaN can be identified if the value does not fall within the range from minus infinity to infinity."
},
{
"code": null,
"e": 2483,
"s": 2449,
"text": "This can be implemented as below:"
},
{
"code": null,
"e": 2629,
"s": 2483,
"text": "def isNaN(num): if float('-inf') < float(num) < float('inf'): return False else: return Truex=float(\"nan\")isNaN(x)OutputTrue"
},
{
"code": null,
"e": 2863,
"s": 2629,
"text": "I hope you have found the above article helpful. I am sure there would be many other techniques to check for NaN values based on various other logics. Please share the other methods you have come across to check for NaN/ Null values."
},
{
"code": null,
"e": 2871,
"s": 2863,
"text": "Cheers!"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.