title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to create multiple CSV files from existing CSV file using Pandas ?
|
22 Jul, 2021
In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting into rows, columns, specific values of columns, etc.
First, let’s create a simple CSV file and use it for all examples below in the article. Create dataset using dataframe method of pandas and then save it to “Customers.csv” file or we can load existing dataset with the Pandas read_csv() function.
Python3
import pandas as pd # initialise data dictionary.data_dict = {'CustomerID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Gender': ["Male", "Female", "Female", "Male", "Male", "Female", "Male", "Male", "Female", "Male"], 'Age': [20, 21, 19, 18, 25, 26, 32, 41, 20, 19], 'Annual Income(k$)': [10, 20, 30, 10, 25, 60, 70, 15, 21, 22], 'Spending Score': [30, 50, 48, 84, 90, 65, 32, 46, 12, 56]} # Create DataFramedata = pd.DataFrame(data_dict) # Write to CSV filedata.to_csv("Customers.csv") # Print the output.print(data)
Output:
To do our work, we will discuss different methods that are as follows:
In this method, we will split one CSV file into multiple CSVs based on rows.
Python3
import pandas as pd # read DataFramedata = pd.read_csv("Customers.csv") # no of csv files with row sizek = 2size = 5 for i in range(k): df = data[size*i:size*(i+1)] df.to_csv(f'Customers_{i+1}.csv', index=False) df_1 = pd.read_csv("Customers_1.csv")print(df_1) df_2 = pd.read_csv("Customers_2.csv")print(df_2)
Output:
Example 1:
Using groupby() method of Pandas we can create multiple CSV files. To create a file we can use the to_csv() method of Pandas. Here created two files based on “male” and “female” values of Gender columns.
Python3
import pandas as pd # read DataFramedata = pd.read_csv("Customers.csv") for (gender), group in data.groupby(['Gender']): group.to_csv(f'{gender}.csv', index=False) print(pd.read_csv("Male.csv"))print(pd.read_csv("Female.csv"))
Output:
Male.csv
Female.csv
Example 2:
We can group more than two columns and can create multiple files on the basis of a combination of unique values from both Columns value. Take Gender and Annual Income columns.
Python3
import pandas as pd # read DataFramedata = pd.read_csv("Customers.csv") for (Gender, Income), group in data.groupby(['Gender', 'Annual Income(k$)']): group.to_csv(f'{Gender} {Income}.csv', index=False) print(pd.read_csv(f'{Gender} {Income}.csv'))
Output:
All Nine CSV files
Example 3:
We will filter the columns based on the specific column name Gender to its values (Male and Female). Then convert that to CSV file using to_csv in pandas.
Python3
import pandas as pd # read DataFramedata = pd.read_csv("Customers.csv") male = data[data['Gender'] == 'Male']female = data[data['Gender'] == 'Female'] male.to_csv('Gender_male.csv', index=False)female.to_csv('Gender_female.csv', index=False) print(pd.read_csv("Gender_male.csv"))print(pd.read_csv("Gender_female.csv"))
Output:
Using groupby() method of Pandas we can create multiple CSV files row-wise. To create a file we can use the to_csv() method of Pandas. Here created two files based on row values “male” and “female” values of specific Gender column for Spending Score.
Python3
for (gender), group in data['Spending Score'].groupby(data['Gender']): group.to_csv(f'{gender}Score.csv', index=False) print(pd.read_csv("MaleScore.csv"))print(pd.read_csv("FemaleScore.csv"))
Output:
anikakapoor
Picked
Python pandas-io
python-csv
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": "\n22 Jul, 2021"
},
{
"code": null,
"e": 430,
"s": 28,
"text": "In this article, we will learn how to create multiple CSV files from existing CSV file using Pandas. When we enter our code into production, we will need to deal with editing our data files. Due to the large size of the data file, we will encounter more problems, so we divided this file into some small files based on some criteria like splitting into rows, columns, specific values of columns, etc. "
},
{
"code": null,
"e": 676,
"s": 430,
"text": "First, let’s create a simple CSV file and use it for all examples below in the article. Create dataset using dataframe method of pandas and then save it to “Customers.csv” file or we can load existing dataset with the Pandas read_csv() function."
},
{
"code": null,
"e": 684,
"s": 676,
"text": "Python3"
},
{
"code": "import pandas as pd # initialise data dictionary.data_dict = {'CustomerID': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 'Gender': [\"Male\", \"Female\", \"Female\", \"Male\", \"Male\", \"Female\", \"Male\", \"Male\", \"Female\", \"Male\"], 'Age': [20, 21, 19, 18, 25, 26, 32, 41, 20, 19], 'Annual Income(k$)': [10, 20, 30, 10, 25, 60, 70, 15, 21, 22], 'Spending Score': [30, 50, 48, 84, 90, 65, 32, 46, 12, 56]} # Create DataFramedata = pd.DataFrame(data_dict) # Write to CSV filedata.to_csv(\"Customers.csv\") # Print the output.print(data)",
"e": 1408,
"s": 684,
"text": null
},
{
"code": null,
"e": 1416,
"s": 1408,
"text": "Output:"
},
{
"code": null,
"e": 1487,
"s": 1416,
"text": "To do our work, we will discuss different methods that are as follows:"
},
{
"code": null,
"e": 1564,
"s": 1487,
"text": "In this method, we will split one CSV file into multiple CSVs based on rows."
},
{
"code": null,
"e": 1572,
"s": 1564,
"text": "Python3"
},
{
"code": "import pandas as pd # read DataFramedata = pd.read_csv(\"Customers.csv\") # no of csv files with row sizek = 2size = 5 for i in range(k): df = data[size*i:size*(i+1)] df.to_csv(f'Customers_{i+1}.csv', index=False) df_1 = pd.read_csv(\"Customers_1.csv\")print(df_1) df_2 = pd.read_csv(\"Customers_2.csv\")print(df_2)",
"e": 1888,
"s": 1572,
"text": null
},
{
"code": null,
"e": 1896,
"s": 1888,
"text": "Output:"
},
{
"code": null,
"e": 1907,
"s": 1896,
"text": "Example 1:"
},
{
"code": null,
"e": 2113,
"s": 1907,
"text": "Using groupby() method of Pandas we can create multiple CSV files. To create a file we can use the to_csv() method of Pandas. Here created two files based on “male” and “female” values of Gender columns. "
},
{
"code": null,
"e": 2121,
"s": 2113,
"text": "Python3"
},
{
"code": "import pandas as pd # read DataFramedata = pd.read_csv(\"Customers.csv\") for (gender), group in data.groupby(['Gender']): group.to_csv(f'{gender}.csv', index=False) print(pd.read_csv(\"Male.csv\"))print(pd.read_csv(\"Female.csv\"))",
"e": 2352,
"s": 2121,
"text": null
},
{
"code": null,
"e": 2361,
"s": 2352,
"text": "Output: "
},
{
"code": null,
"e": 2370,
"s": 2361,
"text": "Male.csv"
},
{
"code": null,
"e": 2381,
"s": 2370,
"text": "Female.csv"
},
{
"code": null,
"e": 2392,
"s": 2381,
"text": "Example 2:"
},
{
"code": null,
"e": 2569,
"s": 2392,
"text": "We can group more than two columns and can create multiple files on the basis of a combination of unique values from both Columns value. Take Gender and Annual Income columns. "
},
{
"code": null,
"e": 2577,
"s": 2569,
"text": "Python3"
},
{
"code": "import pandas as pd # read DataFramedata = pd.read_csv(\"Customers.csv\") for (Gender, Income), group in data.groupby(['Gender', 'Annual Income(k$)']): group.to_csv(f'{Gender} {Income}.csv', index=False) print(pd.read_csv(f'{Gender} {Income}.csv'))",
"e": 2830,
"s": 2577,
"text": null
},
{
"code": null,
"e": 2838,
"s": 2830,
"text": "Output:"
},
{
"code": null,
"e": 2857,
"s": 2838,
"text": "All Nine CSV files"
},
{
"code": null,
"e": 2868,
"s": 2857,
"text": "Example 3:"
},
{
"code": null,
"e": 3024,
"s": 2868,
"text": "We will filter the columns based on the specific column name Gender to its values (Male and Female). Then convert that to CSV file using to_csv in pandas. "
},
{
"code": null,
"e": 3032,
"s": 3024,
"text": "Python3"
},
{
"code": "import pandas as pd # read DataFramedata = pd.read_csv(\"Customers.csv\") male = data[data['Gender'] == 'Male']female = data[data['Gender'] == 'Female'] male.to_csv('Gender_male.csv', index=False)female.to_csv('Gender_female.csv', index=False) print(pd.read_csv(\"Gender_male.csv\"))print(pd.read_csv(\"Gender_female.csv\"))",
"e": 3351,
"s": 3032,
"text": null
},
{
"code": null,
"e": 3359,
"s": 3351,
"text": "Output:"
},
{
"code": null,
"e": 3610,
"s": 3359,
"text": "Using groupby() method of Pandas we can create multiple CSV files row-wise. To create a file we can use the to_csv() method of Pandas. Here created two files based on row values “male” and “female” values of specific Gender column for Spending Score."
},
{
"code": null,
"e": 3618,
"s": 3610,
"text": "Python3"
},
{
"code": "for (gender), group in data['Spending Score'].groupby(data['Gender']): group.to_csv(f'{gender}Score.csv', index=False) print(pd.read_csv(\"MaleScore.csv\"))print(pd.read_csv(\"FemaleScore.csv\"))",
"e": 3817,
"s": 3618,
"text": null
},
{
"code": null,
"e": 3825,
"s": 3817,
"text": "Output:"
},
{
"code": null,
"e": 3837,
"s": 3825,
"text": "anikakapoor"
},
{
"code": null,
"e": 3844,
"s": 3837,
"text": "Picked"
},
{
"code": null,
"e": 3861,
"s": 3844,
"text": "Python pandas-io"
},
{
"code": null,
"e": 3872,
"s": 3861,
"text": "python-csv"
},
{
"code": null,
"e": 3886,
"s": 3872,
"text": "Python-pandas"
},
{
"code": null,
"e": 3893,
"s": 3886,
"text": "Python"
},
{
"code": null,
"e": 3991,
"s": 3893,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4023,
"s": 3991,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4050,
"s": 4023,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4081,
"s": 4050,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4104,
"s": 4081,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4125,
"s": 4104,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4181,
"s": 4125,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4223,
"s": 4181,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4265,
"s": 4223,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4304,
"s": 4265,
"text": "Python | Get unique values from a list"
}
] |
Python | Adding two list elements
|
01 Dec, 2018
There can be many situations in which one requires to find index wise summation of two different lists. This can have a possible applications in day-day programming. Lets discuss various ways in which this task can be performed.
Method #1 : Naive MethodIn this method, we simply run a loop and append to the new list the summation of the both list elements at similar index till we reach end of the smaller list. This is the basic method to achieve this task.
# Python code to demonstrate # addition of two list # naive method # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2)) # using naive method to # add two list res_list = []for i in range(0, len(test_list1)): res_list.append(test_list1[i] + test_list2[i]) # printing resultant list print ("Resultant list is : " + str(res_list))
Output :
Original list 1 : [1, 3, 4, 6, 8]
Original list 2 : [4, 5, 6, 2, 10]
Resultant list is : [5, 8, 10, 8, 18]
Method #2 : Using List ComprehensionThe shorthand for the above explained technique, list comprehensions are usually quicker to type and hence must be preferred to perform these kind of programming tasks.
# Python code to demonstrate # addition of two list # list comprehension # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2)) # using list comprehension to # add two list res_list = [test_list1[i] + test_list2[i] for i in range(len(test_list1))] # printing resultant list print ("Resultant list is : " + str(res_list))
Output :
Original list 1 : [1, 3, 4, 6, 8]
Original list 2 : [4, 5, 6, 2, 10]
Resultant list is : [5, 8, 10, 8, 18]
Method #3 : Using map() + add()map() can also be used, as we can input the add operation to the map() along with the two list and map() can perform the addition of both the techniques. This can be extended to any mathematical operation possible.
# Python code to demonstrate # addition of two list # map() + add()from operator import add # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2)) # using map() + add() to # add two list res_list = list(map(add, test_list1, test_list2)) # printing resultant list print ("Resultant list is : " + str(res_list))
Output :
Original list 1 : [1, 3, 4, 6, 8]
Original list 2 : [4, 5, 6, 2, 10]
Resultant list is : [5, 8, 10, 8, 18]
Method #4 : Using zip() + sum()sum() can perform the index-wise addition of the list that can be “zipped” together using the zip(). This is quite elegant way to perform this particular task.
# Python code to demonstrate # addition of two list # zip() + sum()from operator import add # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint ("Original list 1 : " + str(test_list1))print ("Original list 2 : " + str(test_list2)) # using zip() + sum() to # add two list res_list = [sum(i) for i in zip(test_list1, test_list2)] # printing resultant list print ("Resultant list is : " + str(res_list))
Output :
Original list 1 : [1, 3, 4, 6, 8]
Original list 2 : [4, 5, 6, 2, 10]
Resultant list is : [5, 8, 10, 8, 18]
Python list-programs
python-list
Python
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Dec, 2018"
},
{
"code": null,
"e": 281,
"s": 52,
"text": "There can be many situations in which one requires to find index wise summation of two different lists. This can have a possible applications in day-day programming. Lets discuss various ways in which this task can be performed."
},
{
"code": null,
"e": 512,
"s": 281,
"text": "Method #1 : Naive MethodIn this method, we simply run a loop and append to the new list the summation of the both list elements at similar index till we reach end of the smaller list. This is the basic method to achieve this task."
},
{
"code": "# Python code to demonstrate # addition of two list # naive method # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint (\"Original list 1 : \" + str(test_list1))print (\"Original list 2 : \" + str(test_list2)) # using naive method to # add two list res_list = []for i in range(0, len(test_list1)): res_list.append(test_list1[i] + test_list2[i]) # printing resultant list print (\"Resultant list is : \" + str(res_list))",
"e": 991,
"s": 512,
"text": null
},
{
"code": null,
"e": 1000,
"s": 991,
"text": "Output :"
},
{
"code": null,
"e": 1108,
"s": 1000,
"text": "Original list 1 : [1, 3, 4, 6, 8]\nOriginal list 2 : [4, 5, 6, 2, 10]\nResultant list is : [5, 8, 10, 8, 18]\n"
},
{
"code": null,
"e": 1313,
"s": 1108,
"text": "Method #2 : Using List ComprehensionThe shorthand for the above explained technique, list comprehensions are usually quicker to type and hence must be preferred to perform these kind of programming tasks."
},
{
"code": "# Python code to demonstrate # addition of two list # list comprehension # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint (\"Original list 1 : \" + str(test_list1))print (\"Original list 2 : \" + str(test_list2)) # using list comprehension to # add two list res_list = [test_list1[i] + test_list2[i] for i in range(len(test_list1))] # printing resultant list print (\"Resultant list is : \" + str(res_list))",
"e": 1779,
"s": 1313,
"text": null
},
{
"code": null,
"e": 1788,
"s": 1779,
"text": "Output :"
},
{
"code": null,
"e": 1896,
"s": 1788,
"text": "Original list 1 : [1, 3, 4, 6, 8]\nOriginal list 2 : [4, 5, 6, 2, 10]\nResultant list is : [5, 8, 10, 8, 18]\n"
},
{
"code": null,
"e": 2142,
"s": 1896,
"text": "Method #3 : Using map() + add()map() can also be used, as we can input the add operation to the map() along with the two list and map() can perform the addition of both the techniques. This can be extended to any mathematical operation possible."
},
{
"code": "# Python code to demonstrate # addition of two list # map() + add()from operator import add # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint (\"Original list 1 : \" + str(test_list1))print (\"Original list 2 : \" + str(test_list2)) # using map() + add() to # add two list res_list = list(map(add, test_list1, test_list2)) # printing resultant list print (\"Resultant list is : \" + str(res_list))",
"e": 2597,
"s": 2142,
"text": null
},
{
"code": null,
"e": 2606,
"s": 2597,
"text": "Output :"
},
{
"code": null,
"e": 2714,
"s": 2606,
"text": "Original list 1 : [1, 3, 4, 6, 8]\nOriginal list 2 : [4, 5, 6, 2, 10]\nResultant list is : [5, 8, 10, 8, 18]\n"
},
{
"code": null,
"e": 2905,
"s": 2714,
"text": "Method #4 : Using zip() + sum()sum() can perform the index-wise addition of the list that can be “zipped” together using the zip(). This is quite elegant way to perform this particular task."
},
{
"code": "# Python code to demonstrate # addition of two list # zip() + sum()from operator import add # initializing liststest_list1 = [1, 3, 4, 6, 8]test_list2 = [4, 5, 6, 2, 10] # printing original listsprint (\"Original list 1 : \" + str(test_list1))print (\"Original list 2 : \" + str(test_list2)) # using zip() + sum() to # add two list res_list = [sum(i) for i in zip(test_list1, test_list2)] # printing resultant list print (\"Resultant list is : \" + str(res_list))",
"e": 3367,
"s": 2905,
"text": null
},
{
"code": null,
"e": 3376,
"s": 3367,
"text": "Output :"
},
{
"code": null,
"e": 3484,
"s": 3376,
"text": "Original list 1 : [1, 3, 4, 6, 8]\nOriginal list 2 : [4, 5, 6, 2, 10]\nResultant list is : [5, 8, 10, 8, 18]\n"
},
{
"code": null,
"e": 3505,
"s": 3484,
"text": "Python list-programs"
},
{
"code": null,
"e": 3517,
"s": 3505,
"text": "python-list"
},
{
"code": null,
"e": 3524,
"s": 3517,
"text": "Python"
},
{
"code": null,
"e": 3536,
"s": 3524,
"text": "python-list"
},
{
"code": null,
"e": 3634,
"s": 3536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3652,
"s": 3634,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3694,
"s": 3652,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3729,
"s": 3694,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3755,
"s": 3729,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3787,
"s": 3755,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3816,
"s": 3787,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3843,
"s": 3816,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3879,
"s": 3843,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 3900,
"s": 3879,
"text": "Python OOPs Concepts"
}
] |
XOR of every element of an Array with a given number K
|
13 Mar, 2022
Given an array arr and a number K, find the new array formed by performing XOR of the corresponding element from the given array with the given number K.Examples:
Input: arr[] = { 2, 4, 1, 3, 5 }, K = 5 Output: 7 1 4 6 0 Explanation: 2 XOR 5 = 7 4 XOR 5 = 1 1 XOR 5 = 4 3 XOR 5 = 6 5 XOR 5 = 0 Input: arr[] = { 4, 75, 45, 42 }, K = 2 Output: 6 73 47 40
Approach:
Traverse the given array.Then calculate the XOR of each element with K.Then store it as the element at that index in the output array.Print the updated array.
Traverse the given array.
Then calculate the XOR of each element with K.
Then store it as the element at that index in the output array.
Print the updated array.
Below is the implementation of the above approach.
CPP
Java
Python3
C#
Javascript
// C++ program to find XOR of every element// of an array with a given number K #include <bits/stdc++.h>using namespace std; // Function to construct new arrayvoid constructXORArray(int A[], int n, int K){ int B[n]; // Traverse the array and // compute XOR with K for (int i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (int i = 0; i < n; i++) cout << B[i] << " "; cout << endl;} // Driver codeint main(){ int A[] = { 2, 4, 1, 3, 5 }; int K = 5; int n = sizeof(A) / sizeof(A[0]); constructXORArray(A, n, K); int B[] = { 4, 75, 45, 42 }; K = 2; n = sizeof(B) / sizeof(B[0]); constructXORArray(B, n, K); return 0;}
// Java program to find XOR of every element// of an array with a given number Kimport java.util.*;class GFG{ // Function to construct new arraystatic void constructXORArray(int A[], int n, int K){ int[] B = new int[n]; // Traverse the array and // compute XOR with K for (int i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (int i = 0; i < n; i++) System.out.print( B[i] +" "); System.out.println();} // Driver codepublic static void main(String args[]){ int A[] = { 2, 4, 1, 3, 5 }; int K = 5; int n = A.length; constructXORArray(A, n, K); int B[] = { 4, 75, 45, 42 }; K = 2; n = B.length; constructXORArray(B, n, K); }} // This code is contributed by shivanisinghss2110
# Python program to find XOR of every element# of an array with a given number K # Function to construct new arraydef constructXORArray(A, n, K): B = [0]*n; # Traverse the array and # compute XOR with K for i in range(n): B[i] = A[i] ^ K; # Print new array for i in range(n): print(B[i], end=" "); print(); # Driver codeif __name__ == '__main__': A = [ 2, 4, 1, 3, 5 ]; K = 5; n = len(A); constructXORArray(A, n, K); B = [ 4, 75, 45, 42 ]; K = 2; n = len(B); constructXORArray(B, n, K);# This code contributed by sapnasingh4991
// C# program to find XOR of every element// of an array with a given number Kusing System; class GFG{ // Function to construct new arraystatic void constructXORArray(int []A, int n, int K){ int[] B = new int[n]; // Traverse the array and // compute XOR with K for (int i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (int i = 0; i < n; i++) Console.Write( B[i] +" "); Console.WriteLine();} // Driver codepublic static void Main(String []args){ int []A = { 2, 4, 1, 3, 5 }; int K = 5; int n = A.Length; constructXORArray(A, n, K); int []B = { 4, 75, 45, 42 }; K = 2; n = B.Length; constructXORArray(B, n, K);}} // This code is contributed by Rajput-Ji
<script> // Javascript program to find XOR of every element // of an array with a given number K // Function to construct new array function constructXORArray(A, n, K) { let B = new Array(n); // Traverse the array and // compute XOR with K for (let i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (let i = 0; i < n; i++) document.write(B[i] + " "); document.write("</br>") } let A = [ 2, 4, 1, 3, 5 ]; let K = 5; let n = A.length; constructXORArray(A, n, K); let B = [ 4, 75, 45, 42 ]; K = 2; n = B.length; constructXORArray(B, n, K); // This code is contributed by divyeshrabadiya07.</script>
7 1 4 6 0
6 73 47 40
Time Complexity: O(n)Auxiliary Space: O(n)
shivanisinghss2110
Rajput-Ji
sapnasingh4991
divyeshrabadiya07
singhh3010
Bitwise-XOR
Arrays
Bit Magic
School Programming
Arrays
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Bitwise Operators in C/C++
Left Shift and Right Shift Operators in C/C++
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Count set bits in an integer
How to swap two numbers without using a temporary variable?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 217,
"s": 52,
"text": "Given an array arr and a number K, find the new array formed by performing XOR of the corresponding element from the given array with the given number K.Examples: "
},
{
"code": null,
"e": 409,
"s": 217,
"text": "Input: arr[] = { 2, 4, 1, 3, 5 }, K = 5 Output: 7 1 4 6 0 Explanation: 2 XOR 5 = 7 4 XOR 5 = 1 1 XOR 5 = 4 3 XOR 5 = 6 5 XOR 5 = 0 Input: arr[] = { 4, 75, 45, 42 }, K = 2 Output: 6 73 47 40 "
},
{
"code": null,
"e": 422,
"s": 411,
"text": "Approach: "
},
{
"code": null,
"e": 581,
"s": 422,
"text": "Traverse the given array.Then calculate the XOR of each element with K.Then store it as the element at that index in the output array.Print the updated array."
},
{
"code": null,
"e": 607,
"s": 581,
"text": "Traverse the given array."
},
{
"code": null,
"e": 654,
"s": 607,
"text": "Then calculate the XOR of each element with K."
},
{
"code": null,
"e": 718,
"s": 654,
"text": "Then store it as the element at that index in the output array."
},
{
"code": null,
"e": 743,
"s": 718,
"text": "Print the updated array."
},
{
"code": null,
"e": 795,
"s": 743,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 799,
"s": 795,
"text": "CPP"
},
{
"code": null,
"e": 804,
"s": 799,
"text": "Java"
},
{
"code": null,
"e": 812,
"s": 804,
"text": "Python3"
},
{
"code": null,
"e": 815,
"s": 812,
"text": "C#"
},
{
"code": null,
"e": 826,
"s": 815,
"text": "Javascript"
},
{
"code": "// C++ program to find XOR of every element// of an array with a given number K #include <bits/stdc++.h>using namespace std; // Function to construct new arrayvoid constructXORArray(int A[], int n, int K){ int B[n]; // Traverse the array and // compute XOR with K for (int i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (int i = 0; i < n; i++) cout << B[i] << \" \"; cout << endl;} // Driver codeint main(){ int A[] = { 2, 4, 1, 3, 5 }; int K = 5; int n = sizeof(A) / sizeof(A[0]); constructXORArray(A, n, K); int B[] = { 4, 75, 45, 42 }; K = 2; n = sizeof(B) / sizeof(B[0]); constructXORArray(B, n, K); return 0;}",
"e": 1517,
"s": 826,
"text": null
},
{
"code": "// Java program to find XOR of every element// of an array with a given number Kimport java.util.*;class GFG{ // Function to construct new arraystatic void constructXORArray(int A[], int n, int K){ int[] B = new int[n]; // Traverse the array and // compute XOR with K for (int i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (int i = 0; i < n; i++) System.out.print( B[i] +\" \"); System.out.println();} // Driver codepublic static void main(String args[]){ int A[] = { 2, 4, 1, 3, 5 }; int K = 5; int n = A.length; constructXORArray(A, n, K); int B[] = { 4, 75, 45, 42 }; K = 2; n = B.length; constructXORArray(B, n, K); }} // This code is contributed by shivanisinghss2110",
"e": 2270,
"s": 1517,
"text": null
},
{
"code": "# Python program to find XOR of every element# of an array with a given number K # Function to construct new arraydef constructXORArray(A, n, K): B = [0]*n; # Traverse the array and # compute XOR with K for i in range(n): B[i] = A[i] ^ K; # Print new array for i in range(n): print(B[i], end=\" \"); print(); # Driver codeif __name__ == '__main__': A = [ 2, 4, 1, 3, 5 ]; K = 5; n = len(A); constructXORArray(A, n, K); B = [ 4, 75, 45, 42 ]; K = 2; n = len(B); constructXORArray(B, n, K);# This code contributed by sapnasingh4991",
"e": 2862,
"s": 2270,
"text": null
},
{
"code": "// C# program to find XOR of every element// of an array with a given number Kusing System; class GFG{ // Function to construct new arraystatic void constructXORArray(int []A, int n, int K){ int[] B = new int[n]; // Traverse the array and // compute XOR with K for (int i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (int i = 0; i < n; i++) Console.Write( B[i] +\" \"); Console.WriteLine();} // Driver codepublic static void Main(String []args){ int []A = { 2, 4, 1, 3, 5 }; int K = 5; int n = A.Length; constructXORArray(A, n, K); int []B = { 4, 75, 45, 42 }; K = 2; n = B.Length; constructXORArray(B, n, K);}} // This code is contributed by Rajput-Ji",
"e": 3600,
"s": 2862,
"text": null
},
{
"code": "<script> // Javascript program to find XOR of every element // of an array with a given number K // Function to construct new array function constructXORArray(A, n, K) { let B = new Array(n); // Traverse the array and // compute XOR with K for (let i = 0; i < n; i++) B[i] = A[i] ^ K; // Print new array for (let i = 0; i < n; i++) document.write(B[i] + \" \"); document.write(\"</br>\") } let A = [ 2, 4, 1, 3, 5 ]; let K = 5; let n = A.length; constructXORArray(A, n, K); let B = [ 4, 75, 45, 42 ]; K = 2; n = B.length; constructXORArray(B, n, K); // This code is contributed by divyeshrabadiya07.</script>",
"e": 4341,
"s": 3600,
"text": null
},
{
"code": null,
"e": 4363,
"s": 4341,
"text": "7 1 4 6 0 \n6 73 47 40"
},
{
"code": null,
"e": 4408,
"s": 4365,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 4427,
"s": 4408,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 4437,
"s": 4427,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 4452,
"s": 4437,
"text": "sapnasingh4991"
},
{
"code": null,
"e": 4470,
"s": 4452,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 4481,
"s": 4470,
"text": "singhh3010"
},
{
"code": null,
"e": 4493,
"s": 4481,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 4500,
"s": 4493,
"text": "Arrays"
},
{
"code": null,
"e": 4510,
"s": 4500,
"text": "Bit Magic"
},
{
"code": null,
"e": 4529,
"s": 4510,
"text": "School Programming"
},
{
"code": null,
"e": 4536,
"s": 4529,
"text": "Arrays"
},
{
"code": null,
"e": 4546,
"s": 4536,
"text": "Bit Magic"
},
{
"code": null,
"e": 4644,
"s": 4546,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4676,
"s": 4644,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 4701,
"s": 4676,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 4748,
"s": 4701,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 4812,
"s": 4748,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 4843,
"s": 4812,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 4870,
"s": 4843,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 4916,
"s": 4870,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 4984,
"s": 4916,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 5013,
"s": 4984,
"text": "Count set bits in an integer"
}
] |
How to Make ECDF Plot with Seaborn in Python?
|
24 Jan, 2021
Prerequisites: Seaborn
In this article, we are going to make the ECDF plot with Seaborn Library.
ECDF stands for Empirical Commutative Distribution. It is more likely to use instead of the histogram for visualizing the data because the ECDF plot visualizes each and every data point of the dataset directly, which makes it easy for the user to interact with the plot.
This plot contains more information because it has no bin size setting, which means it doesn’t have any smoothing parameters.
Since its curves are monotonically increasing, so it is well suited for comparing multiple distributions at the same time.
In an ECDF plot, the x-axis corresponds to the range of values for the variable whereas the y-axis corresponds to the proportion of data points that are less than or equal to the corresponding value of the x-axis.
We can make the ECDF plot directly by using ecdfplot() function, or we can also make the plot by using displot() function with the new Seaborn version.
To install the Seaborn library, write the following command in your command prompt.
pip install seaborn
This ECDF plot and displot() function is available only in the new version of Seaborn that is version 0.11.0 or above. If already install Seaborn upgrade it by writing the following command.
pip install seaborn==0.11.0
For a better understanding of the ECDF plot. Let’s plot and do some examples using the datasets.
Import the seaborn library.
Create or load the dataset from the seaborn library.
Select the column for which you are plotting the ECDF plot.
For plotting the ECDF plot there are two ways are as follows:
The first way is to use ecdfplot() function to directly plot the ECDF plot and in the function pass you data and column name on which you are plotting.
Syntax:
seaborn.ecdfplot(data=’dataframe’,x=’column_name’,y=’column_name’, hue=’color_column’)
The second way is to use displot() function and pass your data and column on which you are making the plot and pass the parameter of displot kind=’ecdf’.
Syntax:
seaborn.displot(data=’dataframe’, x=’column_name’,y=’column_name’ kind=’type_of_plot’,hue=’color_column’, palette=’color’
The below table shows the list of parameters used in this article.
This parameter is used to choose color when mapping the hue.
It can be string, list, dict.
Method 1: Using ecdfplot() method
In this method, we are using ‘excerise’ data provided by seaborn.
Python
# importing libraryimport seaborn as sns # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # printing the datasetprint(excr)
Output:
Example 1: Making ECDF plot by using exercise dataset provided by seaborn.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # making ECDF plot sns.ecdfplot(data=excr,x='pulse') # visualizing the plot using matplotlib.pyplot # show() functionplt.show()
Output:
Example 2: Making ECDF plot by interchanging the plot axis.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # making ECDF plot sns.ecdfplot(data=excr,y='pulse') # visualizing the plot using matplotlib.pyplot# show() functionplt.show()
Output:
Example 3: Making ECDF plot when we have multiple distributions.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # making ECDF plot when we have multiple # distributionssns.ecdfplot(data=excr, x='pulse', hue='kind') # visualizing the plot using matplotlib.pyplot # show() functionplt.show()
Output:
The above plot shows the distribution of pulse rate of the peoples with respect to the kind i.e, rest, walking, running.
Method 2: Using displot() method
In this method, we are using ‘diamonds’ data provided by seaborn.
Python
# importing libraryimport seaborn as sns # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # printing the datasetprint(diam)
Output:
Example 1: Plotting ECDF plot using displot() on penguins dataset provided by seaborn.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # making ECDF plot using displot() on depth # of the diamondssns.displot(data=diam,x='depth',kind='ecdf') # visualizing the plot using matplotlib.pyplot # show() functionplt.show()
Output:
Example 2: Plotting ECDF plot using displot() when we have multiple distributions with default setting.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # making ECDF plot using displot() on depth# of the diamond on the basis of cutsns.displot(data=diam,x='depth',kind='ecdf',hue='cut') # visualizing the plot using matplotlib.pyplot# show() functionplt.show()
Output:
The above plot shows the depth of the diamonds on the basis of their cut.
Example 3: Making ECDF plot using displot() by setting up the color.
Python
# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # making ECDF plot using displot() on table # column on the basis of cut of diamond# setting up the color of plot by setting# up the palette to icefire_rsns.displot(data=diam,x='table',kind='ecdf',hue='cut',palette='icefire_r') # visualizing the plot using matplotlib.pyplot# show() functionplt.show()
Output:
We can set the palette to Accent_r, magma_r, plasma, plasma_r, etc, according to our choice, it has many other options available.
Picked
Python-Seaborn
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 78,
"s": 54,
"text": "Prerequisites: Seaborn"
},
{
"code": null,
"e": 152,
"s": 78,
"text": "In this article, we are going to make the ECDF plot with Seaborn Library."
},
{
"code": null,
"e": 423,
"s": 152,
"text": "ECDF stands for Empirical Commutative Distribution. It is more likely to use instead of the histogram for visualizing the data because the ECDF plot visualizes each and every data point of the dataset directly, which makes it easy for the user to interact with the plot."
},
{
"code": null,
"e": 549,
"s": 423,
"text": "This plot contains more information because it has no bin size setting, which means it doesn’t have any smoothing parameters."
},
{
"code": null,
"e": 672,
"s": 549,
"text": "Since its curves are monotonically increasing, so it is well suited for comparing multiple distributions at the same time."
},
{
"code": null,
"e": 886,
"s": 672,
"text": "In an ECDF plot, the x-axis corresponds to the range of values for the variable whereas the y-axis corresponds to the proportion of data points that are less than or equal to the corresponding value of the x-axis."
},
{
"code": null,
"e": 1038,
"s": 886,
"text": "We can make the ECDF plot directly by using ecdfplot() function, or we can also make the plot by using displot() function with the new Seaborn version."
},
{
"code": null,
"e": 1122,
"s": 1038,
"text": "To install the Seaborn library, write the following command in your command prompt."
},
{
"code": null,
"e": 1142,
"s": 1122,
"text": "pip install seaborn"
},
{
"code": null,
"e": 1333,
"s": 1142,
"text": "This ECDF plot and displot() function is available only in the new version of Seaborn that is version 0.11.0 or above. If already install Seaborn upgrade it by writing the following command."
},
{
"code": null,
"e": 1361,
"s": 1333,
"text": "pip install seaborn==0.11.0"
},
{
"code": null,
"e": 1458,
"s": 1361,
"text": "For a better understanding of the ECDF plot. Let’s plot and do some examples using the datasets."
},
{
"code": null,
"e": 1486,
"s": 1458,
"text": "Import the seaborn library."
},
{
"code": null,
"e": 1539,
"s": 1486,
"text": "Create or load the dataset from the seaborn library."
},
{
"code": null,
"e": 1599,
"s": 1539,
"text": "Select the column for which you are plotting the ECDF plot."
},
{
"code": null,
"e": 1661,
"s": 1599,
"text": "For plotting the ECDF plot there are two ways are as follows:"
},
{
"code": null,
"e": 1813,
"s": 1661,
"text": "The first way is to use ecdfplot() function to directly plot the ECDF plot and in the function pass you data and column name on which you are plotting."
},
{
"code": null,
"e": 1821,
"s": 1813,
"text": "Syntax:"
},
{
"code": null,
"e": 1908,
"s": 1821,
"text": "seaborn.ecdfplot(data=’dataframe’,x=’column_name’,y=’column_name’, hue=’color_column’)"
},
{
"code": null,
"e": 2062,
"s": 1908,
"text": "The second way is to use displot() function and pass your data and column on which you are making the plot and pass the parameter of displot kind=’ecdf’."
},
{
"code": null,
"e": 2070,
"s": 2062,
"text": "Syntax:"
},
{
"code": null,
"e": 2192,
"s": 2070,
"text": "seaborn.displot(data=’dataframe’, x=’column_name’,y=’column_name’ kind=’type_of_plot’,hue=’color_column’, palette=’color’"
},
{
"code": null,
"e": 2259,
"s": 2192,
"text": "The below table shows the list of parameters used in this article."
},
{
"code": null,
"e": 2321,
"s": 2259,
"text": "This parameter is used to choose color when mapping the hue. "
},
{
"code": null,
"e": 2351,
"s": 2321,
"text": "It can be string, list, dict."
},
{
"code": null,
"e": 2385,
"s": 2351,
"text": "Method 1: Using ecdfplot() method"
},
{
"code": null,
"e": 2451,
"s": 2385,
"text": "In this method, we are using ‘excerise’ data provided by seaborn."
},
{
"code": null,
"e": 2458,
"s": 2451,
"text": "Python"
},
{
"code": "# importing libraryimport seaborn as sns # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # printing the datasetprint(excr)",
"e": 2617,
"s": 2458,
"text": null
},
{
"code": null,
"e": 2625,
"s": 2617,
"text": "Output:"
},
{
"code": null,
"e": 2700,
"s": 2625,
"text": "Example 1: Making ECDF plot by using exercise dataset provided by seaborn."
},
{
"code": null,
"e": 2707,
"s": 2700,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # making ECDF plot sns.ecdfplot(data=excr,x='pulse') # visualizing the plot using matplotlib.pyplot # show() functionplt.show()",
"e": 2994,
"s": 2707,
"text": null
},
{
"code": null,
"e": 3002,
"s": 2994,
"text": "Output:"
},
{
"code": null,
"e": 3062,
"s": 3002,
"text": "Example 2: Making ECDF plot by interchanging the plot axis."
},
{
"code": null,
"e": 3069,
"s": 3062,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # making ECDF plot sns.ecdfplot(data=excr,y='pulse') # visualizing the plot using matplotlib.pyplot# show() functionplt.show()",
"e": 3355,
"s": 3069,
"text": null
},
{
"code": null,
"e": 3363,
"s": 3355,
"text": "Output:"
},
{
"code": null,
"e": 3428,
"s": 3363,
"text": "Example 3: Making ECDF plot when we have multiple distributions."
},
{
"code": null,
"e": 3435,
"s": 3428,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading exercise dataset provided by seabornexcr = sns.load_dataset('exercise') # making ECDF plot when we have multiple # distributionssns.ecdfplot(data=excr, x='pulse', hue='kind') # visualizing the plot using matplotlib.pyplot # show() functionplt.show()",
"e": 3772,
"s": 3435,
"text": null
},
{
"code": null,
"e": 3780,
"s": 3772,
"text": "Output:"
},
{
"code": null,
"e": 3901,
"s": 3780,
"text": "The above plot shows the distribution of pulse rate of the peoples with respect to the kind i.e, rest, walking, running."
},
{
"code": null,
"e": 3934,
"s": 3901,
"text": "Method 2: Using displot() method"
},
{
"code": null,
"e": 4000,
"s": 3934,
"text": "In this method, we are using ‘diamonds’ data provided by seaborn."
},
{
"code": null,
"e": 4007,
"s": 4000,
"text": "Python"
},
{
"code": "# importing libraryimport seaborn as sns # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # printing the datasetprint(diam)",
"e": 4166,
"s": 4007,
"text": null
},
{
"code": null,
"e": 4174,
"s": 4166,
"text": "Output:"
},
{
"code": null,
"e": 4261,
"s": 4174,
"text": "Example 1: Plotting ECDF plot using displot() on penguins dataset provided by seaborn."
},
{
"code": null,
"e": 4268,
"s": 4261,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # making ECDF plot using displot() on depth # of the diamondssns.displot(data=diam,x='depth',kind='ecdf') # visualizing the plot using matplotlib.pyplot # show() functionplt.show()",
"e": 4608,
"s": 4268,
"text": null
},
{
"code": null,
"e": 4616,
"s": 4608,
"text": "Output:"
},
{
"code": null,
"e": 4720,
"s": 4616,
"text": "Example 2: Plotting ECDF plot using displot() when we have multiple distributions with default setting."
},
{
"code": null,
"e": 4727,
"s": 4720,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # making ECDF plot using displot() on depth# of the diamond on the basis of cutsns.displot(data=diam,x='depth',kind='ecdf',hue='cut') # visualizing the plot using matplotlib.pyplot# show() functionplt.show()",
"e": 5094,
"s": 4727,
"text": null
},
{
"code": null,
"e": 5102,
"s": 5094,
"text": "Output:"
},
{
"code": null,
"e": 5176,
"s": 5102,
"text": "The above plot shows the depth of the diamonds on the basis of their cut."
},
{
"code": null,
"e": 5245,
"s": 5176,
"text": "Example 3: Making ECDF plot using displot() by setting up the color."
},
{
"code": null,
"e": 5252,
"s": 5245,
"text": "Python"
},
{
"code": "# importing librariesimport seaborn as snsimport matplotlib.pyplot as plt # loading diamonds dataset provided by seaborndiam = sns.load_dataset('diamonds') # making ECDF plot using displot() on table # column on the basis of cut of diamond# setting up the color of plot by setting# up the palette to icefire_rsns.displot(data=diam,x='table',kind='ecdf',hue='cut',palette='icefire_r') # visualizing the plot using matplotlib.pyplot# show() functionplt.show()",
"e": 5713,
"s": 5252,
"text": null
},
{
"code": null,
"e": 5721,
"s": 5713,
"text": "Output:"
},
{
"code": null,
"e": 5851,
"s": 5721,
"text": "We can set the palette to Accent_r, magma_r, plasma, plasma_r, etc, according to our choice, it has many other options available."
},
{
"code": null,
"e": 5858,
"s": 5851,
"text": "Picked"
},
{
"code": null,
"e": 5873,
"s": 5858,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 5897,
"s": 5873,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 5904,
"s": 5897,
"text": "Python"
},
{
"code": null,
"e": 5923,
"s": 5904,
"text": "Technical Scripter"
}
] |
How to Use a .dockerignore File?
|
29 Oct, 2020
If you are a Docker Developer, you might have noticed that when you build a Docker Image either using a dockerfile or directly pull an image from the Docker registry, the size of the image can be considerably large depending upon your Docker Build Context.
Since Docker is a client-server application, we know that the Docker Client is the actual Command Line Interface that we used to access the Docker Containers and the Docker Server is actually called the Docker Daemon which helps you in maintaining the Containers. When we are trying to build a Docker Image, we need to send some files to the Docker Daemon or the server so that those files can be used and included inside the Docker Container that we are trying to build. This set of files and directories is called the Docker Build Context.
It’s obvious that the larger the size of the files and folders inside the Docker build context, the larger is the size of the Docker Image. Now, inside the folder where you keep your dockerfile and through which you are trying to build the Image, there might contain some files and folders that are although a part of the project and you don’t want to include those files in the Docker Build Context. Let’s look at some reasons for not including these files and directories.
Security Issues – Some important files such as passwords, secret keys, .git folders, etc contain a lot of information about your project and you might now want to expose those details to the outside world to prevent intrusion.
Cache Invalidation – When you write the Dockerfile, it’s a general practice to use the COPY instruction to copy the files and folders inside the Docker build context. Each statement inside the Dockerfile results in building a new intermediate image layer. Hence, when you make changes in your dockerfile again and again, this might lead to multiple Cache Invalidation and leads to wastage of resources.
Also, excluding unnecessary large files from your Docker Build Context will lead to lower Docker Image size.
It speeds up the process of building the Docker Image.
Due to all these reasons, you might want to exclude some files and folders from your Docker Build Context.
Now, similar to a .gitignore file that is commonly used when you build Git repositories, a .dockerignore file is used to ignore files and folders when you try to build a Docker Image. You can specify the list of files and directories inside the .dockerignore file.
Let’s look at an example of .dockerignore file.
passphrase.txt
logs/
.git
*.md
.cache
Let’s take a look at a practical example of using a .dockerignore file.
Step 1: Create a directory containing a dockerfile where you specify the instructions and a folder that you want to ignore (say ignore-this).
In this case, the dockerfile simply pulls the Ubuntu Image from the repository and copy the build context.
FROM ubuntu:latest
COPY . .
Step 2: Inside the same directory, create a .dockerignore file and include the name of the folder you want to exclude from the Docker Build Context.
ignore-this
Now, the main directory contains a dockerfile, a .dockerignore file, and a folder called ignore-this.
Directory structure
Step 3: Build the Docker Image.
sudo docker build -t sample-image .
Building the Docker Image
Step 4: Run the Docker Container and check the folder.
sudo docker run -it sample-image bash
ls
Running the Container
You will find that the Container only contains the dockerfile and not the “ignore-this” folder. Not that it also does not contain the .dockerignore file.
It is true that you can also mention the dockerfile inside the .dockerignore file and exclude it from the Docker build context. In fact, it is a common practice than you might have thought. This allows you not to expose the entire blueprint of your Docker application.
Docker Container
linux
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Markov Decision Process
Getting Started with System Design
Principal Component Analysis with Python
Fuzzy Logic | Introduction
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
ML | Introduction to Data in Machine Learning
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 285,
"s": 28,
"text": "If you are a Docker Developer, you might have noticed that when you build a Docker Image either using a dockerfile or directly pull an image from the Docker registry, the size of the image can be considerably large depending upon your Docker Build Context."
},
{
"code": null,
"e": 828,
"s": 285,
"text": "Since Docker is a client-server application, we know that the Docker Client is the actual Command Line Interface that we used to access the Docker Containers and the Docker Server is actually called the Docker Daemon which helps you in maintaining the Containers. When we are trying to build a Docker Image, we need to send some files to the Docker Daemon or the server so that those files can be used and included inside the Docker Container that we are trying to build. This set of files and directories is called the Docker Build Context. "
},
{
"code": null,
"e": 1303,
"s": 828,
"text": "It’s obvious that the larger the size of the files and folders inside the Docker build context, the larger is the size of the Docker Image. Now, inside the folder where you keep your dockerfile and through which you are trying to build the Image, there might contain some files and folders that are although a part of the project and you don’t want to include those files in the Docker Build Context. Let’s look at some reasons for not including these files and directories."
},
{
"code": null,
"e": 1530,
"s": 1303,
"text": "Security Issues – Some important files such as passwords, secret keys, .git folders, etc contain a lot of information about your project and you might now want to expose those details to the outside world to prevent intrusion."
},
{
"code": null,
"e": 1933,
"s": 1530,
"text": "Cache Invalidation – When you write the Dockerfile, it’s a general practice to use the COPY instruction to copy the files and folders inside the Docker build context. Each statement inside the Dockerfile results in building a new intermediate image layer. Hence, when you make changes in your dockerfile again and again, this might lead to multiple Cache Invalidation and leads to wastage of resources."
},
{
"code": null,
"e": 2042,
"s": 1933,
"text": "Also, excluding unnecessary large files from your Docker Build Context will lead to lower Docker Image size."
},
{
"code": null,
"e": 2097,
"s": 2042,
"text": "It speeds up the process of building the Docker Image."
},
{
"code": null,
"e": 2204,
"s": 2097,
"text": "Due to all these reasons, you might want to exclude some files and folders from your Docker Build Context."
},
{
"code": null,
"e": 2470,
"s": 2204,
"text": "Now, similar to a .gitignore file that is commonly used when you build Git repositories, a .dockerignore file is used to ignore files and folders when you try to build a Docker Image. You can specify the list of files and directories inside the .dockerignore file. "
},
{
"code": null,
"e": 2518,
"s": 2470,
"text": "Let’s look at an example of .dockerignore file."
},
{
"code": null,
"e": 2557,
"s": 2518,
"text": "passphrase.txt\nlogs/\n.git\n*.md\n.cache\n"
},
{
"code": null,
"e": 2629,
"s": 2557,
"text": "Let’s take a look at a practical example of using a .dockerignore file."
},
{
"code": null,
"e": 2771,
"s": 2629,
"text": "Step 1: Create a directory containing a dockerfile where you specify the instructions and a folder that you want to ignore (say ignore-this)."
},
{
"code": null,
"e": 2878,
"s": 2771,
"text": "In this case, the dockerfile simply pulls the Ubuntu Image from the repository and copy the build context."
},
{
"code": null,
"e": 2907,
"s": 2878,
"text": "FROM ubuntu:latest\nCOPY . .\n"
},
{
"code": null,
"e": 3056,
"s": 2907,
"text": "Step 2: Inside the same directory, create a .dockerignore file and include the name of the folder you want to exclude from the Docker Build Context."
},
{
"code": null,
"e": 3069,
"s": 3056,
"text": "ignore-this\n"
},
{
"code": null,
"e": 3171,
"s": 3069,
"text": "Now, the main directory contains a dockerfile, a .dockerignore file, and a folder called ignore-this."
},
{
"code": null,
"e": 3191,
"s": 3171,
"text": "Directory structure"
},
{
"code": null,
"e": 3223,
"s": 3191,
"text": "Step 3: Build the Docker Image."
},
{
"code": null,
"e": 3260,
"s": 3223,
"text": "sudo docker build -t sample-image .\n"
},
{
"code": null,
"e": 3286,
"s": 3260,
"text": "Building the Docker Image"
},
{
"code": null,
"e": 3341,
"s": 3286,
"text": "Step 4: Run the Docker Container and check the folder."
},
{
"code": null,
"e": 3383,
"s": 3341,
"text": "sudo docker run -it sample-image bash\nls\n"
},
{
"code": null,
"e": 3405,
"s": 3383,
"text": "Running the Container"
},
{
"code": null,
"e": 3559,
"s": 3405,
"text": "You will find that the Container only contains the dockerfile and not the “ignore-this” folder. Not that it also does not contain the .dockerignore file."
},
{
"code": null,
"e": 3828,
"s": 3559,
"text": "It is true that you can also mention the dockerfile inside the .dockerignore file and exclude it from the Docker build context. In fact, it is a common practice than you might have thought. This allows you not to expose the entire blueprint of your Docker application."
},
{
"code": null,
"e": 3845,
"s": 3828,
"text": "Docker Container"
},
{
"code": null,
"e": 3851,
"s": 3845,
"text": "linux"
},
{
"code": null,
"e": 3877,
"s": 3851,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 3975,
"s": 3877,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4011,
"s": 3975,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4047,
"s": 4011,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 4091,
"s": 4047,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 4115,
"s": 4091,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4150,
"s": 4115,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 4191,
"s": 4150,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 4218,
"s": 4191,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 4266,
"s": 4218,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 4307,
"s": 4266,
"text": "Monolithic vs Microservices architecture"
}
] |
Smallest sum contiguous subarray
|
03 Feb, 2022
Given an array containing n integers. The problem is to find the sum of the elements of the contiguous subarray having the smallest(minimum) sum.Examples:
Input : arr[] = {3, -4, 2, -3, -1, 7, -5}
Output : -6
Subarray is {-4, 2, -3, -1} = -6
Input : arr = {2, 6, 8, 1, 4}
Output : 1
Naive Approach: Consider all the contiguous subarrays of different sizes and find their sum. The subarray having the smallest(minimum) sum is the required answer.Efficient Approach: It is a variation to the problem of finding the largest sum contiguous subarray based on the idea of Kadane’s algorithm. Algorithm:
smallestSumSubarr(arr, n)
Initialize min_ending_here = INT_MAX
Initialize min_so_far = INT_MAX
for i = 0 to n-1
if min_ending_here > 0
min_ending_here = arr[i]
else
min_ending_here += arr[i]
min_so_far = min(min_so_far, min_ending_here)
return min_so_far
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation to find the smallest sum// contiguous subarray#include <bits/stdc++.h> using namespace std; // function to find the smallest sum contiguous subarrayint smallestSumSubarr(int arr[], int n){ // to store the minimum value that is ending // up to the current index int min_ending_here = INT_MAX; // to store the minimum value encountered so far int min_so_far = INT_MAX; // traverse the array elements for (int i=0; i<n; i++) { // if min_ending_here > 0, then it could not possibly // contribute to the minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = min(min_so_far, min_ending_here); } // required smallest sum contiguous subarray value return min_so_far;} // Driver program to test aboveint main(){ int arr[] = {3, -4, 2, -3, -1, 7, -5}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Smallest sum: " << smallestSumSubarr(arr, n); return 0; }
// Java implementation to find the smallest sum// contiguous subarrayclass GFG { // function to find the smallest sum contiguous // subarray static int smallestSumSubarr(int arr[], int n) { // to store the minimum value that is // ending up to the current index int min_ending_here = 2147483647; // to store the minimum value encountered // so far int min_so_far = 2147483647; // traverse the array elements for (int i = 0; i < n; i++) { // if min_ending_here > 0, then it could // not possibly contribute to the // minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to // min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = Math.min(min_so_far, min_ending_here); } // required smallest sum contiguous // subarray value return min_so_far; } // Driver method public static void main(String[] args) { int arr[] = {3, -4, 2, -3, -1, 7, -5}; int n = arr.length; System.out.print("Smallest sum: " + smallestSumSubarr(arr, n)); }} // This code is contributed by Anant Agarwal.
# Python program to find the smallest sum# contiguous subarraymaxsize=int(1e9+7) # function to find the smallest sum# contiguous subarraydef smallestSumSubarr(arr, n): # to store the minimum value that is ending # up to the current index min_ending_here = maxsize # to store the minimum value encountered so far min_so_far = maxsize # traverse the array elements for i in range(n): # if min_ending_here > 0, then it could not possibly # contribute to the minimum sum further if (min_ending_here > 0): min_ending_here = arr[i] # else add the value arr[i] to min_ending_here else: min_ending_here += arr[i] # update min_so_far min_so_far = min(min_so_far, min_ending_here) # required smallest sum contiguous subarray value return min_so_far # Driver codearr = [3, -4, 2, -3, -1, 7, -5]n = len(arr)print ("Smallest sum: ", smallestSumSubarr(arr, n)) # This code is contributed by Sachin Bisht
// C# implementation to find the// smallest sum contiguous subarrayusing System; class GFG { // function to find the smallest sum // contiguous subarray static int smallestSumSubarr(int[] arr, int n) { // to store the minimum value that is // ending up to the current index int min_ending_here = 2147483647; // to store the minimum value encountered // so far int min_so_far = 2147483647; // traverse the array elements for (int i = 0; i < n; i++) { // if min_ending_here > 0, then it could // not possibly contribute to the // minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to // min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = Math.Min(min_so_far, min_ending_here); } // required smallest sum contiguous // subarray value return min_so_far; } // Driver method public static void Main() { int[] arr = { 3, -4, 2, -3, -1, 7, -5 }; int n = arr.Length; Console.Write("Smallest sum: " + smallestSumSubarr(arr, n)); }} // This code is contributed by Sam007
<?php// PHP implementation to find the// smallest sum contiguous subarray // function to find the smallest// sum contiguous subarrayfunction smallestSumSubarr($arr, $n){ // to store the minimum // value that is ending // up to the current index $min_ending_here = 999999; // to store the minimum value // encountered so far $min_so_far = 999999; // traverse the array elements for($i = 0; $i < $n; $i++) { // if min_ending_here > 0, // then it could not possibly // contribute to the minimum // sum further if ($min_ending_here > 0) $min_ending_here = $arr[$i]; // else add the value arr[i] // to min_ending_here else $min_ending_here += $arr[$i]; // update min_so_far $min_so_far = min($min_so_far, $min_ending_here); } // required smallest sum // contiguous subarray value return $min_so_far;} // Driver Code $arr = array(3, -4, 2, -3, -1, 7, -5); $n = count($arr) ; echo "Smallest sum: " .smallestSumSubarr($arr, $n); // This code is contributed by Sam007?>
<script> // JavaScript implementation to find the // smallest sum contiguous subarray // function to find the smallest sum // contiguous subarray function smallestSumSubarr(arr, n) { // to store the minimum value that is // ending up to the current index let min_ending_here = 2147483647; // to store the minimum value encountered // so far let min_so_far = 2147483647; // traverse the array elements for (let i = 0; i < n; i++) { // if min_ending_here > 0, then it could // not possibly contribute to the // minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to // min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = Math.min(min_so_far, min_ending_here); } // required smallest sum contiguous // subarray value return min_so_far; } let arr = [ 3, -4, 2, -3, -1, 7, -5 ]; let n = arr.length; document.write("Smallest sum: " + smallestSumSubarr(arr, n)); </script>
Output:
Smallest sum: -6
Time Complexity: O(n)This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
Sam007
Nikhil.01a
suresh07
amartyaghoshgfg
subarray
subarray-sum
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Find the smallest positive integer value that cannot be represented as sum of any subset of a given array
Find a triplet that sum to a given value
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Longest Common Subsequence | DP-4
Subset Sum Problem | DP-25
Longest Increasing Subsequence | DP-3
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Feb, 2022"
},
{
"code": null,
"e": 209,
"s": 52,
"text": "Given an array containing n integers. The problem is to find the sum of the elements of the contiguous subarray having the smallest(minimum) sum.Examples: "
},
{
"code": null,
"e": 338,
"s": 209,
"text": "Input : arr[] = {3, -4, 2, -3, -1, 7, -5}\nOutput : -6\nSubarray is {-4, 2, -3, -1} = -6\n\nInput : arr = {2, 6, 8, 1, 4}\nOutput : 1"
},
{
"code": null,
"e": 656,
"s": 340,
"text": "Naive Approach: Consider all the contiguous subarrays of different sizes and find their sum. The subarray having the smallest(minimum) sum is the required answer.Efficient Approach: It is a variation to the problem of finding the largest sum contiguous subarray based on the idea of Kadane’s algorithm. Algorithm: "
},
{
"code": null,
"e": 989,
"s": 656,
"text": "smallestSumSubarr(arr, n)\n Initialize min_ending_here = INT_MAX\n Initialize min_so_far = INT_MAX\n \n for i = 0 to n-1\n if min_ending_here > 0\n min_ending_here = arr[i] \n else\n min_ending_here += arr[i]\n min_so_far = min(min_so_far, min_ending_here)\n\n return min_so_far"
},
{
"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": 1015,
"s": 1011,
"text": "PHP"
},
{
"code": null,
"e": 1026,
"s": 1015,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the smallest sum// contiguous subarray#include <bits/stdc++.h> using namespace std; // function to find the smallest sum contiguous subarrayint smallestSumSubarr(int arr[], int n){ // to store the minimum value that is ending // up to the current index int min_ending_here = INT_MAX; // to store the minimum value encountered so far int min_so_far = INT_MAX; // traverse the array elements for (int i=0; i<n; i++) { // if min_ending_here > 0, then it could not possibly // contribute to the minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = min(min_so_far, min_ending_here); } // required smallest sum contiguous subarray value return min_so_far;} // Driver program to test aboveint main(){ int arr[] = {3, -4, 2, -3, -1, 7, -5}; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Smallest sum: \" << smallestSumSubarr(arr, n); return 0; }",
"e": 2201,
"s": 1026,
"text": null
},
{
"code": "// Java implementation to find the smallest sum// contiguous subarrayclass GFG { // function to find the smallest sum contiguous // subarray static int smallestSumSubarr(int arr[], int n) { // to store the minimum value that is // ending up to the current index int min_ending_here = 2147483647; // to store the minimum value encountered // so far int min_so_far = 2147483647; // traverse the array elements for (int i = 0; i < n; i++) { // if min_ending_here > 0, then it could // not possibly contribute to the // minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to // min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = Math.min(min_so_far, min_ending_here); } // required smallest sum contiguous // subarray value return min_so_far; } // Driver method public static void main(String[] args) { int arr[] = {3, -4, 2, -3, -1, 7, -5}; int n = arr.length; System.out.print(\"Smallest sum: \" + smallestSumSubarr(arr, n)); }} // This code is contributed by Anant Agarwal.",
"e": 3679,
"s": 2201,
"text": null
},
{
"code": "# Python program to find the smallest sum# contiguous subarraymaxsize=int(1e9+7) # function to find the smallest sum# contiguous subarraydef smallestSumSubarr(arr, n): # to store the minimum value that is ending # up to the current index min_ending_here = maxsize # to store the minimum value encountered so far min_so_far = maxsize # traverse the array elements for i in range(n): # if min_ending_here > 0, then it could not possibly # contribute to the minimum sum further if (min_ending_here > 0): min_ending_here = arr[i] # else add the value arr[i] to min_ending_here else: min_ending_here += arr[i] # update min_so_far min_so_far = min(min_so_far, min_ending_here) # required smallest sum contiguous subarray value return min_so_far # Driver codearr = [3, -4, 2, -3, -1, 7, -5]n = len(arr)print (\"Smallest sum: \", smallestSumSubarr(arr, n)) # This code is contributed by Sachin Bisht",
"e": 4705,
"s": 3679,
"text": null
},
{
"code": "// C# implementation to find the// smallest sum contiguous subarrayusing System; class GFG { // function to find the smallest sum // contiguous subarray static int smallestSumSubarr(int[] arr, int n) { // to store the minimum value that is // ending up to the current index int min_ending_here = 2147483647; // to store the minimum value encountered // so far int min_so_far = 2147483647; // traverse the array elements for (int i = 0; i < n; i++) { // if min_ending_here > 0, then it could // not possibly contribute to the // minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to // min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = Math.Min(min_so_far, min_ending_here); } // required smallest sum contiguous // subarray value return min_so_far; } // Driver method public static void Main() { int[] arr = { 3, -4, 2, -3, -1, 7, -5 }; int n = arr.Length; Console.Write(\"Smallest sum: \" + smallestSumSubarr(arr, n)); }} // This code is contributed by Sam007",
"e": 6059,
"s": 4705,
"text": null
},
{
"code": "<?php// PHP implementation to find the// smallest sum contiguous subarray // function to find the smallest// sum contiguous subarrayfunction smallestSumSubarr($arr, $n){ // to store the minimum // value that is ending // up to the current index $min_ending_here = 999999; // to store the minimum value // encountered so far $min_so_far = 999999; // traverse the array elements for($i = 0; $i < $n; $i++) { // if min_ending_here > 0, // then it could not possibly // contribute to the minimum // sum further if ($min_ending_here > 0) $min_ending_here = $arr[$i]; // else add the value arr[i] // to min_ending_here else $min_ending_here += $arr[$i]; // update min_so_far $min_so_far = min($min_so_far, $min_ending_here); } // required smallest sum // contiguous subarray value return $min_so_far;} // Driver Code $arr = array(3, -4, 2, -3, -1, 7, -5); $n = count($arr) ; echo \"Smallest sum: \" .smallestSumSubarr($arr, $n); // This code is contributed by Sam007?>",
"e": 7251,
"s": 6059,
"text": null
},
{
"code": "<script> // JavaScript implementation to find the // smallest sum contiguous subarray // function to find the smallest sum // contiguous subarray function smallestSumSubarr(arr, n) { // to store the minimum value that is // ending up to the current index let min_ending_here = 2147483647; // to store the minimum value encountered // so far let min_so_far = 2147483647; // traverse the array elements for (let i = 0; i < n; i++) { // if min_ending_here > 0, then it could // not possibly contribute to the // minimum sum further if (min_ending_here > 0) min_ending_here = arr[i]; // else add the value arr[i] to // min_ending_here else min_ending_here += arr[i]; // update min_so_far min_so_far = Math.min(min_so_far, min_ending_here); } // required smallest sum contiguous // subarray value return min_so_far; } let arr = [ 3, -4, 2, -3, -1, 7, -5 ]; let n = arr.length; document.write(\"Smallest sum: \" + smallestSumSubarr(arr, n)); </script>",
"e": 8520,
"s": 7251,
"text": null
},
{
"code": null,
"e": 8530,
"s": 8520,
"text": "Output: "
},
{
"code": null,
"e": 8547,
"s": 8530,
"text": "Smallest sum: -6"
},
{
"code": null,
"e": 8990,
"s": 8547,
"text": "Time Complexity: O(n)This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 8997,
"s": 8990,
"text": "Sam007"
},
{
"code": null,
"e": 9008,
"s": 8997,
"text": "Nikhil.01a"
},
{
"code": null,
"e": 9017,
"s": 9008,
"text": "suresh07"
},
{
"code": null,
"e": 9033,
"s": 9017,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 9042,
"s": 9033,
"text": "subarray"
},
{
"code": null,
"e": 9055,
"s": 9042,
"text": "subarray-sum"
},
{
"code": null,
"e": 9062,
"s": 9055,
"text": "Arrays"
},
{
"code": null,
"e": 9082,
"s": 9062,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9089,
"s": 9082,
"text": "Arrays"
},
{
"code": null,
"e": 9109,
"s": 9089,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 9207,
"s": 9109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9239,
"s": 9207,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 9307,
"s": 9239,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 9352,
"s": 9307,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 9458,
"s": 9352,
"text": "Find the smallest positive integer value that cannot be represented as sum of any subset of a given array"
},
{
"code": null,
"e": 9499,
"s": 9458,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 9529,
"s": 9499,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 9558,
"s": 9529,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 9592,
"s": 9558,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 9619,
"s": 9592,
"text": "Subset Sum Problem | DP-25"
}
] |
C# | Thread(ParameterizedThreadStart) Constructor
|
14 Sep, 2021
Thread(ParameterizedThreadStart) Constructor is used to initialize a new instance of the Thread class. It defined a delegate which allows an object to pass to the thread when the thread starts. This constructor gives ArgumentNullException if the parameter of this constructor is null.
Syntax:
public Thread(ParameterizedThreadStart start);
Here, start is a delegate which represents a method to be invoked when this thread begins executing.Below programs illustrate the use of Thread(ParameterizedThreadStart) Constructor:Example 1:
CSharp
// C# program to illustrate the// use of Thread(ParameterizedThreadStart)// constructor with non-static methodusing System;using System.Threading; public class MYTHREAD { // Non-static method public void Job() { for (int z = 0; z < 3; z++) { Console.WriteLine("My thread is "+ "in progress...!!"); } }} // Driver Classpublic class GFG { // Main Method public static void Main() { // Creating object of MYTHREAD class MYTHREAD obj = new MYTHREAD(); // Creating a thread which // calls a parameterized instance method Thread thr = new Thread(obj.Job); thr.Start(); }}
Output:
My thread is in progress...!!
My thread is in progress...!!
My thread is in progress...!!
Example 2:
CSharp
// C# program to illustrate the use of// Thread(ParameterizedThreadStart)// constructor with static methodusing System;using System.Threading; // Driver Classpublic class GFG { // Main Method public static void Main() { // Creating a thread which calls // a parameterized static-method Thread thr = new Thread(Job); thr.Start(); } // Static method public static void Job() { Console.WriteLine("My thread is"+ " in progress...!!"); for (int z = 0; z < 3; z++) { Console.WriteLine(z); } }}
Output:
My thread is in progress...!!
0
1
2
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.-ctor?view=netframework-4.7.2#System_Threading_Thread__ctor_System_Threading_ParameterizedThreadStart_
gulshankumarar231
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
Extension Method in C#
C# | List Class
HashSet in C# with Examples
C# | .NET Framework (Basic Architecture and Component Stack)
Switch Statement in C#
Partial Classes in C#
Lambda Expressions in C#
Hello World in C#
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 314,
"s": 28,
"text": "Thread(ParameterizedThreadStart) Constructor is used to initialize a new instance of the Thread class. It defined a delegate which allows an object to pass to the thread when the thread starts. This constructor gives ArgumentNullException if the parameter of this constructor is null. "
},
{
"code": null,
"e": 324,
"s": 314,
"text": "Syntax: "
},
{
"code": null,
"e": 371,
"s": 324,
"text": "public Thread(ParameterizedThreadStart start);"
},
{
"code": null,
"e": 565,
"s": 371,
"text": "Here, start is a delegate which represents a method to be invoked when this thread begins executing.Below programs illustrate the use of Thread(ParameterizedThreadStart) Constructor:Example 1: "
},
{
"code": null,
"e": 572,
"s": 565,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the// use of Thread(ParameterizedThreadStart)// constructor with non-static methodusing System;using System.Threading; public class MYTHREAD { // Non-static method public void Job() { for (int z = 0; z < 3; z++) { Console.WriteLine(\"My thread is \"+ \"in progress...!!\"); } }} // Driver Classpublic class GFG { // Main Method public static void Main() { // Creating object of MYTHREAD class MYTHREAD obj = new MYTHREAD(); // Creating a thread which // calls a parameterized instance method Thread thr = new Thread(obj.Job); thr.Start(); }}",
"e": 1258,
"s": 572,
"text": null
},
{
"code": null,
"e": 1267,
"s": 1258,
"text": "Output: "
},
{
"code": null,
"e": 1357,
"s": 1267,
"text": "My thread is in progress...!!\nMy thread is in progress...!!\nMy thread is in progress...!!"
},
{
"code": null,
"e": 1368,
"s": 1357,
"text": "Example 2:"
},
{
"code": null,
"e": 1375,
"s": 1368,
"text": "CSharp"
},
{
"code": "// C# program to illustrate the use of// Thread(ParameterizedThreadStart)// constructor with static methodusing System;using System.Threading; // Driver Classpublic class GFG { // Main Method public static void Main() { // Creating a thread which calls // a parameterized static-method Thread thr = new Thread(Job); thr.Start(); } // Static method public static void Job() { Console.WriteLine(\"My thread is\"+ \" in progress...!!\"); for (int z = 0; z < 3; z++) { Console.WriteLine(z); } }}",
"e": 1969,
"s": 1375,
"text": null
},
{
"code": null,
"e": 1978,
"s": 1969,
"text": "Output: "
},
{
"code": null,
"e": 2014,
"s": 1978,
"text": "My thread is in progress...!!\n0\n1\n2"
},
{
"code": null,
"e": 2026,
"s": 2014,
"text": "Reference: "
},
{
"code": null,
"e": 2197,
"s": 2026,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.-ctor?view=netframework-4.7.2#System_Threading_Thread__ctor_System_Threading_ParameterizedThreadStart_"
},
{
"code": null,
"e": 2215,
"s": 2197,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 2237,
"s": 2215,
"text": "CSharp Multithreading"
},
{
"code": null,
"e": 2257,
"s": 2237,
"text": "CSharp Thread Class"
},
{
"code": null,
"e": 2260,
"s": 2257,
"text": "C#"
},
{
"code": null,
"e": 2358,
"s": 2260,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2401,
"s": 2358,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2450,
"s": 2401,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2473,
"s": 2450,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 2489,
"s": 2473,
"text": "C# | List Class"
},
{
"code": null,
"e": 2517,
"s": 2489,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 2578,
"s": 2517,
"text": "C# | .NET Framework (Basic Architecture and Component Stack)"
},
{
"code": null,
"e": 2601,
"s": 2578,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 2623,
"s": 2601,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 2648,
"s": 2623,
"text": "Lambda Expressions in C#"
}
] |
Python | How to put limits on Memory and CPU Usage
|
24 Jun, 2019
This article aims to show how to put limits on the memory or CPU use of a program running. Well to do so, Resource module can be used and thus both the task can be performed very well as shown in the code given below:
Code #1 : Restrict CPU time
# importing librariesimport signalimport resourceimport os # checking time limit exceeddef time_exceeded(signo, frame): print("Time's up !") raise SystemExit(1) def set_max_runtime(seconds): # setting up the resource limit soft, hard = resource.getrlimit(resource.RLIMIT_CPU) resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard)) signal.signal(signal.SIGXCPU, time_exceeded) # max run time of 15 millisecondif __name__ == '__main__': set_max_runtime(15) while True: pass
SIGXCPU signal is generated when the time expires on running this code and the program can clean up and exit. Code #2 : In order to restrict memory use, the code puts a limit on the total address space
# using resource import resource def limit_memory(maxsize): soft, hard = resource.getrlimit(resource.RLIMIT_AS) resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))
When no more memory is available then the program will start generating MemoryError exceptions with a memory limit.
How it works ?
To set a soft and hard limit on a particular resource, setrlimit() function is used.
The soft limit is a value upon which the operating system will notify the process via a signal or typically restrict it.
An upper bound on the values is defined by the hard limit and it may be used for the soft limit.
Although the hard limit can be lowered, it can never be raised by user processes and is controlled by a system-wide parameter set by the system administrator. (even if the process lowered itself).
The setrlimit() function can additionally be used to set limits on things such as the number of child processes, number of open files, and similar system resources.
The code in this article only works on Unix systems, and that it might not work on all of them.
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Create a Pandas DataFrame from Lists
Python | os.path.join() method
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jun, 2019"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "This article aims to show how to put limits on the memory or CPU use of a program running. Well to do so, Resource module can be used and thus both the task can be performed very well as shown in the code given below:"
},
{
"code": null,
"e": 274,
"s": 246,
"text": "Code #1 : Restrict CPU time"
},
{
"code": "# importing librariesimport signalimport resourceimport os # checking time limit exceeddef time_exceeded(signo, frame): print(\"Time's up !\") raise SystemExit(1) def set_max_runtime(seconds): # setting up the resource limit soft, hard = resource.getrlimit(resource.RLIMIT_CPU) resource.setrlimit(resource.RLIMIT_CPU, (seconds, hard)) signal.signal(signal.SIGXCPU, time_exceeded) # max run time of 15 millisecondif __name__ == '__main__': set_max_runtime(15) while True: pass",
"e": 782,
"s": 274,
"text": null
},
{
"code": null,
"e": 984,
"s": 782,
"text": "SIGXCPU signal is generated when the time expires on running this code and the program can clean up and exit. Code #2 : In order to restrict memory use, the code puts a limit on the total address space"
},
{
"code": "# using resource import resource def limit_memory(maxsize): soft, hard = resource.getrlimit(resource.RLIMIT_AS) resource.setrlimit(resource.RLIMIT_AS, (maxsize, hard))",
"e": 1159,
"s": 984,
"text": null
},
{
"code": null,
"e": 1275,
"s": 1159,
"text": "When no more memory is available then the program will start generating MemoryError exceptions with a memory limit."
},
{
"code": null,
"e": 1290,
"s": 1275,
"text": "How it works ?"
},
{
"code": null,
"e": 1375,
"s": 1290,
"text": "To set a soft and hard limit on a particular resource, setrlimit() function is used."
},
{
"code": null,
"e": 1496,
"s": 1375,
"text": "The soft limit is a value upon which the operating system will notify the process via a signal or typically restrict it."
},
{
"code": null,
"e": 1593,
"s": 1496,
"text": "An upper bound on the values is defined by the hard limit and it may be used for the soft limit."
},
{
"code": null,
"e": 1790,
"s": 1593,
"text": "Although the hard limit can be lowered, it can never be raised by user processes and is controlled by a system-wide parameter set by the system administrator. (even if the process lowered itself)."
},
{
"code": null,
"e": 1955,
"s": 1790,
"text": "The setrlimit() function can additionally be used to set limits on things such as the number of child processes, number of open files, and similar system resources."
},
{
"code": null,
"e": 2051,
"s": 1955,
"text": "The code in this article only works on Unix systems, and that it might not work on all of them."
},
{
"code": null,
"e": 2066,
"s": 2051,
"text": "python-utility"
},
{
"code": null,
"e": 2073,
"s": 2066,
"text": "Python"
},
{
"code": null,
"e": 2171,
"s": 2073,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2189,
"s": 2171,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2231,
"s": 2189,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2253,
"s": 2231,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2279,
"s": 2253,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2311,
"s": 2279,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2338,
"s": 2311,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2359,
"s": 2338,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2382,
"s": 2359,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2419,
"s": 2382,
"text": "Create a Pandas DataFrame from Lists"
}
] |
Rearrange an array such that arr[i] = i
|
08 Jul, 2022
Given an array of elements of length N, ranging from 0 to N – 1. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present, display -1 at that place.
Examples:
Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}
Output : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]
Input : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,
11, 10, 9, 5, 13, 16, 2, 14, 17, 4}
Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19]
Approach(Naive Approach):
Navigate the numbers from 0 to n-1.Now navigate through array.If (i==a[j]) , then replace the element at i position with a[j] position.If there is any element in which -1 is used instead of the number then it will be replaced automatically.Now, iterate through the array and check if (a[i]!=i) , if it s true then replace a[i] with -1.
Navigate the numbers from 0 to n-1.
Now navigate through array.
If (i==a[j]) , then replace the element at i position with a[j] position.
If there is any element in which -1 is used instead of the number then it will be replaced automatically.
Now, iterate through the array and check if (a[i]!=i) , if it s true then replace a[i] with -1.
Below is the implementation for the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program for above approach#include <iostream>using namespace std; // Function to transform the arrayvoid fixArray(int ar[], int n){ int i, j, temp; // Iterate over the array for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for (i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output cout << "Array after Rearranging" << endl; for (i = 0; i < n; i++) { cout << ar[i] << " "; }} // Driver Codeint main(){ int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; n = sizeof(ar) / sizeof(ar[0]); // Function Call fixArray(ar, n);} // Code BY Tanmay Anand
// C program for above approach#include <stdio.h> // Function to transform the arrayvoid fixArray(int ar[], int n){ int i, j, temp; // Iterate over the array for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for (i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output printf("Array after Rearranging\n"); for (i = 0; i < n; i++) { printf("%d ",ar[i]); }} // Driver Codeint main(){ int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; n = sizeof(ar) / sizeof(ar[0]); // Function Call fixArray(ar, n);} // This code is contributed by kothvvsaakash.
// Java program for above approachclass GFG{ // Function to transform the arraypublic static void fixArray(int ar[], int n){ int i, j, temp; // Iterate over the array for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for(i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output System.out.println("Array after Rearranging"); for(i = 0; i < n; i++) { System.out.print(ar[i] + " "); }} // Driver Codepublic static void main(String[] args){ int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; n = ar.length; // Function Call fixArray(ar, n);}} // This code is contributed by divyesh072019
# Python3 program for above approach # Function to transform the arraydef fixArray(ar, n): # Iterate over the array for i in range(n): for j in range(n): # Check is any ar[j] # exists such that # ar[j] is equal to i if (ar[j] == i): ar[j], ar[i] = ar[i], ar[j] # Iterate over array for i in range(n): # If not present if (ar[i] != i): ar[i] = -1 # Print the output print("Array after Rearranging") for i in range(n): print(ar[i], end = " ") # Driver Codear = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]n = len(ar) # Function CallfixArray(ar, n); # This code is contributed by rag2127
// C# program for above approachusing System;class GFG { // Function to transform the array static void fixArray(int[] ar, int n) { int i, j, temp; // Iterate over the array for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for(i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output Console.WriteLine("Array after Rearranging"); for(i = 0; i < n; i++) { Console.Write(ar[i] + " "); } } static void Main() { int[] ar = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int n = ar.Length; // Function Call fixArray(ar, n); }} // This code is contributed by divyeshrabadiya07
<script> // JavaScript program for above approach // Function to transform the array function fixArray(ar, n) { var i, j, temp; // Iterate over the array for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for (i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output document.write("Array after Rearranging"); document.write("<br>"); for (i = 0; i < n; i++) { document.write(ar[i] + " "); } } // Driver Code var n, ar = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]; n = ar.length; // Function Call fixArray(ar, n); // This code is contributed BY Rahul Tank </script>
Array after Rearranging
-1 1 2 3 4 -1 6 -1 -1 9
Time Complexity: O(n2)Auxiliary Space: O(1)
Another Approach: 1. Navigate through the array. 2. Check if a[i] = -1, if yes then ignore it. 3. If a[i] != -1, Check if element a[i] is at its correct position (i=A[i]). If yes then ignore it. 4. If a[i] != -1 and element a[i] is not at its correct position (i!=A[i]) then place it to its correct position, but there are two conditions:
Either A[i] is vacate, means A[i] = -1, then just put A[i] = i .
OR A[i] is not vacate, means A[i] = x, then int y=x put A[i] = i. Now, we need to place y to its correct place, so repeat from step 3.
Below is the implementation for the above approach:
C++
Java
C
Python3
C#
PHP
Javascript
// C++ program for rearrange an// array such that arr[i] = i.#include <bits/stdc++.h> using namespace std; // Function to rearrange an array// such that arr[i] = i.void fixArray(int A[], int len){ for (int i = 0; i < len; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired place // is not vacate while (A[x] != -1 && A[x] != x) { // store the value from // desired place int y = A[x]; // place the x to its correct // position A[x] = x; // now y will become x, now // search the place for x x = y; } // place the x to its correct // position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 at // the vacated place A[i] = -1; } } }} // Driver codeint main(){ int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int len = sizeof(A) / sizeof(A[0]); // Function Call fixArray(A, len); // Print the output for (int i = 0; i < len; i++) cout << A[i] << " ";} // This code is contributed by Smitha Dinesh Semwal
// Java program for rearrange an// array such that arr[i] = i.import java.util.*;import java.lang.*; public class GfG { // Function to rearrange an array // such that arr[i] = i. public static int[] fix(int[] A) { for (int i = 0; i < A.length; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired place // is not vacate while (A[x] != -1 && A[x] != x) { // store the value from // desired place int y = A[x]; // place the x to its correct // position A[x] = x; // now y will become x, now // search the place for x x = y; } // place the x to its correct // position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 at // the vacated place A[i] = -1; } } } return A; } // Driver code public static void main(String[] args) { int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; System.out.println(Arrays.toString(fix(A))); }}
// C program for rearrange an// array such that arr[i] = i.#include <stdio.h> // Function to rearrange an array// such that arr[i] = i.void fixArray(int A[], int len){ for (int i = 0; i < len; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired place // is not vacate while (A[x] != -1 && A[x] != x) { // store the value from // desired place int y = A[x]; // place the x to its correct // position A[x] = x; // now y will become x, now // search the place for x x = y; } // place the x to its correct // position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 at // the vacated place A[i] = -1; } } }} // Driver codeint main(){ int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int len = sizeof(A) / sizeof(A[0]); // Function Call fixArray(A, len); // Print the output for (int i = 0; i < len; i++) printf("%d ",A[i]);} // This code is contributed by kothavvsaakash
# Python3 program for rearrange an# array such that arr[i] = i. # Function to rearrange an array# such that arr[i] = i. def fix(A, len): for i in range(0, len): if (A[i] != -1 and A[i] != i): x = A[i] # check if desired place # is not vacate while (A[x] != -1 and A[x] != x): # store the value from # desired place y = A[x] # place the x to its correct # position A[x] = x # now y will become x, now # search the place for x x = y # place the x to its correct # position A[x] = x # check if while loop hasn't # set the correct value at A[i] if (A[i] != i): # if not then put -1 at # the vacated place A[i] = -1 # Driver codeA = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] fix(A, len(A)) for i in range(0, len(A)): print(A[i], end=' ') # This code is contributed by Saloni1297
// C# program for rearrange// an array such that// arr[i] = i.using System; class GfG { // Function to rearrange an // array such that arr[i] = i. public static int[] fix(int[] A) { for (int i = 0; i < A.Length; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired // place is not vacate while (A[x] != -1 && A[x] != x) { // store the value // from desired place int y = A[x]; // place the x to its // correct position A[x] = x; // now y will become x, // now search the place // for x x = y; } // place the x to its // correct position A[x] = x; // check if while loop // hasn't set the correct // value at A[i] if (A[i] != i) { // if not then put -1 // at the vacated place A[i] = -1; } } } return A; } // Driver Code static void Main() { int[] A = new int[] { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; Console.WriteLine(string.Join(",", fix(A))); }} // This code is contributed by// Manish Shaw(manishshaw1)
<?php// PHP program for rearrange an// array such that arr[i] = i. // Function to rearrange an// array such that arr[i] = i.function fix(&$A, $len){ for ($i = 0; $i < $len; $i++) { if ($A[$i] != -1 && $A[$i] != $i) { $x = $A[$i]; // check if desired // place is not vacate while ($A[$x] != -1 && $A[$x] != $x) { // store the value // from desired place $y = $A[$x]; // place the x to its // correct position $A[$x] = $x; // now y will become x, // now search the place // for x $x = $y; } // place the x to its // correct position $A[$x] = $x; // check if while loop hasn't // set the correct value at A[i] if ($A[$i] != $i) { // if not then put -1 // at the vacated place $A[$i] = -1; } } }} // Driver Code$A = array(-1, -1, 6, 1, 9, 3, 2, -1, 4, -1); $len = count($A);fix($A, $len); for ($i = 0; $i < $len; $i++) echo ($A[$i]." "); // This code is contributed by// Manish Shaw(manishshaw1)?>
<script>// Javascript program for rearrange an// array such that arr[i] = i. // Function to rearrange an// array such that arr[i] = i.function fix(A, len){ for (let i = 0; i < len; i++) { if (A[i] != -1 && A[i] != i) { let x = A[i]; // check if desired // place is not vacate while (A[x] != -1 && A[x] != x) { // store the value // from desired place let y = A[x]; // place the x to its // correct position A[x] = x; // now y will become x, // now search the place // for x x = y; } // place the x to its // correct position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 // at the vacated place A[i] = -1; } } }} // Driver Codelet A = new Array(-1, -1, 6, 1, 9, 3, 2, -1, 4, -1); let len = A.length;fix(A, len); for (let i = 0; i < len; i++) document.write(A[i] + " "); // This code is contributed by gfgking</script>
-1 1 2 3 4 -1 6 -1 -1 9
Time Complexity: O(n2)Auxiliary Space: O(1)
Another Approach (Using Set) : 1) Store all the numbers present in the array into a Set 2) Iterate through the length of the array, if the corresponding position element is present in the Set, then set A[i] = i, else A[i] = -1
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
#include <iostream>#include <unordered_set> using namespace std; void fixArray(int arr[], int n){ // a set unordered_set<int> s; // Enter each element which is not -1 in set for(int i=0; i<n; i++) { if(arr[i] != -1) s.insert(arr[i]); } // Navigate through array, // and put A[i] = i, // if i is present in set for(int i=0; i<n; i++) { // if i(index) is found in hmap if(s.find(i) != s.end()) { arr[i] = i; } // if i not found else { arr[i] = -1; } } } // Driver Codeint main() { // Array initialization int arr[] {-1, -1, 6, 1, 9, 3, 2, -1, 4,-1}; int n = sizeof(arr) / sizeof(arr[0]); // Function Call fixArray(arr, n); // Print output for(int i=0; i<n; i++) cout << arr[i] << ' '; return 0;} // this code is contributed by dev chaudhary
// Java program for rearrange an// array such that arr[i] = i.import java.util.*;import java.lang.*; class GfG { // Function to rearrange an array // such that arr[i] = i. public static int[] fix(int[] A) { Set<Integer> s = new HashSet<Integer>(); // Storing all the values in the HashSet for(int i = 0; i < A.length; i++) { s.add(A[i]); } for(int i = 0; i < A.length; i++) { if(s.contains(i)) A[i] = i; else A[i] = -1; } return A;} // Driver code public static void main(String[] args) { int A[] = {-1, -1, 6, 1, 9, 3, 2, -1, 4,-1}; // Function calling System.out.println(Arrays.toString(fix(A))); }}
# Python3 program for rearrange an# array such that arr[i] = i. # Function to rearrange an array# such that arr[i] = i.def fix(A): s = set() # Storing all the values in the Set for i in range(len(A)): s.add(A[i]) for i in range(len(A)): # check for item if present in set if i in s: A[i] = i else: A[i] = -1 return A # Driver codeif __name__ == "__main__": A = [-1, -1, 6, 1, 9, 3, 2, -1, 4,-1] print(fix(A)) # This code is contributed by Chitranayal
using System;using System.Collections.Generic;public class main{ static void fix(int[] a,int n){ HashSet<int> hs=new HashSet<int>(); // Traverse the array // and add each element // to the HashSet for(int i=0;i<n;i++) hs.Add(a[i]); // Again traverse from i=0 -> i=n-1 for(int i=0;i<n;i++) { // If HashSet contains i // Then make a[i]=i, // else a[i]=-1 if(hs.Contains(i)) a[i]=i; else a[i]=-1; } } static public void Main (){ int[] arr={-1, -1, 6, 1, 9, 3, 2, -1, 4,-1}; int n=arr.Length; fix(arr,n); for(int i=0;i<n;i++) Console.Write(arr[i]+" "); Console.WriteLine(); }}
<script> // JavaScript program for rearrange an // array such that arr[i] = i. // Function to rearrange an array // such that arr[i] = i. function fix(A) { let s = new Set(); // Storing all the values in the HashSet for(let i = 0; i < A.length; i++) { s.add(A[i]); } for(let i = 0; i < A.length; i++) { if(s.has(i)) A[i] = i; else A[i] = -1; } return A; } let A = [-1, -1, 6, 1, 9, 3, 2, -1, 4,-1]; // Function calling let ans = fix(A); for(let i = 0; i < ans.length; i++) { document.write(ans[i] + " "); } </script>
-1 1 2 3 4 -1 6 -1 -1 9
Time Complexity: O(n)Auxiliary Space: O(n)
Another Approach (Swap elements in Array) : Using cyclic sort1) Iterate through elements in an array 2) If arr[i] >= 0 && arr[i] != i, put arr[i] at i ( swap arr[i] with arr[arr[i]])
Below is the implementation of the above approach.
C++
C
Java
Python3
C#
Javascript
// C++ program for rearrange an// array such that arr[i] = i.#include <iostream>using namespace std; void fixArray(int arr[], int n){ int i = 0; while (i < n) { int correct = arr[i]; if (arr[i] != -1 && arr[i] != arr[correct]) { // if array element should be lesser than // size and array element should not be at // its correct postion then only swap with // its correct positioin or index value swap(arr[i], arr[correct]); } else { // if element is at its correct position // just increment i and check for remaining // array elements i++; } } return arr;} // Driver Codeint main(){ int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call fixArray(arr, n); // Print output for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // This Code is Contributed by kothavvsaakash
// C program for rearrange an// array such that arr[i] = i.#include <stdio.h> void fixArray(int arr[], int n){ for (int i = 0; i < n;) { if (arr[i] >= 0 && arr[i] != i) arr[arr[i]] = (arr[arr[i]] + arr[i]) - (arr[i] = arr[arr[i]]); else i++; }} // Driver Codeint main(){ int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call fixArray(arr, n); // Print output for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0;} // This Code is Contributed by Adarsh_Verma
// Java program for rearrange an// array such that arr[i] = i.import java.util.Arrays; class Program{ public static void main(String[] args) { int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; for (int i = 0; i < arr.length;) { if (arr[i] >= 0 && arr[i] != i) { int ele = arr[arr[i]]; arr[arr[i]] = arr[i]; arr[i] = ele; } else { i++; } } System.out.println(Arrays.toString(arr)); }} /* This Java code is contributed by PrinciRaj1992*/
# Python3 program for rearrange an# array such that arr[i] = i.if __name__ == "__main__": arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] n = len(arr) i = 0 while i < n: if (arr[i] >= 0 and arr[i] != i): (arr[arr[i]], arr[i]) = (arr[i], arr[arr[i]]) else: i += 1 for i in range(n): print(arr[i], end=" ") # This code is contributed by Chitranayal
// C# program for rearrange an// array such that arr[i] = i.using System; namespace GFG { class Program { static void Main(string[] args) { int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; for (int i = 0; i < arr.Length;) { if (arr[i] >= 0 && arr[i] != i) { int ele = arr[arr[i]]; arr[arr[i]] = arr[i]; arr[i] = ele; } else { i++; } } Console.WriteLine(String.Join(",", arr)); }}}// This code is contributed by// Venkata VardhiReddy(venkata)
<script>// Javascript program for rearrange an// array such that arr[i] = i. function fixArray(arr, n){ for (let i = 0; i < n;) { if (arr[i] >= 0 && arr[i] != i) arr[arr[i]] = (arr[arr[i]] + arr[i]) - (arr[i] = arr[arr[i]]); else i++; }} // Driver Code let arr = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]; let n = arr.length; // Function Call fixArray(arr, n); // Print output for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This Code is Contributed by _saurabh_jaiswal</script>
-1 1 2 3 4 -1 6 -1 -1 9
Time Complexity: O(n)Auxiliary Space: O(1)
manishshaw1
rahulpy
Venkata
RoshanDaruka
sanjeetkumarSingh
princiraj1992
Adarsh_Verma
gfg_sal_gfg
ukasp
demon9689
faizanurrahman
divyesh072019
divyeshrabadiya07
rag2127
rdtank
parascoding
_saurabh_jaiswal
bunnyram19
gfgking
vaibhavrabadiya117
sweetyty
saurabh1990aror
devchaudhary1911
kothavvsaakash
codewithmini
prasanna1995
array-rearrange
Arrays
Hash
Arrays
Hash
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Longest Consecutive Subsequence
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jul, 2022"
},
{
"code": null,
"e": 327,
"s": 52,
"text": "Given an array of elements of length N, ranging from 0 to N – 1. All elements may not be present in the array. If the element is not present then there will be -1 present in the array. Rearrange the array such that A[i] = i and if i is not present, display -1 at that place."
},
{
"code": null,
"e": 338,
"s": 327,
"text": "Examples: "
},
{
"code": null,
"e": 621,
"s": 338,
"text": "Input : arr = {-1, -1, 6, 1, 9, 3, 2, -1, 4, -1}\nOutput : [-1, 1, 2, 3, 4, -1, 6, -1, -1, 9]\n\nInput : arr = {19, 7, 0, 3, 18, 15, 12, 6, 1, 8,\n 11, 10, 9, 5, 13, 16, 2, 14, 17, 4}\nOutput : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, \n 11, 12, 13, 14, 15, 16, 17, 18, 19]"
},
{
"code": null,
"e": 647,
"s": 621,
"text": "Approach(Naive Approach):"
},
{
"code": null,
"e": 985,
"s": 647,
"text": "Navigate the numbers from 0 to n-1.Now navigate through array.If (i==a[j]) , then replace the element at i position with a[j] position.If there is any element in which -1 is used instead of the number then it will be replaced automatically.Now, iterate through the array and check if (a[i]!=i) , if it s true then replace a[i] with -1."
},
{
"code": null,
"e": 1023,
"s": 985,
"text": "Navigate the numbers from 0 to n-1."
},
{
"code": null,
"e": 1051,
"s": 1023,
"text": "Now navigate through array."
},
{
"code": null,
"e": 1125,
"s": 1051,
"text": "If (i==a[j]) , then replace the element at i position with a[j] position."
},
{
"code": null,
"e": 1231,
"s": 1125,
"text": "If there is any element in which -1 is used instead of the number then it will be replaced automatically."
},
{
"code": null,
"e": 1327,
"s": 1231,
"text": "Now, iterate through the array and check if (a[i]!=i) , if it s true then replace a[i] with -1."
},
{
"code": null,
"e": 1381,
"s": 1327,
"text": "Below is the implementation for the above approach: "
},
{
"code": null,
"e": 1385,
"s": 1381,
"text": "C++"
},
{
"code": null,
"e": 1387,
"s": 1385,
"text": "C"
},
{
"code": null,
"e": 1392,
"s": 1387,
"text": "Java"
},
{
"code": null,
"e": 1400,
"s": 1392,
"text": "Python3"
},
{
"code": null,
"e": 1403,
"s": 1400,
"text": "C#"
},
{
"code": null,
"e": 1414,
"s": 1403,
"text": "Javascript"
},
{
"code": "// C++ program for above approach#include <iostream>using namespace std; // Function to transform the arrayvoid fixArray(int ar[], int n){ int i, j, temp; // Iterate over the array for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for (i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output cout << \"Array after Rearranging\" << endl; for (i = 0; i < n; i++) { cout << ar[i] << \" \"; }} // Driver Codeint main(){ int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; n = sizeof(ar) / sizeof(ar[0]); // Function Call fixArray(ar, n);} // Code BY Tanmay Anand",
"e": 2406,
"s": 1414,
"text": null
},
{
"code": "// C program for above approach#include <stdio.h> // Function to transform the arrayvoid fixArray(int ar[], int n){ int i, j, temp; // Iterate over the array for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for (i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output printf(\"Array after Rearranging\\n\"); for (i = 0; i < n; i++) { printf(\"%d \",ar[i]); }} // Driver Codeint main(){ int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; n = sizeof(ar) / sizeof(ar[0]); // Function Call fixArray(ar, n);} // This code is contributed by kothvvsaakash.",
"e": 3390,
"s": 2406,
"text": null
},
{
"code": "// Java program for above approachclass GFG{ // Function to transform the arraypublic static void fixArray(int ar[], int n){ int i, j, temp; // Iterate over the array for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for(i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output System.out.println(\"Array after Rearranging\"); for(i = 0; i < n; i++) { System.out.print(ar[i] + \" \"); }} // Driver Codepublic static void main(String[] args){ int n, ar[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; n = ar.length; // Function Call fixArray(ar, n);}} // This code is contributed by divyesh072019",
"e": 4477,
"s": 3390,
"text": null
},
{
"code": "# Python3 program for above approach # Function to transform the arraydef fixArray(ar, n): # Iterate over the array for i in range(n): for j in range(n): # Check is any ar[j] # exists such that # ar[j] is equal to i if (ar[j] == i): ar[j], ar[i] = ar[i], ar[j] # Iterate over array for i in range(n): # If not present if (ar[i] != i): ar[i] = -1 # Print the output print(\"Array after Rearranging\") for i in range(n): print(ar[i], end = \" \") # Driver Codear = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]n = len(ar) # Function CallfixArray(ar, n); # This code is contributed by rag2127",
"e": 5191,
"s": 4477,
"text": null
},
{
"code": "// C# program for above approachusing System;class GFG { // Function to transform the array static void fixArray(int[] ar, int n) { int i, j, temp; // Iterate over the array for(i = 0; i < n; i++) { for(j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for(i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output Console.WriteLine(\"Array after Rearranging\"); for(i = 0; i < n; i++) { Console.Write(ar[i] + \" \"); } } static void Main() { int[] ar = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int n = ar.Length; // Function Call fixArray(ar, n); }} // This code is contributed by divyeshrabadiya07",
"e": 6454,
"s": 5191,
"text": null
},
{
"code": "<script> // JavaScript program for above approach // Function to transform the array function fixArray(ar, n) { var i, j, temp; // Iterate over the array for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { // Check is any ar[j] // exists such that // ar[j] is equal to i if (ar[j] == i) { temp = ar[j]; ar[j] = ar[i]; ar[i] = temp; break; } } } // Iterate over array for (i = 0; i < n; i++) { // If not present if (ar[i] != i) { ar[i] = -1; } } // Print the output document.write(\"Array after Rearranging\"); document.write(\"<br>\"); for (i = 0; i < n; i++) { document.write(ar[i] + \" \"); } } // Driver Code var n, ar = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1]; n = ar.length; // Function Call fixArray(ar, n); // This code is contributed BY Rahul Tank </script>",
"e": 7574,
"s": 6454,
"text": null
},
{
"code": null,
"e": 7623,
"s": 7574,
"text": "Array after Rearranging\n-1 1 2 3 4 -1 6 -1 -1 9 "
},
{
"code": null,
"e": 7667,
"s": 7623,
"text": "Time Complexity: O(n2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8016,
"s": 7667,
"text": "Another Approach: 1. Navigate through the array. 2. Check if a[i] = -1, if yes then ignore it. 3. If a[i] != -1, Check if element a[i] is at its correct position (i=A[i]). If yes then ignore it. 4. If a[i] != -1 and element a[i] is not at its correct position (i!=A[i]) then place it to its correct position, but there are two conditions: "
},
{
"code": null,
"e": 8081,
"s": 8016,
"text": "Either A[i] is vacate, means A[i] = -1, then just put A[i] = i ."
},
{
"code": null,
"e": 8217,
"s": 8081,
"text": "OR A[i] is not vacate, means A[i] = x, then int y=x put A[i] = i. Now, we need to place y to its correct place, so repeat from step 3."
},
{
"code": null,
"e": 8270,
"s": 8217,
"text": "Below is the implementation for the above approach: "
},
{
"code": null,
"e": 8274,
"s": 8270,
"text": "C++"
},
{
"code": null,
"e": 8279,
"s": 8274,
"text": "Java"
},
{
"code": null,
"e": 8281,
"s": 8279,
"text": "C"
},
{
"code": null,
"e": 8289,
"s": 8281,
"text": "Python3"
},
{
"code": null,
"e": 8292,
"s": 8289,
"text": "C#"
},
{
"code": null,
"e": 8296,
"s": 8292,
"text": "PHP"
},
{
"code": null,
"e": 8307,
"s": 8296,
"text": "Javascript"
},
{
"code": "// C++ program for rearrange an// array such that arr[i] = i.#include <bits/stdc++.h> using namespace std; // Function to rearrange an array// such that arr[i] = i.void fixArray(int A[], int len){ for (int i = 0; i < len; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired place // is not vacate while (A[x] != -1 && A[x] != x) { // store the value from // desired place int y = A[x]; // place the x to its correct // position A[x] = x; // now y will become x, now // search the place for x x = y; } // place the x to its correct // position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 at // the vacated place A[i] = -1; } } }} // Driver codeint main(){ int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int len = sizeof(A) / sizeof(A[0]); // Function Call fixArray(A, len); // Print the output for (int i = 0; i < len; i++) cout << A[i] << \" \";} // This code is contributed by Smitha Dinesh Semwal",
"e": 9704,
"s": 8307,
"text": null
},
{
"code": "// Java program for rearrange an// array such that arr[i] = i.import java.util.*;import java.lang.*; public class GfG { // Function to rearrange an array // such that arr[i] = i. public static int[] fix(int[] A) { for (int i = 0; i < A.length; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired place // is not vacate while (A[x] != -1 && A[x] != x) { // store the value from // desired place int y = A[x]; // place the x to its correct // position A[x] = x; // now y will become x, now // search the place for x x = y; } // place the x to its correct // position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 at // the vacated place A[i] = -1; } } } return A; } // Driver code public static void main(String[] args) { int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; System.out.println(Arrays.toString(fix(A))); }}",
"e": 11153,
"s": 9704,
"text": null
},
{
"code": "// C program for rearrange an// array such that arr[i] = i.#include <stdio.h> // Function to rearrange an array// such that arr[i] = i.void fixArray(int A[], int len){ for (int i = 0; i < len; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired place // is not vacate while (A[x] != -1 && A[x] != x) { // store the value from // desired place int y = A[x]; // place the x to its correct // position A[x] = x; // now y will become x, now // search the place for x x = y; } // place the x to its correct // position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 at // the vacated place A[i] = -1; } } }} // Driver codeint main(){ int A[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int len = sizeof(A) / sizeof(A[0]); // Function Call fixArray(A, len); // Print the output for (int i = 0; i < len; i++) printf(\"%d \",A[i]);} // This code is contributed by kothavvsaakash",
"e": 12514,
"s": 11153,
"text": null
},
{
"code": "# Python3 program for rearrange an# array such that arr[i] = i. # Function to rearrange an array# such that arr[i] = i. def fix(A, len): for i in range(0, len): if (A[i] != -1 and A[i] != i): x = A[i] # check if desired place # is not vacate while (A[x] != -1 and A[x] != x): # store the value from # desired place y = A[x] # place the x to its correct # position A[x] = x # now y will become x, now # search the place for x x = y # place the x to its correct # position A[x] = x # check if while loop hasn't # set the correct value at A[i] if (A[i] != i): # if not then put -1 at # the vacated place A[i] = -1 # Driver codeA = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] fix(A, len(A)) for i in range(0, len(A)): print(A[i], end=' ') # This code is contributed by Saloni1297",
"e": 13611,
"s": 12514,
"text": null
},
{
"code": "// C# program for rearrange// an array such that// arr[i] = i.using System; class GfG { // Function to rearrange an // array such that arr[i] = i. public static int[] fix(int[] A) { for (int i = 0; i < A.Length; i++) { if (A[i] != -1 && A[i] != i) { int x = A[i]; // check if desired // place is not vacate while (A[x] != -1 && A[x] != x) { // store the value // from desired place int y = A[x]; // place the x to its // correct position A[x] = x; // now y will become x, // now search the place // for x x = y; } // place the x to its // correct position A[x] = x; // check if while loop // hasn't set the correct // value at A[i] if (A[i] != i) { // if not then put -1 // at the vacated place A[i] = -1; } } } return A; } // Driver Code static void Main() { int[] A = new int[] { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; Console.WriteLine(string.Join(\",\", fix(A))); }} // This code is contributed by// Manish Shaw(manishshaw1)",
"e": 15147,
"s": 13611,
"text": null
},
{
"code": "<?php// PHP program for rearrange an// array such that arr[i] = i. // Function to rearrange an// array such that arr[i] = i.function fix(&$A, $len){ for ($i = 0; $i < $len; $i++) { if ($A[$i] != -1 && $A[$i] != $i) { $x = $A[$i]; // check if desired // place is not vacate while ($A[$x] != -1 && $A[$x] != $x) { // store the value // from desired place $y = $A[$x]; // place the x to its // correct position $A[$x] = $x; // now y will become x, // now search the place // for x $x = $y; } // place the x to its // correct position $A[$x] = $x; // check if while loop hasn't // set the correct value at A[i] if ($A[$i] != $i) { // if not then put -1 // at the vacated place $A[$i] = -1; } } }} // Driver Code$A = array(-1, -1, 6, 1, 9, 3, 2, -1, 4, -1); $len = count($A);fix($A, $len); for ($i = 0; $i < $len; $i++) echo ($A[$i].\" \"); // This code is contributed by// Manish Shaw(manishshaw1)?>",
"e": 16472,
"s": 15147,
"text": null
},
{
"code": "<script>// Javascript program for rearrange an// array such that arr[i] = i. // Function to rearrange an// array such that arr[i] = i.function fix(A, len){ for (let i = 0; i < len; i++) { if (A[i] != -1 && A[i] != i) { let x = A[i]; // check if desired // place is not vacate while (A[x] != -1 && A[x] != x) { // store the value // from desired place let y = A[x]; // place the x to its // correct position A[x] = x; // now y will become x, // now search the place // for x x = y; } // place the x to its // correct position A[x] = x; // check if while loop hasn't // set the correct value at A[i] if (A[i] != i) { // if not then put -1 // at the vacated place A[i] = -1; } } }} // Driver Codelet A = new Array(-1, -1, 6, 1, 9, 3, 2, -1, 4, -1); let len = A.length;fix(A, len); for (let i = 0; i < len; i++) document.write(A[i] + \" \"); // This code is contributed by gfgking</script>",
"e": 17787,
"s": 16472,
"text": null
},
{
"code": null,
"e": 17812,
"s": 17787,
"text": "-1 1 2 3 4 -1 6 -1 -1 9 "
},
{
"code": null,
"e": 17856,
"s": 17812,
"text": "Time Complexity: O(n2)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 18083,
"s": 17856,
"text": "Another Approach (Using Set) : 1) Store all the numbers present in the array into a Set 2) Iterate through the length of the array, if the corresponding position element is present in the Set, then set A[i] = i, else A[i] = -1"
},
{
"code": null,
"e": 18135,
"s": 18083,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 18139,
"s": 18135,
"text": "C++"
},
{
"code": null,
"e": 18144,
"s": 18139,
"text": "Java"
},
{
"code": null,
"e": 18152,
"s": 18144,
"text": "Python3"
},
{
"code": null,
"e": 18155,
"s": 18152,
"text": "C#"
},
{
"code": null,
"e": 18166,
"s": 18155,
"text": "Javascript"
},
{
"code": "#include <iostream>#include <unordered_set> using namespace std; void fixArray(int arr[], int n){ // a set unordered_set<int> s; // Enter each element which is not -1 in set for(int i=0; i<n; i++) { if(arr[i] != -1) s.insert(arr[i]); } // Navigate through array, // and put A[i] = i, // if i is present in set for(int i=0; i<n; i++) { // if i(index) is found in hmap if(s.find(i) != s.end()) { arr[i] = i; } // if i not found else { arr[i] = -1; } } } // Driver Codeint main() { // Array initialization int arr[] {-1, -1, 6, 1, 9, 3, 2, -1, 4,-1}; int n = sizeof(arr) / sizeof(arr[0]); // Function Call fixArray(arr, n); // Print output for(int i=0; i<n; i++) cout << arr[i] << ' '; return 0;} // this code is contributed by dev chaudhary",
"e": 18999,
"s": 18166,
"text": null
},
{
"code": "// Java program for rearrange an// array such that arr[i] = i.import java.util.*;import java.lang.*; class GfG { // Function to rearrange an array // such that arr[i] = i. public static int[] fix(int[] A) { Set<Integer> s = new HashSet<Integer>(); // Storing all the values in the HashSet for(int i = 0; i < A.length; i++) { s.add(A[i]); } for(int i = 0; i < A.length; i++) { if(s.contains(i)) A[i] = i; else A[i] = -1; } return A;} // Driver code public static void main(String[] args) { int A[] = {-1, -1, 6, 1, 9, 3, 2, -1, 4,-1}; // Function calling System.out.println(Arrays.toString(fix(A))); }}",
"e": 19806,
"s": 18999,
"text": null
},
{
"code": "# Python3 program for rearrange an# array such that arr[i] = i. # Function to rearrange an array# such that arr[i] = i.def fix(A): s = set() # Storing all the values in the Set for i in range(len(A)): s.add(A[i]) for i in range(len(A)): # check for item if present in set if i in s: A[i] = i else: A[i] = -1 return A # Driver codeif __name__ == \"__main__\": A = [-1, -1, 6, 1, 9, 3, 2, -1, 4,-1] print(fix(A)) # This code is contributed by Chitranayal",
"e": 20354,
"s": 19806,
"text": null
},
{
"code": "using System;using System.Collections.Generic;public class main{ static void fix(int[] a,int n){ HashSet<int> hs=new HashSet<int>(); // Traverse the array // and add each element // to the HashSet for(int i=0;i<n;i++) hs.Add(a[i]); // Again traverse from i=0 -> i=n-1 for(int i=0;i<n;i++) { // If HashSet contains i // Then make a[i]=i, // else a[i]=-1 if(hs.Contains(i)) a[i]=i; else a[i]=-1; } } static public void Main (){ int[] arr={-1, -1, 6, 1, 9, 3, 2, -1, 4,-1}; int n=arr.Length; fix(arr,n); for(int i=0;i<n;i++) Console.Write(arr[i]+\" \"); Console.WriteLine(); }}",
"e": 21191,
"s": 20354,
"text": null
},
{
"code": "<script> // JavaScript program for rearrange an // array such that arr[i] = i. // Function to rearrange an array // such that arr[i] = i. function fix(A) { let s = new Set(); // Storing all the values in the HashSet for(let i = 0; i < A.length; i++) { s.add(A[i]); } for(let i = 0; i < A.length; i++) { if(s.has(i)) A[i] = i; else A[i] = -1; } return A; } let A = [-1, -1, 6, 1, 9, 3, 2, -1, 4,-1]; // Function calling let ans = fix(A); for(let i = 0; i < ans.length; i++) { document.write(ans[i] + \" \"); } </script>",
"e": 21912,
"s": 21191,
"text": null
},
{
"code": null,
"e": 21937,
"s": 21912,
"text": "-1 1 2 3 4 -1 6 -1 -1 9 "
},
{
"code": null,
"e": 21980,
"s": 21937,
"text": "Time Complexity: O(n)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 22163,
"s": 21980,
"text": "Another Approach (Swap elements in Array) : Using cyclic sort1) Iterate through elements in an array 2) If arr[i] >= 0 && arr[i] != i, put arr[i] at i ( swap arr[i] with arr[arr[i]])"
},
{
"code": null,
"e": 22215,
"s": 22163,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 22219,
"s": 22215,
"text": "C++"
},
{
"code": null,
"e": 22221,
"s": 22219,
"text": "C"
},
{
"code": null,
"e": 22226,
"s": 22221,
"text": "Java"
},
{
"code": null,
"e": 22234,
"s": 22226,
"text": "Python3"
},
{
"code": null,
"e": 22237,
"s": 22234,
"text": "C#"
},
{
"code": null,
"e": 22248,
"s": 22237,
"text": "Javascript"
},
{
"code": "// C++ program for rearrange an// array such that arr[i] = i.#include <iostream>using namespace std; void fixArray(int arr[], int n){ int i = 0; while (i < n) { int correct = arr[i]; if (arr[i] != -1 && arr[i] != arr[correct]) { // if array element should be lesser than // size and array element should not be at // its correct postion then only swap with // its correct positioin or index value swap(arr[i], arr[correct]); } else { // if element is at its correct position // just increment i and check for remaining // array elements i++; } } return arr;} // Driver Codeint main(){ int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call fixArray(arr, n); // Print output for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;} // This Code is Contributed by kothavvsaakash",
"e": 23243,
"s": 22248,
"text": null
},
{
"code": "// C program for rearrange an// array such that arr[i] = i.#include <stdio.h> void fixArray(int arr[], int n){ for (int i = 0; i < n;) { if (arr[i] >= 0 && arr[i] != i) arr[arr[i]] = (arr[arr[i]] + arr[i]) - (arr[i] = arr[arr[i]]); else i++; }} // Driver Codeint main(){ int arr[] = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call fixArray(arr, n); // Print output for (int i = 0; i < n; i++) printf(\"%d \", arr[i]); return 0;} // This Code is Contributed by Adarsh_Verma",
"e": 23860,
"s": 23243,
"text": null
},
{
"code": "// Java program for rearrange an// array such that arr[i] = i.import java.util.Arrays; class Program{ public static void main(String[] args) { int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; for (int i = 0; i < arr.length;) { if (arr[i] >= 0 && arr[i] != i) { int ele = arr[arr[i]]; arr[arr[i]] = arr[i]; arr[i] = ele; } else { i++; } } System.out.println(Arrays.toString(arr)); }} /* This Java code is contributed by PrinciRaj1992*/",
"e": 24466,
"s": 23860,
"text": null
},
{
"code": "# Python3 program for rearrange an# array such that arr[i] = i.if __name__ == \"__main__\": arr = [-1, -1, 6, 1, 9, 3, 2, -1, 4, -1] n = len(arr) i = 0 while i < n: if (arr[i] >= 0 and arr[i] != i): (arr[arr[i]], arr[i]) = (arr[i], arr[arr[i]]) else: i += 1 for i in range(n): print(arr[i], end=\" \") # This code is contributed by Chitranayal",
"e": 24912,
"s": 24466,
"text": null
},
{
"code": "// C# program for rearrange an// array such that arr[i] = i.using System; namespace GFG { class Program { static void Main(string[] args) { int[] arr = { -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 }; for (int i = 0; i < arr.Length;) { if (arr[i] >= 0 && arr[i] != i) { int ele = arr[arr[i]]; arr[arr[i]] = arr[i]; arr[i] = ele; } else { i++; } } Console.WriteLine(String.Join(\",\", arr)); }}}// This code is contributed by// Venkata VardhiReddy(venkata)",
"e": 25545,
"s": 24912,
"text": null
},
{
"code": "<script>// Javascript program for rearrange an// array such that arr[i] = i. function fixArray(arr, n){ for (let i = 0; i < n;) { if (arr[i] >= 0 && arr[i] != i) arr[arr[i]] = (arr[arr[i]] + arr[i]) - (arr[i] = arr[arr[i]]); else i++; }} // Driver Code let arr = [ -1, -1, 6, 1, 9, 3, 2, -1, 4, -1 ]; let n = arr.length; // Function Call fixArray(arr, n); // Print output for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This Code is Contributed by _saurabh_jaiswal</script>",
"e": 26134,
"s": 25545,
"text": null
},
{
"code": null,
"e": 26159,
"s": 26134,
"text": "-1 1 2 3 4 -1 6 -1 -1 9 "
},
{
"code": null,
"e": 26202,
"s": 26159,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 26214,
"s": 26202,
"text": "manishshaw1"
},
{
"code": null,
"e": 26222,
"s": 26214,
"text": "rahulpy"
},
{
"code": null,
"e": 26230,
"s": 26222,
"text": "Venkata"
},
{
"code": null,
"e": 26243,
"s": 26230,
"text": "RoshanDaruka"
},
{
"code": null,
"e": 26261,
"s": 26243,
"text": "sanjeetkumarSingh"
},
{
"code": null,
"e": 26275,
"s": 26261,
"text": "princiraj1992"
},
{
"code": null,
"e": 26288,
"s": 26275,
"text": "Adarsh_Verma"
},
{
"code": null,
"e": 26300,
"s": 26288,
"text": "gfg_sal_gfg"
},
{
"code": null,
"e": 26306,
"s": 26300,
"text": "ukasp"
},
{
"code": null,
"e": 26316,
"s": 26306,
"text": "demon9689"
},
{
"code": null,
"e": 26331,
"s": 26316,
"text": "faizanurrahman"
},
{
"code": null,
"e": 26345,
"s": 26331,
"text": "divyesh072019"
},
{
"code": null,
"e": 26363,
"s": 26345,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 26371,
"s": 26363,
"text": "rag2127"
},
{
"code": null,
"e": 26378,
"s": 26371,
"text": "rdtank"
},
{
"code": null,
"e": 26390,
"s": 26378,
"text": "parascoding"
},
{
"code": null,
"e": 26407,
"s": 26390,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 26418,
"s": 26407,
"text": "bunnyram19"
},
{
"code": null,
"e": 26426,
"s": 26418,
"text": "gfgking"
},
{
"code": null,
"e": 26445,
"s": 26426,
"text": "vaibhavrabadiya117"
},
{
"code": null,
"e": 26454,
"s": 26445,
"text": "sweetyty"
},
{
"code": null,
"e": 26470,
"s": 26454,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 26487,
"s": 26470,
"text": "devchaudhary1911"
},
{
"code": null,
"e": 26502,
"s": 26487,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 26515,
"s": 26502,
"text": "codewithmini"
},
{
"code": null,
"e": 26528,
"s": 26515,
"text": "prasanna1995"
},
{
"code": null,
"e": 26544,
"s": 26528,
"text": "array-rearrange"
},
{
"code": null,
"e": 26551,
"s": 26544,
"text": "Arrays"
},
{
"code": null,
"e": 26556,
"s": 26551,
"text": "Hash"
},
{
"code": null,
"e": 26563,
"s": 26556,
"text": "Arrays"
},
{
"code": null,
"e": 26568,
"s": 26563,
"text": "Hash"
},
{
"code": null,
"e": 26666,
"s": 26568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26681,
"s": 26666,
"text": "Arrays in Java"
},
{
"code": null,
"e": 26727,
"s": 26681,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 26795,
"s": 26727,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 26839,
"s": 26795,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 26871,
"s": 26839,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 26909,
"s": 26871,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 26945,
"s": 26909,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 26976,
"s": 26945,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 27003,
"s": 26976,
"text": "Count pairs with given sum"
}
] |
Mathematical Functions in SQL
|
Mathematical functions are very important in SQL to implement different mathematical concepts in queries.
Some of the the major mathematical functions in SQL are as follows −
This function returns the absolute value of X. For example −
Select abs(-6);
This returns 6.
The variable X is divided by Y and their remainder is returned. For example −
Select mod(9,5);
This returns 4.
This method returns 1 if X is positive, -1 if it is negative and 0 if the value of X is 0. For example −
Select sign(10);
This returns 1.
This returns the largest integer value that is either less than X or equal to it. For example −
Select floor(5.7);
This returns 5.
This returns the smallest integer value that is either more than X or equal to it. For example −
Select ceil(5.7);
This returns 6.
This function returns the value of x raised to the power of Y For example −
Select power(2,5);
This returns 32.
This function returns the value of X rounded off to the whole integer that is nearest to it. For example −
Select round(5.7);
This returns 6.
This function returns the square root of X. For example −
Select sqrt(9);
This returns 3.
This function accepts a Sin value as the input and returns the angle in radians. For example −
Select asin(0);
This returns 0.
This function accepts a Cos value as the input and returns the angle in radians. For example −
Select acos(1);
This returns 0.
This function accepts a Tan value as the input and returns the angle in radians. For example −
Select atan(0);
This returns 0.
This function accepts an angle in radians as its parameter and returns its Sine value. For example −
Select sin(0);
This returns 0.
This function accepts an angle in radians as its parameter and returns its Cosine value. For example −
Select cos(0);
This returns 1.
This function accepts an angle in radians as its parameter and returns its Tan value. For example −
Select tan(0);
This returns 0.
|
[
{
"code": null,
"e": 1293,
"s": 1187,
"text": "Mathematical functions are very important in SQL to implement different mathematical concepts in queries."
},
{
"code": null,
"e": 1362,
"s": 1293,
"text": "Some of the the major mathematical functions in SQL are as follows −"
},
{
"code": null,
"e": 1423,
"s": 1362,
"text": "This function returns the absolute value of X. For example −"
},
{
"code": null,
"e": 1439,
"s": 1423,
"text": "Select abs(-6);"
},
{
"code": null,
"e": 1455,
"s": 1439,
"text": "This returns 6."
},
{
"code": null,
"e": 1533,
"s": 1455,
"text": "The variable X is divided by Y and their remainder is returned. For example −"
},
{
"code": null,
"e": 1550,
"s": 1533,
"text": "Select mod(9,5);"
},
{
"code": null,
"e": 1566,
"s": 1550,
"text": "This returns 4."
},
{
"code": null,
"e": 1671,
"s": 1566,
"text": "This method returns 1 if X is positive, -1 if it is negative and 0 if the value of X is 0. For example −"
},
{
"code": null,
"e": 1688,
"s": 1671,
"text": "Select sign(10);"
},
{
"code": null,
"e": 1704,
"s": 1688,
"text": "This returns 1."
},
{
"code": null,
"e": 1800,
"s": 1704,
"text": "This returns the largest integer value that is either less than X or equal to it. For example −"
},
{
"code": null,
"e": 1819,
"s": 1800,
"text": "Select floor(5.7);"
},
{
"code": null,
"e": 1835,
"s": 1819,
"text": "This returns 5."
},
{
"code": null,
"e": 1932,
"s": 1835,
"text": "This returns the smallest integer value that is either more than X or equal to it. For example −"
},
{
"code": null,
"e": 1950,
"s": 1932,
"text": "Select ceil(5.7);"
},
{
"code": null,
"e": 1966,
"s": 1950,
"text": "This returns 6."
},
{
"code": null,
"e": 2043,
"s": 1966,
"text": "This function returns the value of x raised to the power of Y For example −"
},
{
"code": null,
"e": 2062,
"s": 2043,
"text": "Select power(2,5);"
},
{
"code": null,
"e": 2079,
"s": 2062,
"text": "This returns 32."
},
{
"code": null,
"e": 2187,
"s": 2079,
"text": "This function returns the value of X rounded off to the whole integer that is nearest to it. For example −"
},
{
"code": null,
"e": 2206,
"s": 2187,
"text": "Select round(5.7);"
},
{
"code": null,
"e": 2222,
"s": 2206,
"text": "This returns 6."
},
{
"code": null,
"e": 2280,
"s": 2222,
"text": "This function returns the square root of X. For example −"
},
{
"code": null,
"e": 2296,
"s": 2280,
"text": "Select sqrt(9);"
},
{
"code": null,
"e": 2312,
"s": 2296,
"text": "This returns 3."
},
{
"code": null,
"e": 2408,
"s": 2312,
"text": "This function accepts a Sin value as the input and returns the angle in radians. For example −"
},
{
"code": null,
"e": 2424,
"s": 2408,
"text": "Select asin(0);"
},
{
"code": null,
"e": 2440,
"s": 2424,
"text": "This returns 0."
},
{
"code": null,
"e": 2535,
"s": 2440,
"text": "This function accepts a Cos value as the input and returns the angle in radians. For example −"
},
{
"code": null,
"e": 2551,
"s": 2535,
"text": "Select acos(1);"
},
{
"code": null,
"e": 2567,
"s": 2551,
"text": "This returns 0."
},
{
"code": null,
"e": 2662,
"s": 2567,
"text": "This function accepts a Tan value as the input and returns the angle in radians. For example −"
},
{
"code": null,
"e": 2678,
"s": 2662,
"text": "Select atan(0);"
},
{
"code": null,
"e": 2694,
"s": 2678,
"text": "This returns 0."
},
{
"code": null,
"e": 2795,
"s": 2694,
"text": "This function accepts an angle in radians as its parameter and returns its Sine value. For example −"
},
{
"code": null,
"e": 2810,
"s": 2795,
"text": "Select sin(0);"
},
{
"code": null,
"e": 2826,
"s": 2810,
"text": "This returns 0."
},
{
"code": null,
"e": 2929,
"s": 2826,
"text": "This function accepts an angle in radians as its parameter and returns its Cosine value. For example −"
},
{
"code": null,
"e": 2944,
"s": 2929,
"text": "Select cos(0);"
},
{
"code": null,
"e": 2960,
"s": 2944,
"text": "This returns 1."
},
{
"code": null,
"e": 3060,
"s": 2960,
"text": "This function accepts an angle in radians as its parameter and returns its Tan value. For example −"
},
{
"code": null,
"e": 3075,
"s": 3060,
"text": "Select tan(0);"
},
{
"code": null,
"e": 3091,
"s": 3075,
"text": "This returns 0."
}
] |
What are the template literals in ES6 ?
|
10 Oct, 2021
Template Literals are literal words in programming that are used to represent some kind of fixed value and template means a blueprint that can generate some entity, Therefore, the template literals are used to generate strings of a fixed value. These are delimited with the backticks ` `, We can inject the JavaScript expressions and strings inside it.
Syntax:
`Any string ${jsExpression} can appear here`
Example: In this example, we are illustrating a simple demo of template literals.
Javascript
<script>const str1 = `Hi, GeeksforGeeks Learner`;console.log(str1); const str = "GeeksforGeeks";const str2 = `Hi, ${str} Learner`;console.log(str2);</script>
Output:
Hi, GeeksforGeeks Learner
Hi, GeeksforGeeks Learner
Advantages: The usage of template strings has the following advantages:
1. Concatenating Strings: Template literals provide a much simpler way to concatenate two strings. Normally we use the “+” operator but with template literals, we can write whatever we want.
Example:
Javascript
<script>const strA1 = "Normal Javascript techniques";const strA2 = "are a little bit lengthy";console.log(strA1 + " " + strA2 + "."); const strB1 = "Template literals";const strB2 = "make them simple";console.log(`${strB1} ${strB2}.`);</script>
Output:
Normal Javascript techniques are a little bit lengthy.
Template literals make them simple.
2. No need to use \n and \t escape sequences: Template literals reserve each type of space so we don’t need to tell explicitly for a new line or extra space.
Example:
Javascript
<script>console.log("There will be a tab space after this" + "\t" + "end of string.");console.log("First Line" + "\n" + "Second Line"); console.log(`There will be a tab space after this end of string.`);console.log(`First Line Second Line`);</script>
Output:
There will be a tab space after this end of string.
First Line
Second Line
There will be a tab space after this end of string.
First Line
Second Line
3. Combination of expressions and strings becomes easy: With template literals, we can inject any kind of expression which will be executed and determined at runtime inside strings.
Example 1: In this example, we are showing how a ternary operator can be used to generate a dynamic string with template literals.
Javascript
<script>let darkMode = true; console.log(`The current background coloris ${darkMode ? "#000000" : "#FFFFFF" }`);</script>
Output:
The current background color
is #000000
Example 2: The simple illustration of how a mathematical expression can be inserted in template literals.
Javascript
const price = 5799.00; console.log(`The price of product is ${price} andafter 16% discount it would cost ${price-price*16*0.01}`);
Output:
The price of product is 5799 and
after 16% discount it would cost 4871.16
ES6
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 381,
"s": 28,
"text": "Template Literals are literal words in programming that are used to represent some kind of fixed value and template means a blueprint that can generate some entity, Therefore, the template literals are used to generate strings of a fixed value. These are delimited with the backticks ` `, We can inject the JavaScript expressions and strings inside it."
},
{
"code": null,
"e": 389,
"s": 381,
"text": "Syntax:"
},
{
"code": null,
"e": 434,
"s": 389,
"text": "`Any string ${jsExpression} can appear here`"
},
{
"code": null,
"e": 516,
"s": 434,
"text": "Example: In this example, we are illustrating a simple demo of template literals."
},
{
"code": null,
"e": 527,
"s": 516,
"text": "Javascript"
},
{
"code": "<script>const str1 = `Hi, GeeksforGeeks Learner`;console.log(str1); const str = \"GeeksforGeeks\";const str2 = `Hi, ${str} Learner`;console.log(str2);</script>",
"e": 686,
"s": 527,
"text": null
},
{
"code": null,
"e": 694,
"s": 686,
"text": "Output:"
},
{
"code": null,
"e": 746,
"s": 694,
"text": "Hi, GeeksforGeeks Learner\nHi, GeeksforGeeks Learner"
},
{
"code": null,
"e": 818,
"s": 746,
"text": "Advantages: The usage of template strings has the following advantages:"
},
{
"code": null,
"e": 1009,
"s": 818,
"text": "1. Concatenating Strings: Template literals provide a much simpler way to concatenate two strings. Normally we use the “+” operator but with template literals, we can write whatever we want."
},
{
"code": null,
"e": 1018,
"s": 1009,
"text": "Example:"
},
{
"code": null,
"e": 1029,
"s": 1018,
"text": "Javascript"
},
{
"code": "<script>const strA1 = \"Normal Javascript techniques\";const strA2 = \"are a little bit lengthy\";console.log(strA1 + \" \" + strA2 + \".\"); const strB1 = \"Template literals\";const strB2 = \"make them simple\";console.log(`${strB1} ${strB2}.`);</script>",
"e": 1277,
"s": 1029,
"text": null
},
{
"code": null,
"e": 1285,
"s": 1277,
"text": "Output:"
},
{
"code": null,
"e": 1376,
"s": 1285,
"text": "Normal Javascript techniques are a little bit lengthy.\nTemplate literals make them simple."
},
{
"code": null,
"e": 1534,
"s": 1376,
"text": "2. No need to use \\n and \\t escape sequences: Template literals reserve each type of space so we don’t need to tell explicitly for a new line or extra space."
},
{
"code": null,
"e": 1543,
"s": 1534,
"text": "Example:"
},
{
"code": null,
"e": 1554,
"s": 1543,
"text": "Javascript"
},
{
"code": "<script>console.log(\"There will be a tab space after this\" + \"\\t\" + \"end of string.\");console.log(\"First Line\" + \"\\n\" + \"Second Line\"); console.log(`There will be a tab space after this end of string.`);console.log(`First Line Second Line`);</script>",
"e": 1812,
"s": 1554,
"text": null
},
{
"code": null,
"e": 1820,
"s": 1812,
"text": "Output:"
},
{
"code": null,
"e": 1976,
"s": 1820,
"text": "There will be a tab space after this end of string.\nFirst Line\nSecond Line\nThere will be a tab space after this end of string.\nFirst Line\nSecond Line"
},
{
"code": null,
"e": 2159,
"s": 1976,
"text": "3. Combination of expressions and strings becomes easy: With template literals, we can inject any kind of expression which will be executed and determined at runtime inside strings. "
},
{
"code": null,
"e": 2290,
"s": 2159,
"text": "Example 1: In this example, we are showing how a ternary operator can be used to generate a dynamic string with template literals."
},
{
"code": null,
"e": 2301,
"s": 2290,
"text": "Javascript"
},
{
"code": "<script>let darkMode = true; console.log(`The current background coloris ${darkMode ? \"#000000\" : \"#FFFFFF\" }`);</script>",
"e": 2424,
"s": 2301,
"text": null
},
{
"code": null,
"e": 2432,
"s": 2424,
"text": "Output:"
},
{
"code": null,
"e": 2472,
"s": 2432,
"text": "The current background color\nis #000000"
},
{
"code": null,
"e": 2578,
"s": 2472,
"text": "Example 2: The simple illustration of how a mathematical expression can be inserted in template literals."
},
{
"code": null,
"e": 2589,
"s": 2578,
"text": "Javascript"
},
{
"code": "const price = 5799.00; console.log(`The price of product is ${price} andafter 16% discount it would cost ${price-price*16*0.01}`);",
"e": 2721,
"s": 2589,
"text": null
},
{
"code": null,
"e": 2729,
"s": 2721,
"text": "Output:"
},
{
"code": null,
"e": 2803,
"s": 2729,
"text": "The price of product is 5799 and\nafter 16% discount it would cost 4871.16"
},
{
"code": null,
"e": 2807,
"s": 2803,
"text": "ES6"
},
{
"code": null,
"e": 2828,
"s": 2807,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2835,
"s": 2828,
"text": "Picked"
},
{
"code": null,
"e": 2846,
"s": 2835,
"text": "JavaScript"
},
{
"code": null,
"e": 2863,
"s": 2846,
"text": "Web Technologies"
},
{
"code": null,
"e": 2961,
"s": 2863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3022,
"s": 2961,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3062,
"s": 3022,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3103,
"s": 3062,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3145,
"s": 3103,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3167,
"s": 3145,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 3229,
"s": 3167,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3262,
"s": 3229,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3323,
"s": 3262,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3373,
"s": 3323,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Ordinal Encoding Tips | Towards Data Science
|
I was working with a team relatively new to business/data analytics when the group discussions on feature engineering for machine learning came up. Understandably, it may be confusing and intimidating for people new to machine learning. Working in Jupyter Notebooks and Python, we naturally would refer to 1) the built-in documentation within packages such as Pandas and Sklearn, or 2) online, in-depth technical documentation for these packages. Interestingly, the documentation does not detail the method to resolve the specific issue that the team faced with the dataset — feature engineering of multiple ordinal variables, each with unique ordering sequences.
🔆 Code implementation is arranged after this section.
❓ What are Categorical variables?
📔 Categorical variables are arranged by groups with corresponding value ranges (i.e. group labels). Variables without inherent hierarchy are Nominal variables; group labels are arbitrary. Variables with an ordered sequence are Ordinal variables; group labels are in ascending/ descending order.
❓ How is this related to feature engineering?
📔 For many algorithms (machine learning models), the input must be numerical. Hence, categorical variables need to be converted into numerical values. The code implementation below illustrates some feature engineering techniques and steps to avoid potential pitfalls.
# Begin by importing the librariesimport pandas as pdimport numpy as npfrom sklearn.preprocessing import OrdinalEncoderfrom sklearn.preprocessing import LabelEncoder# Create a dataframe with artifical values# Salary Grade, G to L, G ranked highest# Sector Ranking, SR1 to SR9, SR1 ranked highest# retentionRisks, Low, Med, HighGrades = ['K', 'I', 'G', 'L', 'H', 'G', 'H', 'I', 'K'] # mixed to see effectSRs = ['SR1', 'SR9', 'SR2', 'SR8', 'SR3', 'SR7', 'SR4', 'SR6', 'SR5'] # mixed to see effectretentionRisks = ['Low', 'High', 'Low', 'High', 'Low', 'Med', 'Low', 'High', 'Med']Ex = pd.DataFrame({'grades':Grades, 'ranks':SRs, 'retnRisks':retentionRisks })Ex
The example dataset comprises three columns (grades, ranks and, retention risk — abbreviated as ‘retnRisks’). All are deliberately categorical for illustrative purposes. Let’s assume the retention risks as the target variable (variable for machine learning classification output).
# Split the datasetX_Ex = Ex.loc[:,:'ranks']y_Ex = Ex['retnRisks']
📓 Some might wonder about the upper and lower case differences here. Generally, it is a way to note the differences between the predictor variables (X_Ex) and target variable (y_Ex). The target variable is a Pandas series. Let’s start with the target variable.
# Let's look at the target variable first# Instantiate the label encoderlabel_encoder = LabelEncoder()# Assign the encoded values to y_ExTy_ExT = label_encoder.fit_transform(y_Ex)# Code block to review encodingy_Exunique = np.unique(y_Ex)y_ExTunique = np.unique(y_ExT)y_encode = dict(zip(y_Exunique, y_ExTunique))print(y_encode)
The encoding is not in the order desired, regardless of ascending or descending order. For the above, the ordering sequence is alphabetical. Ideally, we would want something per High(2) > Med(1) > Low(0). We can do this via Pandas.
# Define a dictionary for encoding target variableenc_dict = {'Low':0, 'Med':1, 'High':2}# Create the mapped values in a new columnEx['target_ordinal'] = Ex['retnRisks'].map(enc_dict)# Review datasetEx
Next, the predictor variables.
# Instantiate ordinal encoderordinal_encoder = OrdinalEncoder()# Assign the encoded values to X_ExTX_ExT = ordinal_encoder.fit_transform(X_Ex)# define function to return encoded values for categorical variable valuesdef enc(array, frame): for idx in range(array.shape[1]): X_Exunique =sorted(frame.loc[:,frame.columns[idx]].unique()) X_ExTunique = np.unique(array[:,idx]) encode = dict(zip(X_Exunique, X_ExTunique)) print(encode)# Check encoding using the funcenc(X_ExT, X_Ex)
The encoded sequence is fine except that in the context of the dataset, ‘G’ is ranked higher than ‘L’ for grades. Similar applies for ranks. We need to reverse the order of sequence. We can do that as follows:
# Create lists to hold the order sequence needed# for gradesg = sorted(Ex['grades'].unique(),reverse=True)# for ranksr = sorted(Ex['ranks'].unique(),reverse=True)
Sklearn’s Ordinal encoder takes in a parameter, categories.
‘auto’ — implies the alphabetical ordering
‘list’ — refers to the two lists with our desired sequence. The order in which they are passing into the encoder have to correspond with the order of the variables in the dataset.
# Pass in the correctly-ordered sequence into Ordinal Encoderordinal_encoder = OrdinalEncoder(categories=[g,r])X_ExT2 = ordinal_encoder.fit_transform(X_ex)# gradesX_ExT2_grades_unique = np.unique(X_ExT2[:,0])grades_encode = dict(zip(g, X_ExT2_grades_unique))grades_encode
# rankingX_ExT2_rank_unique = np.unique(X_ExT2[:,1])rank_encode = dict(zip(r, X_ExT2_rank_unique))print(rank_encode)
Data input. Another alternative for data input can be getting the values, then processing them as appropriate.
# Alternative data load approachEx_values = Ex.values# Predictor variablesX_ = Ex_values[:, :-1].astype(str)# target variablesy_ = Ex_values[:,-1].astype(str)
Range of values. For the encoders, the current default is to raise an error if there are new values where the encoder has not seen in the fitting process. This can be configured as per documentation. The other approach is to list out the full range of expected values to be encoded, and pass them into the encoder.
To recap,
regardless of target or independent variables (i.e. predictor variables), we need to understand the correct order sequence, then apply the encoding accordingly. It’s always a good idea to check the encoded values after encoding each columns.
for the target variable, we can opt to use Label Encoder or Pandas.
for the independent variables we can use Ordinal Encoder over Pandas for more efficient process.
where the ordering sequence is unique, these can be defined and passed into the encoders.
|
[
{
"code": null,
"e": 835,
"s": 171,
"text": "I was working with a team relatively new to business/data analytics when the group discussions on feature engineering for machine learning came up. Understandably, it may be confusing and intimidating for people new to machine learning. Working in Jupyter Notebooks and Python, we naturally would refer to 1) the built-in documentation within packages such as Pandas and Sklearn, or 2) online, in-depth technical documentation for these packages. Interestingly, the documentation does not detail the method to resolve the specific issue that the team faced with the dataset — feature engineering of multiple ordinal variables, each with unique ordering sequences."
},
{
"code": null,
"e": 889,
"s": 835,
"text": "🔆 Code implementation is arranged after this section."
},
{
"code": null,
"e": 923,
"s": 889,
"text": "❓ What are Categorical variables?"
},
{
"code": null,
"e": 1218,
"s": 923,
"text": "📔 Categorical variables are arranged by groups with corresponding value ranges (i.e. group labels). Variables without inherent hierarchy are Nominal variables; group labels are arbitrary. Variables with an ordered sequence are Ordinal variables; group labels are in ascending/ descending order."
},
{
"code": null,
"e": 1264,
"s": 1218,
"text": "❓ How is this related to feature engineering?"
},
{
"code": null,
"e": 1532,
"s": 1264,
"text": "📔 For many algorithms (machine learning models), the input must be numerical. Hence, categorical variables need to be converted into numerical values. The code implementation below illustrates some feature engineering techniques and steps to avoid potential pitfalls."
},
{
"code": null,
"e": 2249,
"s": 1532,
"text": "# Begin by importing the librariesimport pandas as pdimport numpy as npfrom sklearn.preprocessing import OrdinalEncoderfrom sklearn.preprocessing import LabelEncoder# Create a dataframe with artifical values# Salary Grade, G to L, G ranked highest# Sector Ranking, SR1 to SR9, SR1 ranked highest# retentionRisks, Low, Med, HighGrades = ['K', 'I', 'G', 'L', 'H', 'G', 'H', 'I', 'K'] # mixed to see effectSRs = ['SR1', 'SR9', 'SR2', 'SR8', 'SR3', 'SR7', 'SR4', 'SR6', 'SR5'] # mixed to see effectretentionRisks = ['Low', 'High', 'Low', 'High', 'Low', 'Med', 'Low', 'High', 'Med']Ex = pd.DataFrame({'grades':Grades, 'ranks':SRs, 'retnRisks':retentionRisks })Ex"
},
{
"code": null,
"e": 2530,
"s": 2249,
"text": "The example dataset comprises three columns (grades, ranks and, retention risk — abbreviated as ‘retnRisks’). All are deliberately categorical for illustrative purposes. Let’s assume the retention risks as the target variable (variable for machine learning classification output)."
},
{
"code": null,
"e": 2597,
"s": 2530,
"text": "# Split the datasetX_Ex = Ex.loc[:,:'ranks']y_Ex = Ex['retnRisks']"
},
{
"code": null,
"e": 2858,
"s": 2597,
"text": "📓 Some might wonder about the upper and lower case differences here. Generally, it is a way to note the differences between the predictor variables (X_Ex) and target variable (y_Ex). The target variable is a Pandas series. Let’s start with the target variable."
},
{
"code": null,
"e": 3187,
"s": 2858,
"text": "# Let's look at the target variable first# Instantiate the label encoderlabel_encoder = LabelEncoder()# Assign the encoded values to y_ExTy_ExT = label_encoder.fit_transform(y_Ex)# Code block to review encodingy_Exunique = np.unique(y_Ex)y_ExTunique = np.unique(y_ExT)y_encode = dict(zip(y_Exunique, y_ExTunique))print(y_encode)"
},
{
"code": null,
"e": 3419,
"s": 3187,
"text": "The encoding is not in the order desired, regardless of ascending or descending order. For the above, the ordering sequence is alphabetical. Ideally, we would want something per High(2) > Med(1) > Low(0). We can do this via Pandas."
},
{
"code": null,
"e": 3643,
"s": 3419,
"text": "# Define a dictionary for encoding target variableenc_dict = {'Low':0, 'Med':1, 'High':2}# Create the mapped values in a new columnEx['target_ordinal'] = Ex['retnRisks'].map(enc_dict)# Review datasetEx"
},
{
"code": null,
"e": 3674,
"s": 3643,
"text": "Next, the predictor variables."
},
{
"code": null,
"e": 4182,
"s": 3674,
"text": "# Instantiate ordinal encoderordinal_encoder = OrdinalEncoder()# Assign the encoded values to X_ExTX_ExT = ordinal_encoder.fit_transform(X_Ex)# define function to return encoded values for categorical variable valuesdef enc(array, frame): for idx in range(array.shape[1]): X_Exunique =sorted(frame.loc[:,frame.columns[idx]].unique()) X_ExTunique = np.unique(array[:,idx]) encode = dict(zip(X_Exunique, X_ExTunique)) print(encode)# Check encoding using the funcenc(X_ExT, X_Ex)"
},
{
"code": null,
"e": 4392,
"s": 4182,
"text": "The encoded sequence is fine except that in the context of the dataset, ‘G’ is ranked higher than ‘L’ for grades. Similar applies for ranks. We need to reverse the order of sequence. We can do that as follows:"
},
{
"code": null,
"e": 4555,
"s": 4392,
"text": "# Create lists to hold the order sequence needed# for gradesg = sorted(Ex['grades'].unique(),reverse=True)# for ranksr = sorted(Ex['ranks'].unique(),reverse=True)"
},
{
"code": null,
"e": 4615,
"s": 4555,
"text": "Sklearn’s Ordinal encoder takes in a parameter, categories."
},
{
"code": null,
"e": 4658,
"s": 4615,
"text": "‘auto’ — implies the alphabetical ordering"
},
{
"code": null,
"e": 4838,
"s": 4658,
"text": "‘list’ — refers to the two lists with our desired sequence. The order in which they are passing into the encoder have to correspond with the order of the variables in the dataset."
},
{
"code": null,
"e": 5110,
"s": 4838,
"text": "# Pass in the correctly-ordered sequence into Ordinal Encoderordinal_encoder = OrdinalEncoder(categories=[g,r])X_ExT2 = ordinal_encoder.fit_transform(X_ex)# gradesX_ExT2_grades_unique = np.unique(X_ExT2[:,0])grades_encode = dict(zip(g, X_ExT2_grades_unique))grades_encode"
},
{
"code": null,
"e": 5227,
"s": 5110,
"text": "# rankingX_ExT2_rank_unique = np.unique(X_ExT2[:,1])rank_encode = dict(zip(r, X_ExT2_rank_unique))print(rank_encode)"
},
{
"code": null,
"e": 5338,
"s": 5227,
"text": "Data input. Another alternative for data input can be getting the values, then processing them as appropriate."
},
{
"code": null,
"e": 5497,
"s": 5338,
"text": "# Alternative data load approachEx_values = Ex.values# Predictor variablesX_ = Ex_values[:, :-1].astype(str)# target variablesy_ = Ex_values[:,-1].astype(str)"
},
{
"code": null,
"e": 5812,
"s": 5497,
"text": "Range of values. For the encoders, the current default is to raise an error if there are new values where the encoder has not seen in the fitting process. This can be configured as per documentation. The other approach is to list out the full range of expected values to be encoded, and pass them into the encoder."
},
{
"code": null,
"e": 5822,
"s": 5812,
"text": "To recap,"
},
{
"code": null,
"e": 6064,
"s": 5822,
"text": "regardless of target or independent variables (i.e. predictor variables), we need to understand the correct order sequence, then apply the encoding accordingly. It’s always a good idea to check the encoded values after encoding each columns."
},
{
"code": null,
"e": 6132,
"s": 6064,
"text": "for the target variable, we can opt to use Label Encoder or Pandas."
},
{
"code": null,
"e": 6229,
"s": 6132,
"text": "for the independent variables we can use Ordinal Encoder over Pandas for more efficient process."
}
] |
What are the rules for a functional interface in Java?
|
A functional interface is a special kind of interface with exactly one abstract method in which lambda expression parameters and return types are matched. It provides target types for lambda expressions and method references.
A functional interface must have exactly one abstract method.
A functional interface has any number of
default methods because they are not abstract and implementation already provided by the same.
A functional interface declares an abstract method overriding one of the public methods from java.lang.Object still considered as functional interface. The reason is any implementation class to this interface can have implementation for this abstract method either from a superclass or defined by the implementation class itself.
@FunctionalInterface
interface <interface-name> {
// only one abstract method
// static or default methods
}
import java.util.Date;
@FunctionalInterface
interface DateFunction {
int process();
static Date now() {
return new Date();
}
default String formatDate(Date date) {
return date.toString();
}
default int sum(int a, int b) {
return a + b;
}
}
public class LambdaFunctionalInterfaceTest {
public static void main(String[] args) {
DateFunction dateFunc = () -> 77; // lambda expression
System.out.println(dateFunc.process());
}
}
77
|
[
{
"code": null,
"e": 1288,
"s": 1062,
"text": "A functional interface is a special kind of interface with exactly one abstract method in which lambda expression parameters and return types are matched. It provides target types for lambda expressions and method references."
},
{
"code": null,
"e": 1350,
"s": 1288,
"text": "A functional interface must have exactly one abstract method."
},
{
"code": null,
"e": 1486,
"s": 1350,
"text": "A functional interface has any number of\ndefault methods because they are not abstract and implementation already provided by the same."
},
{
"code": null,
"e": 1816,
"s": 1486,
"text": "A functional interface declares an abstract method overriding one of the public methods from java.lang.Object still considered as functional interface. The reason is any implementation class to this interface can have implementation for this abstract method either from a superclass or defined by the implementation class itself."
},
{
"code": null,
"e": 1927,
"s": 1816,
"text": "@FunctionalInterface\ninterface <interface-name> {\n // only one abstract method\n // static or default methods\n}"
},
{
"code": null,
"e": 2409,
"s": 1927,
"text": "import java.util.Date;\n\n@FunctionalInterface\ninterface DateFunction {\n int process();\n static Date now() {\n return new Date();\n }\n default String formatDate(Date date) {\n return date.toString();\n }\n default int sum(int a, int b) {\n return a + b;\n }\n}\npublic class LambdaFunctionalInterfaceTest {\n public static void main(String[] args) {\n DateFunction dateFunc = () -> 77; // lambda expression\n System.out.println(dateFunc.process());\n }\n}"
},
{
"code": null,
"e": 2412,
"s": 2409,
"text": "77"
}
] |
Difference between Yield and Return in Python - GeeksforGeeks
|
20 Oct, 2020
Python YieldIt is generally used to convert a regular Python function into a generator. A generator is a special function in Python that returns a generator object to the caller. Since it stores the local variable states, hence overhead of memory allocation is controlled.
Example:
# Python3 code to demonstrate yield keyword # Use of yielddef printresult(String) : for i in String: if i == "e": yield i # initializing string String = "GeeksforGeeks" ans = 0print ("The number of 'e' in word is : ", end = "" ) String = String.strip() for j in printresult(String): ans = ans + 1 print (ans)
Output:
The number of 'e' in word is : 4
Python ReturnIt is generally used for the end of the execution and “returns” the result to the caller statement. It can return all type of values and it returns None when there is no expression with the statement “return”.
Example:
# A Python program to show return statement class Test: def __init__(self): self.str = "GeeksForGeeks" self.x = "Shubham Singh" # This function returns an object of Test def fun(): return Test() # Driver code to test above method t = fun() print(t.str) print(t.x)
Output:
GeeksForGeeks
Shubham Singh
python-basics
Python
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
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Get unique values from a list
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 24317,
"s": 24289,
"text": "\n20 Oct, 2020"
},
{
"code": null,
"e": 24590,
"s": 24317,
"text": "Python YieldIt is generally used to convert a regular Python function into a generator. A generator is a special function in Python that returns a generator object to the caller. Since it stores the local variable states, hence overhead of memory allocation is controlled."
},
{
"code": null,
"e": 24599,
"s": 24590,
"text": "Example:"
},
{
"code": "# Python3 code to demonstrate yield keyword # Use of yielddef printresult(String) : for i in String: if i == \"e\": yield i # initializing string String = \"GeeksforGeeks\" ans = 0print (\"The number of 'e' in word is : \", end = \"\" ) String = String.strip() for j in printresult(String): ans = ans + 1 print (ans) ",
"e": 24944,
"s": 24599,
"text": null
},
{
"code": null,
"e": 24952,
"s": 24944,
"text": "Output:"
},
{
"code": null,
"e": 24985,
"s": 24952,
"text": "The number of 'e' in word is : 4"
},
{
"code": null,
"e": 25208,
"s": 24985,
"text": "Python ReturnIt is generally used for the end of the execution and “returns” the result to the caller statement. It can return all type of values and it returns None when there is no expression with the statement “return”."
},
{
"code": null,
"e": 25217,
"s": 25208,
"text": "Example:"
},
{
"code": "# A Python program to show return statement class Test: def __init__(self): self.str = \"GeeksForGeeks\" self.x = \"Shubham Singh\" # This function returns an object of Test def fun(): return Test() # Driver code to test above method t = fun() print(t.str) print(t.x) ",
"e": 25532,
"s": 25217,
"text": null
},
{
"code": null,
"e": 25540,
"s": 25532,
"text": "Output:"
},
{
"code": null,
"e": 25568,
"s": 25540,
"text": "GeeksForGeeks\nShubham Singh"
},
{
"code": null,
"e": 25582,
"s": 25568,
"text": "python-basics"
},
{
"code": null,
"e": 25589,
"s": 25582,
"text": "Python"
},
{
"code": null,
"e": 25687,
"s": 25589,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25719,
"s": 25687,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25761,
"s": 25719,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25817,
"s": 25761,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25859,
"s": 25817,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25914,
"s": 25859,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 25945,
"s": 25914,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25967,
"s": 25945,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25996,
"s": 25967,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 26035,
"s": 25996,
"text": "Python | Get unique values from a list"
}
] |
Bootstrap .pager class
|
Get the pager links using the .pager Bootstrap class.
You can try to run the following code to implement the .pager class in Bootstrap
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h2>Questions</h2>
<br>
<ul class = "pager">
<li><a href = "#">Previous</a></li>
<li><a href = "#">Next</a></li>
</ul>
</body>
</html>
|
[
{
"code": null,
"e": 1116,
"s": 1062,
"text": "Get the pager links using the .pager Bootstrap class."
},
{
"code": null,
"e": 1197,
"s": 1116,
"text": "You can try to run the following code to implement the .pager class in Bootstrap"
},
{
"code": null,
"e": 1207,
"s": 1197,
"text": "Live Demo"
},
{
"code": null,
"e": 1672,
"s": 1207,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <h2>Questions</h2>\n <br>\n <ul class = \"pager\">\n <li><a href = \"#\">Previous</a></li>\n <li><a href = \"#\">Next</a></li>\n </ul>\n </body>\n</html>"
}
] |
Logistic Regression: A Simplified Approach Using Python | by Surya Remanan | Towards Data Science
|
In Logistic Regression, we wish to model a dependent variable(Y) in terms of one or more independent variables(X). It is a method for classification. This algorithm is used for the dependent variable that is Categorical. Y is modeled using a function that gives output between 0 and 1 for all values of X. In Logistic Regression, the Sigmoid (aka Logistic) Function is used.
After we train a logistic regression model on some training data, we will evaluate the performance of the model on some test data. For this, we use the Confusion Matrix. A Confusion Matrix is a table that is often used to describe the performance of the classification model on a set of test data for which the true values are already known. Given below is a Confusion Matrix.
Here, TP stands for True Positive which are the cases in which we predicted yes and the actual value was true. TN stands for True Negative which are the cases in which we predicted no and the actual value was false.FP stands for False Positive which are the cases which we predicted yes and the actual value was False.FN stands for False Negative which are the cases which we predicted No and the actual value was true.
Confusion Matrix helps us determine how often the model prediction is correct or in other words, the accuracy of the model. By the above table, It is given by:
( TP + TN ) / Total = 100 + 50 / 165 = 0.91
This means that the model is 91% correct. The Confusion Matrix is also used to measure the error rate which is given by:
( FP + FN ) / Total = 15 /165 = 0.09
There is 9% error in the model.
In this article, we will be dealing with very simple steps in python to model the Logistic Regression.
We will observe the data, analyze it, visualize it, clean the data, build a logistic regression model, split into train and test data, make predictions and finally evaluate it. All these will be done step by step. The Data we will deal with is the ‘Titanic Data Set’ available in kaggle.com. This is a very famous dataset and often a student’s first step towards learning Machine Learning based on classification. We are trying to predict the classification: Survival or deceased
First, we will import the numpy and pandas libraries:
import numpy as npimport pandas as pd
Let us do the visualization imports:
import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline
We’ll proceed by importing the Titanic data set into a pandas dataframe. After that, we’ll be checking the head of the dataframe just to get a clear idea of all the columns in the dataframe.
train=pd.read_csv('titanic_train.csv')train.head()
Most of the data that we come across has missing data. We’ll check for missing data, also visualize them to get a better idea and remove them.
train.isnull()
Here, we find boolean values. True indicating that the value is null and False the vice versa. Since there are a lot of data, we use the seaborn library to visualize the null values. In that case, our task becomes much easier.
sns.heatmap(train.isnull())
The Age and Cabin column have null values. I have dealt with the problem of dealing with NA values in my previous blog. Please have a look at it.
It is always a good practice to play around with the data and fully exploit the visualization libraries to have fun with the data.
sns.countplot(x='Survived',data=train)
This is a count plot that shows the number of people who survived which is our target variable. Further, we can plot count plots on the basis of gender and passenger class.
sns.countplot(x='Survived',hue='Sex',data=train)
Here, we see a trend that more females survived than males.
sns.countplot(x='Survived',hue='Pclass',data=train)
From the above plot, we can infer that passengers belonging to class 3 died the most.
There are many more ways by which we can visualize data. However, I’m not discussing them here because we need to get to the step of model building.
We want to fill in the missing age data instead of just dropping the missing age data rows. One way to do this is by filling in the mean age of all the passengers (imputation). However, we can be smarter about this and check the average age by passenger class. For example:
plt.figure(figsize=(12, 7))sns.boxplot(x='Pclass',y='Age',data=train,palette='winter')
We can see the wealthier passengers in the higher classes tend to be older, which makes sense. We’ll use these average age values to impute based on Pclass for Age.
def impute_age(cols): Age = cols[0] Pclass = cols[1] if pd.isnull(Age):if Pclass == 1: return 37elif Pclass == 2: return 29else: return 24else: return Age
Now apply that function!
train['Age'] = train[['Age','Pclass']].apply(impute_age,axis=1)
Now let’s check that heat map again.
sns.heatmap(train.isnull(),yticklabels=False,cbar=False)
Great! Let’s go ahead and drop the Cabin column.
train.drop('Cabin',axis=1,inplace=True)
We’ll need to convert categorical features to dummy variables using pandas! Otherwise, our machine learning algorithm won’t be able to directly take in those features as inputs.
train.info()
sex = pd.get_dummies(train['Sex'],drop_first=True)embark = pd.get_dummies(train['Embarked'],drop_first=True)
Here, we are dummying the sex and embark columns. After dummying, we will drop the rest of the columns which are not needed.
train.drop(['Sex','Embarked','Name','Ticket'],axis=1,inplace=True)
We will concatenate the new sex and embarked columns to the dataframe.
train = pd.concat([train,sex,embark],axis=1)
Now, the dataframe looks like this:
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(train.drop('Survived',axis=1), train['Survived'], test_size=0.30, random_state=101)
from sklearn.linear_model import LogisticRegressionlogmodel = LogisticRegression()logmodel.fit(X_train,y_train)predictions = logmodel.predict(X_test)
We can check precision, recall,f1-score using classification report
from sklearn.metrics import classification_reportprint(classification_report(y_test,predictions))
|
[
{
"code": null,
"e": 547,
"s": 172,
"text": "In Logistic Regression, we wish to model a dependent variable(Y) in terms of one or more independent variables(X). It is a method for classification. This algorithm is used for the dependent variable that is Categorical. Y is modeled using a function that gives output between 0 and 1 for all values of X. In Logistic Regression, the Sigmoid (aka Logistic) Function is used."
},
{
"code": null,
"e": 924,
"s": 547,
"text": "After we train a logistic regression model on some training data, we will evaluate the performance of the model on some test data. For this, we use the Confusion Matrix. A Confusion Matrix is a table that is often used to describe the performance of the classification model on a set of test data for which the true values are already known. Given below is a Confusion Matrix."
},
{
"code": null,
"e": 1344,
"s": 924,
"text": "Here, TP stands for True Positive which are the cases in which we predicted yes and the actual value was true. TN stands for True Negative which are the cases in which we predicted no and the actual value was false.FP stands for False Positive which are the cases which we predicted yes and the actual value was False.FN stands for False Negative which are the cases which we predicted No and the actual value was true."
},
{
"code": null,
"e": 1504,
"s": 1344,
"text": "Confusion Matrix helps us determine how often the model prediction is correct or in other words, the accuracy of the model. By the above table, It is given by:"
},
{
"code": null,
"e": 1548,
"s": 1504,
"text": "( TP + TN ) / Total = 100 + 50 / 165 = 0.91"
},
{
"code": null,
"e": 1669,
"s": 1548,
"text": "This means that the model is 91% correct. The Confusion Matrix is also used to measure the error rate which is given by:"
},
{
"code": null,
"e": 1706,
"s": 1669,
"text": "( FP + FN ) / Total = 15 /165 = 0.09"
},
{
"code": null,
"e": 1738,
"s": 1706,
"text": "There is 9% error in the model."
},
{
"code": null,
"e": 1841,
"s": 1738,
"text": "In this article, we will be dealing with very simple steps in python to model the Logistic Regression."
},
{
"code": null,
"e": 2321,
"s": 1841,
"text": "We will observe the data, analyze it, visualize it, clean the data, build a logistic regression model, split into train and test data, make predictions and finally evaluate it. All these will be done step by step. The Data we will deal with is the ‘Titanic Data Set’ available in kaggle.com. This is a very famous dataset and often a student’s first step towards learning Machine Learning based on classification. We are trying to predict the classification: Survival or deceased"
},
{
"code": null,
"e": 2375,
"s": 2321,
"text": "First, we will import the numpy and pandas libraries:"
},
{
"code": null,
"e": 2413,
"s": 2375,
"text": "import numpy as npimport pandas as pd"
},
{
"code": null,
"e": 2450,
"s": 2413,
"text": "Let us do the visualization imports:"
},
{
"code": null,
"e": 2521,
"s": 2450,
"text": "import matplotlib.pyplot as pltimport seaborn as sns%matplotlib inline"
},
{
"code": null,
"e": 2712,
"s": 2521,
"text": "We’ll proceed by importing the Titanic data set into a pandas dataframe. After that, we’ll be checking the head of the dataframe just to get a clear idea of all the columns in the dataframe."
},
{
"code": null,
"e": 2763,
"s": 2712,
"text": "train=pd.read_csv('titanic_train.csv')train.head()"
},
{
"code": null,
"e": 2906,
"s": 2763,
"text": "Most of the data that we come across has missing data. We’ll check for missing data, also visualize them to get a better idea and remove them."
},
{
"code": null,
"e": 2921,
"s": 2906,
"text": "train.isnull()"
},
{
"code": null,
"e": 3148,
"s": 2921,
"text": "Here, we find boolean values. True indicating that the value is null and False the vice versa. Since there are a lot of data, we use the seaborn library to visualize the null values. In that case, our task becomes much easier."
},
{
"code": null,
"e": 3176,
"s": 3148,
"text": "sns.heatmap(train.isnull())"
},
{
"code": null,
"e": 3322,
"s": 3176,
"text": "The Age and Cabin column have null values. I have dealt with the problem of dealing with NA values in my previous blog. Please have a look at it."
},
{
"code": null,
"e": 3453,
"s": 3322,
"text": "It is always a good practice to play around with the data and fully exploit the visualization libraries to have fun with the data."
},
{
"code": null,
"e": 3492,
"s": 3453,
"text": "sns.countplot(x='Survived',data=train)"
},
{
"code": null,
"e": 3665,
"s": 3492,
"text": "This is a count plot that shows the number of people who survived which is our target variable. Further, we can plot count plots on the basis of gender and passenger class."
},
{
"code": null,
"e": 3714,
"s": 3665,
"text": "sns.countplot(x='Survived',hue='Sex',data=train)"
},
{
"code": null,
"e": 3774,
"s": 3714,
"text": "Here, we see a trend that more females survived than males."
},
{
"code": null,
"e": 3826,
"s": 3774,
"text": "sns.countplot(x='Survived',hue='Pclass',data=train)"
},
{
"code": null,
"e": 3912,
"s": 3826,
"text": "From the above plot, we can infer that passengers belonging to class 3 died the most."
},
{
"code": null,
"e": 4061,
"s": 3912,
"text": "There are many more ways by which we can visualize data. However, I’m not discussing them here because we need to get to the step of model building."
},
{
"code": null,
"e": 4335,
"s": 4061,
"text": "We want to fill in the missing age data instead of just dropping the missing age data rows. One way to do this is by filling in the mean age of all the passengers (imputation). However, we can be smarter about this and check the average age by passenger class. For example:"
},
{
"code": null,
"e": 4422,
"s": 4335,
"text": "plt.figure(figsize=(12, 7))sns.boxplot(x='Pclass',y='Age',data=train,palette='winter')"
},
{
"code": null,
"e": 4587,
"s": 4422,
"text": "We can see the wealthier passengers in the higher classes tend to be older, which makes sense. We’ll use these average age values to impute based on Pclass for Age."
},
{
"code": null,
"e": 4795,
"s": 4587,
"text": "def impute_age(cols): Age = cols[0] Pclass = cols[1] if pd.isnull(Age):if Pclass == 1: return 37elif Pclass == 2: return 29else: return 24else: return Age"
},
{
"code": null,
"e": 4820,
"s": 4795,
"text": "Now apply that function!"
},
{
"code": null,
"e": 4884,
"s": 4820,
"text": "train['Age'] = train[['Age','Pclass']].apply(impute_age,axis=1)"
},
{
"code": null,
"e": 4921,
"s": 4884,
"text": "Now let’s check that heat map again."
},
{
"code": null,
"e": 4978,
"s": 4921,
"text": "sns.heatmap(train.isnull(),yticklabels=False,cbar=False)"
},
{
"code": null,
"e": 5027,
"s": 4978,
"text": "Great! Let’s go ahead and drop the Cabin column."
},
{
"code": null,
"e": 5067,
"s": 5027,
"text": "train.drop('Cabin',axis=1,inplace=True)"
},
{
"code": null,
"e": 5245,
"s": 5067,
"text": "We’ll need to convert categorical features to dummy variables using pandas! Otherwise, our machine learning algorithm won’t be able to directly take in those features as inputs."
},
{
"code": null,
"e": 5258,
"s": 5245,
"text": "train.info()"
},
{
"code": null,
"e": 5367,
"s": 5258,
"text": "sex = pd.get_dummies(train['Sex'],drop_first=True)embark = pd.get_dummies(train['Embarked'],drop_first=True)"
},
{
"code": null,
"e": 5492,
"s": 5367,
"text": "Here, we are dummying the sex and embark columns. After dummying, we will drop the rest of the columns which are not needed."
},
{
"code": null,
"e": 5559,
"s": 5492,
"text": "train.drop(['Sex','Embarked','Name','Ticket'],axis=1,inplace=True)"
},
{
"code": null,
"e": 5630,
"s": 5559,
"text": "We will concatenate the new sex and embarked columns to the dataframe."
},
{
"code": null,
"e": 5675,
"s": 5630,
"text": "train = pd.concat([train,sex,embark],axis=1)"
},
{
"code": null,
"e": 5711,
"s": 5675,
"text": "Now, the dataframe looks like this:"
},
{
"code": null,
"e": 6003,
"s": 5711,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(train.drop('Survived',axis=1), train['Survived'], test_size=0.30, random_state=101)"
},
{
"code": null,
"e": 6153,
"s": 6003,
"text": "from sklearn.linear_model import LogisticRegressionlogmodel = LogisticRegression()logmodel.fit(X_train,y_train)predictions = logmodel.predict(X_test)"
},
{
"code": null,
"e": 6221,
"s": 6153,
"text": "We can check precision, recall,f1-score using classification report"
}
] |
Python | Pandas Timestamp.time - GeeksforGeeks
|
14 Jan, 2019
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.
Pandas Timestamp.time() function return time object with same time but with tzinfo equal to None.
Syntax :Timestamp.time()
Parameters : None
Return : datetime object
Example #1: Use Timestamp.time() function to return the time from the given Timestamp object.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.time() function to return the time
# return timets.time()
Output :
As we can see in the output, the Timestamp.time() function has returned the time of the given Timestamp object. Notice the given object is not aware of the timezone. Example #2: Use Timestamp.time() function to return the time from the given Timestamp object.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.time() function to return the time
# return timets.time()
Output :
As we can see in the output, the Timestamp.time() function has returned the time of the given Timestamp object. Notice the given object is not aware of the timezone.
Python Pandas-Timestamp
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25441,
"s": 25413,
"text": "\n14 Jan, 2019"
},
{
"code": null,
"e": 25655,
"s": 25441,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 25753,
"s": 25655,
"text": "Pandas Timestamp.time() function return time object with same time but with tzinfo equal to None."
},
{
"code": null,
"e": 25778,
"s": 25753,
"text": "Syntax :Timestamp.time()"
},
{
"code": null,
"e": 25796,
"s": 25778,
"text": "Parameters : None"
},
{
"code": null,
"e": 25821,
"s": 25796,
"text": "Return : datetime object"
},
{
"code": null,
"e": 25915,
"s": 25821,
"text": "Example #1: Use Timestamp.time() function to return the time from the given Timestamp object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)",
"e": 26135,
"s": 25915,
"text": null
},
{
"code": null,
"e": 26144,
"s": 26135,
"text": "Output :"
},
{
"code": null,
"e": 26209,
"s": 26144,
"text": "Now we will use the Timestamp.time() function to return the time"
},
{
"code": "# return timets.time()",
"e": 26232,
"s": 26209,
"text": null
},
{
"code": null,
"e": 26241,
"s": 26232,
"text": "Output :"
},
{
"code": null,
"e": 26501,
"s": 26241,
"text": "As we can see in the output, the Timestamp.time() function has returned the time of the given Timestamp object. Notice the given object is not aware of the timezone. Example #2: Use Timestamp.time() function to return the time from the given Timestamp object."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)",
"e": 26717,
"s": 26501,
"text": null
},
{
"code": null,
"e": 26726,
"s": 26717,
"text": "Output :"
},
{
"code": null,
"e": 26791,
"s": 26726,
"text": "Now we will use the Timestamp.time() function to return the time"
},
{
"code": "# return timets.time()",
"e": 26814,
"s": 26791,
"text": null
},
{
"code": null,
"e": 26823,
"s": 26814,
"text": "Output :"
},
{
"code": null,
"e": 26989,
"s": 26823,
"text": "As we can see in the output, the Timestamp.time() function has returned the time of the given Timestamp object. Notice the given object is not aware of the timezone."
},
{
"code": null,
"e": 27013,
"s": 26989,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 27027,
"s": 27013,
"text": "Python-pandas"
},
{
"code": null,
"e": 27034,
"s": 27027,
"text": "Python"
},
{
"code": null,
"e": 27132,
"s": 27034,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27150,
"s": 27132,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27185,
"s": 27150,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27217,
"s": 27185,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27239,
"s": 27217,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27281,
"s": 27239,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27311,
"s": 27281,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27337,
"s": 27311,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27381,
"s": 27337,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27410,
"s": 27381,
"text": "*args and **kwargs in Python"
}
] |
HTML | DOM Input Range step Property - GeeksforGeeks
|
29 Mar, 2019
The DOM Input Range step Property in HTML DOM is used to set or return the value of the step attribute of the slider control. The step attribute is used to specify the size of space between two values. This attribute can be used with both min and max to create a range of values.
Syntax:
It returns the Input Range step Property:rangeObject.step
rangeObject.step
It is used to set Input Range step Property:rangeObject.step = number
rangeObject.step = number
Property Values: It contains single value number which specify the size of steps. The default value of steps is 1.
Return Values: It return a number which represents the increment between values.
Example-1:
<!DOCTYPE html><html> <head> <title> DOM Input Range step Property </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM Input Range step Property </h2> <input type="range" id="myRange" step="15"> <br> <br> <button onclick="myGeeks()"> Click Here! </button> <p id="GFG" style="font-size:23px; color:green;"> </p> <script> function myGeeks() { // Accessing input value var x = document.getElementById( "myRange").step; document.getElementById( "GFG").innerHTML = x; } </script> </body> </html>
Output:Before Click on button:
After Click on button:
Example-2:
<!DOCTYPE html><html> <head> <title> DOM Input Range step Property </title></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h2> DOM Input Range step Property </h2> <input type="range" id="myRange" step="15"> <br> <br> <button onclick="myGeeks()"> Click Here! </button> <p id="GFG" style="font-size:23px; color:green;"> </p> <script> function myGeeks() { // Accessing input value var x = document.getElementById( "myRange").step = "25"; document.getElementById( "GFG").innerHTML = "The value of the step attribute"+ " was changed to " + x; } </script> </body> </html>
Output:Before Click on button:
After Click on button:
Supported Browsers: The browser supported by DOM Input Range step Property are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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 ?
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26190,
"s": 26162,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 26470,
"s": 26190,
"text": "The DOM Input Range step Property in HTML DOM is used to set or return the value of the step attribute of the slider control. The step attribute is used to specify the size of space between two values. This attribute can be used with both min and max to create a range of values."
},
{
"code": null,
"e": 26478,
"s": 26470,
"text": "Syntax:"
},
{
"code": null,
"e": 26536,
"s": 26478,
"text": "It returns the Input Range step Property:rangeObject.step"
},
{
"code": null,
"e": 26553,
"s": 26536,
"text": "rangeObject.step"
},
{
"code": null,
"e": 26623,
"s": 26553,
"text": "It is used to set Input Range step Property:rangeObject.step = number"
},
{
"code": null,
"e": 26649,
"s": 26623,
"text": "rangeObject.step = number"
},
{
"code": null,
"e": 26764,
"s": 26649,
"text": "Property Values: It contains single value number which specify the size of steps. The default value of steps is 1."
},
{
"code": null,
"e": 26845,
"s": 26764,
"text": "Return Values: It return a number which represents the increment between values."
},
{
"code": null,
"e": 26856,
"s": 26845,
"text": "Example-1:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM Input Range step Property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM Input Range step Property </h2> <input type=\"range\" id=\"myRange\" step=\"15\"> <br> <br> <button onclick=\"myGeeks()\"> Click Here! </button> <p id=\"GFG\" style=\"font-size:23px; color:green;\"> </p> <script> function myGeeks() { // Accessing input value var x = document.getElementById( \"myRange\").step; document.getElementById( \"GFG\").innerHTML = x; } </script> </body> </html>",
"e": 27643,
"s": 26856,
"text": null
},
{
"code": null,
"e": 27674,
"s": 27643,
"text": "Output:Before Click on button:"
},
{
"code": null,
"e": 27697,
"s": 27674,
"text": "After Click on button:"
},
{
"code": null,
"e": 27708,
"s": 27697,
"text": "Example-2:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> DOM Input Range step Property </title></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <h2> DOM Input Range step Property </h2> <input type=\"range\" id=\"myRange\" step=\"15\"> <br> <br> <button onclick=\"myGeeks()\"> Click Here! </button> <p id=\"GFG\" style=\"font-size:23px; color:green;\"> </p> <script> function myGeeks() { // Accessing input value var x = document.getElementById( \"myRange\").step = \"25\"; document.getElementById( \"GFG\").innerHTML = \"The value of the step attribute\"+ \" was changed to \" + x; } </script> </body> </html>",
"e": 28576,
"s": 27708,
"text": null
},
{
"code": null,
"e": 28607,
"s": 28576,
"text": "Output:Before Click on button:"
},
{
"code": null,
"e": 28630,
"s": 28607,
"text": "After Click on button:"
},
{
"code": null,
"e": 28723,
"s": 28630,
"text": "Supported Browsers: The browser supported by DOM Input Range step Property are listed below:"
},
{
"code": null,
"e": 28737,
"s": 28723,
"text": "Google Chrome"
},
{
"code": null,
"e": 28755,
"s": 28737,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28763,
"s": 28755,
"text": "Firefox"
},
{
"code": null,
"e": 28770,
"s": 28763,
"text": "Safari"
},
{
"code": null,
"e": 28776,
"s": 28770,
"text": "Opera"
},
{
"code": null,
"e": 28913,
"s": 28776,
"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": 28922,
"s": 28913,
"text": "HTML-DOM"
},
{
"code": null,
"e": 28927,
"s": 28922,
"text": "HTML"
},
{
"code": null,
"e": 28944,
"s": 28927,
"text": "Web Technologies"
},
{
"code": null,
"e": 28949,
"s": 28944,
"text": "HTML"
},
{
"code": null,
"e": 29047,
"s": 28949,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29071,
"s": 29047,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29112,
"s": 29071,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 29149,
"s": 29112,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29178,
"s": 29149,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29198,
"s": 29178,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29238,
"s": 29198,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29271,
"s": 29238,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29316,
"s": 29271,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29359,
"s": 29316,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
PostgreSQL - Subquery - GeeksforGeeks
|
28 Aug, 2020
In this article we will discuss the process of constructing complex queries using the PostgreSQL subquery. Subqueries in the simplest term can be defined as multiple queries disguised in a single PostgreSQL command.For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Now, let’s look into a few examples of PostgreSQL subqueries.Example 1:Here we will query for all films whose rental rate is higher than the average rental rate from the “film” table of our sample database. For that we will need to find the average rental rate by using the SELECT statement and average function( AVG). Then use the result of the first query in the second SELECT statement to find the films that has higher rental rate than the average.
SELECT
AVG (rental_rate)
FROM
film;
Output:Now we will query for films whose rental rate is higher than the average rental rate.
SELECT
film_id,
title,
rental_rate
FROM
film
WHERE
rental_rate > 2.98;
Output:
As you can observe the above query is not too elegant and requires an unnecessary amount of multiple queries.This can be avoided by using PostgreSQL subqueries as below.
SELECT
film_id,
title,
rental_rate
FROM
film
WHERE
rental_rate > (
SELECT
AVG (rental_rate)
FROM
film
);
Output:
A couple of this to notice about the sequence of execution of the above query:
First, executes the subquery.
Second, gets the result and passes it to the outer query.
Third, executes the outer query.
Example 2:Here we will query for all films that have the returned date between 2005-05-29 and 2005-05-30, using the IN operator in the “rental” table of our sample database.
SELECT
film_id,
title
FROM
film
WHERE
film_id IN (
SELECT
inventory.film_id
FROM
rental
INNER JOIN inventory ON inventory.inventory_id = rental.inventory_id
WHERE
return_date BETWEEN '2005-05-29'
AND '2005-05-30'
);
Output:
postgreSQL-basics
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - Copy Table
PostgreSQL - REPLACE Function
PostgreSQL - TIME Data Type
PostgreSQL - CREATE SCHEMA
PostgreSQL - Cursor
PostgreSQL - SELECT
PostgreSQL - ROW_NUMBER Function
|
[
{
"code": null,
"e": 25479,
"s": 25451,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 26312,
"s": 25479,
"text": "In this article we will discuss the process of constructing complex queries using the PostgreSQL subquery. Subqueries in the simplest term can be defined as multiple queries disguised in a single PostgreSQL command.For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link in our examples.Now, let’s look into a few examples of PostgreSQL subqueries.Example 1:Here we will query for all films whose rental rate is higher than the average rental rate from the “film” table of our sample database. For that we will need to find the average rental rate by using the SELECT statement and average function( AVG). Then use the result of the first query in the second SELECT statement to find the films that has higher rental rate than the average."
},
{
"code": null,
"e": 26356,
"s": 26312,
"text": "SELECT\n AVG (rental_rate)\nFROM\n film;"
},
{
"code": null,
"e": 26449,
"s": 26356,
"text": "Output:Now we will query for films whose rental rate is higher than the average rental rate."
},
{
"code": null,
"e": 26540,
"s": 26449,
"text": "SELECT\n film_id,\n title,\n rental_rate\nFROM\n film\nWHERE\n rental_rate > 2.98;"
},
{
"code": null,
"e": 26548,
"s": 26540,
"text": "Output:"
},
{
"code": null,
"e": 26718,
"s": 26548,
"text": "As you can observe the above query is not too elegant and requires an unnecessary amount of multiple queries.This can be avoided by using PostgreSQL subqueries as below."
},
{
"code": null,
"e": 26887,
"s": 26718,
"text": "SELECT\n film_id,\n title,\n rental_rate\nFROM\n film\nWHERE\n rental_rate > (\n SELECT\n AVG (rental_rate)\n FROM\n film\n );"
},
{
"code": null,
"e": 26895,
"s": 26887,
"text": "Output:"
},
{
"code": null,
"e": 26974,
"s": 26895,
"text": "A couple of this to notice about the sequence of execution of the above query:"
},
{
"code": null,
"e": 27004,
"s": 26974,
"text": "First, executes the subquery."
},
{
"code": null,
"e": 27062,
"s": 27004,
"text": "Second, gets the result and passes it to the outer query."
},
{
"code": null,
"e": 27095,
"s": 27062,
"text": "Third, executes the outer query."
},
{
"code": null,
"e": 27269,
"s": 27095,
"text": "Example 2:Here we will query for all films that have the returned date between 2005-05-29 and 2005-05-30, using the IN operator in the “rental” table of our sample database."
},
{
"code": null,
"e": 27581,
"s": 27269,
"text": "SELECT\n film_id,\n title\nFROM\n film\nWHERE\n film_id IN (\n SELECT\n inventory.film_id\n FROM\n rental\n INNER JOIN inventory ON inventory.inventory_id = rental.inventory_id\n WHERE\n return_date BETWEEN '2005-05-29'\n AND '2005-05-30'\n );"
},
{
"code": null,
"e": 27589,
"s": 27581,
"text": "Output:"
},
{
"code": null,
"e": 27607,
"s": 27589,
"text": "postgreSQL-basics"
},
{
"code": null,
"e": 27618,
"s": 27607,
"text": "PostgreSQL"
},
{
"code": null,
"e": 27716,
"s": 27618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27746,
"s": 27716,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 27775,
"s": 27746,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 27799,
"s": 27775,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 27823,
"s": 27799,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 27853,
"s": 27823,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 27881,
"s": 27853,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 27908,
"s": 27881,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 27928,
"s": 27908,
"text": "PostgreSQL - Cursor"
},
{
"code": null,
"e": 27948,
"s": 27928,
"text": "PostgreSQL - SELECT"
}
] |
How to Find the Antilog of Values in R? - GeeksforGeeks
|
22 Dec, 2021
The antilog or anti-logarithm is the inverse process of finding log or logarithm. If q is the value of logb p then p is the antilog of q to the base b that is, q = logb p then p = antilogb q
Examples,
antilog2 3 = 8, since 23 yields 8
antilog4 2 = 16, since 42 yields 16
antilog10 4 = 10000, since 104 yields 10000
The antilog or anti-logarithm of a number, number to base, the base can be calculated as,
Syntax:
basenumber
Here,
base: a positive integer (base of antilog)
number: an integer whose antilog to be computed
Return type:
a positive integer: antilog of number to base
Example 1:
In this example, we will see how we can calculate antilog of the following positive numbers,
antilog2 (3)
antilog4 (2)
antilog10 (4)
antiloge (4.60517018598809)
Since antilog2 (3) is equal to 23 = 8, antilog4 (2) is equal to 42 = 16 and antilog10 (4) is equal to 104 = 10000 we can calculate these values with the help of exponentiation operator (^) in R. We can also compute the antilogarithm of a number to base e by passing a single parameter to the exp() inbuilt function.
R
# R program to illustrate how we can# compute antilog # An integer whose antilog to be computednumber = 3 # Initializing basebase = 2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste("The value of antilog2(3) is equal to", answer)) # Initializing basebase = 4 # An integer whose antilog to be computednumber = 2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste("The value of antilog4(2) is equal to", answer)) # An integer whose antilog to be computednumber = 4 # Initializing basebase = 10 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste("The value of antilog2(3) is equal to", answer)) # An integer whose antilog to be computednumber = 4.60517018598809 # Print the value of antilogprint(paste("The value of antiloge(4.60517018598809) is equal to", exp(number)))
Output:
Example 2:
In this example, we will see how we can calculate antilog of the following negative numbers,
antilog2 (-3)
antilog4 (-2)
antilog10 (-4)
antiloge (-4.60517018598809)
Since antilog2 (-3) is equal to 2-3 = 1 / 8 , antilog4 (-2) is equal to 4-2 = 1 / 16 and antilog10 (-4) is equal to 10-4 = 1 / 10000 we can calculate these value with the help of exponentiation operator (^) in R. We can also compute the antilogarithm of a number to base e by passing a single parameter to the exp() inbuilt function.
R
# R program to illustrate how we can compute antilog # An integer whose antilog to be computednumber = -3 # Initializing basebase = 2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste("The value of antilog2(-3) is equal to", answer)) # Initializing basebase = 4 # An integer whose antilog to be computednumber = -2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste("The value of antilog4(-2) is equal to", answer)) # An integer whose antilog to be computednumber = -4 # Initializing basebase = 10 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste("The value of antilog10(-4) is equal to", answer)) # An integer whose antilog to be computednumber = -4.60517018598809 # Print the value of antilogprint(paste("The value of antiloge(-4.60517018598809) is equal to", exp(number)))
Output:
anikakapoor
Picked
R-Mathematics
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 Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
Time Series Analysis in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 26788,
"s": 26597,
"text": "The antilog or anti-logarithm is the inverse process of finding log or logarithm. If q is the value of logb p then p is the antilog of q to the base b that is, q = logb p then p = antilogb q"
},
{
"code": null,
"e": 26798,
"s": 26788,
"text": "Examples,"
},
{
"code": null,
"e": 26832,
"s": 26798,
"text": "antilog2 3 = 8, since 23 yields 8"
},
{
"code": null,
"e": 26868,
"s": 26832,
"text": "antilog4 2 = 16, since 42 yields 16"
},
{
"code": null,
"e": 26912,
"s": 26868,
"text": "antilog10 4 = 10000, since 104 yields 10000"
},
{
"code": null,
"e": 27002,
"s": 26912,
"text": "The antilog or anti-logarithm of a number, number to base, the base can be calculated as,"
},
{
"code": null,
"e": 27010,
"s": 27002,
"text": "Syntax:"
},
{
"code": null,
"e": 27021,
"s": 27010,
"text": "basenumber"
},
{
"code": null,
"e": 27027,
"s": 27021,
"text": "Here,"
},
{
"code": null,
"e": 27070,
"s": 27027,
"text": "base: a positive integer (base of antilog)"
},
{
"code": null,
"e": 27118,
"s": 27070,
"text": "number: an integer whose antilog to be computed"
},
{
"code": null,
"e": 27131,
"s": 27118,
"text": "Return type:"
},
{
"code": null,
"e": 27178,
"s": 27131,
"text": "a positive integer: antilog of number to base "
},
{
"code": null,
"e": 27189,
"s": 27178,
"text": "Example 1:"
},
{
"code": null,
"e": 27282,
"s": 27189,
"text": "In this example, we will see how we can calculate antilog of the following positive numbers,"
},
{
"code": null,
"e": 27295,
"s": 27282,
"text": "antilog2 (3)"
},
{
"code": null,
"e": 27308,
"s": 27295,
"text": "antilog4 (2)"
},
{
"code": null,
"e": 27322,
"s": 27308,
"text": "antilog10 (4)"
},
{
"code": null,
"e": 27350,
"s": 27322,
"text": "antiloge (4.60517018598809)"
},
{
"code": null,
"e": 27667,
"s": 27350,
"text": "Since antilog2 (3) is equal to 23 = 8, antilog4 (2) is equal to 42 = 16 and antilog10 (4) is equal to 104 = 10000 we can calculate these values with the help of exponentiation operator (^) in R. We can also compute the antilogarithm of a number to base e by passing a single parameter to the exp() inbuilt function. "
},
{
"code": null,
"e": 27669,
"s": 27667,
"text": "R"
},
{
"code": "# R program to illustrate how we can# compute antilog # An integer whose antilog to be computednumber = 3 # Initializing basebase = 2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste(\"The value of antilog2(3) is equal to\", answer)) # Initializing basebase = 4 # An integer whose antilog to be computednumber = 2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste(\"The value of antilog4(2) is equal to\", answer)) # An integer whose antilog to be computednumber = 4 # Initializing basebase = 10 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste(\"The value of antilog2(3) is equal to\", answer)) # An integer whose antilog to be computednumber = 4.60517018598809 # Print the value of antilogprint(paste(\"The value of antiloge(4.60517018598809) is equal to\", exp(number)))",
"e": 28552,
"s": 27669,
"text": null
},
{
"code": null,
"e": 28560,
"s": 28552,
"text": "Output:"
},
{
"code": null,
"e": 28571,
"s": 28560,
"text": "Example 2:"
},
{
"code": null,
"e": 28664,
"s": 28571,
"text": "In this example, we will see how we can calculate antilog of the following negative numbers,"
},
{
"code": null,
"e": 28678,
"s": 28664,
"text": "antilog2 (-3)"
},
{
"code": null,
"e": 28692,
"s": 28678,
"text": "antilog4 (-2)"
},
{
"code": null,
"e": 28707,
"s": 28692,
"text": "antilog10 (-4)"
},
{
"code": null,
"e": 28736,
"s": 28707,
"text": "antiloge (-4.60517018598809)"
},
{
"code": null,
"e": 29072,
"s": 28736,
"text": "Since antilog2 (-3) is equal to 2-3 = 1 / 8 , antilog4 (-2) is equal to 4-2 = 1 / 16 and antilog10 (-4) is equal to 10-4 = 1 / 10000 we can calculate these value with the help of exponentiation operator (^) in R. We can also compute the antilogarithm of a number to base e by passing a single parameter to the exp() inbuilt function. "
},
{
"code": null,
"e": 29074,
"s": 29072,
"text": "R"
},
{
"code": "# R program to illustrate how we can compute antilog # An integer whose antilog to be computednumber = -3 # Initializing basebase = 2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste(\"The value of antilog2(-3) is equal to\", answer)) # Initializing basebase = 4 # An integer whose antilog to be computednumber = -2 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste(\"The value of antilog4(-2) is equal to\", answer)) # An integer whose antilog to be computednumber = -4 # Initializing basebase = 10 # Computing antilog valueanswer = base ^ number # Print the value of antilogprint(paste(\"The value of antilog10(-4) is equal to\", answer)) # An integer whose antilog to be computednumber = -4.60517018598809 # Print the value of antilogprint(paste(\"The value of antiloge(-4.60517018598809) is equal to\", exp(number)))",
"e": 29965,
"s": 29074,
"text": null
},
{
"code": null,
"e": 29973,
"s": 29965,
"text": "Output:"
},
{
"code": null,
"e": 29985,
"s": 29973,
"text": "anikakapoor"
},
{
"code": null,
"e": 29992,
"s": 29985,
"text": "Picked"
},
{
"code": null,
"e": 30006,
"s": 29992,
"text": "R-Mathematics"
},
{
"code": null,
"e": 30017,
"s": 30006,
"text": "R Language"
},
{
"code": null,
"e": 30115,
"s": 30017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30167,
"s": 30115,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 30202,
"s": 30167,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30260,
"s": 30202,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30298,
"s": 30260,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30341,
"s": 30298,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30391,
"s": 30341,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 30408,
"s": 30391,
"text": "R - if statement"
},
{
"code": null,
"e": 30457,
"s": 30408,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30494,
"s": 30457,
"text": "How to import an Excel File into R ?"
}
] |
Getting changes from a Git Repository - GeeksforGeeks
|
23 Jan, 2020
Git allows performing various operations on the Repositories including the local repositories and remote repositories. The user when downloads a project to work upon, a local repository is created to store a copy of the original project. This local repository stores the changes that are being made by the user. This way, the user can edit the changes before adding them to the main project. Multiple users can perform work on the same project at the same time by using local repositories.The central repository gets updated every time a user pushes the modifications done on the local repository. These changes do not get updated on the local repository of any other developer that is working on the same project. This might create confusion because different collaborators may end up contributing the same feature in the project. To avoid this, the collaborator updates the local copy on their machine every time before starting the work on their repository. This updation of local copy is done by downloading the recent copy of the project on the central repository. This process of updating the local repository is termed as Pulling or Fetching. Git provides git pull command and git fetch command to do the cloning of the central repository into the local repository.
Pull command: Before starting the work on a project, the collaborator needs to clone his local repository with the central repository in order to get the latest copy of the project. This is done by the use of git pull command. This command updates the local repository immediately after its execution.Syntax:
git pull <remote> <branch-name>
git pull command is a combination of two other commands which are git fetch and git merge.
Attributes of Pull Command:Pulling changes from the central repository can be done along with the use of certain attributes that can be used to perform multiple pull operations on the repository. These attributes can be used to perform specific pulls from the repository. These are:
--no-commit: By default git pull command when called will perform the merging of two branches and then automatically executes the commit operation to create a new commit. But, when the pull operation is called with --no-commit attribute, only the merging process is performed and the commit operation will not take place.Syntax:$ git pull <remote> --no-commit
$ git pull <remote> --no-commit
--rebase: When a git pull command is called it will merge two branches and will create a separate branch which inherits the changes of both the branches being merged. This will create some confusion among the collaborators as an extra branch will be created. To avoid this confusion, this command is used. It will also create a separate branch that inherits the changes from both the branches but, the branch which is to be merged will be removed from the repository.Syntax:$ git pull <remote> <branch-name> --rebase
$ git pull <remote> <branch-name> --rebase
--verbose: This git pull method when called with the --verbose attribute, will display all the files and content that is being downloaded with the pull method. This will also print all the details of the merging process done by git pull.Syntax:$ git pull <remote> --verbose Fetch Command: This command works just like the git pull command, but the only difference between the both is that git fetch command will not perform the merge operation after cloning the repository. This command will update the remote-tracking branches i.e. the local branches that are stored in the remote repository. It will not update the local copy of the branches. This helps to review the changes that are being downloaded before merging those changes with the local repository.git pull command, on the other hand, performs fetching and merging both the operations. Hence, the collaborator will not be able to review the changes that are being downloaded.git pull = git fetch + git mergeAttributes of fetch command:Fetching changes from the central repository can be done along with the use of certain attributes that can be used to perform multiple fetch operations on the repository. These attributes can be used to perform specific fetch operations from the repository. These are:--all: When the fetch command is used with --all attribute, it will fetch all the registered remotes along with their branches in a single call.Syntax:$ git fetch --all--dry-run:This option will actually do not perform any action on the repository but will give a demo for the test run of the command on the repository. It will output the changes or actions that will take place on the execution of command but will not apply them.Syntax:$ git fetch --dry-runHence, git fetch and git pull both commands can be used to update the local repository with the central repository by downloading the latest changes from the central repository.My Personal Notes
arrow_drop_upSave
$ git pull <remote> --verbose
Fetch Command: This command works just like the git pull command, but the only difference between the both is that git fetch command will not perform the merge operation after cloning the repository. This command will update the remote-tracking branches i.e. the local branches that are stored in the remote repository. It will not update the local copy of the branches. This helps to review the changes that are being downloaded before merging those changes with the local repository.git pull command, on the other hand, performs fetching and merging both the operations. Hence, the collaborator will not be able to review the changes that are being downloaded.
git pull = git fetch + git merge
Attributes of fetch command:Fetching changes from the central repository can be done along with the use of certain attributes that can be used to perform multiple fetch operations on the repository. These attributes can be used to perform specific fetch operations from the repository. These are:
--all: When the fetch command is used with --all attribute, it will fetch all the registered remotes along with their branches in a single call.Syntax:$ git fetch --all
$ git fetch --all
--dry-run:This option will actually do not perform any action on the repository but will give a demo for the test run of the command on the repository. It will output the changes or actions that will take place on the execution of command but will not apply them.Syntax:$ git fetch --dry-run
$ git fetch --dry-run
Hence, git fetch and git pull both commands can be used to update the local repository with the central repository by downloading the latest changes from the central repository.
GitHub
Git
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference Between Git Push Origin and Git Push Origin Master
Git - Difference Between Git Fetch and Git Pull
How to Push Git Branch to Remote?
How to Export Eclipse projects to GitHub?
Merge Conflicts and How to handle them
Git - Origin Master
Git - Cherry Pick
How to Set Upstream Branch on Git?
Git - Merge
How to Add Git Credentials in Eclipse?
|
[
{
"code": null,
"e": 25869,
"s": 25841,
"text": "\n23 Jan, 2020"
},
{
"code": null,
"e": 27142,
"s": 25869,
"text": "Git allows performing various operations on the Repositories including the local repositories and remote repositories. The user when downloads a project to work upon, a local repository is created to store a copy of the original project. This local repository stores the changes that are being made by the user. This way, the user can edit the changes before adding them to the main project. Multiple users can perform work on the same project at the same time by using local repositories.The central repository gets updated every time a user pushes the modifications done on the local repository. These changes do not get updated on the local repository of any other developer that is working on the same project. This might create confusion because different collaborators may end up contributing the same feature in the project. To avoid this, the collaborator updates the local copy on their machine every time before starting the work on their repository. This updation of local copy is done by downloading the recent copy of the project on the central repository. This process of updating the local repository is termed as Pulling or Fetching. Git provides git pull command and git fetch command to do the cloning of the central repository into the local repository."
},
{
"code": null,
"e": 27451,
"s": 27142,
"text": "Pull command: Before starting the work on a project, the collaborator needs to clone his local repository with the central repository in order to get the latest copy of the project. This is done by the use of git pull command. This command updates the local repository immediately after its execution.Syntax:"
},
{
"code": null,
"e": 27483,
"s": 27451,
"text": "git pull <remote> <branch-name>"
},
{
"code": null,
"e": 27574,
"s": 27483,
"text": "git pull command is a combination of two other commands which are git fetch and git merge."
},
{
"code": null,
"e": 27857,
"s": 27574,
"text": "Attributes of Pull Command:Pulling changes from the central repository can be done along with the use of certain attributes that can be used to perform multiple pull operations on the repository. These attributes can be used to perform specific pulls from the repository. These are:"
},
{
"code": null,
"e": 28217,
"s": 27857,
"text": "--no-commit: By default git pull command when called will perform the merging of two branches and then automatically executes the commit operation to create a new commit. But, when the pull operation is called with --no-commit attribute, only the merging process is performed and the commit operation will not take place.Syntax:$ git pull <remote> --no-commit"
},
{
"code": null,
"e": 28249,
"s": 28217,
"text": "$ git pull <remote> --no-commit"
},
{
"code": null,
"e": 28766,
"s": 28249,
"text": "--rebase: When a git pull command is called it will merge two branches and will create a separate branch which inherits the changes of both the branches being merged. This will create some confusion among the collaborators as an extra branch will be created. To avoid this confusion, this command is used. It will also create a separate branch that inherits the changes from both the branches but, the branch which is to be merged will be removed from the repository.Syntax:$ git pull <remote> <branch-name> --rebase"
},
{
"code": null,
"e": 28809,
"s": 28766,
"text": "$ git pull <remote> <branch-name> --rebase"
},
{
"code": null,
"e": 30745,
"s": 28809,
"text": "--verbose: This git pull method when called with the --verbose attribute, will display all the files and content that is being downloaded with the pull method. This will also print all the details of the merging process done by git pull.Syntax:$ git pull <remote> --verbose Fetch Command: This command works just like the git pull command, but the only difference between the both is that git fetch command will not perform the merge operation after cloning the repository. This command will update the remote-tracking branches i.e. the local branches that are stored in the remote repository. It will not update the local copy of the branches. This helps to review the changes that are being downloaded before merging those changes with the local repository.git pull command, on the other hand, performs fetching and merging both the operations. Hence, the collaborator will not be able to review the changes that are being downloaded.git pull = git fetch + git mergeAttributes of fetch command:Fetching changes from the central repository can be done along with the use of certain attributes that can be used to perform multiple fetch operations on the repository. These attributes can be used to perform specific fetch operations from the repository. These are:--all: When the fetch command is used with --all attribute, it will fetch all the registered remotes along with their branches in a single call.Syntax:$ git fetch --all--dry-run:This option will actually do not perform any action on the repository but will give a demo for the test run of the command on the repository. It will output the changes or actions that will take place on the execution of command but will not apply them.Syntax:$ git fetch --dry-runHence, git fetch and git pull both commands can be used to update the local repository with the central repository by downloading the latest changes from the central repository.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 30775,
"s": 30745,
"text": "$ git pull <remote> --verbose"
},
{
"code": null,
"e": 31439,
"s": 30775,
"text": " Fetch Command: This command works just like the git pull command, but the only difference between the both is that git fetch command will not perform the merge operation after cloning the repository. This command will update the remote-tracking branches i.e. the local branches that are stored in the remote repository. It will not update the local copy of the branches. This helps to review the changes that are being downloaded before merging those changes with the local repository.git pull command, on the other hand, performs fetching and merging both the operations. Hence, the collaborator will not be able to review the changes that are being downloaded."
},
{
"code": null,
"e": 31472,
"s": 31439,
"text": "git pull = git fetch + git merge"
},
{
"code": null,
"e": 31769,
"s": 31472,
"text": "Attributes of fetch command:Fetching changes from the central repository can be done along with the use of certain attributes that can be used to perform multiple fetch operations on the repository. These attributes can be used to perform specific fetch operations from the repository. These are:"
},
{
"code": null,
"e": 31938,
"s": 31769,
"text": "--all: When the fetch command is used with --all attribute, it will fetch all the registered remotes along with their branches in a single call.Syntax:$ git fetch --all"
},
{
"code": null,
"e": 31956,
"s": 31938,
"text": "$ git fetch --all"
},
{
"code": null,
"e": 32248,
"s": 31956,
"text": "--dry-run:This option will actually do not perform any action on the repository but will give a demo for the test run of the command on the repository. It will output the changes or actions that will take place on the execution of command but will not apply them.Syntax:$ git fetch --dry-run"
},
{
"code": null,
"e": 32270,
"s": 32248,
"text": "$ git fetch --dry-run"
},
{
"code": null,
"e": 32448,
"s": 32270,
"text": "Hence, git fetch and git pull both commands can be used to update the local repository with the central repository by downloading the latest changes from the central repository."
},
{
"code": null,
"e": 32455,
"s": 32448,
"text": "GitHub"
},
{
"code": null,
"e": 32459,
"s": 32455,
"text": "Git"
},
{
"code": null,
"e": 32557,
"s": 32459,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32619,
"s": 32557,
"text": "Difference Between Git Push Origin and Git Push Origin Master"
},
{
"code": null,
"e": 32667,
"s": 32619,
"text": "Git - Difference Between Git Fetch and Git Pull"
},
{
"code": null,
"e": 32701,
"s": 32667,
"text": "How to Push Git Branch to Remote?"
},
{
"code": null,
"e": 32743,
"s": 32701,
"text": "How to Export Eclipse projects to GitHub?"
},
{
"code": null,
"e": 32782,
"s": 32743,
"text": "Merge Conflicts and How to handle them"
},
{
"code": null,
"e": 32802,
"s": 32782,
"text": "Git - Origin Master"
},
{
"code": null,
"e": 32820,
"s": 32802,
"text": "Git - Cherry Pick"
},
{
"code": null,
"e": 32855,
"s": 32820,
"text": "How to Set Upstream Branch on Git?"
},
{
"code": null,
"e": 32867,
"s": 32855,
"text": "Git - Merge"
}
] |
How to show contents of selected row of a table in Bootstrap model using jQuery ? - GeeksforGeeks
|
03 Aug, 2021
The task is to fetch data from a row of the table and show them on the bootstrap model.
Bootstrap model: The Modal component is a kind of dialog box or a popup window that is displayed on top of the present page, on clicking the provided button on the page. However, the Model automatically closes on clicking the model’s backdrop. Moreover, it should be taken into consideration that Bootstrap doesn’t hold nested modals as they generate worse UI experience for the user. Hence, only one modal window is supported at a time.
Approach: We are given data in the form of an HTML table. In our code, we are using jQuery to complete our task. The jQuery code helps to fetch the data from the row of the table and to place it in the body of the bootstrap model. Initially, it finds the location of the required data from the table using find() method. It uses the text() method to fetch textual content from the location and stores them into different variables. Then we form a string containing HTML code to display the data in the body of the model. The empty() method is used to clear the prefilled data in the model body. The append() method is used to place the string in the body of the model.
Code:
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <title>GFG User Details</title> <!-- CSS FOR STYLING THE PAGE --> <style> table { margin: 0 auto; font-size: large; border: 1px solid black; } h1 { text-align: center; color: #006600; font-size: xx-large; font-family: "Gill Sans", "Gill Sans MT", " Calibri", "Trebuchet MS", "sans-serif"; } td { background-color: #e4f5d4; border: 1px solid black; } th, td { font-weight: bold; border: 1px solid black; padding: 10px; text-align: center; } td { font-weight: lighter; } </style> <!-- BOOTSTRAP CSS AND PLUGINS--> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"> </script> <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"> </script> </head> <body> <section> <h1>GeeksForGeeks</h1> <!-- TABLE CONSTRUCTION--> <table id="GFGtable"> <tr> <!-- TABLE HEADING --> <th>GFG UserHandle</th> <th>Practice Problems</th> <th>Coding Score</th> <th>GFG Articles</th> <th>SELECT</th> </tr> <!-- TABLE DATA --> <tr> <td class="gfgusername">User-1</td> <td class="gfgpp">150</td> <td class="gfgscores">100</td> <td class="gfgarticles">30</td> <td><button class="gfgselect bg-secondary" data-toggle="modal" data-target="#gfgmodal"> SELECT</button></td> </tr> <tr> <td class="gfgusername">User-2</td> <td class="gfgpp">100</td> <td class="gfgscores">75</td> <td class="gfgarticles">30</td> <td><button class="gfgselect bg-secondary" data-toggle="modal" data-target="#gfgmodal"> SELECT</button></td> </tr> <tr> <td class="gfgusername">User-3</td> <td class="gfgpp">200</td> <td class="gfgscores">50</td> <td class="gfgarticles">10</td> <td><button class="gfgselect bg-secondary" data-toggle="modal" data-target="#gfgmodal"> SELECT</button></td> </tr> <tr> <td class="gfgusername">User-4</td> <td class="gfgpp">50</td> <td class="gfgscores">5</td> <td class="gfgarticles">2</td> <td> <button class="gfgselect bg-secondary" data-toggle="modal" data-target="#gfgmodal"> SELECT</button></td> </tr> <tr> <td class="gfgusername">User-5</td> <td class="gfgpp">0</td> <td class="gfgscores">0</td> <td class="gfgarticles">0</td> <td><button class="gfgselect bg-secondary" data-toggle="modal" data-target="#gfgmodal"> SELECT</button></td> </tr> </table> </section> <script> $(function () { // ON SELECTING ROW $(".gfgselect").click(function () { //FINDING ELEMENTS OF ROWS AND STORING THEM IN VARIABLES var a = $(this).parents("tr").find(".gfgusername").text(); var c = $(this).parents("tr").find(".gfgpp").text(); var d = $(this).parents("tr").find(".gfgscores").text(); var e = $(this).parents("tr").find(".gfgarticles").text(); var p = ""; // CREATING DATA TO SHOW ON MODEL p += "<p id='a' name='GFGusername' >GFG UserHandle: " + a + " </p>"; p += "<p id='c' name='GFGpp'>Practice Problems: " + c + "</p>"; p += "<p id='d' name='GFGscores' >Coding Score: " + d + " </p>"; p += "<p id='e' name='GFGcoding' >GFG Article: " + e + " </p>"; //CLEARING THE PREFILLED DATA $("#divGFG").empty(); //WRITING THE DATA ON MODEL $("#divGFG").append(p); }); }); </script> <!-- CREATING BOOTSTRAP MODEL --> <div class="modal fade" id="gfgmodal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <!-- MODEL TITLE --> <h2 class="modal-title" id="gfgmodallabel"> Selected row</h2> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true"> ×</span> </button> </div> <!-- MODEL BODY --> <div class="modal-body"> <div class="GFGclass" id="divGFG"></div> <div class="modal-footer"> <!-- The close button in the bottom of the modal --> <button type="button" class="btn btn-secondary" data-dismiss="modal"> Close</button> </div> </div> </div> </div> </div> </body></html>
Output:
On triggering select button beside row 1:
On triggering select button beside row 2:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Bootstrap-Misc
Bootstrap
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
How to keep gap between columns using Bootstrap?
How to change the background color of the active nav-item?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
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
|
[
{
"code": null,
"e": 26287,
"s": 26259,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 26375,
"s": 26287,
"text": "The task is to fetch data from a row of the table and show them on the bootstrap model."
},
{
"code": null,
"e": 26813,
"s": 26375,
"text": "Bootstrap model: The Modal component is a kind of dialog box or a popup window that is displayed on top of the present page, on clicking the provided button on the page. However, the Model automatically closes on clicking the model’s backdrop. Moreover, it should be taken into consideration that Bootstrap doesn’t hold nested modals as they generate worse UI experience for the user. Hence, only one modal window is supported at a time."
},
{
"code": null,
"e": 27482,
"s": 26813,
"text": "Approach: We are given data in the form of an HTML table. In our code, we are using jQuery to complete our task. The jQuery code helps to fetch the data from the row of the table and to place it in the body of the bootstrap model. Initially, it finds the location of the required data from the table using find() method. It uses the text() method to fetch textual content from the location and stores them into different variables. Then we form a string containing HTML code to display the data in the body of the model. The empty() method is used to clear the prefilled data in the model body. The append() method is used to place the string in the body of the model."
},
{
"code": null,
"e": 27488,
"s": 27482,
"text": "Code:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <title>GFG User Details</title> <!-- CSS FOR STYLING THE PAGE --> <style> table { margin: 0 auto; font-size: large; border: 1px solid black; } h1 { text-align: center; color: #006600; font-size: xx-large; font-family: \"Gill Sans\", \"Gill Sans MT\", \" Calibri\", \"Trebuchet MS\", \"sans-serif\"; } td { background-color: #e4f5d4; border: 1px solid black; } th, td { font-weight: bold; border: 1px solid black; padding: 10px; text-align: center; } td { font-weight: lighter; } </style> <!-- BOOTSTRAP CSS AND PLUGINS--> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css\" integrity=\"sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk\" crossorigin=\"anonymous\" /> <script src=\"https://code.jquery.com/jquery-3.2.1.slim.min.js\" integrity=\"sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js\" integrity=\"sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q\" crossorigin=\"anonymous\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js\" integrity=\"sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl\" crossorigin=\"anonymous\"> </script> <script src=\"https://code.jquery.com/jquery-3.5.1.js\" integrity=\"sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=\" crossorigin=\"anonymous\"> </script> </head> <body> <section> <h1>GeeksForGeeks</h1> <!-- TABLE CONSTRUCTION--> <table id=\"GFGtable\"> <tr> <!-- TABLE HEADING --> <th>GFG UserHandle</th> <th>Practice Problems</th> <th>Coding Score</th> <th>GFG Articles</th> <th>SELECT</th> </tr> <!-- TABLE DATA --> <tr> <td class=\"gfgusername\">User-1</td> <td class=\"gfgpp\">150</td> <td class=\"gfgscores\">100</td> <td class=\"gfgarticles\">30</td> <td><button class=\"gfgselect bg-secondary\" data-toggle=\"modal\" data-target=\"#gfgmodal\"> SELECT</button></td> </tr> <tr> <td class=\"gfgusername\">User-2</td> <td class=\"gfgpp\">100</td> <td class=\"gfgscores\">75</td> <td class=\"gfgarticles\">30</td> <td><button class=\"gfgselect bg-secondary\" data-toggle=\"modal\" data-target=\"#gfgmodal\"> SELECT</button></td> </tr> <tr> <td class=\"gfgusername\">User-3</td> <td class=\"gfgpp\">200</td> <td class=\"gfgscores\">50</td> <td class=\"gfgarticles\">10</td> <td><button class=\"gfgselect bg-secondary\" data-toggle=\"modal\" data-target=\"#gfgmodal\"> SELECT</button></td> </tr> <tr> <td class=\"gfgusername\">User-4</td> <td class=\"gfgpp\">50</td> <td class=\"gfgscores\">5</td> <td class=\"gfgarticles\">2</td> <td> <button class=\"gfgselect bg-secondary\" data-toggle=\"modal\" data-target=\"#gfgmodal\"> SELECT</button></td> </tr> <tr> <td class=\"gfgusername\">User-5</td> <td class=\"gfgpp\">0</td> <td class=\"gfgscores\">0</td> <td class=\"gfgarticles\">0</td> <td><button class=\"gfgselect bg-secondary\" data-toggle=\"modal\" data-target=\"#gfgmodal\"> SELECT</button></td> </tr> </table> </section> <script> $(function () { // ON SELECTING ROW $(\".gfgselect\").click(function () { //FINDING ELEMENTS OF ROWS AND STORING THEM IN VARIABLES var a = $(this).parents(\"tr\").find(\".gfgusername\").text(); var c = $(this).parents(\"tr\").find(\".gfgpp\").text(); var d = $(this).parents(\"tr\").find(\".gfgscores\").text(); var e = $(this).parents(\"tr\").find(\".gfgarticles\").text(); var p = \"\"; // CREATING DATA TO SHOW ON MODEL p += \"<p id='a' name='GFGusername' >GFG UserHandle: \" + a + \" </p>\"; p += \"<p id='c' name='GFGpp'>Practice Problems: \" + c + \"</p>\"; p += \"<p id='d' name='GFGscores' >Coding Score: \" + d + \" </p>\"; p += \"<p id='e' name='GFGcoding' >GFG Article: \" + e + \" </p>\"; //CLEARING THE PREFILLED DATA $(\"#divGFG\").empty(); //WRITING THE DATA ON MODEL $(\"#divGFG\").append(p); }); }); </script> <!-- CREATING BOOTSTRAP MODEL --> <div class=\"modal fade\" id=\"gfgmodal\" tabindex=\"-1\" role=\"dialog\"> <div class=\"modal-dialog\"> <div class=\"modal-content\"> <div class=\"modal-header\"> <!-- MODEL TITLE --> <h2 class=\"modal-title\" id=\"gfgmodallabel\"> Selected row</h2> <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-label=\"Close\"> <span aria-hidden=\"true\"> ×</span> </button> </div> <!-- MODEL BODY --> <div class=\"modal-body\"> <div class=\"GFGclass\" id=\"divGFG\"></div> <div class=\"modal-footer\"> <!-- The close button in the bottom of the modal --> <button type=\"button\" class=\"btn btn-secondary\" data-dismiss=\"modal\"> Close</button> </div> </div> </div> </div> </div> </body></html>",
"e": 35274,
"s": 27488,
"text": null
},
{
"code": null,
"e": 35282,
"s": 35274,
"text": "Output:"
},
{
"code": null,
"e": 35324,
"s": 35282,
"text": "On triggering select button beside row 1:"
},
{
"code": null,
"e": 35366,
"s": 35324,
"text": "On triggering select button beside row 2:"
},
{
"code": null,
"e": 35634,
"s": 35366,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 35771,
"s": 35634,
"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": 35786,
"s": 35771,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 35796,
"s": 35786,
"text": "Bootstrap"
},
{
"code": null,
"e": 35801,
"s": 35796,
"text": "HTML"
},
{
"code": null,
"e": 35808,
"s": 35801,
"text": "JQuery"
},
{
"code": null,
"e": 35825,
"s": 35808,
"text": "Web Technologies"
},
{
"code": null,
"e": 35830,
"s": 35825,
"text": "HTML"
},
{
"code": null,
"e": 35928,
"s": 35830,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35969,
"s": 35928,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 36032,
"s": 35969,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 36065,
"s": 36032,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 36114,
"s": 36065,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 36173,
"s": 36114,
"text": "How to change the background color of the active nav-item?"
},
{
"code": null,
"e": 36223,
"s": 36173,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 36285,
"s": 36223,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36333,
"s": 36285,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 36393,
"s": 36333,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Tuple Division in Python
|
When it is required to perform tuple division in Python, the 'zip' method and generator expressions can be used.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = ( 7, 8, 3, 4, 3, 2)
my_tuple_2 = (9, 6, 8, 2, 1, 4)
print ("The first tuple is : " )
print(my_tuple_1)
print ("The second tuple is : " )
print(my_tuple_2)
my_result = tuple(elem_1 // elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))
print("The divided tuple value is : " )
print(my_result)
The first tuple is :
(7, 8, 3, 4, 3, 2)
The second tuple is :
(9, 6, 8, 2, 1, 4)
The divided tuple value is :
(0, 1, 0, 2, 3, 0)
Two tuples are defined, and displayed on the console.
The lists are iterated over, and they are zipped using the 'zip' method.
The first element is taken and 'divided' with the second element from both the tuples using the '//' operator.
This is then converted to a tuple.
This operation is assigned to a variable.
This variable is the output that is displayed on the console.
|
[
{
"code": null,
"e": 1175,
"s": 1062,
"text": "When it is required to perform tuple division in Python, the 'zip' method and generator expressions can be used."
},
{
"code": null,
"e": 1267,
"s": 1175,
"text": "The zip method takes iterables, aggregates them into a tuple, and returns it as the result."
},
{
"code": null,
"e": 1530,
"s": 1267,
"text": "Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned."
},
{
"code": null,
"e": 1569,
"s": 1530,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1579,
"s": 1569,
"text": "Live Demo"
},
{
"code": null,
"e": 1893,
"s": 1579,
"text": "my_tuple_1 = ( 7, 8, 3, 4, 3, 2)\nmy_tuple_2 = (9, 6, 8, 2, 1, 4)\n\nprint (\"The first tuple is : \" )\nprint(my_tuple_1)\nprint (\"The second tuple is : \" )\nprint(my_tuple_2)\n\nmy_result = tuple(elem_1 // elem_2 for elem_1, elem_2 in zip(my_tuple_1, my_tuple_2))\n\nprint(\"The divided tuple value is : \" )\nprint(my_result)"
},
{
"code": null,
"e": 2022,
"s": 1893,
"text": "The first tuple is :\n(7, 8, 3, 4, 3, 2)\nThe second tuple is :\n(9, 6, 8, 2, 1, 4)\nThe divided tuple value is :\n(0, 1, 0, 2, 3, 0)"
},
{
"code": null,
"e": 2076,
"s": 2022,
"text": "Two tuples are defined, and displayed on the console."
},
{
"code": null,
"e": 2149,
"s": 2076,
"text": "The lists are iterated over, and they are zipped using the 'zip' method."
},
{
"code": null,
"e": 2260,
"s": 2149,
"text": "The first element is taken and 'divided' with the second element from both the tuples using the '//' operator."
},
{
"code": null,
"e": 2295,
"s": 2260,
"text": "This is then converted to a tuple."
},
{
"code": null,
"e": 2337,
"s": 2295,
"text": "This operation is assigned to a variable."
},
{
"code": null,
"e": 2399,
"s": 2337,
"text": "This variable is the output that is displayed on the console."
}
] |
CodeIgniter - Working with Database
|
Like any other framework, we need to interact with the database very often and CodeIgniter makes this job easy for us. It provides rich set of functionalities to interact with database.
In this section, we will understand how the CRUD (Create, Read, Update, Delete) functions work with CodeIgniter. We will use stud table to select, update, delete, and insert the data in stud table.
We can connect to database in the following two way −
Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −
Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −
$autoload['libraries'] = array(‘database’);
Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class.
$this->load->database();
Here, we are not passing any argument because everything is set in the database config file application/config/database.php
To insert a record in the database, the insert() function is used as shown in the following table −
Syntax
Parameters
$table (string) − Table name
$table (string) − Table name
$set (array) − An associative array of field/value pairs
$set (array) − An associative array of field/value pairs
$escape (bool) − Whether to escape values and identifiers
$escape (bool) − Whether to escape values and identifiers
Returns
Return Type
The following example shows how to insert a record in stud table. The $data is an array in which we have set the data and to insert this data to the table stud, we just need to pass this array to the insert function in the 2nd argument.
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->insert("stud", $data);
To update a record in the database, the update() function is used along with set() and where() functions as shown in the tables below. The set() function will set the data to be updated.
Syntax
Parameters
$key (mixed) − Field name, or an array of field/value pairs
$key (mixed) − Field name, or an array of field/value pairs
$value (string) − Field value, if $key is a single field
$value (string) − Field value, if $key is a single field
$escape (bool) − Whether to escape values and identifiers
$escape (bool) − Whether to escape values and identifiers
Returns
Return Type
The where() function will decide which record to update.
Syntax
Parameters
$key (mixed) − Name of field to compare, or associative array
$key (mixed) − Name of field to compare, or associative array
$value (mixed) − If a single key, compared to this value
$value (mixed) − If a single key, compared to this value
$escape (bool) − Whether to escape values and identifiers
$escape (bool) − Whether to escape values and identifiers
Returns
Return Type
Finally, the update() function will update data in the database.
Syntax
Parameters
$table (string) − Table name
$table (string) − Table name
$set (array) − An associative array of field/value pairs
$set (array) − An associative array of field/value pairs
$where (string) − The WHERE clause
$where (string) − The WHERE clause
$limit (int) − The LIMIT clause
$limit (int) − The LIMIT clause
Returns
Return Type
$data = array(
'roll_no' => ‘1’,
'name' => ‘Virat’
);
$this->db->set($data);
$this->db->where("roll_no", ‘1’);
$this->db->update("stud", $data);
To delete a record in the database, the delete() function is used as shown in the following table −
Syntax
Parameters
$table (mixed) − The table(s) to delete from; string or array
$table (mixed) − The table(s) to delete from; string or array
$where (string) − The WHERE clause
$where (string) − The WHERE clause
$limit (int) − The LIMIT clause
$limit (int) − The LIMIT clause
$reset_data (bool) − TRUE to reset the query “write” clause
$reset_data (bool) − TRUE to reset the query “write” clause
Returns
Return Type
Use the following code to to delete a record in the stud table. The first argument indicates the name of the table to delete record and the second argument decides which record to delete.
$this->db->delete("stud", "roll_no = 1");
To select a record in the database, the get function is used, as shown in the following table −
Syntax
Parameters
$table (string) − The table to query array
$table (string) − The table to query array
$limit (int) − The LIMIT clause
$limit (int) − The LIMIT clause
$offset (int) − The OFFSET clause
$offset (int) − The OFFSET clause
Returns
Return Type
Use the following code to get all the records from the database. The first statement fetches all the records from “stud” table and returns the object, which will be stored in $query object. The second statement calls the result() function with $query object to get all the records as array.
$query = $this->db->get("stud");
$data['records'] = $query->result();
Database connection can be closed manually, by executing the following code −
$this->db->close();
Create a controller class called Stud_controller.php and save it at application/controller/Stud_controller.php
Here is a complete example, wherein all of the above-mentioned operations are performed. Before executing the following example, create a database and table as instructed at the starting of this chapter and make necessary changes in the database config file stored at application/config/database.php
<?php
class Stud_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index() {
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->helper('url');
$this->load->view('Stud_view',$data);
}
public function add_student_view() {
$this->load->helper('form');
$this->load->view('Stud_add');
}
public function add_student() {
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function update_student_view() {
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}
public function update_student(){
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function delete_student() {
$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
}
?>
Create a model class called Stud_Model.php and save it in application/models/Stud_Model.php
<?php
class Stud_Model extends CI_Model {
function __construct() {
parent::__construct();
}
public function insert($data) {
if ($this->db->insert("stud", $data)) {
return true;
}
}
public function delete($roll_no) {
if ($this->db->delete("stud", "roll_no = ".$roll_no)) {
return true;
}
}
public function update($data,$old_roll_no) {
$this->db->set($data);
$this->db->where("roll_no", $old_roll_no);
$this->db->update("stud", $data);
}
}
?>
Create a view file called Stud_add.php and save it in application/views/Stud_add.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<?php
echo form_open('Stud_controller/add_student');
echo form_label('Roll No.');
echo form_input(array('id'=>'roll_no','name'=>'roll_no'));
echo "<br/>";
echo form_label('Name');
echo form_input(array('id'=>'name','name'=>'name'));
echo "<br/>";
echo form_submit(array('id'=>'submit','value'=>'Add'));
echo form_close();
?>
</body>
</html>
Create a view file called Stud_edit.php and save it in application/views/Stud_edit.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<form method = "" action = "">
<?php
echo form_open('Stud_controller/update_student');
echo form_hidden('old_roll_no',$old_roll_no);
echo form_label('Roll No.');
echo form_input(array('id'⇒'roll_no',
'name'⇒'roll_no','value'⇒$records[0]→roll_no));
echo "
";
echo form_label('Name');
echo form_input(array('id'⇒'name','name'⇒'name',
'value'⇒$records[0]→name));
echo "
";
echo form_submit(array('id'⇒'sub mit','value'⇒'Edit'));
echo form_close();
?>
</form>
</body>
</html>
Create a view file called Stud_view.php and save it in application/views/Stud_view.php
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "utf-8">
<title>Students Example</title>
</head>
<body>
<a href = "<?php echo base_url(); ?>
index.php/stud/add_view">Add</a>
<table border = "1">
<?php
$i = 1;
echo "<tr>";
echo "<td>Sr#</td>";
echo "<td>Roll No.</td>";
echo "<td>Name</td>";
echo "<td>Edit</td>";
echo "<td>Delete</td>";
echo "<tr>";
foreach($records as $r) {
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$r->roll_no."</td>";
echo "<td>".$r->name."</td>";
echo "<td><a href = '".base_url()."index.php/stud/edit/"
.$r->roll_no."'>Edit</a></td>";
echo "<td><a href = '".base_url()."index.php/stud/delete/"
.$r->roll_no."'>Delete</a></td>";
echo "<tr>";
}
?>
</table>
</body>
</html>
Make the following change in the route file at application/config/routes.php and add the following line at the end of file.
$route['stud'] = "Stud_controller";
$route['stud/add'] = 'Stud_controller/add_student';
$route['stud/add_view'] = 'Stud_controller/add_student_view';
$route['stud/edit/(\d+)'] = 'Stud_controller/update_student_view/$1';
$route['stud/delete/(\d+)'] = 'Stud_controller/delete_student/$1';
Now, let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL.
http://yoursite.com/index.php/stud
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2505,
"s": 2319,
"text": "Like any other framework, we need to interact with the database very often and CodeIgniter makes this job easy for us. It provides rich set of functionalities to interact with database."
},
{
"code": null,
"e": 2703,
"s": 2505,
"text": "In this section, we will understand how the CRUD (Create, Read, Update, Delete) functions work with CodeIgniter. We will use stud table to select, update, delete, and insert the data in stud table."
},
{
"code": null,
"e": 2757,
"s": 2703,
"text": "We can connect to database in the following two way −"
},
{
"code": null,
"e": 2991,
"s": 2757,
"text": "Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −"
},
{
"code": null,
"e": 3225,
"s": 2991,
"text": "Automatic Connecting − Automatic connection can be done by using the file application/config/autoload.php. Automatic connection will load the database for each and every page. We just need to add the database library as shown below −"
},
{
"code": null,
"e": 3270,
"s": 3225,
"text": "$autoload['libraries'] = array(‘database’);\n"
},
{
"code": null,
"e": 3469,
"s": 3270,
"text": "Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class."
},
{
"code": null,
"e": 3668,
"s": 3469,
"text": "Manual Connecting − If you want database connectivity for only some of the pages, then we can go for manual connecting. We can connect to database manually by adding the following line in any class."
},
{
"code": null,
"e": 3694,
"s": 3668,
"text": "$this->load->database();\n"
},
{
"code": null,
"e": 3818,
"s": 3694,
"text": "Here, we are not passing any argument because everything is set in the database config file application/config/database.php"
},
{
"code": null,
"e": 3918,
"s": 3818,
"text": "To insert a record in the database, the insert() function is used as shown in the following table −"
},
{
"code": null,
"e": 3925,
"s": 3918,
"text": "Syntax"
},
{
"code": null,
"e": 3936,
"s": 3925,
"text": "Parameters"
},
{
"code": null,
"e": 3965,
"s": 3936,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 3994,
"s": 3965,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 4051,
"s": 3994,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 4108,
"s": 4051,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 4166,
"s": 4108,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 4224,
"s": 4166,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 4232,
"s": 4224,
"text": "Returns"
},
{
"code": null,
"e": 4244,
"s": 4232,
"text": "Return Type"
},
{
"code": null,
"e": 4481,
"s": 4244,
"text": "The following example shows how to insert a record in stud table. The $data is an array in which we have set the data and to insert this data to the table stud, we just need to pass this array to the insert function in the 2nd argument."
},
{
"code": null,
"e": 4580,
"s": 4481,
"text": "$data = array( \n 'roll_no' => ‘1’, \n 'name' => ‘Virat’ \n); \n\n$this->db->insert(\"stud\", $data);"
},
{
"code": null,
"e": 4767,
"s": 4580,
"text": "To update a record in the database, the update() function is used along with set() and where() functions as shown in the tables below. The set() function will set the data to be updated."
},
{
"code": null,
"e": 4774,
"s": 4767,
"text": "Syntax"
},
{
"code": null,
"e": 4785,
"s": 4774,
"text": "Parameters"
},
{
"code": null,
"e": 4845,
"s": 4785,
"text": "$key (mixed) − Field name, or an array of field/value pairs"
},
{
"code": null,
"e": 4905,
"s": 4845,
"text": "$key (mixed) − Field name, or an array of field/value pairs"
},
{
"code": null,
"e": 4962,
"s": 4905,
"text": "$value (string) − Field value, if $key is a single field"
},
{
"code": null,
"e": 5019,
"s": 4962,
"text": "$value (string) − Field value, if $key is a single field"
},
{
"code": null,
"e": 5077,
"s": 5019,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 5135,
"s": 5077,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 5143,
"s": 5135,
"text": "Returns"
},
{
"code": null,
"e": 5155,
"s": 5143,
"text": "Return Type"
},
{
"code": null,
"e": 5212,
"s": 5155,
"text": "The where() function will decide which record to update."
},
{
"code": null,
"e": 5219,
"s": 5212,
"text": "Syntax"
},
{
"code": null,
"e": 5230,
"s": 5219,
"text": "Parameters"
},
{
"code": null,
"e": 5292,
"s": 5230,
"text": "$key (mixed) − Name of field to compare, or associative array"
},
{
"code": null,
"e": 5354,
"s": 5292,
"text": "$key (mixed) − Name of field to compare, or associative array"
},
{
"code": null,
"e": 5411,
"s": 5354,
"text": "$value (mixed) − If a single key, compared to this value"
},
{
"code": null,
"e": 5468,
"s": 5411,
"text": "$value (mixed) − If a single key, compared to this value"
},
{
"code": null,
"e": 5526,
"s": 5468,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 5584,
"s": 5526,
"text": "$escape (bool) − Whether to escape values and identifiers"
},
{
"code": null,
"e": 5592,
"s": 5584,
"text": "Returns"
},
{
"code": null,
"e": 5604,
"s": 5592,
"text": "Return Type"
},
{
"code": null,
"e": 5669,
"s": 5604,
"text": "Finally, the update() function will update data in the database."
},
{
"code": null,
"e": 5676,
"s": 5669,
"text": "Syntax"
},
{
"code": null,
"e": 5687,
"s": 5676,
"text": "Parameters"
},
{
"code": null,
"e": 5716,
"s": 5687,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 5745,
"s": 5716,
"text": "$table (string) − Table name"
},
{
"code": null,
"e": 5802,
"s": 5745,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 5859,
"s": 5802,
"text": "$set (array) − An associative array of field/value pairs"
},
{
"code": null,
"e": 5894,
"s": 5859,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 5929,
"s": 5894,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 5961,
"s": 5929,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 5993,
"s": 5961,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 6001,
"s": 5993,
"text": "Returns"
},
{
"code": null,
"e": 6013,
"s": 6001,
"text": "Return Type"
},
{
"code": null,
"e": 6171,
"s": 6013,
"text": "$data = array( \n 'roll_no' => ‘1’, \n 'name' => ‘Virat’ \n); \n\n$this->db->set($data); \n$this->db->where(\"roll_no\", ‘1’); \n$this->db->update(\"stud\", $data);"
},
{
"code": null,
"e": 6271,
"s": 6171,
"text": "To delete a record in the database, the delete() function is used as shown in the following table −"
},
{
"code": null,
"e": 6278,
"s": 6271,
"text": "Syntax"
},
{
"code": null,
"e": 6289,
"s": 6278,
"text": "Parameters"
},
{
"code": null,
"e": 6351,
"s": 6289,
"text": "$table (mixed) − The table(s) to delete from; string or array"
},
{
"code": null,
"e": 6413,
"s": 6351,
"text": "$table (mixed) − The table(s) to delete from; string or array"
},
{
"code": null,
"e": 6448,
"s": 6413,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 6483,
"s": 6448,
"text": "$where (string) − The WHERE clause"
},
{
"code": null,
"e": 6515,
"s": 6483,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 6547,
"s": 6515,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 6607,
"s": 6547,
"text": "$reset_data (bool) − TRUE to reset the query “write” clause"
},
{
"code": null,
"e": 6667,
"s": 6607,
"text": "$reset_data (bool) − TRUE to reset the query “write” clause"
},
{
"code": null,
"e": 6675,
"s": 6667,
"text": "Returns"
},
{
"code": null,
"e": 6687,
"s": 6675,
"text": "Return Type"
},
{
"code": null,
"e": 6876,
"s": 6687,
"text": "Use the following code to to delete a record in the stud table. The first argument indicates the name of the table to delete record and the second argument decides which record to delete."
},
{
"code": null,
"e": 6919,
"s": 6876,
"text": "$this->db->delete(\"stud\", \"roll_no = 1\");\n"
},
{
"code": null,
"e": 7015,
"s": 6919,
"text": "To select a record in the database, the get function is used, as shown in the following table −"
},
{
"code": null,
"e": 7022,
"s": 7015,
"text": "Syntax"
},
{
"code": null,
"e": 7033,
"s": 7022,
"text": "Parameters"
},
{
"code": null,
"e": 7076,
"s": 7033,
"text": "$table (string) − The table to query array"
},
{
"code": null,
"e": 7119,
"s": 7076,
"text": "$table (string) − The table to query array"
},
{
"code": null,
"e": 7151,
"s": 7119,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 7183,
"s": 7151,
"text": "$limit (int) − The LIMIT clause"
},
{
"code": null,
"e": 7217,
"s": 7183,
"text": "$offset (int) − The OFFSET clause"
},
{
"code": null,
"e": 7251,
"s": 7217,
"text": "$offset (int) − The OFFSET clause"
},
{
"code": null,
"e": 7259,
"s": 7251,
"text": "Returns"
},
{
"code": null,
"e": 7271,
"s": 7259,
"text": "Return Type"
},
{
"code": null,
"e": 7562,
"s": 7271,
"text": "Use the following code to get all the records from the database. The first statement fetches all the records from “stud” table and returns the object, which will be stored in $query object. The second statement calls the result() function with $query object to get all the records as array."
},
{
"code": null,
"e": 7633,
"s": 7562,
"text": "$query = $this->db->get(\"stud\"); \n$data['records'] = $query->result();"
},
{
"code": null,
"e": 7711,
"s": 7633,
"text": "Database connection can be closed manually, by executing the following code −"
},
{
"code": null,
"e": 7733,
"s": 7711,
"text": "$this->db->close(); \n"
},
{
"code": null,
"e": 7844,
"s": 7733,
"text": "Create a controller class called Stud_controller.php and save it at application/controller/Stud_controller.php"
},
{
"code": null,
"e": 8144,
"s": 7844,
"text": "Here is a complete example, wherein all of the above-mentioned operations are performed. Before executing the following example, create a database and table as instructed at the starting of this chapter and make necessary changes in the database config file stored at application/config/database.php"
},
{
"code": null,
"e": 10352,
"s": 8144,
"text": "<?php \n class Stud_controller extends CI_Controller {\n\t\n function __construct() { \n parent::__construct(); \n $this->load->helper('url'); \n $this->load->database(); \n } \n \n public function index() { \n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n\t\t\t\n $this->load->helper('url'); \n $this->load->view('Stud_view',$data); \n } \n \n public function add_student_view() { \n $this->load->helper('form'); \n $this->load->view('Stud_add'); \n } \n \n public function add_student() { \n $this->load->model('Stud_Model');\n\t\t\t\n $data = array( \n 'roll_no' => $this->input->post('roll_no'), \n 'name' => $this->input->post('name') \n ); \n\t\t\t\n $this->Stud_Model->insert($data); \n \n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n $this->load->view('Stud_view',$data); \n } \n \n public function update_student_view() { \n $this->load->helper('form'); \n $roll_no = $this->uri->segment('3'); \n $query = $this->db->get_where(\"stud\",array(\"roll_no\"=>$roll_no));\n $data['records'] = $query->result(); \n $data['old_roll_no'] = $roll_no; \n $this->load->view('Stud_edit',$data); \n } \n \n public function update_student(){ \n $this->load->model('Stud_Model');\n\t\t\t\n $data = array( \n 'roll_no' => $this->input->post('roll_no'), \n 'name' => $this->input->post('name') \n ); \n\t\t\t\n $old_roll_no = $this->input->post('old_roll_no'); \n $this->Stud_Model->update($data,$old_roll_no); \n\t\t\t\n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n $this->load->view('Stud_view',$data); \n } \n \n public function delete_student() { \n $this->load->model('Stud_Model'); \n $roll_no = $this->uri->segment('3'); \n $this->Stud_Model->delete($roll_no); \n \n $query = $this->db->get(\"stud\"); \n $data['records'] = $query->result(); \n $this->load->view('Stud_view',$data); \n } \n } \n?>"
},
{
"code": null,
"e": 10444,
"s": 10352,
"text": "Create a model class called Stud_Model.php and save it in application/models/Stud_Model.php"
},
{
"code": null,
"e": 11070,
"s": 10444,
"text": "<?php \n class Stud_Model extends CI_Model {\n\t\n function __construct() { \n parent::__construct(); \n } \n \n public function insert($data) { \n if ($this->db->insert(\"stud\", $data)) { \n return true; \n } \n } \n \n public function delete($roll_no) { \n if ($this->db->delete(\"stud\", \"roll_no = \".$roll_no)) { \n return true; \n } \n } \n \n public function update($data,$old_roll_no) { \n $this->db->set($data); \n $this->db->where(\"roll_no\", $old_roll_no); \n $this->db->update(\"stud\", $data); \n } \n } \n?> "
},
{
"code": null,
"e": 11155,
"s": 11070,
"text": "Create a view file called Stud_add.php and save it in application/views/Stud_add.php"
},
{
"code": null,
"e": 11786,
"s": 11155,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>Students Example</title> \n </head> \n <body> \n <?php \n echo form_open('Stud_controller/add_student');\n echo form_label('Roll No.'); \n echo form_input(array('id'=>'roll_no','name'=>'roll_no')); \n echo \"<br/>\"; \n\t\t\t\n echo form_label('Name'); \n echo form_input(array('id'=>'name','name'=>'name')); \n echo \"<br/>\"; \n\t\t\t\n echo form_submit(array('id'=>'submit','value'=>'Add')); \n echo form_close(); \n ?> \n </body>\n</html>"
},
{
"code": null,
"e": 11873,
"s": 11786,
"text": "Create a view file called Stud_edit.php and save it in application/views/Stud_edit.php"
},
{
"code": null,
"e": 12720,
"s": 11873,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>Students Example</title> \n </head> \n\t\n <body> \n <form method = \"\" action = \"\">\n\t\t\n <?php \n echo form_open('Stud_controller/update_student'); \n echo form_hidden('old_roll_no',$old_roll_no); \n echo form_label('Roll No.'); \n echo form_input(array('id'⇒'roll_no',\n 'name'⇒'roll_no','value'⇒$records[0]→roll_no)); \n echo \"\n \"; \n\n echo form_label('Name'); \n echo form_input(array('id'⇒'name','name'⇒'name',\n 'value'⇒$records[0]→name)); \n echo \"\n \"; \n\n echo form_submit(array('id'⇒'sub mit','value'⇒'Edit')); \n echo form_close();\n ?> \n\t\t\t\n </form> \n </body>\n\t\n</html>"
},
{
"code": null,
"e": 12807,
"s": 12720,
"text": "Create a view file called Stud_view.php and save it in application/views/Stud_view.php"
},
{
"code": null,
"e": 13892,
"s": 12807,
"text": "<!DOCTYPE html> \n<html lang = \"en\">\n \n <head> \n <meta charset = \"utf-8\"> \n <title>Students Example</title> \n </head>\n\t\n <body> \n <a href = \"<?php echo base_url(); ?>\n index.php/stud/add_view\">Add</a>\n\t\t\n <table border = \"1\"> \n <?php \n $i = 1; \n echo \"<tr>\"; \n echo \"<td>Sr#</td>\"; \n echo \"<td>Roll No.</td>\"; \n echo \"<td>Name</td>\"; \n echo \"<td>Edit</td>\"; \n echo \"<td>Delete</td>\"; \n echo \"<tr>\"; \n\t\t\t\t\n foreach($records as $r) { \n echo \"<tr>\"; \n echo \"<td>\".$i++.\"</td>\"; \n echo \"<td>\".$r->roll_no.\"</td>\"; \n echo \"<td>\".$r->name.\"</td>\"; \n echo \"<td><a href = '\".base_url().\"index.php/stud/edit/\"\n .$r->roll_no.\"'>Edit</a></td>\"; \n echo \"<td><a href = '\".base_url().\"index.php/stud/delete/\"\n .$r->roll_no.\"'>Delete</a></td>\"; \n echo \"<tr>\"; \n } \n ?>\n </table> \n\t\t\n </body>\n\t\n</html>"
},
{
"code": null,
"e": 14016,
"s": 13892,
"text": "Make the following change in the route file at application/config/routes.php and add the following line at the end of file."
},
{
"code": null,
"e": 14308,
"s": 14016,
"text": "$route['stud'] = \"Stud_controller\"; \n$route['stud/add'] = 'Stud_controller/add_student'; \n$route['stud/add_view'] = 'Stud_controller/add_student_view'; \n$route['stud/edit/(\\d+)'] = 'Stud_controller/update_student_view/$1'; \n$route['stud/delete/(\\d+)'] = 'Stud_controller/delete_student/$1';\n"
},
{
"code": null,
"e": 14427,
"s": 14308,
"text": "Now, let us execute this example by visiting the following URL in the browser. Replace the yoursite.com with your URL."
},
{
"code": null,
"e": 14463,
"s": 14427,
"text": "http://yoursite.com/index.php/stud\n"
},
{
"code": null,
"e": 14470,
"s": 14463,
"text": " Print"
},
{
"code": null,
"e": 14481,
"s": 14470,
"text": " Add Notes"
}
] |
PHP | date_default_timezone_set() Function - GeeksforGeeks
|
14 Sep, 2018
The date_default_timezone_set() function is an inbuilt function in PHP which is used to set the default timezone used by all date/time functions in a script. This function returns False if the timezone is not valid, or True otherwise.
Syntax:
bool date_default_timezone_set( $timezone_identifier )
Parameters: This function accepts single parameter $timezone_identifier which is mandatory. This parameter set the timezone identifier, like UTC or Asia/Kolkata.
Return Value: This function returns False if the timezone_identifier is not valid, or True otherwise.
Below programs illustrate the date_default_timezone_set() function in PHP:
Program 1:
<?php // Set timezonedate_default_timezone_set('Asia/Kolkata'); // Create $timezone_object = date_default_timezone_get(); // Compare the timezone with ini-set timezoneif (strcmp($timezone_object, ini_get('date.timezone'))){ echo 'Script timezone differs from ini-set timezone.';} else { echo 'Script timezone and ini-set timezone match.';}?>
Script timezone differs from ini-set timezone.
Program 2:
<?php // Set the timezonedate_default_timezone_set('Asia/Dubai'); // Create the timezone object$timezone_object = date_default_timezone_get(); // Compare the timezone with ini-set timezoneif (strcmp($timezone_object, ini_get('date.timezone'))){ echo 'Script timezone differs from ini-set timezone.';} else { echo 'Script timezone and ini-set timezone match.';}?>
Script timezone differs from ini-set timezone.
Related Articles:
PHP | date_parse() Function
PHP | date_sunset() Function
PHP | date_sun_info() Function
Reference: http://php.net/manual/en/function.date-default-timezone-set.php
PHP-date-time
PHP-function
PHP
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 ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
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": 42139,
"s": 42111,
"text": "\n14 Sep, 2018"
},
{
"code": null,
"e": 42374,
"s": 42139,
"text": "The date_default_timezone_set() function is an inbuilt function in PHP which is used to set the default timezone used by all date/time functions in a script. This function returns False if the timezone is not valid, or True otherwise."
},
{
"code": null,
"e": 42382,
"s": 42374,
"text": "Syntax:"
},
{
"code": null,
"e": 42437,
"s": 42382,
"text": "bool date_default_timezone_set( $timezone_identifier )"
},
{
"code": null,
"e": 42599,
"s": 42437,
"text": "Parameters: This function accepts single parameter $timezone_identifier which is mandatory. This parameter set the timezone identifier, like UTC or Asia/Kolkata."
},
{
"code": null,
"e": 42701,
"s": 42599,
"text": "Return Value: This function returns False if the timezone_identifier is not valid, or True otherwise."
},
{
"code": null,
"e": 42776,
"s": 42701,
"text": "Below programs illustrate the date_default_timezone_set() function in PHP:"
},
{
"code": null,
"e": 42787,
"s": 42776,
"text": "Program 1:"
},
{
"code": "<?php // Set timezonedate_default_timezone_set('Asia/Kolkata'); // Create $timezone_object = date_default_timezone_get(); // Compare the timezone with ini-set timezoneif (strcmp($timezone_object, ini_get('date.timezone'))){ echo 'Script timezone differs from ini-set timezone.';} else { echo 'Script timezone and ini-set timezone match.';}?>",
"e": 43138,
"s": 42787,
"text": null
},
{
"code": null,
"e": 43186,
"s": 43138,
"text": "Script timezone differs from ini-set timezone.\n"
},
{
"code": null,
"e": 43197,
"s": 43186,
"text": "Program 2:"
},
{
"code": "<?php // Set the timezonedate_default_timezone_set('Asia/Dubai'); // Create the timezone object$timezone_object = date_default_timezone_get(); // Compare the timezone with ini-set timezoneif (strcmp($timezone_object, ini_get('date.timezone'))){ echo 'Script timezone differs from ini-set timezone.';} else { echo 'Script timezone and ini-set timezone match.';}?>",
"e": 43569,
"s": 43197,
"text": null
},
{
"code": null,
"e": 43617,
"s": 43569,
"text": "Script timezone differs from ini-set timezone.\n"
},
{
"code": null,
"e": 43635,
"s": 43617,
"text": "Related Articles:"
},
{
"code": null,
"e": 43663,
"s": 43635,
"text": "PHP | date_parse() Function"
},
{
"code": null,
"e": 43692,
"s": 43663,
"text": "PHP | date_sunset() Function"
},
{
"code": null,
"e": 43723,
"s": 43692,
"text": "PHP | date_sun_info() Function"
},
{
"code": null,
"e": 43798,
"s": 43723,
"text": "Reference: http://php.net/manual/en/function.date-default-timezone-set.php"
},
{
"code": null,
"e": 43812,
"s": 43798,
"text": "PHP-date-time"
},
{
"code": null,
"e": 43825,
"s": 43812,
"text": "PHP-function"
},
{
"code": null,
"e": 43829,
"s": 43825,
"text": "PHP"
},
{
"code": null,
"e": 43846,
"s": 43829,
"text": "Web Technologies"
},
{
"code": null,
"e": 43850,
"s": 43846,
"text": "PHP"
},
{
"code": null,
"e": 43948,
"s": 43850,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43993,
"s": 43948,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 44043,
"s": 43993,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 44083,
"s": 44043,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 44107,
"s": 44083,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 44151,
"s": 44107,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 44191,
"s": 44151,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 44224,
"s": 44191,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 44269,
"s": 44224,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 44312,
"s": 44269,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Add Hyperlink to the Contents of a Cell using Java? - GeeksforGeeks
|
17 Dec, 2020
Add a hyperlink to a content of the cell using Java and Apache POI. Apache POI is a Java library that is used to handle Microsoft Office Documents.
Installation:
There are two ways to install the Apache POI dependency in our java project:
Download below mentioned Jar files from poi.apache.org/download.html:poi-3.17.jarpoi-ooxml-3.17.jarcommons-codec-1.10.jarpoi-ooxml-schemas-3.17.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.6.0.jardom4j-1.6.1.jarMaven Dependency: Set the following dependency in the maven project as:
Download below mentioned Jar files from poi.apache.org/download.html:poi-3.17.jarpoi-ooxml-3.17.jarcommons-codec-1.10.jarpoi-ooxml-schemas-3.17.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.6.0.jardom4j-1.6.1.jar
poi-3.17.jar
poi-ooxml-3.17.jar
commons-codec-1.10.jar
poi-ooxml-schemas-3.17.jar
xml-apis-1.0.b2.jar
stax-api-1.0.1.jar
xmlbeans-2.6.0.jar
dom4j-1.6.1.jar
Maven Dependency: Set the following dependency in the maven project as:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
Environment Setup:
Make a project Using java maven.
Go to poi.apache.org/download.html and add the dependency into your project. By this, the libraries get imported into your project.
Now, make a java class under com.mycompany.<Your Project Name> in Source Packages.
Nice, now you can use the libraries.
Approach:
Create a workbook.
Create a spreadsheet in workbook.
Create a cell and add color, content and styling to it.
Add the address and apply the link colors to it.
Add cell in spreadsheet.
Repeat step 3 to 5 to write more data
Below is the implementation of the above approach:
Java
// How to add hyperlink to the// contents of a cell using Java?import java.io.File;import java.io.FileOutputStream; import org.apache.poi.common.usermodel.Hyperlink;import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.ss.usermodel.CreationHelper;import org.apache.poi.xssf.usermodel.XSSFCell;import org.apache.poi.xssf.usermodel.XSSFCellStyle;import org.apache.poi.xssf.usermodel.XSSFFont;import org.apache.poi.xssf.usermodel.XSSFHyperlink;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class HyperLink { public static void addLink() { // Create a Workbook XSSFWorkbook myWorkbook = new XSSFWorkbook(); // Create a Spread Sheet XSSFSheet newSpreadsheet = myWorkbook.createSheet("Custom Links"); XSSFCell cell; // Create Helpers CreationHelper helper = myWorkbook.getCreationHelper(); XSSFCellStyle linkStyle = myWorkbook.createCellStyle(); XSSFFont linkFont = myWorkbook.createFont(); // Setting the Link Style linkFont.setUnderline(XSSFFont.U_SINGLE); linkFont.setColor(HSSFColor.BLUE.index); linkStyle.setFont(linkFont); // Adding a Link cell = newSpreadsheet.createRow(1).createCell( (short)2); cell.setCellValue("Link"); XSSFHyperlink link = (XSSFHyperlink)helper.createHyperlink( Hyperlink.LINK_URL); link.setAddress("http://www.geeksforgeeks.com/"); cell.setHyperlink((XSSFHyperlink)link); cell.setCellStyle(linkStyle); // Writing the File FileOutputStream output = new FileOutputStream( new File("C:/HyperLink.xlsx")); // Writing the content myWorkbook.write(output); output.close(); } public static void main(String[] args) throws Exception { addLink(); }}
Output:
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n17 Dec, 2020"
},
{
"code": null,
"e": 25374,
"s": 25225,
"text": "Add a hyperlink to a content of the cell using Java and Apache POI. Apache POI is a Java library that is used to handle Microsoft Office Documents. "
},
{
"code": null,
"e": 25388,
"s": 25374,
"text": "Installation:"
},
{
"code": null,
"e": 25465,
"s": 25388,
"text": "There are two ways to install the Apache POI dependency in our java project:"
},
{
"code": null,
"e": 25754,
"s": 25465,
"text": "Download below mentioned Jar files from poi.apache.org/download.html:poi-3.17.jarpoi-ooxml-3.17.jarcommons-codec-1.10.jarpoi-ooxml-schemas-3.17.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.6.0.jardom4j-1.6.1.jarMaven Dependency: Set the following dependency in the maven project as:"
},
{
"code": null,
"e": 25972,
"s": 25754,
"text": "Download below mentioned Jar files from poi.apache.org/download.html:poi-3.17.jarpoi-ooxml-3.17.jarcommons-codec-1.10.jarpoi-ooxml-schemas-3.17.jarxml-apis-1.0.b2.jarstax-api-1.0.1.jarxmlbeans-2.6.0.jardom4j-1.6.1.jar"
},
{
"code": null,
"e": 25985,
"s": 25972,
"text": "poi-3.17.jar"
},
{
"code": null,
"e": 26004,
"s": 25985,
"text": "poi-ooxml-3.17.jar"
},
{
"code": null,
"e": 26027,
"s": 26004,
"text": "commons-codec-1.10.jar"
},
{
"code": null,
"e": 26054,
"s": 26027,
"text": "poi-ooxml-schemas-3.17.jar"
},
{
"code": null,
"e": 26074,
"s": 26054,
"text": "xml-apis-1.0.b2.jar"
},
{
"code": null,
"e": 26093,
"s": 26074,
"text": "stax-api-1.0.1.jar"
},
{
"code": null,
"e": 26112,
"s": 26093,
"text": "xmlbeans-2.6.0.jar"
},
{
"code": null,
"e": 26128,
"s": 26112,
"text": "dom4j-1.6.1.jar"
},
{
"code": null,
"e": 26200,
"s": 26128,
"text": "Maven Dependency: Set the following dependency in the maven project as:"
},
{
"code": null,
"e": 26353,
"s": 26200,
"text": " <dependency> \n <groupId>org.apache.poi</groupId> \n <artifactId>poi</artifactId> \n <version>3.9</version> \n </dependency>"
},
{
"code": null,
"e": 26372,
"s": 26353,
"text": "Environment Setup:"
},
{
"code": null,
"e": 26405,
"s": 26372,
"text": "Make a project Using java maven."
},
{
"code": null,
"e": 26537,
"s": 26405,
"text": "Go to poi.apache.org/download.html and add the dependency into your project. By this, the libraries get imported into your project."
},
{
"code": null,
"e": 26620,
"s": 26537,
"text": "Now, make a java class under com.mycompany.<Your Project Name> in Source Packages."
},
{
"code": null,
"e": 26657,
"s": 26620,
"text": "Nice, now you can use the libraries."
},
{
"code": null,
"e": 26667,
"s": 26657,
"text": "Approach:"
},
{
"code": null,
"e": 26686,
"s": 26667,
"text": "Create a workbook."
},
{
"code": null,
"e": 26720,
"s": 26686,
"text": "Create a spreadsheet in workbook."
},
{
"code": null,
"e": 26776,
"s": 26720,
"text": "Create a cell and add color, content and styling to it."
},
{
"code": null,
"e": 26825,
"s": 26776,
"text": "Add the address and apply the link colors to it."
},
{
"code": null,
"e": 26850,
"s": 26825,
"text": "Add cell in spreadsheet."
},
{
"code": null,
"e": 26888,
"s": 26850,
"text": "Repeat step 3 to 5 to write more data"
},
{
"code": null,
"e": 26939,
"s": 26888,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26944,
"s": 26939,
"text": "Java"
},
{
"code": "// How to add hyperlink to the// contents of a cell using Java?import java.io.File;import java.io.FileOutputStream; import org.apache.poi.common.usermodel.Hyperlink;import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.ss.usermodel.CreationHelper;import org.apache.poi.xssf.usermodel.XSSFCell;import org.apache.poi.xssf.usermodel.XSSFCellStyle;import org.apache.poi.xssf.usermodel.XSSFFont;import org.apache.poi.xssf.usermodel.XSSFHyperlink;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class HyperLink { public static void addLink() { // Create a Workbook XSSFWorkbook myWorkbook = new XSSFWorkbook(); // Create a Spread Sheet XSSFSheet newSpreadsheet = myWorkbook.createSheet(\"Custom Links\"); XSSFCell cell; // Create Helpers CreationHelper helper = myWorkbook.getCreationHelper(); XSSFCellStyle linkStyle = myWorkbook.createCellStyle(); XSSFFont linkFont = myWorkbook.createFont(); // Setting the Link Style linkFont.setUnderline(XSSFFont.U_SINGLE); linkFont.setColor(HSSFColor.BLUE.index); linkStyle.setFont(linkFont); // Adding a Link cell = newSpreadsheet.createRow(1).createCell( (short)2); cell.setCellValue(\"Link\"); XSSFHyperlink link = (XSSFHyperlink)helper.createHyperlink( Hyperlink.LINK_URL); link.setAddress(\"http://www.geeksforgeeks.com/\"); cell.setHyperlink((XSSFHyperlink)link); cell.setCellStyle(linkStyle); // Writing the File FileOutputStream output = new FileOutputStream( new File(\"C:/HyperLink.xlsx\")); // Writing the content myWorkbook.write(output); output.close(); } public static void main(String[] args) throws Exception { addLink(); }}",
"e": 28875,
"s": 26944,
"text": null
},
{
"code": null,
"e": 28883,
"s": 28875,
"text": "Output:"
},
{
"code": null,
"e": 28890,
"s": 28883,
"text": "Picked"
},
{
"code": null,
"e": 28895,
"s": 28890,
"text": "Java"
},
{
"code": null,
"e": 28909,
"s": 28895,
"text": "Java Programs"
},
{
"code": null,
"e": 28914,
"s": 28909,
"text": "Java"
},
{
"code": null,
"e": 29012,
"s": 28914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29027,
"s": 29012,
"text": "Stream In Java"
},
{
"code": null,
"e": 29048,
"s": 29027,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29067,
"s": 29048,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29097,
"s": 29067,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29143,
"s": 29097,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29169,
"s": 29143,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29203,
"s": 29169,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29250,
"s": 29203,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29282,
"s": 29250,
"text": "How to Iterate HashMap in Java?"
}
] |
Transitive Closure of a Graph using DFS - GeeksforGeeks
|
22 Jan, 2022
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph.
For example, consider below graph
Transitive closure of above graphs is
1 1 1 1
1 1 1 1
1 1 1 1
0 0 0 1
We have discussed an O(V3) solution for this here. The solution was based on Floyd Warshall Algorithm. In this post, an O(V(V+E)) algorithm for the same is discussed. So for dense graph, it would become O(V3) and for sparse graph, it would become O(V2).Below are the abstract steps of the algorithm.
Create a matrix tc[V][V] that would finally have transitive closure of the given graph. Initialize all entries of tc[][] as 0.Call DFS for every node of the graph to mark reachable vertices in tc[][]. In recursive calls to DFS, we don’t call DFS for an adjacent vertex if it is already marked as reachable in tc[][].
Create a matrix tc[V][V] that would finally have transitive closure of the given graph. Initialize all entries of tc[][] as 0.
Call DFS for every node of the graph to mark reachable vertices in tc[][]. In recursive calls to DFS, we don’t call DFS for an adjacent vertex if it is already marked as reachable in tc[][].
Below is the implementation of the above idea. The code uses adjacency list representation of input graph and builds a matrix tc[V][V] such that tc[u][v] would be true if v is reachable from u.
C++
Java
Python3
C#
// C++ program to print transitive closure of a graph#include<bits/stdc++.h>using namespace std; class Graph{ int V; // No. of vertices bool **tc; // To store transitive closure list<int> *adj; // array of adjacency lists void DFSUtil(int u, int v);public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w) { adj[v].push_back(w); } // prints transitive closure matrix void transitiveClosure();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V]; tc = new bool* [V]; for (int i = 0; i < V; i++) { tc[i] = new bool[V]; memset(tc[i], false, V*sizeof(bool)); }} // A recursive DFS traversal function that finds// all reachable vertices for s.void Graph::DFSUtil(int s, int v){ // Mark reachability from s to t as true. if(s==v){ if(find(adj[v].begin(),adj[v].end(),v)!=adj[v].end()) tc[s][v] = true; } else tc[s][v] = true; // Find all the vertices reachable through v list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { if (tc[s][*i] == false) { if(*i==s) { tc[s][*i]=1; } else { DFSUtil(s, *i); } } }} // The function to find transitive closure. It uses// recursive DFSUtil()void Graph::transitiveClosure(){ // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (int i = 0; i < V; i++) DFSUtil(i, i); // Every vertex is reachable from self. for (int i=0; i<V; i++) { for (int j=0; j<V; j++) cout << tc[i][j] << " "; cout << endl; }} // Driver codeint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << "Transitive closure matrix is \n"; g.transitiveClosure(); return 0;}
// JAVA program to print transitive// closure of a graph. import java.util.ArrayList;import java.util.Arrays; // A directed graph using// adjacency list representationpublic class Graph { // No. of vertices in graph private int vertices; // adjacency list private ArrayList<Integer>[] adjList; // To store transitive closure private int[][] tc; // Constructor public Graph(int vertices) { // initialise vertex count this.vertices = vertices; this.tc = new int[this.vertices][this.vertices]; // initialise adjacency list initAdjList(); } // utility method to initialise adjacency list @SuppressWarnings("unchecked") private void initAdjList() { adjList = new ArrayList[vertices]; for (int i = 0; i < vertices; i++) { adjList[i] = new ArrayList<>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].add(v); } // The function to find transitive // closure. It uses // recursive DFSUtil() public void transitiveClosure() { // Call the recursive helper // function to print DFS // traversal starting from all // vertices one by one for (int i = 0; i < vertices; i++) { dfsUtil(i, i); } for (int i = 0; i < vertices; i++) { System.out.println(Arrays.toString(tc[i])); } } // A recursive DFS traversal // function that finds // all reachable vertices for s private void dfsUtil(int s, int v) { // Mark reachability from // s to v as true. if(s==v){ if(adjList[v].contains(v)) tc[s][v] = 1; } else tc[s][v] = 1; // Find all the vertices reachable // through v for (int adj : adjList[v]) { if (tc[s][adj]==0) { dfsUtil(s, adj); } } } // Driver Code public static void main(String[] args) { // Create a graph given // in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Transitive closure " + "matrix is"); g.transitiveClosure(); }} // This code is contributed// by Himanshu Shekhar
# Python program to print transitive# closure of a graph.from collections import defaultdict class Graph: def __init__(self,vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # To store transitive closure self.tc = [[0 for j in range(self.V)] for i in range(self.V)] # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A recursive DFS traversal function that finds # all reachable vertices for s def DFSUtil(self, s, v): # Mark reachability from s to v as true. if(s == v): if( v in self.graph[s]): self.tc[s][v] = 1 else: self.tc[s][v] = 1 # Find all the vertices reachable through v for i in self.graph[v]: if self.tc[s][i] == 0: if s==i: self.tc[s][i]=1 else: self.DFSUtil(s, i) # The function to find transitive closure. It uses # recursive DFSUtil() def transitiveClosure(self): # Call the recursive helper function to print DFS # traversal starting from all vertices one by one for i in range(self.V): self.DFSUtil(i, i) print(self.tc) # Create a graph given in the above diagramg = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) g.transitiveClosure()
// C# program to print transitive// closure of a graph.using System;using System.Collections.Generic; // A directed graph using// adjacency list representationpublic class Graph{ // No. of vertices in graph private int vertices; // adjacency list private List<int>[] adjList; // To store transitive closure private int[,] tc; // Constructor public Graph(int vertices) { // initialise vertex count this.vertices = vertices; this.tc = new int[this.vertices, this.vertices]; // initialise adjacency list initAdjList(); } // utility method to initialise adjacency list private void initAdjList() { adjList = new List<int>[vertices]; for (int i = 0; i < vertices; i++) { adjList[i] = new List<int>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].Add(v); } // The function to find transitive // closure. It uses // recursive DFSUtil() public void transitiveClosure() { // Call the recursive helper // function to print DFS // traversal starting from all // vertices one by one for (int i = 0; i < vertices; i++) { dfsUtil(i, i); } for (int i = 0; i < vertices; i++) { for(int j = 0; j < vertices; j++) Console.Write(tc[i, j] + " "); Console.WriteLine(); } } // A recursive DFS traversal // function that finds // all reachable vertices for s private void dfsUtil(int s, int v) { // Mark reachability from // s to v as true. if(s==v){ if(adjList[v].contains(v)) tc[s][v] = 1; } else tc[s, v] = 1; // Find all the vertices reachable // through v foreach (int adj in adjList[v]) { if (tc[s, adj] == 0) { dfsUtil(s, adj); } } } // Driver Code public static void Main(String[] args) { // Create a graph given // in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); Console.WriteLine("Transitive closure " + "matrix is"); g.transitiveClosure(); }} // This code is contributed by Rajput-Ji
Transitive closure matrix is
1 1 1 1
1 1 1 1
1 1 1 1
0 0 0 1
Output:
Transitive closure matrix is
1 1 1 1
1 1 1 1
1 1 1 1
0 0 0 1
References: http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/digraph.4up.pdfThis article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
csecec1702556
Rajput-Ji
easeit
dsnehasish74
jatinmittal1995
apra8001
nandinisharma3
amartyaniel20
Graph
Graph
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": 26225,
"s": 26197,
"text": "\n22 Jan, 2022"
},
{
"code": null,
"e": 26484,
"s": 26225,
"text": "Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. "
},
{
"code": null,
"e": 26614,
"s": 26484,
"text": "For example, consider below graph\n\nTransitive closure of above graphs is \n 1 1 1 1 \n 1 1 1 1 \n 1 1 1 1 \n 0 0 0 1 "
},
{
"code": null,
"e": 26916,
"s": 26614,
"text": "We have discussed an O(V3) solution for this here. The solution was based on Floyd Warshall Algorithm. In this post, an O(V(V+E)) algorithm for the same is discussed. So for dense graph, it would become O(V3) and for sparse graph, it would become O(V2).Below are the abstract steps of the algorithm. "
},
{
"code": null,
"e": 27233,
"s": 26916,
"text": "Create a matrix tc[V][V] that would finally have transitive closure of the given graph. Initialize all entries of tc[][] as 0.Call DFS for every node of the graph to mark reachable vertices in tc[][]. In recursive calls to DFS, we don’t call DFS for an adjacent vertex if it is already marked as reachable in tc[][]."
},
{
"code": null,
"e": 27360,
"s": 27233,
"text": "Create a matrix tc[V][V] that would finally have transitive closure of the given graph. Initialize all entries of tc[][] as 0."
},
{
"code": null,
"e": 27551,
"s": 27360,
"text": "Call DFS for every node of the graph to mark reachable vertices in tc[][]. In recursive calls to DFS, we don’t call DFS for an adjacent vertex if it is already marked as reachable in tc[][]."
},
{
"code": null,
"e": 27746,
"s": 27551,
"text": "Below is the implementation of the above idea. The code uses adjacency list representation of input graph and builds a matrix tc[V][V] such that tc[u][v] would be true if v is reachable from u. "
},
{
"code": null,
"e": 27750,
"s": 27746,
"text": "C++"
},
{
"code": null,
"e": 27755,
"s": 27750,
"text": "Java"
},
{
"code": null,
"e": 27763,
"s": 27755,
"text": "Python3"
},
{
"code": null,
"e": 27766,
"s": 27763,
"text": "C#"
},
{
"code": "// C++ program to print transitive closure of a graph#include<bits/stdc++.h>using namespace std; class Graph{ int V; // No. of vertices bool **tc; // To store transitive closure list<int> *adj; // array of adjacency lists void DFSUtil(int u, int v);public: Graph(int V); // Constructor // function to add an edge to graph void addEdge(int v, int w) { adj[v].push_back(w); } // prints transitive closure matrix void transitiveClosure();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V]; tc = new bool* [V]; for (int i = 0; i < V; i++) { tc[i] = new bool[V]; memset(tc[i], false, V*sizeof(bool)); }} // A recursive DFS traversal function that finds// all reachable vertices for s.void Graph::DFSUtil(int s, int v){ // Mark reachability from s to t as true. if(s==v){ if(find(adj[v].begin(),adj[v].end(),v)!=adj[v].end()) tc[s][v] = true; } else tc[s][v] = true; // Find all the vertices reachable through v list<int>::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) { if (tc[s][*i] == false) { if(*i==s) { tc[s][*i]=1; } else { DFSUtil(s, *i); } } }} // The function to find transitive closure. It uses// recursive DFSUtil()void Graph::transitiveClosure(){ // Call the recursive helper function to print DFS // traversal starting from all vertices one by one for (int i = 0; i < V; i++) DFSUtil(i, i); // Every vertex is reachable from self. for (int i=0; i<V; i++) { for (int j=0; j<V; j++) cout << tc[i][j] << \" \"; cout << endl; }} // Driver codeint main(){ // Create a graph given in the above diagram Graph g(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); cout << \"Transitive closure matrix is \\n\"; g.transitiveClosure(); return 0;}",
"e": 29830,
"s": 27766,
"text": null
},
{
"code": "// JAVA program to print transitive// closure of a graph. import java.util.ArrayList;import java.util.Arrays; // A directed graph using// adjacency list representationpublic class Graph { // No. of vertices in graph private int vertices; // adjacency list private ArrayList<Integer>[] adjList; // To store transitive closure private int[][] tc; // Constructor public Graph(int vertices) { // initialise vertex count this.vertices = vertices; this.tc = new int[this.vertices][this.vertices]; // initialise adjacency list initAdjList(); } // utility method to initialise adjacency list @SuppressWarnings(\"unchecked\") private void initAdjList() { adjList = new ArrayList[vertices]; for (int i = 0; i < vertices; i++) { adjList[i] = new ArrayList<>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].add(v); } // The function to find transitive // closure. It uses // recursive DFSUtil() public void transitiveClosure() { // Call the recursive helper // function to print DFS // traversal starting from all // vertices one by one for (int i = 0; i < vertices; i++) { dfsUtil(i, i); } for (int i = 0; i < vertices; i++) { System.out.println(Arrays.toString(tc[i])); } } // A recursive DFS traversal // function that finds // all reachable vertices for s private void dfsUtil(int s, int v) { // Mark reachability from // s to v as true. if(s==v){ if(adjList[v].contains(v)) tc[s][v] = 1; } else tc[s][v] = 1; // Find all the vertices reachable // through v for (int adj : adjList[v]) { if (tc[s][adj]==0) { dfsUtil(s, adj); } } } // Driver Code public static void main(String[] args) { // Create a graph given // in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println(\"Transitive closure \" + \"matrix is\"); g.transitiveClosure(); }} // This code is contributed// by Himanshu Shekhar",
"e": 32321,
"s": 29830,
"text": null
},
{
"code": "# Python program to print transitive# closure of a graph.from collections import defaultdict class Graph: def __init__(self,vertices): # No. of vertices self.V = vertices # default dictionary to store graph self.graph = defaultdict(list) # To store transitive closure self.tc = [[0 for j in range(self.V)] for i in range(self.V)] # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # A recursive DFS traversal function that finds # all reachable vertices for s def DFSUtil(self, s, v): # Mark reachability from s to v as true. if(s == v): if( v in self.graph[s]): self.tc[s][v] = 1 else: self.tc[s][v] = 1 # Find all the vertices reachable through v for i in self.graph[v]: if self.tc[s][i] == 0: if s==i: self.tc[s][i]=1 else: self.DFSUtil(s, i) # The function to find transitive closure. It uses # recursive DFSUtil() def transitiveClosure(self): # Call the recursive helper function to print DFS # traversal starting from all vertices one by one for i in range(self.V): self.DFSUtil(i, i) print(self.tc) # Create a graph given in the above diagramg = Graph(4)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 2)g.addEdge(2, 0)g.addEdge(2, 3)g.addEdge(3, 3) g.transitiveClosure()",
"e": 33820,
"s": 32321,
"text": null
},
{
"code": "// C# program to print transitive// closure of a graph.using System;using System.Collections.Generic; // A directed graph using// adjacency list representationpublic class Graph{ // No. of vertices in graph private int vertices; // adjacency list private List<int>[] adjList; // To store transitive closure private int[,] tc; // Constructor public Graph(int vertices) { // initialise vertex count this.vertices = vertices; this.tc = new int[this.vertices, this.vertices]; // initialise adjacency list initAdjList(); } // utility method to initialise adjacency list private void initAdjList() { adjList = new List<int>[vertices]; for (int i = 0; i < vertices; i++) { adjList[i] = new List<int>(); } } // add edge from u to v public void addEdge(int u, int v) { // Add v to u's list. adjList[u].Add(v); } // The function to find transitive // closure. It uses // recursive DFSUtil() public void transitiveClosure() { // Call the recursive helper // function to print DFS // traversal starting from all // vertices one by one for (int i = 0; i < vertices; i++) { dfsUtil(i, i); } for (int i = 0; i < vertices; i++) { for(int j = 0; j < vertices; j++) Console.Write(tc[i, j] + \" \"); Console.WriteLine(); } } // A recursive DFS traversal // function that finds // all reachable vertices for s private void dfsUtil(int s, int v) { // Mark reachability from // s to v as true. if(s==v){ if(adjList[v].contains(v)) tc[s][v] = 1; } else tc[s, v] = 1; // Find all the vertices reachable // through v foreach (int adj in adjList[v]) { if (tc[s, adj] == 0) { dfsUtil(s, adj); } } } // Driver Code public static void Main(String[] args) { // Create a graph given // in the above diagram Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); Console.WriteLine(\"Transitive closure \" + \"matrix is\"); g.transitiveClosure(); }} // This code is contributed by Rajput-Ji",
"e": 36016,
"s": 33820,
"text": null
},
{
"code": null,
"e": 36082,
"s": 36016,
"text": "Transitive closure matrix is \n1 1 1 1 \n1 1 1 1 \n1 1 1 1 \n0 0 0 1 "
},
{
"code": null,
"e": 36091,
"s": 36082,
"text": "Output: "
},
{
"code": null,
"e": 36157,
"s": 36091,
"text": "Transitive closure matrix is \n1 1 1 1 \n1 1 1 1 \n1 1 1 1 \n0 0 0 1 "
},
{
"code": null,
"e": 36418,
"s": 36157,
"text": "References: http://www.cs.princeton.edu/courses/archive/spr03/cs226/lectures/digraph.4up.pdfThis article is contributed by Aditya Goel. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 36432,
"s": 36418,
"text": "csecec1702556"
},
{
"code": null,
"e": 36442,
"s": 36432,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36449,
"s": 36442,
"text": "easeit"
},
{
"code": null,
"e": 36462,
"s": 36449,
"text": "dsnehasish74"
},
{
"code": null,
"e": 36478,
"s": 36462,
"text": "jatinmittal1995"
},
{
"code": null,
"e": 36487,
"s": 36478,
"text": "apra8001"
},
{
"code": null,
"e": 36502,
"s": 36487,
"text": "nandinisharma3"
},
{
"code": null,
"e": 36516,
"s": 36502,
"text": "amartyaniel20"
},
{
"code": null,
"e": 36522,
"s": 36516,
"text": "Graph"
},
{
"code": null,
"e": 36528,
"s": 36522,
"text": "Graph"
},
{
"code": null,
"e": 36626,
"s": 36528,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36684,
"s": 36626,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 36704,
"s": 36684,
"text": "Topological Sorting"
},
{
"code": null,
"e": 36735,
"s": 36704,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 36768,
"s": 36735,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 36801,
"s": 36768,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 36869,
"s": 36801,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 36919,
"s": 36869,
"text": "Ford-Fulkerson Algorithm for Maximum Flow Problem"
},
{
"code": null,
"e": 36994,
"s": 36919,
"text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)"
},
{
"code": null,
"e": 37024,
"s": 36994,
"text": "Strongly Connected Components"
}
] |
Sum of digits of a number in PL/ SQL - GeeksforGeeks
|
09 Jul, 2018
Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a number and task is to find the sum of digits of the number.Examples:
Input: 123456
Output: 21
Input: 9874
Output: 28
Approach is to take a number and getting each digit with MOD function and summing it up.
Below is the required implementation:
DECLARE --Declare variable n, temp_sum -- and r of datatype number n INTEGER; temp_sum INTEGER; r INTEGER; BEGIN n := 123456; temp_sum := 0; -- here we check condition with the help of while loop -- here <> symbol represent for not null WHILE n <> 0 LOOP r := MOD(n, 10); temp_sum := temp_sum + r; n := Trunc(n / 10); END LOOP; dbms_output.Put_line('sum of digits = ' || temp_sum); END; -- Program End
Output:
sum of digits = 21
SQL-PL/SQL
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL Interview Questions
CTE in SQL
How to Update Multiple Columns in Single Update Statement in SQL?
Difference between SQL and NoSQL
Difference between DELETE, DROP and TRUNCATE
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
SQL | Subquery
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n09 Jul, 2018"
},
{
"code": null,
"e": 25805,
"s": 25561,
"text": "Prerequisite – PL/SQL introductionIn PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations."
},
{
"code": null,
"e": 25882,
"s": 25805,
"text": "Given a number and task is to find the sum of digits of the number.Examples:"
},
{
"code": null,
"e": 25932,
"s": 25882,
"text": "Input: 123456\nOutput: 21\n\nInput: 9874\nOutput: 28\n"
},
{
"code": null,
"e": 26021,
"s": 25932,
"text": "Approach is to take a number and getting each digit with MOD function and summing it up."
},
{
"code": null,
"e": 26059,
"s": 26021,
"text": "Below is the required implementation:"
},
{
"code": "DECLARE --Declare variable n, temp_sum -- and r of datatype number n INTEGER; temp_sum INTEGER; r INTEGER; BEGIN n := 123456; temp_sum := 0; -- here we check condition with the help of while loop -- here <> symbol represent for not null WHILE n <> 0 LOOP r := MOD(n, 10); temp_sum := temp_sum + r; n := Trunc(n / 10); END LOOP; dbms_output.Put_line('sum of digits = ' || temp_sum); END; -- Program End ",
"e": 26578,
"s": 26059,
"text": null
},
{
"code": null,
"e": 26586,
"s": 26578,
"text": "Output:"
},
{
"code": null,
"e": 26606,
"s": 26586,
"text": "sum of digits = 21\n"
},
{
"code": null,
"e": 26617,
"s": 26606,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 26621,
"s": 26617,
"text": "SQL"
},
{
"code": null,
"e": 26625,
"s": 26621,
"text": "SQL"
},
{
"code": null,
"e": 26723,
"s": 26625,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26747,
"s": 26723,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 26758,
"s": 26747,
"text": "CTE in SQL"
},
{
"code": null,
"e": 26824,
"s": 26758,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 26857,
"s": 26824,
"text": "Difference between SQL and NoSQL"
},
{
"code": null,
"e": 26902,
"s": 26857,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 26934,
"s": 26902,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 26973,
"s": 26934,
"text": "Difference between DELETE and TRUNCATE"
},
{
"code": null,
"e": 26988,
"s": 26973,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27045,
"s": 26988,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
}
] |
numpy.ndarray.flat() in Python - GeeksforGeeks
|
28 Mar, 2022
The numpy.ndarray.flat() function is used as a 1_D iterator over N-dimensional arrays. It is not a subclass of, Python’s built-in iterator object, otherwise it a numpy.flatiter instance. Syntax :
numpy.ndarray.flat()
Parameters :
index : [tuple(int)] index of the values to iterate
Return :
1-D iteration of array
Code 1 : Working on 2D array
Python
# Python Program illustrating# working of ndarray.flat() import numpy as geek # Working on 1D iteration of 2D arrayarray = geek.arange(15).reshape(3, 5)print("2D array : \n",array ) # Using flat() : 1D iterator over rangeprint("\nUsing Array : ", array.flat[2:6]) # Using flat() to Print 1D represented arrayprint("\n1D representation of array : \n ->", array.flat[0:15])
Output :
2D array :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
Using Array : [2 3 4 5]
1D representation of array :
-> [ 0 1 2 ..., 12 13 14]
Code 2 : Changing the values of array
Python
# Python Program illustrating# working of ndarray.flat() import numpy as geek # Working on 1D iteration of 2D arrayarray = geek.arange(15).reshape(3, 5)print("2D array : \n",array ) # All elements set to 1array.flat = 1print("\nAll Values set to 1 : \n", array) array.flat[3:6] = 8array.flat[8:10] = 9print("Changing values in a range : \n", array)
Output :
2D array :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
All Values set to 1 :
[[1 1 1 1 1]
[1 1 1 1 1]
[1 1 1 1 1]]
Changing values in a range :
[[1 1 1 8 8]
[8 1 1 9 9]
[1 1 1 1 1]]
What actually numpy.flatiter is ? A flatiter iterator is returned by x.flat for any array x. It allows iterating(in row-major manner)over N-dimensional arrays, either in a for-loop or by calling its next method.Code 3 : Role of numpy.flatitter()
Python
# Python Program illustrating# working of ndarray.flat() import numpy as geek # Working on 1D iteration of 2D arrayarray = geek.arange(15).reshape(3, 5)print("2D array : \n",array ) print("\nID array : \n", array.flat[0:15]) print("\nType of array,flat() : ", type(array.flat)) for i in array.flat: print(i, end = ' ')
Output :
2D array :
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
ID array :
[ 0 1 2 ..., 12 13 14]
Type of array,flat() :
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html#numpy.ndarray.flatNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working.
This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
abhishek0719kadiyan
vinayedula
Python numpy-ndarray
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25580,
"s": 25552,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 25777,
"s": 25580,
"text": "The numpy.ndarray.flat() function is used as a 1_D iterator over N-dimensional arrays. It is not a subclass of, Python’s built-in iterator object, otherwise it a numpy.flatiter instance. Syntax : "
},
{
"code": null,
"e": 25798,
"s": 25777,
"text": "numpy.ndarray.flat()"
},
{
"code": null,
"e": 25812,
"s": 25798,
"text": "Parameters : "
},
{
"code": null,
"e": 25864,
"s": 25812,
"text": "index : [tuple(int)] index of the values to iterate"
},
{
"code": null,
"e": 25875,
"s": 25864,
"text": "Return : "
},
{
"code": null,
"e": 25898,
"s": 25875,
"text": "1-D iteration of array"
},
{
"code": null,
"e": 25929,
"s": 25898,
"text": "Code 1 : Working on 2D array "
},
{
"code": null,
"e": 25936,
"s": 25929,
"text": "Python"
},
{
"code": "# Python Program illustrating# working of ndarray.flat() import numpy as geek # Working on 1D iteration of 2D arrayarray = geek.arange(15).reshape(3, 5)print(\"2D array : \\n\",array ) # Using flat() : 1D iterator over rangeprint(\"\\nUsing Array : \", array.flat[2:6]) # Using flat() to Print 1D represented arrayprint(\"\\n1D representation of array : \\n ->\", array.flat[0:15])",
"e": 26308,
"s": 25936,
"text": null
},
{
"code": null,
"e": 26319,
"s": 26308,
"text": "Output : "
},
{
"code": null,
"e": 26473,
"s": 26319,
"text": "2D array : \n [[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]]\n\nUsing Array : [2 3 4 5]\n\n1D representation of array : \n -> [ 0 1 2 ..., 12 13 14]"
},
{
"code": null,
"e": 26513,
"s": 26473,
"text": "Code 2 : Changing the values of array "
},
{
"code": null,
"e": 26520,
"s": 26513,
"text": "Python"
},
{
"code": "# Python Program illustrating# working of ndarray.flat() import numpy as geek # Working on 1D iteration of 2D arrayarray = geek.arange(15).reshape(3, 5)print(\"2D array : \\n\",array ) # All elements set to 1array.flat = 1print(\"\\nAll Values set to 1 : \\n\", array) array.flat[3:6] = 8array.flat[8:10] = 9print(\"Changing values in a range : \\n\", array) ",
"e": 26872,
"s": 26520,
"text": null
},
{
"code": null,
"e": 26883,
"s": 26872,
"text": "Output : "
},
{
"code": null,
"e": 27088,
"s": 26883,
"text": "2D array : \n [[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]]\n\nAll Values set to 1 : \n [[1 1 1 1 1]\n [1 1 1 1 1]\n [1 1 1 1 1]]\n\nChanging values in a range : \n [[1 1 1 8 8]\n [8 1 1 9 9]\n [1 1 1 1 1]]"
},
{
"code": null,
"e": 27336,
"s": 27088,
"text": "What actually numpy.flatiter is ? A flatiter iterator is returned by x.flat for any array x. It allows iterating(in row-major manner)over N-dimensional arrays, either in a for-loop or by calling its next method.Code 3 : Role of numpy.flatitter() "
},
{
"code": null,
"e": 27343,
"s": 27336,
"text": "Python"
},
{
"code": "# Python Program illustrating# working of ndarray.flat() import numpy as geek # Working on 1D iteration of 2D arrayarray = geek.arange(15).reshape(3, 5)print(\"2D array : \\n\",array ) print(\"\\nID array : \\n\", array.flat[0:15]) print(\"\\nType of array,flat() : \", type(array.flat)) for i in array.flat: print(i, end = ' ')",
"e": 27673,
"s": 27343,
"text": null
},
{
"code": null,
"e": 27684,
"s": 27673,
"text": "Output : "
},
{
"code": null,
"e": 27853,
"s": 27684,
"text": "2D array : \n [[ 0 1 2 3 4]\n [ 5 6 7 8 9]\n [10 11 12 13 14]]\n\nID array : \n [ 0 1 2 ..., 12 13 14]\n\nType of array,flat() : \n0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 "
},
{
"code": null,
"e": 28067,
"s": 27853,
"text": "References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flat.html#numpy.ndarray.flatNote : These codes won’t run on online IDE’s. So please, run them on your systems to explore the working."
},
{
"code": null,
"e": 28492,
"s": 28067,
"text": "This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 28512,
"s": 28492,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 28523,
"s": 28512,
"text": "vinayedula"
},
{
"code": null,
"e": 28544,
"s": 28523,
"text": "Python numpy-ndarray"
},
{
"code": null,
"e": 28557,
"s": 28544,
"text": "Python-numpy"
},
{
"code": null,
"e": 28564,
"s": 28557,
"text": "Python"
},
{
"code": null,
"e": 28662,
"s": 28564,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28694,
"s": 28662,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28736,
"s": 28694,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28778,
"s": 28736,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28834,
"s": 28778,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28861,
"s": 28834,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28892,
"s": 28861,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28931,
"s": 28892,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28960,
"s": 28931,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28982,
"s": 28960,
"text": "Defaultdict in Python"
}
] |
Create a column using for loop in Pandas Dataframe - GeeksforGeeks
|
08 Jan, 2019
Let’s see how to create a column in pandas dataframe using for loop. Such operation is needed sometimes when we need to process the data of dataframe created earlier for that purpose, we need this type of computation so we can process the existing data and make a separate column to store the data.
In this type of computation, we need to take care about the value that is in the existing dataframe. We only use those value to add new column in dataframe.
# importing pandasimport pandas as pd # Creating new dataframeinitial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Marks': [12, 52, 36, 85, 23] } df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Marks']) # Generate result using pandasresult = []for value in df["Marks"]: if value >= 33: result.append("Pass") elif value < 0 and value > 100: result.append("Invalid") else: result.append("Fail") df["Result"] = result print(df)
First_name Last_name Marks Result
0 Ram Kumar 12 Fail
1 Mohan Sharma 52 Pass
2 Tina Ali 36 Pass
3 Jeetu Gandhi 85 Pass
4 Meera Kumari 23 Fail
pandas-dataframe-program
Python pandas-dataFrame
Python-pandas
Technical Scripter 2018
Python
Technical Scripter
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
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
Convert integer to string in Python
Check if element exists in list in Python
|
[
{
"code": null,
"e": 26277,
"s": 26249,
"text": "\n08 Jan, 2019"
},
{
"code": null,
"e": 26576,
"s": 26277,
"text": "Let’s see how to create a column in pandas dataframe using for loop. Such operation is needed sometimes when we need to process the data of dataframe created earlier for that purpose, we need this type of computation so we can process the existing data and make a separate column to store the data."
},
{
"code": null,
"e": 26733,
"s": 26576,
"text": "In this type of computation, we need to take care about the value that is in the existing dataframe. We only use those value to add new column in dataframe."
},
{
"code": "# importing pandasimport pandas as pd # Creating new dataframeinitial_data = {'First_name': ['Ram', 'Mohan', 'Tina', 'Jeetu', 'Meera'], 'Last_name': ['Kumar', 'Sharma', 'Ali', 'Gandhi', 'Kumari'], 'Marks': [12, 52, 36, 85, 23] } df = pd.DataFrame(initial_data, columns = ['First_name', 'Last_name', 'Marks']) # Generate result using pandasresult = []for value in df[\"Marks\"]: if value >= 33: result.append(\"Pass\") elif value < 0 and value > 100: result.append(\"Invalid\") else: result.append(\"Fail\") df[\"Result\"] = result print(df)",
"e": 27337,
"s": 26733,
"text": null
},
{
"code": null,
"e": 27560,
"s": 27337,
"text": " First_name Last_name Marks Result\n0 Ram Kumar 12 Fail\n1 Mohan Sharma 52 Pass\n2 Tina Ali 36 Pass\n3 Jeetu Gandhi 85 Pass\n4 Meera Kumari 23 Fail\n"
},
{
"code": null,
"e": 27585,
"s": 27560,
"text": "pandas-dataframe-program"
},
{
"code": null,
"e": 27609,
"s": 27585,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27623,
"s": 27609,
"text": "Python-pandas"
},
{
"code": null,
"e": 27647,
"s": 27623,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 27654,
"s": 27647,
"text": "Python"
},
{
"code": null,
"e": 27673,
"s": 27654,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27771,
"s": 27673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27789,
"s": 27771,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27821,
"s": 27789,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27843,
"s": 27821,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27885,
"s": 27843,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27915,
"s": 27885,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27944,
"s": 27915,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27988,
"s": 27944,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28025,
"s": 27988,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28061,
"s": 28025,
"text": "Convert integer to string in Python"
}
] |
Python | Numpy np.assert_approx_equal() method - GeeksforGeeks
|
30 Jan, 2020
With the help of np.assert_approx_equal() method, we can get the assertion error if two items are not equal up to significant digits by using np.assert_approx_equal() method.
Syntax : np.assert_approx_equal(actual, desired, significant)Return : Return the assertion error if two values are not equal.
Example #1 :In this example we can see that by using np.assert_approx_equal() method, we are able to get the assertion error if two values are not equal up to a significant digit by using this method.
# import numpy and assert_approx_equalimport numpy as npimport numpy.testing as npt # using np.assert_approx_equal() methodgfg = npt.assert_approx_equal(1.2222222222, 1.2222222222, significant = 5) print(gfg)
Output :
Nope
Example #2 :
# import numpy and assert_approx_equalimport numpy as npimport numpy.testing as npt # using np.assert_approx_equal() methodgfg = npt.assert_approx_equal(1.2222222222, 1.23422222, significant = 5) print(gfg)
Output :
AssertionError:Items are not equal to 5 significant digits:ACTUAL: 1.2222222222DESIRED: 1.23422222
Python numpy-Testing
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 25712,
"s": 25537,
"text": "With the help of np.assert_approx_equal() method, we can get the assertion error if two items are not equal up to significant digits by using np.assert_approx_equal() method."
},
{
"code": null,
"e": 25838,
"s": 25712,
"text": "Syntax : np.assert_approx_equal(actual, desired, significant)Return : Return the assertion error if two values are not equal."
},
{
"code": null,
"e": 26039,
"s": 25838,
"text": "Example #1 :In this example we can see that by using np.assert_approx_equal() method, we are able to get the assertion error if two values are not equal up to a significant digit by using this method."
},
{
"code": "# import numpy and assert_approx_equalimport numpy as npimport numpy.testing as npt # using np.assert_approx_equal() methodgfg = npt.assert_approx_equal(1.2222222222, 1.2222222222, significant = 5) print(gfg)",
"e": 26250,
"s": 26039,
"text": null
},
{
"code": null,
"e": 26259,
"s": 26250,
"text": "Output :"
},
{
"code": null,
"e": 26264,
"s": 26259,
"text": "Nope"
},
{
"code": null,
"e": 26277,
"s": 26264,
"text": "Example #2 :"
},
{
"code": "# import numpy and assert_approx_equalimport numpy as npimport numpy.testing as npt # using np.assert_approx_equal() methodgfg = npt.assert_approx_equal(1.2222222222, 1.23422222, significant = 5) print(gfg)",
"e": 26486,
"s": 26277,
"text": null
},
{
"code": null,
"e": 26495,
"s": 26486,
"text": "Output :"
},
{
"code": null,
"e": 26594,
"s": 26495,
"text": "AssertionError:Items are not equal to 5 significant digits:ACTUAL: 1.2222222222DESIRED: 1.23422222"
},
{
"code": null,
"e": 26615,
"s": 26594,
"text": "Python numpy-Testing"
},
{
"code": null,
"e": 26628,
"s": 26615,
"text": "Python-numpy"
},
{
"code": null,
"e": 26635,
"s": 26628,
"text": "Python"
},
{
"code": null,
"e": 26733,
"s": 26635,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26765,
"s": 26733,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26807,
"s": 26765,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26849,
"s": 26807,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26905,
"s": 26849,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26932,
"s": 26905,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26971,
"s": 26932,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27002,
"s": 26971,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27031,
"s": 27002,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27053,
"s": 27031,
"text": "Defaultdict in Python"
}
] |
Blocks in PL/SQL - GeeksforGeeks
|
03 Dec, 2018
In PL/SQL, All statements are classified into units that is called Blocks. PL/SQL blocks can include variables, SQL statements, loops, constants, conditional statements and exception handling. Blocks can also build a function or a procedure or a package.
Broadly, PL/SQL blocks are two types: Anonymous blocks and
1. Anonymous blocks: In PL/SQL, That’s blocks which is not have header are known as anonymous blocks. These blocks do not form the body of a function or triggers or procedure.
Example: Here a code example of find greatest number with Anonymous blocks.
DECLARE -- declare variable a, b and c -- and these three variables datatype are integer a number; b number; c number; BEGIN a:= 10; b:= 100; --find largest number --take it in c variable IF a > b THEN c:= a; ELSE c:= b; END IF; dbms_output.put_line(' Maximum number in 10 and 100: ' || c); END; / -- Program End
Output:
Maximum number in 10 and 100: 100
2. Named blocks: That’s PL/SQL blocks which having header or labels are known as Named blocks. These blocks can either be subprograms like functions, procedures, packages or Triggers.
Example: Here a code example of find greatest number with Named blocks means using function.
DECLARE -- declare variable a, b and c -- and these three variables datatype are integer DECLARE a number; b number; c number; --Function return largest number of -- two given numberFUNCTION findMax(x IN number, y IN number) RETURN number IS z number; BEGIN IF x > y THEN z:= x; ELSE Z:= y; END IF; RETURN z; END; BEGIN a:= 10; b:= 100; c := findMax(a, b); dbms_output.put_line(' Maximum number in 10 and 100 is: ' || c); END; / -- Program End
Output:
Maximum number in 10 and 100: 100
SQL-PL/SQL
Technical Scripter 2018
SQL
Technical Scripter
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?
How to Create a Table With Multiple Foreign Keys in SQL?
What is Temporary Table in SQL?
SQL | Subquery
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL using Python
How to Write a SQL Query For a Specific Date Range and Date Time?
How to Select Data Between Two Dates and Times in SQL Server?
SQL Query to Compare Two Dates
|
[
{
"code": null,
"e": 25539,
"s": 25511,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 25794,
"s": 25539,
"text": "In PL/SQL, All statements are classified into units that is called Blocks. PL/SQL blocks can include variables, SQL statements, loops, constants, conditional statements and exception handling. Blocks can also build a function or a procedure or a package."
},
{
"code": null,
"e": 25853,
"s": 25794,
"text": "Broadly, PL/SQL blocks are two types: Anonymous blocks and"
},
{
"code": null,
"e": 26029,
"s": 25853,
"text": "1. Anonymous blocks: In PL/SQL, That’s blocks which is not have header are known as anonymous blocks. These blocks do not form the body of a function or triggers or procedure."
},
{
"code": null,
"e": 26105,
"s": 26029,
"text": "Example: Here a code example of find greatest number with Anonymous blocks."
},
{
"code": "DECLARE -- declare variable a, b and c -- and these three variables datatype are integer a number; b number; c number; BEGIN a:= 10; b:= 100; --find largest number --take it in c variable IF a > b THEN c:= a; ELSE c:= b; END IF; dbms_output.put_line(' Maximum number in 10 and 100: ' || c); END; / -- Program End ",
"e": 26472,
"s": 26105,
"text": null
},
{
"code": null,
"e": 26480,
"s": 26472,
"text": "Output:"
},
{
"code": null,
"e": 26515,
"s": 26480,
"text": "Maximum number in 10 and 100: 100\n"
},
{
"code": null,
"e": 26699,
"s": 26515,
"text": "2. Named blocks: That’s PL/SQL blocks which having header or labels are known as Named blocks. These blocks can either be subprograms like functions, procedures, packages or Triggers."
},
{
"code": null,
"e": 26792,
"s": 26699,
"text": "Example: Here a code example of find greatest number with Named blocks means using function."
},
{
"code": "DECLARE -- declare variable a, b and c -- and these three variables datatype are integer DECLARE a number; b number; c number; --Function return largest number of -- two given numberFUNCTION findMax(x IN number, y IN number) RETURN number IS z number; BEGIN IF x > y THEN z:= x; ELSE Z:= y; END IF; RETURN z; END; BEGIN a:= 10; b:= 100; c := findMax(a, b); dbms_output.put_line(' Maximum number in 10 and 100 is: ' || c); END; / -- Program End ",
"e": 27307,
"s": 26792,
"text": null
},
{
"code": null,
"e": 27315,
"s": 27307,
"text": "Output:"
},
{
"code": null,
"e": 27350,
"s": 27315,
"text": "Maximum number in 10 and 100: 100\n"
},
{
"code": null,
"e": 27361,
"s": 27350,
"text": "SQL-PL/SQL"
},
{
"code": null,
"e": 27385,
"s": 27361,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 27389,
"s": 27385,
"text": "SQL"
},
{
"code": null,
"e": 27408,
"s": 27389,
"text": "Technical Scripter"
},
{
"code": null,
"e": 27412,
"s": 27408,
"text": "SQL"
},
{
"code": null,
"e": 27510,
"s": 27412,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27576,
"s": 27510,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27633,
"s": 27576,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 27665,
"s": 27633,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27680,
"s": 27665,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27758,
"s": 27680,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27794,
"s": 27758,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27811,
"s": 27794,
"text": "SQL using Python"
},
{
"code": null,
"e": 27877,
"s": 27811,
"text": "How to Write a SQL Query For a Specific Date Range and Date Time?"
},
{
"code": null,
"e": 27939,
"s": 27877,
"text": "How to Select Data Between Two Dates and Times in SQL Server?"
}
] |
Java Program to Convert an Array into a List - GeeksforGeeks
|
09 Feb, 2022
Given an array. Your task is to convert the given array into a list in Java.
Examples:
Input: Array: [Geeks, forGeeks, A computer Portal]
Output: List: [Geeks, forGeeks, A computer Portal]
Input: Array: [1, 2, 3, 4, 5]
Output: List: [1, 2, 3, 4, 5]
Arrays: An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In the case of primitives data types, the actual values are stored in contiguous memory locations. In the case of objects of a class, the actual objects are stored in a heap segment.
List: The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and Stack classes.
There are numerous approaches to do the conversion of an array to a list in Java. A few of them are listed below.
Brute Force or Naive Method
Using Arrays.asList() Method
Using Collections.addAll() Method
Using Java 8 Stream API
Using Guava Lists.newArrayList()
In this method, an empty List is created and all elements present in the Array are added to it one by one.
Algorithm:
Get the Array to be converted.Create an empty ListIterate through the items in the Array.For each item, add it to the ListReturn the formed List
Get the Array to be converted.
Create an empty List
Iterate through the items in the Array.
For each item, add it to the List
Return the formed List
Java
// Java Program to convert// Array to List import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an Array to List public static <T> List<T> convertArrayToList(T array[]) { // Create an empty List List<T> list = new ArrayList<>(); // Iterate through the array for (T t : array) { // Add each element into the list list.add(t); } // Return the converted List return list; } public static void main(String args[]) { // Create an Array String array[] = { "Geeks", "forGeeks", "A Computer Portal" }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println("List: " + list); }}
Array: [Geeks, forGeeks, A Computer Portal]
List: [Geeks, forGeeks, A Computer Portal]
In this method, the Array is passed as the parameter into the List constructor with the help of the Arrays.asList() method.
Algorithm:
Get the Array to be converted.Create the List bypassing the Array as a parameter in the constructor of the List with the help of Arrays.asList() methodReturn the formed List
Get the Array to be converted.
Create the List bypassing the Array as a parameter in the constructor of the List with the help of Arrays.asList() method
Return the formed List
Java
// Java Program to convert// Array to List import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an Array to List public static <T> List<T> convertArrayToList(T array[]) { // Create the List by passing the Array // as parameter in the constructor List<T> list = Arrays.asList(array); // Return the converted List return list; } public static void main(String args[]) { // Create an Array String array[] = { "Geeks", "forGeeks", "A computer Portal" }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println("List: " + list); }}
Array: [Geeks, forGeeks, A computer Portal]
List: [Geeks, forGeeks, A computer Portal]
Since List is a part of the Collection package in Java. Therefore the Array can be converted into the List with the help of the Collections.addAll() method.
Algorithm:
Get the Array to be converted.Create an empty List.Add the array into the List by passing it as the parameter to the Collections.addAll() method.Return the formed List
Get the Array to be converted.
Create an empty List.
Add the array into the List by passing it as the parameter to the Collections.addAll() method.
Return the formed List
Java
// Java Program to convert// Array to List import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an Array to List public static <T> List<T> convertArrayToList(T array[]) { // Create the List by passing the Array // as parameter in the constructor List<T> list = new ArrayList<>(); // Add the array to list Collections.addAll(list, array); // Return the converted List return list; } public static void main(String args[]) { // Create an Array String array[] = { "Geeks", "forGeeks", "A computer Portal" }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println("List: " + list); }}
Array: [Geeks, forGeeks, A computer Portal]
List: [Geeks, forGeeks, A computer Portal]
An ArrayList constructor can take another collection object to construct a new list containing the elements of the specified array.
Algorithm:
Get the Array to be converted.Convert the array to StreamConvert the Stream to List using Collectors.toList()Collect the formed list using the collect() methodReturn the formed List
Get the Array to be converted.
Convert the array to Stream
Convert the Stream to List using Collectors.toList()
Collect the formed list using the collect() method
Return the formed List
Java
// Java Program to convert// Array to List in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert array to list public static <T> List<T> convertArrayToList(T array[]) { // create a list from the Array return Arrays.stream(array).collect( Collectors.toList()); } public static void main(String args[]) { // Create an Array String array[] = { "Geeks", "forGeeks", "A computer Portal" }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println("List: " + list); }}
Array: [Geeks, forGeeks, A computer Portal]
List: [Geeks, forGeeks, A computer Portal]
Lists.newArrayList() creates a mutable ArrayList instance containing the elements of the specified array.
Algorithm:
Get the Array to be converted.Create an empty List.Add the array into the List by passing it as the parameter to the Lists.newArrayList() method.Return the formed List
Get the Array to be converted.
Create an empty List.
Add the array into the List by passing it as the parameter to the Lists.newArrayList() method.
Return the formed List
Java
// Java Program to convert// Array to List in Java 8 import static com.google.common.collect.Lists.*; import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert array to list public static <T> List<T> convertArrayToList(T array[]) { // create a list from the Array return Lists.newArrayList(array); } public static void main(String args[]) { // Create an Array String array[] = { "Geeks", "forGeeks", "A computer Portal" }; // Print the Array System.out.println("Array: " + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println("List: " + list); }}
Output
Array: [Geeks, forGeeks, A computer Portal]
List: [Geeks, forGeeks, A computer Portal]
nishkarshgandhi
Java-Array-Programs
Java-Arrays
java-list
Java-List-Programs
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map 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
How to Iterate HashMap in Java?
|
[
{
"code": null,
"e": 26195,
"s": 26167,
"text": "\n09 Feb, 2022"
},
{
"code": null,
"e": 26272,
"s": 26195,
"text": "Given an array. Your task is to convert the given array into a list in Java."
},
{
"code": null,
"e": 26283,
"s": 26272,
"text": "Examples: "
},
{
"code": null,
"e": 26449,
"s": 26283,
"text": "Input: Array: [Geeks, forGeeks, A computer Portal] \nOutput: List: [Geeks, forGeeks, A computer Portal]\n\nInput: Array: [1, 2, 3, 4, 5] \nOutput: List: [1, 2, 3, 4, 5] "
},
{
"code": null,
"e": 26838,
"s": 26449,
"text": "Arrays: An array is a group of like-typed variables that are referred to by a common name. An array can contain primitives data types as well as objects of a class depending on the definition of the array. In the case of primitives data types, the actual values are stored in contiguous memory locations. In the case of objects of a class, the actual objects are stored in a heap segment."
},
{
"code": null,
"e": 27159,
"s": 26838,
"text": "List: The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and Stack classes."
},
{
"code": null,
"e": 27273,
"s": 27159,
"text": "There are numerous approaches to do the conversion of an array to a list in Java. A few of them are listed below."
},
{
"code": null,
"e": 27301,
"s": 27273,
"text": "Brute Force or Naive Method"
},
{
"code": null,
"e": 27330,
"s": 27301,
"text": "Using Arrays.asList() Method"
},
{
"code": null,
"e": 27364,
"s": 27330,
"text": "Using Collections.addAll() Method"
},
{
"code": null,
"e": 27388,
"s": 27364,
"text": "Using Java 8 Stream API"
},
{
"code": null,
"e": 27421,
"s": 27388,
"text": "Using Guava Lists.newArrayList()"
},
{
"code": null,
"e": 27528,
"s": 27421,
"text": "In this method, an empty List is created and all elements present in the Array are added to it one by one."
},
{
"code": null,
"e": 27539,
"s": 27528,
"text": "Algorithm:"
},
{
"code": null,
"e": 27684,
"s": 27539,
"text": "Get the Array to be converted.Create an empty ListIterate through the items in the Array.For each item, add it to the ListReturn the formed List"
},
{
"code": null,
"e": 27715,
"s": 27684,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 27736,
"s": 27715,
"text": "Create an empty List"
},
{
"code": null,
"e": 27776,
"s": 27736,
"text": "Iterate through the items in the Array."
},
{
"code": null,
"e": 27810,
"s": 27776,
"text": "For each item, add it to the List"
},
{
"code": null,
"e": 27833,
"s": 27810,
"text": "Return the formed List"
},
{
"code": null,
"e": 27838,
"s": 27833,
"text": "Java"
},
{
"code": "// Java Program to convert// Array to List import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an Array to List public static <T> List<T> convertArrayToList(T array[]) { // Create an empty List List<T> list = new ArrayList<>(); // Iterate through the array for (T t : array) { // Add each element into the list list.add(t); } // Return the converted List return list; } public static void main(String args[]) { // Create an Array String array[] = { \"Geeks\", \"forGeeks\", \"A Computer Portal\" }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println(\"List: \" + list); }}",
"e": 28780,
"s": 27838,
"text": null
},
{
"code": null,
"e": 28867,
"s": 28780,
"text": "Array: [Geeks, forGeeks, A Computer Portal]\nList: [Geeks, forGeeks, A Computer Portal]"
},
{
"code": null,
"e": 28991,
"s": 28867,
"text": "In this method, the Array is passed as the parameter into the List constructor with the help of the Arrays.asList() method."
},
{
"code": null,
"e": 29003,
"s": 28991,
"text": "Algorithm: "
},
{
"code": null,
"e": 29177,
"s": 29003,
"text": "Get the Array to be converted.Create the List bypassing the Array as a parameter in the constructor of the List with the help of Arrays.asList() methodReturn the formed List"
},
{
"code": null,
"e": 29208,
"s": 29177,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 29330,
"s": 29208,
"text": "Create the List bypassing the Array as a parameter in the constructor of the List with the help of Arrays.asList() method"
},
{
"code": null,
"e": 29353,
"s": 29330,
"text": "Return the formed List"
},
{
"code": null,
"e": 29358,
"s": 29353,
"text": "Java"
},
{
"code": "// Java Program to convert// Array to List import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an Array to List public static <T> List<T> convertArrayToList(T array[]) { // Create the List by passing the Array // as parameter in the constructor List<T> list = Arrays.asList(array); // Return the converted List return list; } public static void main(String args[]) { // Create an Array String array[] = { \"Geeks\", \"forGeeks\", \"A computer Portal\" }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println(\"List: \" + list); }}",
"e": 30218,
"s": 29358,
"text": null
},
{
"code": null,
"e": 30305,
"s": 30218,
"text": "Array: [Geeks, forGeeks, A computer Portal]\nList: [Geeks, forGeeks, A computer Portal]"
},
{
"code": null,
"e": 30462,
"s": 30305,
"text": "Since List is a part of the Collection package in Java. Therefore the Array can be converted into the List with the help of the Collections.addAll() method."
},
{
"code": null,
"e": 30474,
"s": 30462,
"text": "Algorithm: "
},
{
"code": null,
"e": 30642,
"s": 30474,
"text": "Get the Array to be converted.Create an empty List.Add the array into the List by passing it as the parameter to the Collections.addAll() method.Return the formed List"
},
{
"code": null,
"e": 30673,
"s": 30642,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 30695,
"s": 30673,
"text": "Create an empty List."
},
{
"code": null,
"e": 30790,
"s": 30695,
"text": "Add the array into the List by passing it as the parameter to the Collections.addAll() method."
},
{
"code": null,
"e": 30813,
"s": 30790,
"text": "Return the formed List"
},
{
"code": null,
"e": 30818,
"s": 30813,
"text": "Java"
},
{
"code": "// Java Program to convert// Array to List import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert an Array to List public static <T> List<T> convertArrayToList(T array[]) { // Create the List by passing the Array // as parameter in the constructor List<T> list = new ArrayList<>(); // Add the array to list Collections.addAll(list, array); // Return the converted List return list; } public static void main(String args[]) { // Create an Array String array[] = { \"Geeks\", \"forGeeks\", \"A computer Portal\" }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println(\"List: \" + list); }}",
"e": 31749,
"s": 30818,
"text": null
},
{
"code": null,
"e": 31836,
"s": 31749,
"text": "Array: [Geeks, forGeeks, A computer Portal]\nList: [Geeks, forGeeks, A computer Portal]"
},
{
"code": null,
"e": 31968,
"s": 31836,
"text": "An ArrayList constructor can take another collection object to construct a new list containing the elements of the specified array."
},
{
"code": null,
"e": 31980,
"s": 31968,
"text": "Algorithm: "
},
{
"code": null,
"e": 32162,
"s": 31980,
"text": "Get the Array to be converted.Convert the array to StreamConvert the Stream to List using Collectors.toList()Collect the formed list using the collect() methodReturn the formed List"
},
{
"code": null,
"e": 32193,
"s": 32162,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 32221,
"s": 32193,
"text": "Convert the array to Stream"
},
{
"code": null,
"e": 32274,
"s": 32221,
"text": "Convert the Stream to List using Collectors.toList()"
},
{
"code": null,
"e": 32325,
"s": 32274,
"text": "Collect the formed list using the collect() method"
},
{
"code": null,
"e": 32348,
"s": 32325,
"text": "Return the formed List"
},
{
"code": null,
"e": 32353,
"s": 32348,
"text": "Java"
},
{
"code": "// Java Program to convert// Array to List in Java 8 import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert array to list public static <T> List<T> convertArrayToList(T array[]) { // create a list from the Array return Arrays.stream(array).collect( Collectors.toList()); } public static void main(String args[]) { // Create an Array String array[] = { \"Geeks\", \"forGeeks\", \"A computer Portal\" }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println(\"List: \" + list); }}",
"e": 33143,
"s": 32353,
"text": null
},
{
"code": null,
"e": 33230,
"s": 33143,
"text": "Array: [Geeks, forGeeks, A computer Portal]\nList: [Geeks, forGeeks, A computer Portal]"
},
{
"code": null,
"e": 33337,
"s": 33230,
"text": "Lists.newArrayList() creates a mutable ArrayList instance containing the elements of the specified array. "
},
{
"code": null,
"e": 33349,
"s": 33337,
"text": "Algorithm: "
},
{
"code": null,
"e": 33517,
"s": 33349,
"text": "Get the Array to be converted.Create an empty List.Add the array into the List by passing it as the parameter to the Lists.newArrayList() method.Return the formed List"
},
{
"code": null,
"e": 33548,
"s": 33517,
"text": "Get the Array to be converted."
},
{
"code": null,
"e": 33570,
"s": 33548,
"text": "Create an empty List."
},
{
"code": null,
"e": 33665,
"s": 33570,
"text": "Add the array into the List by passing it as the parameter to the Lists.newArrayList() method."
},
{
"code": null,
"e": 33688,
"s": 33665,
"text": "Return the formed List"
},
{
"code": null,
"e": 33693,
"s": 33688,
"text": "Java"
},
{
"code": "// Java Program to convert// Array to List in Java 8 import static com.google.common.collect.Lists.*; import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert array to list public static <T> List<T> convertArrayToList(T array[]) { // create a list from the Array return Lists.newArrayList(array); } public static void main(String args[]) { // Create an Array String array[] = { \"Geeks\", \"forGeeks\", \"A computer Portal\" }; // Print the Array System.out.println(\"Array: \" + Arrays.toString(array)); // convert the Array to List List<String> list = convertArrayToList(array); // Print the List System.out.println(\"List: \" + list); }}",
"e": 34497,
"s": 33693,
"text": null
},
{
"code": null,
"e": 34504,
"s": 34497,
"text": "Output"
},
{
"code": null,
"e": 34591,
"s": 34504,
"text": "Array: [Geeks, forGeeks, A computer Portal]\nList: [Geeks, forGeeks, A computer Portal]"
},
{
"code": null,
"e": 34607,
"s": 34591,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 34627,
"s": 34607,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 34639,
"s": 34627,
"text": "Java-Arrays"
},
{
"code": null,
"e": 34649,
"s": 34639,
"text": "java-list"
},
{
"code": null,
"e": 34668,
"s": 34649,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 34673,
"s": 34668,
"text": "Java"
},
{
"code": null,
"e": 34687,
"s": 34673,
"text": "Java Programs"
},
{
"code": null,
"e": 34692,
"s": 34687,
"text": "Java"
},
{
"code": null,
"e": 34790,
"s": 34692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34841,
"s": 34790,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 34871,
"s": 34841,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 34886,
"s": 34871,
"text": "Stream In Java"
},
{
"code": null,
"e": 34905,
"s": 34886,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 34936,
"s": 34905,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 34980,
"s": 34936,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 35006,
"s": 34980,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 35040,
"s": 35006,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 35087,
"s": 35040,
"text": "Implementing a Linked List in Java using Class"
}
] |
Most useful JavaScript Array Functions – Part 2 - GeeksforGeeks
|
16 Mar, 2022
In Most useful JavaScript Array Functions – Part 1, we discussed two array functions namely Array.Prototype.Every() and Array.prototype.some(). It is important to note that both of these array functions accessed the array elements but did not modify/change the array itself. Today we are going to look at 2 array methods that modify the array and return the modified array.
Array.Prototype.filter()
Array.Prototype.map()
Array.Prototype.filter(): It is used to get a new array that has only those array elements which pass the test implemented by the callback function. It accepts a callback function as an argument. This callback function has to return a true or false. Elements for which the callback function returned true are added to the newly returned array.
Syntax:
array.filter(callback(element, index, arr), thisValue)
Parameters: This function accepts five parameter as mentioned above and described below:
callback: This parameter holds the function to be called for each element of the array.
element: The parameter holds the value of the elements being processed currently.
index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
array: This parameter is optional, it holds the complete array on which Array.every is called.
thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Examples: Filter out the students who got more than 80 percent marks.
Program 1: Function to filter out the students who got more than 80 percent marks. It is a naive Method using loop
Javascript
<script> function fnFilterStudents_loop(aStudent){ var tempArr = []; for(var i = 0 ; i< aStudent.length; i ++){ if(aStudent[i].fPercentage > 80.0) { tempArr.push(aStudent[i]);} } return tempArr; } aStudent = [ {sStudentId : "001" , fPercentage : 91.2}, {sStudentId : "002" , fPercentage : 78.7}, {sStudentId : "003" , fPercentage : 62.9}, {sStudentId : "004" , fPercentage : 81.4}]; console.log(fnFilterStudents_loop(aStudent));</script>
Output:
[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];
Program 2: Here we will be using Array.prototype.filter()
Javascript
<script> function fnFilterStudents_filter(aStudent){ return aStudent.filter(function(oStudent){ return oStudent.fPercentage > 80.0; }); } aStudent = [ {sStudentId : "001" , fPercentage : 91.2}, {sStudentId : "002" , fPercentage : 78.7}, {sStudentId : "003" , fPercentage : 62.9}, {sStudentId : "004" , fPercentage : 81.4}]; console.log(fnFilterStudents_filter(aStudent));</script>
Output:
[{sStudentId : "001" , fPercentage : 91.2},
{sStudentId : "004" , fPercentage : 81.4}];
Example: To remove undefined elements from an array
Program: Function to remove undefined elements from an array. In the callback function of the below example, we are returning elements directly. So if the element has value, it will be treated as true and if the element is undefined, it will be automatically treated as false.
Javascript
<script> function removeUndefined(myArray){ return myArray.filter(function(element, index, array) { return element; }); } var arr = [1,undefined,3,undefined,5]; console.log(arr); console.log( removeUndefined(arr));</script>
Output:
[1,undefined,3,undefined,5];
[1,3,5];
Array.Prototype.map(): It is used to modify each element of the array according to the callback function. Array.prototype.map() calls the callback function once for each element in the array in order. The point to note is that callback function is called on indexes of elements who has assigned value including undefined.
Syntax:
array.map(callback(element, index, arr), thisValue)
Parameters: This function accepts five parameter as mentioned above and described below:
callback: This parameter holds the function to be called for each element of the array.
element: The parameter holds the value of the elements being processed currently.
index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0.
array: This parameter is optional, it holds the complete array on which Array.every is called.
thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Examples: A scenario where the user has to reduce each amount in an array by a specific tax value
Program 1: Function to add property bIsDistinction to each object in the array, using Loop.
Javascript
<script> function fnAddDistinction_loop(aStudent){ for(var i = 0 ; i< aStudent.length; i ++){ aStudent[i].bIsDistinction = (aStudent[i].fPercentage >= 75.0) ? true : false; } return aStudent; } aStudent = [ {sStudentId : "001" , fPercentage : 91.2}, {sStudentId : "002" , fPercentage : 78.7}, {sStudentId : "003" , fPercentage : 62.9}, {sStudentId : "004" , fPercentage : 81.4}]; console.log(fnAddDistinction_loop(aStudent));</script>
Output:
[{sStudentId : "001" , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : "002" , fPercentage : 78.7 , bIsDistiction : true},
{sStudentId : "003" , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : "004" , fPercentage : 81.4 , bIsDistiction : true}];
Program 2: Here we will be using Array.prototype.map() function.
Javascript
<script> function fnAddDistinction_map(aStudent){ return aStudent.map(function(student, index, array){ aStudent.bIsDistinction = (aStudent.fPercentage >= 75.0) ? true : false; return aStudent; }); } aStudent = [ {sStudentId : "001" , fPercentage : 91.2}, {sStudentId : "002" , fPercentage : 78.7}, {sStudentId : "003" , fPercentage : 62.9}, {sStudentId : "004" , fPercentage : 81.4}]; console.log(fnAddDistinction_map(aStudent));</script>
Output:
[
{sStudentId : "001" , fPercentage : 91.2 , bIsDistiction : true},
{sStudentId : "002" , fPercentage : 78.7 , bIsDistiction : true},
{sStudentId : "003" , fPercentage : 62.9 , bIsDistiction : false},
{sStudentId : "004" , fPercentage : 81.4 , bIsDistiction : true}];
Example: A scenario where the user has to create a new property of every object in an existing array of objects.
Program: Array.prototype.Map() is used with standard JavaScript functions. For example, with Math.sqrt() function to calculate square root of each element in an array or to parse string values to float.
Javascript
[1,4,9].map(Math.sqrt); // Output : [1,2,3]["1.232","9.345","3.2345"].map(parseFloat)// Output : [1.232, 9.345, 3.2345]
One has to be careful while using Array.prototype.map() with standard functions because something like this can happen.
Javascript
["1","2","3"].map(parseInt);//Output : [1, NaN, NaN]
Why did the above code snippet return NaN? This happened because parseInt function accepts two arguments, First one being the element to be parsed to Integer and second as the radix which acts as base for conversion. When we use it with Array.prototype.map(), although the first argument is the element, the second argument is the index of the array element being processed currently. For first iteration, the index being 0 is passed as radix to parseInt which defaults it to 10 and thus you see first element parsed successfully. After that it gets messed up.
Below is the fix for above mess up.
Javascript
["1","2","3"].map(function(val){return parseInt(val,10)});// output : [1, 2, 3]
As shown in the above examples, both Array.prototype.filter() and Array.prototype.map() can be implemented using for loops. But in the above scenarios, we are trying to work on very specific use cases. Keeping a counter variable, then a checking against array length and then incrementing the counter variable. Keeping these things in mind is not only a hassle, but also make code prone to bugs. For example, a developer might accidentally misspell “array.length” as “array.length”. So as a rule of thumb, the best way to avoid programming bugs is to reduce the number of things that you are keeping track of manually. And these Array Functions do just that.
Browser support is really good for these functions but they are still not supported in IE8 or below as these array functions were introduced in ECMAScript 5. If you need to use it for older browsers as well, then you can either use es5-shim or any library like Underscore or Lodash can come to your rescue which has equivalent utility function.
Must use JavaScript Array Functions -Part 3
Additionally, if you wish to dive deeper into the above functions, you can refer to following official links 1. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.20 2. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19
About the author:
“Harshit is a technology enthusiast and has keen interest in programming. He holds a
B.Tech. degree in Computer Science from JIIT, Noida and currently works as Front-end Developer at SAP. He is also a state level table tennis player. Apart from this he likes to unwind by watching movies and English sitcoms. He is based out of Delhi and you can reach out to him at https://in.linkedin.com/pub/harshit-jain/2a/129/bb5
If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks.
yogigoodman
hchaudhari307
anikakapoor
jochenhansoul
javascript-array
JavaScript
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
Node.js | fs.writeFileSync() Method
How to Use the JavaScript Fetch API to Get Data?
JavaScript | Promises
How to get character array from string in JavaScript?
Set the value of an input field in JavaScript
|
[
{
"code": null,
"e": 25865,
"s": 25837,
"text": "\n16 Mar, 2022"
},
{
"code": null,
"e": 26239,
"s": 25865,
"text": "In Most useful JavaScript Array Functions – Part 1, we discussed two array functions namely Array.Prototype.Every() and Array.prototype.some(). It is important to note that both of these array functions accessed the array elements but did not modify/change the array itself. Today we are going to look at 2 array methods that modify the array and return the modified array."
},
{
"code": null,
"e": 26264,
"s": 26239,
"text": "Array.Prototype.filter()"
},
{
"code": null,
"e": 26286,
"s": 26264,
"text": "Array.Prototype.map()"
},
{
"code": null,
"e": 26630,
"s": 26286,
"text": "Array.Prototype.filter(): It is used to get a new array that has only those array elements which pass the test implemented by the callback function. It accepts a callback function as an argument. This callback function has to return a true or false. Elements for which the callback function returned true are added to the newly returned array."
},
{
"code": null,
"e": 26639,
"s": 26630,
"text": "Syntax: "
},
{
"code": null,
"e": 26694,
"s": 26639,
"text": "array.filter(callback(element, index, arr), thisValue)"
},
{
"code": null,
"e": 26784,
"s": 26694,
"text": "Parameters: This function accepts five parameter as mentioned above and described below: "
},
{
"code": null,
"e": 26872,
"s": 26784,
"text": "callback: This parameter holds the function to be called for each element of the array."
},
{
"code": null,
"e": 26954,
"s": 26872,
"text": "element: The parameter holds the value of the elements being processed currently."
},
{
"code": null,
"e": 27066,
"s": 26954,
"text": "index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0."
},
{
"code": null,
"e": 27161,
"s": 27066,
"text": "array: This parameter is optional, it holds the complete array on which Array.every is called."
},
{
"code": null,
"e": 27428,
"s": 27161,
"text": "thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default."
},
{
"code": null,
"e": 27499,
"s": 27428,
"text": "Examples: Filter out the students who got more than 80 percent marks. "
},
{
"code": null,
"e": 27614,
"s": 27499,
"text": "Program 1: Function to filter out the students who got more than 80 percent marks. It is a naive Method using loop"
},
{
"code": null,
"e": 27625,
"s": 27614,
"text": "Javascript"
},
{
"code": "<script> function fnFilterStudents_loop(aStudent){ var tempArr = []; for(var i = 0 ; i< aStudent.length; i ++){ if(aStudent[i].fPercentage > 80.0) { tempArr.push(aStudent[i]);} } return tempArr; } aStudent = [ {sStudentId : \"001\" , fPercentage : 91.2}, {sStudentId : \"002\" , fPercentage : 78.7}, {sStudentId : \"003\" , fPercentage : 62.9}, {sStudentId : \"004\" , fPercentage : 81.4}]; console.log(fnFilterStudents_loop(aStudent));</script>",
"e": 28179,
"s": 27625,
"text": null
},
{
"code": null,
"e": 28188,
"s": 28179,
"text": "Output: "
},
{
"code": null,
"e": 28276,
"s": 28188,
"text": "[{sStudentId : \"001\" , fPercentage : 91.2},\n{sStudentId : \"004\" , fPercentage : 81.4}];"
},
{
"code": null,
"e": 28334,
"s": 28276,
"text": "Program 2: Here we will be using Array.prototype.filter()"
},
{
"code": null,
"e": 28345,
"s": 28334,
"text": "Javascript"
},
{
"code": "<script> function fnFilterStudents_filter(aStudent){ return aStudent.filter(function(oStudent){ return oStudent.fPercentage > 80.0; }); } aStudent = [ {sStudentId : \"001\" , fPercentage : 91.2}, {sStudentId : \"002\" , fPercentage : 78.7}, {sStudentId : \"003\" , fPercentage : 62.9}, {sStudentId : \"004\" , fPercentage : 81.4}]; console.log(fnFilterStudents_filter(aStudent));</script>",
"e": 28800,
"s": 28345,
"text": null
},
{
"code": null,
"e": 28809,
"s": 28800,
"text": "Output: "
},
{
"code": null,
"e": 28897,
"s": 28809,
"text": "[{sStudentId : \"001\" , fPercentage : 91.2},\n{sStudentId : \"004\" , fPercentage : 81.4}];"
},
{
"code": null,
"e": 28950,
"s": 28897,
"text": "Example: To remove undefined elements from an array "
},
{
"code": null,
"e": 29227,
"s": 28950,
"text": "Program: Function to remove undefined elements from an array. In the callback function of the below example, we are returning elements directly. So if the element has value, it will be treated as true and if the element is undefined, it will be automatically treated as false."
},
{
"code": null,
"e": 29238,
"s": 29227,
"text": "Javascript"
},
{
"code": "<script> function removeUndefined(myArray){ return myArray.filter(function(element, index, array) { return element; }); } var arr = [1,undefined,3,undefined,5]; console.log(arr); console.log( removeUndefined(arr));</script>",
"e": 29524,
"s": 29238,
"text": null
},
{
"code": null,
"e": 29533,
"s": 29524,
"text": "Output: "
},
{
"code": null,
"e": 29571,
"s": 29533,
"text": "[1,undefined,3,undefined,5];\n[1,3,5];"
},
{
"code": null,
"e": 29893,
"s": 29571,
"text": "Array.Prototype.map(): It is used to modify each element of the array according to the callback function. Array.prototype.map() calls the callback function once for each element in the array in order. The point to note is that callback function is called on indexes of elements who has assigned value including undefined."
},
{
"code": null,
"e": 29902,
"s": 29893,
"text": "Syntax: "
},
{
"code": null,
"e": 29954,
"s": 29902,
"text": "array.map(callback(element, index, arr), thisValue)"
},
{
"code": null,
"e": 30044,
"s": 29954,
"text": "Parameters: This function accepts five parameter as mentioned above and described below: "
},
{
"code": null,
"e": 30132,
"s": 30044,
"text": "callback: This parameter holds the function to be called for each element of the array."
},
{
"code": null,
"e": 30214,
"s": 30132,
"text": "element: The parameter holds the value of the elements being processed currently."
},
{
"code": null,
"e": 30326,
"s": 30214,
"text": "index: This parameter is optional, it holds the index of the currentValue element in the array starting from 0."
},
{
"code": null,
"e": 30421,
"s": 30326,
"text": "array: This parameter is optional, it holds the complete array on which Array.every is called."
},
{
"code": null,
"e": 30688,
"s": 30421,
"text": "thisArg: This parameter is optional, it holds the context to be passed as this to be used while executing the callback function. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default."
},
{
"code": null,
"e": 30787,
"s": 30688,
"text": "Examples: A scenario where the user has to reduce each amount in an array by a specific tax value "
},
{
"code": null,
"e": 30879,
"s": 30787,
"text": "Program 1: Function to add property bIsDistinction to each object in the array, using Loop."
},
{
"code": null,
"e": 30890,
"s": 30879,
"text": "Javascript"
},
{
"code": "<script> function fnAddDistinction_loop(aStudent){ for(var i = 0 ; i< aStudent.length; i ++){ aStudent[i].bIsDistinction = (aStudent[i].fPercentage >= 75.0) ? true : false; } return aStudent; } aStudent = [ {sStudentId : \"001\" , fPercentage : 91.2}, {sStudentId : \"002\" , fPercentage : 78.7}, {sStudentId : \"003\" , fPercentage : 62.9}, {sStudentId : \"004\" , fPercentage : 81.4}]; console.log(fnAddDistinction_loop(aStudent));</script>",
"e": 31424,
"s": 30890,
"text": null
},
{
"code": null,
"e": 31433,
"s": 31424,
"text": "Output: "
},
{
"code": null,
"e": 31703,
"s": 31433,
"text": "[{sStudentId : \"001\" , fPercentage : 91.2 , bIsDistiction : true},\n {sStudentId : \"002\" , fPercentage : 78.7 , bIsDistiction : true},\n {sStudentId : \"003\" , fPercentage : 62.9 , bIsDistiction : false},\n {sStudentId : \"004\" , fPercentage : 81.4 , bIsDistiction : true}];"
},
{
"code": null,
"e": 31768,
"s": 31703,
"text": "Program 2: Here we will be using Array.prototype.map() function."
},
{
"code": null,
"e": 31779,
"s": 31768,
"text": "Javascript"
},
{
"code": "<script> function fnAddDistinction_map(aStudent){ return aStudent.map(function(student, index, array){ aStudent.bIsDistinction = (aStudent.fPercentage >= 75.0) ? true : false; return aStudent; }); } aStudent = [ {sStudentId : \"001\" , fPercentage : 91.2}, {sStudentId : \"002\" , fPercentage : 78.7}, {sStudentId : \"003\" , fPercentage : 62.9}, {sStudentId : \"004\" , fPercentage : 81.4}]; console.log(fnAddDistinction_map(aStudent));</script>",
"e": 32317,
"s": 31779,
"text": null
},
{
"code": null,
"e": 32325,
"s": 32317,
"text": "Output:"
},
{
"code": null,
"e": 32593,
"s": 32325,
"text": "[\n{sStudentId : \"001\" , fPercentage : 91.2 , bIsDistiction : true},\n{sStudentId : \"002\" , fPercentage : 78.7 , bIsDistiction : true},\n{sStudentId : \"003\" , fPercentage : 62.9 , bIsDistiction : false},\n{sStudentId : \"004\" , fPercentage : 81.4 , bIsDistiction : true}];"
},
{
"code": null,
"e": 32706,
"s": 32593,
"text": "Example: A scenario where the user has to create a new property of every object in an existing array of objects."
},
{
"code": null,
"e": 32909,
"s": 32706,
"text": "Program: Array.prototype.Map() is used with standard JavaScript functions. For example, with Math.sqrt() function to calculate square root of each element in an array or to parse string values to float."
},
{
"code": null,
"e": 32920,
"s": 32909,
"text": "Javascript"
},
{
"code": "[1,4,9].map(Math.sqrt); // Output : [1,2,3][\"1.232\",\"9.345\",\"3.2345\"].map(parseFloat)// Output : [1.232, 9.345, 3.2345]",
"e": 33040,
"s": 32920,
"text": null
},
{
"code": null,
"e": 33160,
"s": 33040,
"text": "One has to be careful while using Array.prototype.map() with standard functions because something like this can happen."
},
{
"code": null,
"e": 33171,
"s": 33160,
"text": "Javascript"
},
{
"code": "[\"1\",\"2\",\"3\"].map(parseInt);//Output : [1, NaN, NaN]",
"e": 33224,
"s": 33171,
"text": null
},
{
"code": null,
"e": 33785,
"s": 33224,
"text": "Why did the above code snippet return NaN? This happened because parseInt function accepts two arguments, First one being the element to be parsed to Integer and second as the radix which acts as base for conversion. When we use it with Array.prototype.map(), although the first argument is the element, the second argument is the index of the array element being processed currently. For first iteration, the index being 0 is passed as radix to parseInt which defaults it to 10 and thus you see first element parsed successfully. After that it gets messed up."
},
{
"code": null,
"e": 33821,
"s": 33785,
"text": "Below is the fix for above mess up."
},
{
"code": null,
"e": 33832,
"s": 33821,
"text": "Javascript"
},
{
"code": "[\"1\",\"2\",\"3\"].map(function(val){return parseInt(val,10)});// output : [1, 2, 3]",
"e": 33912,
"s": 33832,
"text": null
},
{
"code": null,
"e": 34571,
"s": 33912,
"text": "As shown in the above examples, both Array.prototype.filter() and Array.prototype.map() can be implemented using for loops. But in the above scenarios, we are trying to work on very specific use cases. Keeping a counter variable, then a checking against array length and then incrementing the counter variable. Keeping these things in mind is not only a hassle, but also make code prone to bugs. For example, a developer might accidentally misspell “array.length” as “array.length”. So as a rule of thumb, the best way to avoid programming bugs is to reduce the number of things that you are keeping track of manually. And these Array Functions do just that."
},
{
"code": null,
"e": 34916,
"s": 34571,
"text": "Browser support is really good for these functions but they are still not supported in IE8 or below as these array functions were introduced in ECMAScript 5. If you need to use it for older browsers as well, then you can either use es5-shim or any library like Underscore or Lodash can come to your rescue which has equivalent utility function."
},
{
"code": null,
"e": 34960,
"s": 34916,
"text": "Must use JavaScript Array Functions -Part 3"
},
{
"code": null,
"e": 35199,
"s": 34960,
"text": "Additionally, if you wish to dive deeper into the above functions, you can refer to following official links 1. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.20 2. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.19"
},
{
"code": null,
"e": 35217,
"s": 35199,
"text": "About the author:"
},
{
"code": null,
"e": 35302,
"s": 35217,
"text": "“Harshit is a technology enthusiast and has keen interest in programming. He holds a"
},
{
"code": null,
"e": 35635,
"s": 35302,
"text": "B.Tech. degree in Computer Science from JIIT, Noida and currently works as Front-end Developer at SAP. He is also a state level table tennis player. Apart from this he likes to unwind by watching movies and English sitcoms. He is based out of Delhi and you can reach out to him at https://in.linkedin.com/pub/harshit-jain/2a/129/bb5"
},
{
"code": null,
"e": 35737,
"s": 35635,
"text": "If you also wish to showcase your blog here,please see GBlog for guest blog writing on GeeksforGeeks."
},
{
"code": null,
"e": 35749,
"s": 35737,
"text": "yogigoodman"
},
{
"code": null,
"e": 35763,
"s": 35749,
"text": "hchaudhari307"
},
{
"code": null,
"e": 35775,
"s": 35763,
"text": "anikakapoor"
},
{
"code": null,
"e": 35789,
"s": 35775,
"text": "jochenhansoul"
},
{
"code": null,
"e": 35806,
"s": 35789,
"text": "javascript-array"
},
{
"code": null,
"e": 35817,
"s": 35806,
"text": "JavaScript"
},
{
"code": null,
"e": 35915,
"s": 35817,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35955,
"s": 35915,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 36000,
"s": 35955,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 36061,
"s": 36000,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 36133,
"s": 36061,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 36174,
"s": 36133,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 36210,
"s": 36174,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 36259,
"s": 36210,
"text": "How to Use the JavaScript Fetch API to Get Data?"
},
{
"code": null,
"e": 36281,
"s": 36259,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 36335,
"s": 36281,
"text": "How to get character array from string in JavaScript?"
}
] |
Perl | GET vs POST in CGI - GeeksforGeeks
|
14 Jul, 2019
In Perl, Common Gateway Interface (CGI) is nothing more than a protocol which defines the interaction of web servers with some executable programs in order to produce dynamic web pages. Basically, it shows how the web server sends information to the program and the program sends the information back to the web server which in turn can be sent back to the browser.GET and POST are not interchangeable and both the types are different. Proxy servers may cache the output of GET requests. GET method is the default method for all web request to pass the information from browser to the web server and it also creates a long string that shows up in the browser’s URL box. It sends the encrypted user information attached to the page request. The page and the encrypted information is separated by ? character:Example:
http://servername.com/cgi-bin/script_name.cgi or.pl?key1=value1&key2=value2.......
This information is passed through QUERY_STRING header and by using QUERY_STRING environment variable it can be easily accessed in your CGI program. Only 1024 characters can be there in a request string as the GET method has the size limitation. Information can be passed by simply concatenating key-value pairs along with any URL.
NOTE: If you are dealing with passwords or any other sensitive information in order to pass it to the server, then using the GET method is not a good choice.
Example:
<html><head></head><body><b> Search Your Query:</b><br><FORM action="Gfg_get.pl" method = "GET"><input type="text" name="q" size="20" maxlength="120"><input type="submit" value="Search"><br><input type="radio" name="l" value="Web" checked>Web<input type="radio" name="l" value="India">IND</FORM></body></html>
Output:
Perl-CGI script for the above GET method form:
#!"c:\xampp\perl\bin\perl.exe" $buffer = $ENV{'QUERY_STRING'};#split information into key/value pairs@pairs = split(/&/, $buffer);foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9] [a-fA-F0-9])/pack("C", hex($1))/eg; $value =~ s/~!/ ~!/g; $FORM{$name} = $value;} $SearchTerm = $FORM{'q'};$Location = $FORM{'l'}; print "Content-type:text/html\r\n\r\n";print "<html>";print "<head>";print "<title>GeeksForGeeks - Get Method</title>";print "</head>";print "<body>";print "<h3>Hello You searched '$Location' for '$SearchTerm'<br>Few Matches Found!<br><br>Match 1<br>Match 2<br>Match 3<br>Match 4<br>etc.....</h3>";print "</body>";print "</html>"; 1;
Output:As shown above, in the output image, the information is passed along with the URL:
http://localhost/xampp/cgi-bin/Gfg_get.pl?q=music&l=Web
In contrast, the POST method is the most reliable method to pass information to a CGI program. Generally, the POST method is used when the information is required to be uploaded on the server. Aiming of uploading larger amount of data, POST method is considered more suitable for it instead of GET method as none of the data appears in the URL box. Similar to the GET method, the information is packed in this too but instead of sending it as a text string after ? in the URL box, it sends it as a separate message to the server through a different route which is accessible by your Perl/CGI program.
Example:
<head></head><body><b>Please Fill in the Information:</b><br><form action="GfG_post.pl" method="post">First Name:<br><input type="text" name="first_name" size="25" maxlength="100"><br> Last Name:<br><input type="text" name="last_name" size="25" maxlength="100"><br><br>Languages:<br><input type="checkbox" name="python" value="yes">Python<input type="checkbox" name="java" value="yes">Java<input type="checkbox" name="kotlin" value="yes">Kotlin<input type="checkbox" name="perl" value="yes">Perl<input type="checkbox" name="swift" value="yes">Swift<br>Payment: <select name=payment><option>---Select---</option><Option value="Paypal"> Paypal </option><Option value="Internet Banking"> Internet Banking </option><Option value="Credit Card"> Credict Card </option><Option value="Paytm"> Paytm </option></select><br><br>First Time Customer?<br><input type="radio" name="first_time" value="Yes">Yes<input type="radio" name="first_time" value="No">No<br><br>Feedback:<br><textarea wrap= "virtual" name="feedback" cols="25" rows="3"></textarea><br><br><input type="submit" value="Place Order"></form></body></html>
Output:
Perl-CGI script for the above POST method:
#!"c:\xampp\perl\bin\perl.exe" read (STDIN, $buffer, $ENV{'CONTENT_LENGTH'});@pairs = split(/&/, $buffer);foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9] [a-fA-F0-9])/pack("C", hex($1))/eg; $value =~ s/~!/ ~!/g; $FORM{$name} = $value;} if($FORM{python}) { $python_flag ="YES";} else { $python_flag ="NO";} if($FORM{java}) { $java_flag ="YES";}else { $java_flag ="NO";} if($FORM{kotlin}){ $kotlin_flag ="YES";} else{ $kotlin_flag ="NO";} if($FORM{perl}) { $perl_flag ="YES";} else { $perl_flag ="NO";} if($FORM{swift}) { $swift_flag ="YES";} else{ $swift_flag ="NO";} $first_name= $FORM{'first_name'};$last_name= $FORM{'last_name'};$payment_method= $FORM{'payment'};$first_time= $FORM{'first_time'};$feed_back= $FORM{'feedback'}; print "Content-type:text/html\r\n\r\n";print "<html>";print "<head>";print "<title>GeeksForGeeks - Post Method</title>";print "</head>";print "<body>";print "<h3>Hello $first_name $last_name</h3>";print "<h3>Here is your Purchased Order!</h3>";print "<h3>Python: $python_flag</h3>";print "<h3>Java: $java_flag</h3>";print "<h3>Kotlin: $kotlin_flag</h3>";print "<h3>Perl: $perl_flag</h3>";print "<h3>Swift: $swift_flag</h3>";print "<h3>Payment Method: $payment_method</h3>";print "<h3>First Time Customer: $first_time</h3>";print "<h3>Feedback: $feed_back</h3>";print "</body>";print "</html>"; 1;
Output:
As it can be seen in the image above, that after using POST method the information is uploaded to the server without appearing into the URL box. This makes data sent over the internet, more secure in comparison to the GET method.
Picked
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | split() Function
Perl | push() Function
Perl | chomp() Function
Perl | grep() Function
Perl | substr() function
Perl | exists() Function
Perl Tutorial - Learn Perl With Examples
Perl | Removing leading and trailing white spaces (trim)
Use of print() and say() in Perl
Perl | length() Function
|
[
{
"code": null,
"e": 26525,
"s": 26497,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 27341,
"s": 26525,
"text": "In Perl, Common Gateway Interface (CGI) is nothing more than a protocol which defines the interaction of web servers with some executable programs in order to produce dynamic web pages. Basically, it shows how the web server sends information to the program and the program sends the information back to the web server which in turn can be sent back to the browser.GET and POST are not interchangeable and both the types are different. Proxy servers may cache the output of GET requests. GET method is the default method for all web request to pass the information from browser to the web server and it also creates a long string that shows up in the browser’s URL box. It sends the encrypted user information attached to the page request. The page and the encrypted information is separated by ? character:Example:"
},
{
"code": null,
"e": 27424,
"s": 27341,
"text": "http://servername.com/cgi-bin/script_name.cgi or.pl?key1=value1&key2=value2......."
},
{
"code": null,
"e": 27756,
"s": 27424,
"text": "This information is passed through QUERY_STRING header and by using QUERY_STRING environment variable it can be easily accessed in your CGI program. Only 1024 characters can be there in a request string as the GET method has the size limitation. Information can be passed by simply concatenating key-value pairs along with any URL."
},
{
"code": null,
"e": 27914,
"s": 27756,
"text": "NOTE: If you are dealing with passwords or any other sensitive information in order to pass it to the server, then using the GET method is not a good choice."
},
{
"code": null,
"e": 27923,
"s": 27914,
"text": "Example:"
},
{
"code": "<html><head></head><body><b> Search Your Query:</b><br><FORM action=\"Gfg_get.pl\" method = \"GET\"><input type=\"text\" name=\"q\" size=\"20\" maxlength=\"120\"><input type=\"submit\" value=\"Search\"><br><input type=\"radio\" name=\"l\" value=\"Web\" checked>Web<input type=\"radio\" name=\"l\" value=\"India\">IND</FORM></body></html>",
"e": 28233,
"s": 27923,
"text": null
},
{
"code": null,
"e": 28241,
"s": 28233,
"text": "Output:"
},
{
"code": null,
"e": 28288,
"s": 28241,
"text": "Perl-CGI script for the above GET method form:"
},
{
"code": "#!\"c:\\xampp\\perl\\bin\\perl.exe\" $buffer = $ENV{'QUERY_STRING'};#split information into key/value pairs@pairs = split(/&/, $buffer);foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9] [a-fA-F0-9])/pack(\"C\", hex($1))/eg; $value =~ s/~!/ ~!/g; $FORM{$name} = $value;} $SearchTerm = $FORM{'q'};$Location = $FORM{'l'}; print \"Content-type:text/html\\r\\n\\r\\n\";print \"<html>\";print \"<head>\";print \"<title>GeeksForGeeks - Get Method</title>\";print \"</head>\";print \"<body>\";print \"<h3>Hello You searched '$Location' for '$SearchTerm'<br>Few Matches Found!<br><br>Match 1<br>Match 2<br>Match 3<br>Match 4<br>etc.....</h3>\";print \"</body>\";print \"</html>\"; 1;",
"e": 29011,
"s": 28288,
"text": null
},
{
"code": null,
"e": 29101,
"s": 29011,
"text": "Output:As shown above, in the output image, the information is passed along with the URL:"
},
{
"code": null,
"e": 29157,
"s": 29101,
"text": "http://localhost/xampp/cgi-bin/Gfg_get.pl?q=music&l=Web"
},
{
"code": null,
"e": 29758,
"s": 29157,
"text": "In contrast, the POST method is the most reliable method to pass information to a CGI program. Generally, the POST method is used when the information is required to be uploaded on the server. Aiming of uploading larger amount of data, POST method is considered more suitable for it instead of GET method as none of the data appears in the URL box. Similar to the GET method, the information is packed in this too but instead of sending it as a text string after ? in the URL box, it sends it as a separate message to the server through a different route which is accessible by your Perl/CGI program."
},
{
"code": null,
"e": 29767,
"s": 29758,
"text": "Example:"
},
{
"code": "<head></head><body><b>Please Fill in the Information:</b><br><form action=\"GfG_post.pl\" method=\"post\">First Name:<br><input type=\"text\" name=\"first_name\" size=\"25\" maxlength=\"100\"><br> Last Name:<br><input type=\"text\" name=\"last_name\" size=\"25\" maxlength=\"100\"><br><br>Languages:<br><input type=\"checkbox\" name=\"python\" value=\"yes\">Python<input type=\"checkbox\" name=\"java\" value=\"yes\">Java<input type=\"checkbox\" name=\"kotlin\" value=\"yes\">Kotlin<input type=\"checkbox\" name=\"perl\" value=\"yes\">Perl<input type=\"checkbox\" name=\"swift\" value=\"yes\">Swift<br>Payment: <select name=payment><option>---Select---</option><Option value=\"Paypal\"> Paypal </option><Option value=\"Internet Banking\"> Internet Banking </option><Option value=\"Credit Card\"> Credict Card </option><Option value=\"Paytm\"> Paytm </option></select><br><br>First Time Customer?<br><input type=\"radio\" name=\"first_time\" value=\"Yes\">Yes<input type=\"radio\" name=\"first_time\" value=\"No\">No<br><br>Feedback:<br><textarea wrap= \"virtual\" name=\"feedback\" cols=\"25\" rows=\"3\"></textarea><br><br><input type=\"submit\" value=\"Place Order\"></form></body></html>",
"e": 30877,
"s": 29767,
"text": null
},
{
"code": null,
"e": 30885,
"s": 30877,
"text": "Output:"
},
{
"code": null,
"e": 30928,
"s": 30885,
"text": "Perl-CGI script for the above POST method:"
},
{
"code": "#!\"c:\\xampp\\perl\\bin\\perl.exe\" read (STDIN, $buffer, $ENV{'CONTENT_LENGTH'});@pairs = split(/&/, $buffer);foreach $pair (@pairs) { ($name, $value) = split(/=/, $pair); $value =~ tr/+/ /; $value =~ s/%([a-fA-F0-9] [a-fA-F0-9])/pack(\"C\", hex($1))/eg; $value =~ s/~!/ ~!/g; $FORM{$name} = $value;} if($FORM{python}) { $python_flag =\"YES\";} else { $python_flag =\"NO\";} if($FORM{java}) { $java_flag =\"YES\";}else { $java_flag =\"NO\";} if($FORM{kotlin}){ $kotlin_flag =\"YES\";} else{ $kotlin_flag =\"NO\";} if($FORM{perl}) { $perl_flag =\"YES\";} else { $perl_flag =\"NO\";} if($FORM{swift}) { $swift_flag =\"YES\";} else{ $swift_flag =\"NO\";} $first_name= $FORM{'first_name'};$last_name= $FORM{'last_name'};$payment_method= $FORM{'payment'};$first_time= $FORM{'first_time'};$feed_back= $FORM{'feedback'}; print \"Content-type:text/html\\r\\n\\r\\n\";print \"<html>\";print \"<head>\";print \"<title>GeeksForGeeks - Post Method</title>\";print \"</head>\";print \"<body>\";print \"<h3>Hello $first_name $last_name</h3>\";print \"<h3>Here is your Purchased Order!</h3>\";print \"<h3>Python: $python_flag</h3>\";print \"<h3>Java: $java_flag</h3>\";print \"<h3>Kotlin: $kotlin_flag</h3>\";print \"<h3>Perl: $perl_flag</h3>\";print \"<h3>Swift: $swift_flag</h3>\";print \"<h3>Payment Method: $payment_method</h3>\";print \"<h3>First Time Customer: $first_time</h3>\";print \"<h3>Feedback: $feed_back</h3>\";print \"</body>\";print \"</html>\"; 1;",
"e": 32366,
"s": 30928,
"text": null
},
{
"code": null,
"e": 32374,
"s": 32366,
"text": "Output:"
},
{
"code": null,
"e": 32604,
"s": 32374,
"text": "As it can be seen in the image above, that after using POST method the information is uploaded to the server without appearing into the URL box. This makes data sent over the internet, more secure in comparison to the GET method."
},
{
"code": null,
"e": 32611,
"s": 32604,
"text": "Picked"
},
{
"code": null,
"e": 32616,
"s": 32611,
"text": "Perl"
},
{
"code": null,
"e": 32621,
"s": 32616,
"text": "Perl"
},
{
"code": null,
"e": 32719,
"s": 32621,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32743,
"s": 32719,
"text": "Perl | split() Function"
},
{
"code": null,
"e": 32766,
"s": 32743,
"text": "Perl | push() Function"
},
{
"code": null,
"e": 32790,
"s": 32766,
"text": "Perl | chomp() Function"
},
{
"code": null,
"e": 32813,
"s": 32790,
"text": "Perl | grep() Function"
},
{
"code": null,
"e": 32838,
"s": 32813,
"text": "Perl | substr() function"
},
{
"code": null,
"e": 32863,
"s": 32838,
"text": "Perl | exists() Function"
},
{
"code": null,
"e": 32904,
"s": 32863,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 32961,
"s": 32904,
"text": "Perl | Removing leading and trailing white spaces (trim)"
},
{
"code": null,
"e": 32994,
"s": 32961,
"text": "Use of print() and say() in Perl"
}
] |
Python - Get Function Signature - GeeksforGeeks
|
29 Dec, 2020
Let’s consider a scenario where you have written a very lengthy code and want to know the function call details. So what you can do is scroll through your code each and every time for different functions to know their details or you can work smartly. You can create a code where you can get the function details without scrolling through the code. This can be achieved in two ways –
Using signature() function
Using decorators
We can get function Signature with the help of signature() Function. It takes callable as a parameter and returns the annotation. It raises a value Error if no signature is provided. If the Invalid type object is given then it throws a Type Error.
Syntax:
inspect.signature(callable, *, follow_wrapped=True)
Example 1:
from inspect import signature # declare a function gfg with some# parameterdef gfg(x:str, y:int): pass # with the help of signature function# store signature of the function in# variable tt = signature(gfg) # print the signature of the functionprint(t) # print the annonation of the parameter# of the functionprint(t.parameters['x']) # print the annonation of the parameter# of the functionprint(t.parameters['y'].annotation)
Output
(x:str, y:int)
x:str
<class 'int'>
To do this the functions in Python certain attributes. One such attribute is __code__ that returns the called function bytecode. The __code__ attributes also have certain attributes that will help us in performing our tasks. We will be using the co_varnames attribute that returns the tuple of names of arguments and local variables and co_argcount that returns the number of arguments (not including keyword-only arguments, * or ** args). Let’s see the below implementation of such decorator using these discussed attributes.
Example:
# Decorator to print function call # details def function_details(func): # Getting the argument names of the # called function argnames = func.__code__.co_varnames[:func.__code__.co_argcount] # Getting the Function name of the # called function fname = func.__name__ def inner_func(*args, **kwargs): print(fname, "(", end = "") # printing the function arguments print(', '.join( '% s = % r' % entry for entry in zip(argnames, args[:len(argnames)])), end = ", ") # Printing the variable length Arguments print("args =", list(args[len(argnames):]), end = ", ") # Printing the variable length keyword # arguments print("kwargs =", kwargs, end = "") print(")") return inner_func # Driver Code @function_detailsdef GFG(a, b = 1, *args, **kwargs): pass GFG(1, 2, 3, 4, 5, d = 6, g = 12.9) GFG(1, 2, 3) GFG(1, 2, d = 'Geeks')
Output:
GFG (a = 1, b = 2, args = [3, 4, 5], kwargs = {‘d’: 6, ‘g’: 12.9})GFG (a = 1, b = 2, args = [3], kwargs = {})GFG (a = 1, b = 2, args = [], kwargs = {‘d’: ‘Geeks’})
Python Decorators
Python function-programs
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
|
[
{
"code": null,
"e": 25353,
"s": 25325,
"text": "\n29 Dec, 2020"
},
{
"code": null,
"e": 25736,
"s": 25353,
"text": "Let’s consider a scenario where you have written a very lengthy code and want to know the function call details. So what you can do is scroll through your code each and every time for different functions to know their details or you can work smartly. You can create a code where you can get the function details without scrolling through the code. This can be achieved in two ways –"
},
{
"code": null,
"e": 25763,
"s": 25736,
"text": "Using signature() function"
},
{
"code": null,
"e": 25780,
"s": 25763,
"text": "Using decorators"
},
{
"code": null,
"e": 26028,
"s": 25780,
"text": "We can get function Signature with the help of signature() Function. It takes callable as a parameter and returns the annotation. It raises a value Error if no signature is provided. If the Invalid type object is given then it throws a Type Error."
},
{
"code": null,
"e": 26036,
"s": 26028,
"text": "Syntax:"
},
{
"code": null,
"e": 26088,
"s": 26036,
"text": "inspect.signature(callable, *, follow_wrapped=True)"
},
{
"code": null,
"e": 26099,
"s": 26088,
"text": "Example 1:"
},
{
"code": "from inspect import signature # declare a function gfg with some# parameterdef gfg(x:str, y:int): pass # with the help of signature function# store signature of the function in# variable tt = signature(gfg) # print the signature of the functionprint(t) # print the annonation of the parameter# of the functionprint(t.parameters['x']) # print the annonation of the parameter# of the functionprint(t.parameters['y'].annotation)",
"e": 26535,
"s": 26099,
"text": null
},
{
"code": null,
"e": 26542,
"s": 26535,
"text": "Output"
},
{
"code": null,
"e": 26577,
"s": 26542,
"text": "(x:str, y:int)\nx:str\n<class 'int'>"
},
{
"code": null,
"e": 27104,
"s": 26577,
"text": "To do this the functions in Python certain attributes. One such attribute is __code__ that returns the called function bytecode. The __code__ attributes also have certain attributes that will help us in performing our tasks. We will be using the co_varnames attribute that returns the tuple of names of arguments and local variables and co_argcount that returns the number of arguments (not including keyword-only arguments, * or ** args). Let’s see the below implementation of such decorator using these discussed attributes."
},
{
"code": null,
"e": 27113,
"s": 27104,
"text": "Example:"
},
{
"code": "# Decorator to print function call # details def function_details(func): # Getting the argument names of the # called function argnames = func.__code__.co_varnames[:func.__code__.co_argcount] # Getting the Function name of the # called function fname = func.__name__ def inner_func(*args, **kwargs): print(fname, \"(\", end = \"\") # printing the function arguments print(', '.join( '% s = % r' % entry for entry in zip(argnames, args[:len(argnames)])), end = \", \") # Printing the variable length Arguments print(\"args =\", list(args[len(argnames):]), end = \", \") # Printing the variable length keyword # arguments print(\"kwargs =\", kwargs, end = \"\") print(\")\") return inner_func # Driver Code @function_detailsdef GFG(a, b = 1, *args, **kwargs): pass GFG(1, 2, 3, 4, 5, d = 6, g = 12.9) GFG(1, 2, 3) GFG(1, 2, d = 'Geeks') ",
"e": 28164,
"s": 27113,
"text": null
},
{
"code": null,
"e": 28172,
"s": 28164,
"text": "Output:"
},
{
"code": null,
"e": 28336,
"s": 28172,
"text": "GFG (a = 1, b = 2, args = [3, 4, 5], kwargs = {‘d’: 6, ‘g’: 12.9})GFG (a = 1, b = 2, args = [3], kwargs = {})GFG (a = 1, b = 2, args = [], kwargs = {‘d’: ‘Geeks’})"
},
{
"code": null,
"e": 28354,
"s": 28336,
"text": "Python Decorators"
},
{
"code": null,
"e": 28379,
"s": 28354,
"text": "Python function-programs"
},
{
"code": null,
"e": 28396,
"s": 28379,
"text": "Python-Functions"
},
{
"code": null,
"e": 28403,
"s": 28396,
"text": "Python"
},
{
"code": null,
"e": 28501,
"s": 28403,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28519,
"s": 28501,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28554,
"s": 28519,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28586,
"s": 28554,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28608,
"s": 28586,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28650,
"s": 28608,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28680,
"s": 28650,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28706,
"s": 28680,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28735,
"s": 28706,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28779,
"s": 28735,
"text": "Reading and Writing to text files in Python"
}
] |
Java substring() method memory leak issue and fix - GeeksforGeeks
|
16 Jul, 2021
String is a special class in Java. substring() is one of the widely used methods of String class. It is used to extract part of a string and has two overloaded variants:1. substring(int beginIndex) This method is used to extract a portion of the string starting from beginIndex. Example:
Java
class GFG { public static void main(String args[]) { String s = "geeksforgeeks"; String subString = s.substring(4); System.out.print(subString); }}
The beginIndex parameter must be within the range of source string, otherwise you would see the following exception:
java.lang.StringIndexOutOfBoundsException: String index out of range:
2. substring(int beginIndex, int endIndex) This variant accepts two parameters beginIndex and endIndex. It breaks String starting from beginIndex till endIndex – 1.Example:
Java
class GFG { public static void main(String args[]) { String s = "geeksforgeeks"; String subString = s.substring(5, 13); System.out.print(subString); }}
How substring() works internally We all know that String in Java is sequence of characters. String is internally represented by array of characters, when new String object is created, it has following fields.
char value[] – Array of characters
int count – Total characters in the String
int offset – Starting index offset in character array
String s = “geeksforgeeks”; value[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’} count = 13 offset = 0
When we take substring from original string, new String object will be created in constant pool or in heap. The value[] char array will be shared among two String objects, but count and offset attributes of String object will vary according to substring length and starting index.
String s = “geeksforgeeks”; String substr = s.substring(5, 8)For substr: value[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’} count = 3 offset = 5
Problem caused by substring() in JDK 6 This method works well with small Strings. But when it comes with taking substring() from a String with more characters, it leads to serious memory issues if you are using JDK 6 or below.Example:
String bigString = new String(new byte[100000])
The above String already occupies a lot of memory in heap. Now consider the scenario where we need first 2 characters from bigString,.
String substr = bigString.substring(0, 2)
Now we don’t need the original String.
bigString = null
We might think that bigString object will be Garbage collected as we made it null but our assumption is wrong. When we call substring(), a new String object is created in memory. But still it refers the char[] array value from original String. This prevents bigString from Garbage collection process and we are unnecessarily storing 100000 bytes in memory (just for 2 characters). The bug details can be found here.Handling substring() in JDK 6 This issue should be handled by developers. One option is creating new String object from substring returned String.
String substr = new String(bigString.substring(0, 2))
Now, new String object is created in java heap, having its own char[] array, eventually original bigString will eligible for garbage collection process.Other option is, call intern() method on substring, which will then fetch an existing string from pool or add it if necessary.
String substr = bigString.substring(0, 2).intern()
Fix for substring() in JDK 7 Sun Microsystems has changed the implementation of substring() from JdK 7. When we invoke substring() in JDK 7, instead of referring char[] array from original String, jvm creates new String objects with its own char[] array.
Java
//JDK 7public String(char value[], int offset, int count) { //check boundary this.value = Arrays.copyOfRange(value, offset, offset + count);} public String substring(int beginIndex, int endIndex) { //check boundary int subLen = endIndex - beginIndex; return new String(value, beginIndex, subLen);}
It is worth noting that, new String object from memory is referred when substring() method is invoked in JDK 7, thus making original string eligible for garbage collection.
jyotijindal36
Java-Strings
Technical Scripter 2018
Java
Java Programs
Strings
Technical Scripter
Java-Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Program to print ASCII Value of a character
|
[
{
"code": null,
"e": 25249,
"s": 25221,
"text": "\n16 Jul, 2021"
},
{
"code": null,
"e": 25539,
"s": 25249,
"text": "String is a special class in Java. substring() is one of the widely used methods of String class. It is used to extract part of a string and has two overloaded variants:1. substring(int beginIndex) This method is used to extract a portion of the string starting from beginIndex. Example: "
},
{
"code": null,
"e": 25544,
"s": 25539,
"text": "Java"
},
{
"code": "class GFG { public static void main(String args[]) { String s = \"geeksforgeeks\"; String subString = s.substring(4); System.out.print(subString); }}",
"e": 25719,
"s": 25544,
"text": null
},
{
"code": null,
"e": 25837,
"s": 25719,
"text": "The beginIndex parameter must be within the range of source string, otherwise you would see the following exception: "
},
{
"code": null,
"e": 25907,
"s": 25837,
"text": "java.lang.StringIndexOutOfBoundsException: String index out of range:"
},
{
"code": null,
"e": 26082,
"s": 25907,
"text": "2. substring(int beginIndex, int endIndex) This variant accepts two parameters beginIndex and endIndex. It breaks String starting from beginIndex till endIndex – 1.Example: "
},
{
"code": null,
"e": 26087,
"s": 26082,
"text": "Java"
},
{
"code": "class GFG { public static void main(String args[]) { String s = \"geeksforgeeks\"; String subString = s.substring(5, 13); System.out.print(subString); }}",
"e": 26266,
"s": 26087,
"text": null
},
{
"code": null,
"e": 26477,
"s": 26266,
"text": "How substring() works internally We all know that String in Java is sequence of characters. String is internally represented by array of characters, when new String object is created, it has following fields. "
},
{
"code": null,
"e": 26512,
"s": 26477,
"text": "char value[] – Array of characters"
},
{
"code": null,
"e": 26555,
"s": 26512,
"text": "int count – Total characters in the String"
},
{
"code": null,
"e": 26609,
"s": 26555,
"text": "int offset – Starting index offset in character array"
},
{
"code": null,
"e": 26737,
"s": 26611,
"text": "String s = “geeksforgeeks”; value[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’} count = 13 offset = 0"
},
{
"code": null,
"e": 27019,
"s": 26737,
"text": "When we take substring from original string, new String object will be created in constant pool or in heap. The value[] char array will be shared among two String objects, but count and offset attributes of String object will vary according to substring length and starting index. "
},
{
"code": null,
"e": 27190,
"s": 27019,
"text": "String s = “geeksforgeeks”; String substr = s.substring(5, 8)For substr: value[] = {‘g’, ‘e’, ‘e’, ‘k’, ‘s’, ‘f’, ‘o’, ‘r’, ‘g’, ‘e’, ‘e’, ‘k’, ‘s’} count = 3 offset = 5 "
},
{
"code": null,
"e": 27427,
"s": 27190,
"text": "Problem caused by substring() in JDK 6 This method works well with small Strings. But when it comes with taking substring() from a String with more characters, it leads to serious memory issues if you are using JDK 6 or below.Example: "
},
{
"code": null,
"e": 27475,
"s": 27427,
"text": "String bigString = new String(new byte[100000])"
},
{
"code": null,
"e": 27613,
"s": 27475,
"text": " The above String already occupies a lot of memory in heap. Now consider the scenario where we need first 2 characters from bigString,. "
},
{
"code": null,
"e": 27655,
"s": 27613,
"text": "String substr = bigString.substring(0, 2)"
},
{
"code": null,
"e": 27697,
"s": 27655,
"text": " Now we don’t need the original String. "
},
{
"code": null,
"e": 27714,
"s": 27697,
"text": "bigString = null"
},
{
"code": null,
"e": 28279,
"s": 27714,
"text": " We might think that bigString object will be Garbage collected as we made it null but our assumption is wrong. When we call substring(), a new String object is created in memory. But still it refers the char[] array value from original String. This prevents bigString from Garbage collection process and we are unnecessarily storing 100000 bytes in memory (just for 2 characters). The bug details can be found here.Handling substring() in JDK 6 This issue should be handled by developers. One option is creating new String object from substring returned String. "
},
{
"code": null,
"e": 28333,
"s": 28279,
"text": "String substr = new String(bigString.substring(0, 2))"
},
{
"code": null,
"e": 28615,
"s": 28333,
"text": " Now, new String object is created in java heap, having its own char[] array, eventually original bigString will eligible for garbage collection process.Other option is, call intern() method on substring, which will then fetch an existing string from pool or add it if necessary. "
},
{
"code": null,
"e": 28666,
"s": 28615,
"text": "String substr = bigString.substring(0, 2).intern()"
},
{
"code": null,
"e": 28922,
"s": 28666,
"text": "Fix for substring() in JDK 7 Sun Microsystems has changed the implementation of substring() from JdK 7. When we invoke substring() in JDK 7, instead of referring char[] array from original String, jvm creates new String objects with its own char[] array. "
},
{
"code": null,
"e": 28927,
"s": 28922,
"text": "Java"
},
{
"code": "//JDK 7public String(char value[], int offset, int count) { //check boundary this.value = Arrays.copyOfRange(value, offset, offset + count);} public String substring(int beginIndex, int endIndex) { //check boundary int subLen = endIndex - beginIndex; return new String(value, beginIndex, subLen);}",
"e": 29242,
"s": 28927,
"text": null
},
{
"code": null,
"e": 29416,
"s": 29242,
"text": "It is worth noting that, new String object from memory is referred when substring() method is invoked in JDK 7, thus making original string eligible for garbage collection. "
},
{
"code": null,
"e": 29430,
"s": 29416,
"text": "jyotijindal36"
},
{
"code": null,
"e": 29443,
"s": 29430,
"text": "Java-Strings"
},
{
"code": null,
"e": 29467,
"s": 29443,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 29472,
"s": 29467,
"text": "Java"
},
{
"code": null,
"e": 29486,
"s": 29472,
"text": "Java Programs"
},
{
"code": null,
"e": 29494,
"s": 29486,
"text": "Strings"
},
{
"code": null,
"e": 29513,
"s": 29494,
"text": "Technical Scripter"
},
{
"code": null,
"e": 29526,
"s": 29513,
"text": "Java-Strings"
},
{
"code": null,
"e": 29534,
"s": 29526,
"text": "Strings"
},
{
"code": null,
"e": 29539,
"s": 29534,
"text": "Java"
},
{
"code": null,
"e": 29637,
"s": 29539,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29652,
"s": 29637,
"text": "Stream In Java"
},
{
"code": null,
"e": 29673,
"s": 29652,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29692,
"s": 29673,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29722,
"s": 29692,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29768,
"s": 29722,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29794,
"s": 29768,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29828,
"s": 29794,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29875,
"s": 29828,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 29907,
"s": 29875,
"text": "How to Iterate HashMap in Java?"
}
] |
C# | Convert.ToByte(String, IFormatProvider) Method - GeeksforGeeks
|
02 Sep, 2021
This method is used to convert the specified string representation of a number to an equivalent 8-bit unsigned integer, using specified culture-specific formatting information.Syntax:
public static byte ToByte (string value, IFormatProvider provider);
Parameters:
value: It is a string that contains the number to convert.
provider: It is an object that supplies culture-specific formatting information.
Return Value: This method returns an 8-bit unsigned integer that is equivalent to value, or zero if value is null.Exceptions:
FormatException: If the value does not consist of an optional sign followed by a sequence of digits (0 through 9).
OverflowException: If the value represents a number that is less than MinValue or greater than MaxValue.
Below programs illustrate the use of Convert.ToByte(String, IFormatProvider) Method:Example 1:
csharp
// C# program to demonstrate the// Convert.ToByte() Methodusing System;using System.Globalization;class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = { "234", "+234", "240", "255", "140", "120" }; // calling get() Method Console.WriteLine("Converted bool value "+ "of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine("\n"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool byte val = Convert.ToByte(s, cultures); // display the converted string Console.Write(" {0}, ", val);}}
Converted bool value of specified strings:
234, 234, 240, 255, 140, 120,
Example 2: For FormatException
csharp
// C# program to demonstrate the// Convert.ToByte() Methodusing System;using System.Globalization;class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = {"234", "+234", "240", "255", "140", "A"}; // calling get() Method Console.WriteLine("]n Converted bool value "+ "of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n\nvalue consist invalid format"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine("\n value represents a "+ "number that is less than MinValue"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool byte val = Convert.ToByte(s, cultures); // display the converted string Console.Write(" {0}, ", val);}}
]n Converted bool value of specified strings:
234, 234, 240, 255, 140,
value consist invalid format
Exception Thrown: System.FormatException
Example 3: For OverflowException
csharp
// C# program to demonstrate the// Convert.ToByte() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo("en-US"); // declaring and initializing String array string[] values = {"234", "+234", "240", "255", "140", "-1" }; // calling get() Method Console.WriteLine("]n Converted bool value"+ " of specified strings: "); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine("\n\nvalue consist invalid format"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine("\n\nvalue represents a number"+ " that is less than MinValue"); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool byte val = Convert.ToByte(s, cultures); // display the converted string Console.Write(" {0}, ", val);}}
]n Converted bool value of specified strings:
234, 234, 240, 255, 140,
value represents a number that is less than MinValue
Exception Thrown: System.OverflowException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.convert.tobyte?view=netframework-4.7.2#System_Convert_ToByte_System_String_System_IFormatProvider_
sweetyty
CSharp Convert Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Extension Method in C#
HashSet in C# with Examples
C# | Inheritance
Partial Classes in C#
C# | Generics - Introduction
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Switch Statement in C#
Linked List Implementation in C#
Convert String to Character Array in C#
|
[
{
"code": null,
"e": 25547,
"s": 25519,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 25731,
"s": 25547,
"text": "This method is used to convert the specified string representation of a number to an equivalent 8-bit unsigned integer, using specified culture-specific formatting information.Syntax:"
},
{
"code": null,
"e": 25799,
"s": 25731,
"text": "public static byte ToByte (string value, IFormatProvider provider);"
},
{
"code": null,
"e": 25813,
"s": 25799,
"text": "Parameters: "
},
{
"code": null,
"e": 25872,
"s": 25813,
"text": "value: It is a string that contains the number to convert."
},
{
"code": null,
"e": 25953,
"s": 25872,
"text": "provider: It is an object that supplies culture-specific formatting information."
},
{
"code": null,
"e": 26080,
"s": 25953,
"text": "Return Value: This method returns an 8-bit unsigned integer that is equivalent to value, or zero if value is null.Exceptions: "
},
{
"code": null,
"e": 26195,
"s": 26080,
"text": "FormatException: If the value does not consist of an optional sign followed by a sequence of digits (0 through 9)."
},
{
"code": null,
"e": 26300,
"s": 26195,
"text": "OverflowException: If the value represents a number that is less than MinValue or greater than MaxValue."
},
{
"code": null,
"e": 26396,
"s": 26300,
"text": "Below programs illustrate the use of Convert.ToByte(String, IFormatProvider) Method:Example 1: "
},
{
"code": null,
"e": 26403,
"s": 26396,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToByte() Methodusing System;using System.Globalization;class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = { \"234\", \"+234\", \"240\", \"255\", \"140\", \"120\" }; // calling get() Method Console.WriteLine(\"Converted bool value \"+ \"of specified strings: \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine(\"\\n\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool byte val = Convert.ToByte(s, cultures); // display the converted string Console.Write(\" {0}, \", val);}}",
"e": 27681,
"s": 26403,
"text": null
},
{
"code": null,
"e": 27761,
"s": 27681,
"text": "Converted bool value of specified strings: \n 234, 234, 240, 255, 140, 120,"
},
{
"code": null,
"e": 27794,
"s": 27763,
"text": "Example 2: For FormatException"
},
{
"code": null,
"e": 27801,
"s": 27794,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToByte() Methodusing System;using System.Globalization;class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = {\"234\", \"+234\", \"240\", \"255\", \"140\", \"A\"}; // calling get() Method Console.WriteLine(\"]n Converted bool value \"+ \"of specified strings: \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\\nvalue consist invalid format\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine(\"\\n value represents a \"+ \"number that is less than MinValue\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool byte val = Convert.ToByte(s, cultures); // display the converted string Console.Write(\" {0}, \", val);}}",
"e": 29203,
"s": 27801,
"text": null
},
{
"code": null,
"e": 29352,
"s": 29203,
"text": "]n Converted bool value of specified strings: \n 234, 234, 240, 255, 140, \n\nvalue consist invalid format\nException Thrown: System.FormatException"
},
{
"code": null,
"e": 29387,
"s": 29354,
"text": "Example 3: For OverflowException"
},
{
"code": null,
"e": 29394,
"s": 29387,
"text": "csharp"
},
{
"code": "// C# program to demonstrate the// Convert.ToByte() Methodusing System;using System.Globalization; class GFG { // Main Methodpublic static void Main(){ try { // creating object of CultureInfo CultureInfo cultures = new CultureInfo(\"en-US\"); // declaring and initializing String array string[] values = {\"234\", \"+234\", \"240\", \"255\", \"140\", \"-1\" }; // calling get() Method Console.WriteLine(\"]n Converted bool value\"+ \" of specified strings: \"); for (int j = 0; j < values.Length; j++) { get(values[j], cultures); } } catch (FormatException e) { Console.WriteLine(\"\\n\\nvalue consist invalid format\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (OverflowException e) { Console.WriteLine(\"\\n\\nvalue represents a number\"+ \" that is less than MinValue\"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining get() methodpublic static void get(string s, CultureInfo cultures){ // converting string to specified bool byte val = Convert.ToByte(s, cultures); // display the converted string Console.Write(\" {0}, \", val);}}",
"e": 30782,
"s": 29394,
"text": null
},
{
"code": null,
"e": 30957,
"s": 30782,
"text": "]n Converted bool value of specified strings: \n 234, 234, 240, 255, 140, \n\nvalue represents a number that is less than MinValue\nException Thrown: System.OverflowException"
},
{
"code": null,
"e": 30970,
"s": 30959,
"text": "Reference:"
},
{
"code": null,
"e": 31121,
"s": 30970,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.convert.tobyte?view=netframework-4.7.2#System_Convert_ToByte_System_String_System_IFormatProvider_ "
},
{
"code": null,
"e": 31130,
"s": 31121,
"text": "sweetyty"
},
{
"code": null,
"e": 31151,
"s": 31130,
"text": "CSharp Convert Class"
},
{
"code": null,
"e": 31165,
"s": 31151,
"text": "CSharp-method"
},
{
"code": null,
"e": 31168,
"s": 31165,
"text": "C#"
},
{
"code": null,
"e": 31266,
"s": 31168,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31289,
"s": 31266,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 31317,
"s": 31289,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 31334,
"s": 31317,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 31356,
"s": 31334,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 31385,
"s": 31356,
"text": "C# | Generics - Introduction"
},
{
"code": null,
"e": 31425,
"s": 31385,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 31468,
"s": 31425,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 31491,
"s": 31468,
"text": "Switch Statement in C#"
},
{
"code": null,
"e": 31524,
"s": 31491,
"text": "Linked List Implementation in C#"
}
] |
Sum of Binomial coefficients - GeeksforGeeks
|
30 Apr, 2021
Given a positive integer n, the task is to find the sum of binomial coefficient i.enC0 + nC1 + nC2 + ....... + nCn-1 + nCnExamples:
Input : n = 4
Output : 16
4C0 + 4C1 + 4C2 + 4C3 + 4C4
= 1 + 4 + 6 + 4 + 1
= 16
Input : n = 5
Output : 32
Method 1 (Brute Force): The idea is to evaluate each binomial coefficient term i.e nCr, where 0 <= r <= n and calculate the sum of all the terms.Below is the implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find the sum of Binomial// Coefficient.#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient Sumint binomialCoeffSum(int n){ int C[n + 1][n + 1]; // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // Calculating the sum. int sum = 0; for (int i = 0; i <= n; i++) sum += C[n][i]; return sum;} /* Driver program to test above function*/int main(){ int n = 4; printf("%d", binomialCoeffSum(n)); return 0;}
// Java Program to find the sum// of Binomial Coefficient. class GFG { // Returns value of Binomial // Coefficient Sum static int binomialCoeffSum(int n) { int C[][] = new int[n + 1][n + 1]; // Calculate value of Binomial // Coefficient in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // Calculating the sum. int sum = 0; for (int i = 0; i <= n; i++) sum += C[n][i]; return sum; } /* Driver program to test above function*/ public static void main(String[] args) { int n = 4; System.out.println(binomialCoeffSum(n)); }} // This code is contributed by prerna saini.
# Python Program to find the sum# of Binomial Coefficient. import math # Returns value of Binomial# Coefficient Sumdef binomialCoeffSum( n): C = [[0]*(n+2) for i in range(0,n+2)] # Calculate value of Binomial # Coefficient in bottom up manner for i in range(0,n+1): for j in range(0, min(i, n)+1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j] # Calculating the sum. sum = 0 for i in range(0,n+1): sum += C[n][i] return sum # Driver program to test above functionn = 4print(binomialCoeffSum(n)) # This code is contributed by Gitanjali.
// C# program to find the sum// of Binomial Coefficient.using System; class GFG { // Returns value of Binomial // Coefficient Sum static int binomialCoeffSum(int n) { int[, ] C = new int[n + 1, n + 1]; // Calculate value of Binomial // Coefficient in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.Min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } // Calculating the sum. int sum = 0; for (int i = 0; i <= n; i++) sum += C[n, i]; return sum; } /* Driver program to test above function*/ public static void Main() { int n = 4; Console.WriteLine(binomialCoeffSum(n)); }} // This code is contributed by vt_m.
<?php// PHP Program to find the// sum of Binomial Coefficient.// Returns value of Binomial// Coefficient Sum function binomialCoeffSum($n){ $C[$n + 1][$n + 1] = array(0); // Calculate value of // Binomial Coefficient // in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $n); $j++) { // Base Cases if ($j == 0 || $j == $i) $C[$i][$j] = 1; // Calculate value // using previously // stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } // Calculating the sum. $sum = 0; for ($i = 0; $i <= $n; $i++) $sum += $C[$n][$i]; return $sum;} // Driver Code$n = 4;echo binomialCoeffSum($n); // This code is contributed by ajit?>
<script> // JavaScript Program to find the sum// of Binomial Coefficient. // Returns value of Binomial // Coefficient Sum function binomialCoeffSum(n) { let C = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < C.length; i++) { C[i] = new Array(2); } // Calculate value of Binomial // Coefficient in bottom up manner for (let i = 0; i <= n; i++) { for (let j = 0; j <= Math.min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // Calculating the sum. let sum = 0; for (let i = 0; i <= n; i++) sum += C[n][i]; return sum; } // Driver code let n = 4; document.write(binomialCoeffSum(n)); </script>
Output:
16
Method 2 (Using Formula):
This can be proved in 2 ways. First Proof: Using Principle of induction.
For basic step, n = 0 LHS = 0C0 = (0!)/(0! * 0!) = 1/1 = 1. RHS= 20 = 1. LHS = RHSFor induction step: Let k be an integer such that k > 0 and for all r, 0 <= r <= k, where r belong to integers, the formula stand true. Therefore, kC0 + kC1 + kC2 + ....... + kCk-1 + kCk = 2kNow, we have to prove for n = k + 1, k+1C0 + k+1C1 + k+1C2 + ....... + k+1Ck + k+1Ck+1 = 2k+1LHS = k+1C0 + k+1C1 + k+1C2 + ....... + k+1Ck + k+1Ck+1 (Using nC0 = 0 and n+1Cr = nCr + nCr-1) = 1 + kC0 + kC1 + kC1 + kC2 + ...... + kCk-1 + kCk + 1 = kC0 + kC0 + kC1 + kC1 + ...... + kCk-1 + kCk-1 + kCk + kCk = 2 X ∑ nCr = 2 X 2k = 2k+1 = RHS
Second Proof: Using Binomial theorem expansion
Binomial expansion state, (x + y)n = nC0 xn y0 + nC1 xn-1 y1 + nC2 xn-2 y2 + ......... + nCn-1 x1 yn-1 + nCn x0 ynPut x = 1, y = 1 (1 + 1)n = nC0 1n 10 + nC1 xn-1 11 + nC2 1n-2 12 + ......... + nCn-1 11 1n-1 + nCn 10 1n2n = nC0 + nC1 + nC2 + ....... + nCn-1 + nCn
Below is implementation of this approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to find sum of Binomial// Coefficient.#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient Sum// which is 2 raised to power n.int binomialCoeffSum(int n){ return (1 << n);} /* Driver program to test above function*/int main(){ int n = 4; printf("%d", binomialCoeffSum(n)); return 0;}
// Java Program to find sum// of Binomial Coefficient.import java.io.*; class GFG{ // Returns value of Binomial // Coefficient Sum which is // 2 raised to power n. static int binomialCoeffSum(int n) { return (1 << n); } // Driver Code public static void main (String[] args) { int n = 4; System.out.println(binomialCoeffSum(n)); }} // This code is contributed// by akt_mit.
# Python Program to find the sum# of Binomial Coefficient. import math # Returns value of Binomial# Coefficient Sumdef binomialCoeffSum( n): return (1 << n); # Driver program to test# above functionn = 4print(binomialCoeffSum(n)) # This code is contributed# by Gitanjali.
// C# Program to find sum of// Binomial Coefficient.using System; class GFG { // Returns value of Binomial Coefficient Sum // which is 2 raised to power n. static int binomialCoeffSum(int n) { return (1 << n); } /* Driver program to test above function*/ static public void Main() { int n = 4; Console.WriteLine(binomialCoeffSum(n)); }} // This code is contributed by vt_m.
<?php// PHP Program to find sum// of Binomial Coefficient. // Returns value of Binomial// Coefficient Sum which is// 2 raised to power n.function binomialCoeffSum($n){ return (1 << $n);} // Driver Code$n = 4;echo binomialCoeffSum($n); // This code is contributed// by akt_mit?>
<script> // Javascript Program to find sum of Binomial Coefficient. // Returns value of Binomial Coefficient Sum // which is 2 raised to power n. function binomialCoeffSum(n) { return (1 << n); } let n = 4; document.write(binomialCoeffSum(n)); </script>
Output:
16
jit_t
nidhi_biet
cidacoder
sanjoy_62
rameshtravel07
binomial coefficient
Combinatorial
Mathematical
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python program to get all subsets of given size of a set
Find all distinct subsets of a given set using BitMasking Approach
Heap's Algorithm for generating permutations
Print all distinct permutations of a given string with duplicates
Make all combinations of size k
Set in C++ Standard Template Library (STL)
C++ Data Types
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 26237,
"s": 26209,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 26371,
"s": 26237,
"text": "Given a positive integer n, the task is to find the sum of binomial coefficient i.enC0 + nC1 + nC2 + ....... + nCn-1 + nCnExamples: "
},
{
"code": null,
"e": 26477,
"s": 26371,
"text": "Input : n = 4\nOutput : 16\n4C0 + 4C1 + 4C2 + 4C3 + 4C4\n= 1 + 4 + 6 + 4 + 1\n= 16\n\nInput : n = 5\nOutput : 32"
},
{
"code": null,
"e": 26672,
"s": 26479,
"text": "Method 1 (Brute Force): The idea is to evaluate each binomial coefficient term i.e nCr, where 0 <= r <= n and calculate the sum of all the terms.Below is the implementation of this approach: "
},
{
"code": null,
"e": 26676,
"s": 26672,
"text": "C++"
},
{
"code": null,
"e": 26681,
"s": 26676,
"text": "Java"
},
{
"code": null,
"e": 26689,
"s": 26681,
"text": "Python3"
},
{
"code": null,
"e": 26692,
"s": 26689,
"text": "C#"
},
{
"code": null,
"e": 26696,
"s": 26692,
"text": "PHP"
},
{
"code": null,
"e": 26707,
"s": 26696,
"text": "Javascript"
},
{
"code": "// CPP Program to find the sum of Binomial// Coefficient.#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient Sumint binomialCoeffSum(int n){ int C[n + 1][n + 1]; // Calculate value of Binomial Coefficient // in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // Calculating the sum. int sum = 0; for (int i = 0; i <= n; i++) sum += C[n][i]; return sum;} /* Driver program to test above function*/int main(){ int n = 4; printf(\"%d\", binomialCoeffSum(n)); return 0;}",
"e": 27543,
"s": 26707,
"text": null
},
{
"code": "// Java Program to find the sum// of Binomial Coefficient. class GFG { // Returns value of Binomial // Coefficient Sum static int binomialCoeffSum(int n) { int C[][] = new int[n + 1][n + 1]; // Calculate value of Binomial // Coefficient in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // Calculating the sum. int sum = 0; for (int i = 0; i <= n; i++) sum += C[n][i]; return sum; } /* Driver program to test above function*/ public static void main(String[] args) { int n = 4; System.out.println(binomialCoeffSum(n)); }} // This code is contributed by prerna saini.",
"e": 28664,
"s": 27543,
"text": null
},
{
"code": "# Python Program to find the sum# of Binomial Coefficient. import math # Returns value of Binomial# Coefficient Sumdef binomialCoeffSum( n): C = [[0]*(n+2) for i in range(0,n+2)] # Calculate value of Binomial # Coefficient in bottom up manner for i in range(0,n+1): for j in range(0, min(i, n)+1): # Base Cases if (j == 0 or j == i): C[i][j] = 1 # Calculate value using previously # stored values else: C[i][j] = C[i - 1][j - 1] + C[i - 1][j] # Calculating the sum. sum = 0 for i in range(0,n+1): sum += C[n][i] return sum # Driver program to test above functionn = 4print(binomialCoeffSum(n)) # This code is contributed by Gitanjali.",
"e": 29548,
"s": 28664,
"text": null
},
{
"code": "// C# program to find the sum// of Binomial Coefficient.using System; class GFG { // Returns value of Binomial // Coefficient Sum static int binomialCoeffSum(int n) { int[, ] C = new int[n + 1, n + 1]; // Calculate value of Binomial // Coefficient in bottom up manner for (int i = 0; i <= n; i++) { for (int j = 0; j <= Math.Min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i, j] = 1; // Calculate value using previously // stored values else C[i, j] = C[i - 1, j - 1] + C[i - 1, j]; } } // Calculating the sum. int sum = 0; for (int i = 0; i <= n; i++) sum += C[n, i]; return sum; } /* Driver program to test above function*/ public static void Main() { int n = 4; Console.WriteLine(binomialCoeffSum(n)); }} // This code is contributed by vt_m.",
"e": 30575,
"s": 29548,
"text": null
},
{
"code": "<?php// PHP Program to find the// sum of Binomial Coefficient.// Returns value of Binomial// Coefficient Sum function binomialCoeffSum($n){ $C[$n + 1][$n + 1] = array(0); // Calculate value of // Binomial Coefficient // in bottom up manner for ($i = 0; $i <= $n; $i++) { for ($j = 0; $j <= min($i, $n); $j++) { // Base Cases if ($j == 0 || $j == $i) $C[$i][$j] = 1; // Calculate value // using previously // stored values else $C[$i][$j] = $C[$i - 1][$j - 1] + $C[$i - 1][$j]; } } // Calculating the sum. $sum = 0; for ($i = 0; $i <= $n; $i++) $sum += $C[$n][$i]; return $sum;} // Driver Code$n = 4;echo binomialCoeffSum($n); // This code is contributed by ajit?>",
"e": 31440,
"s": 30575,
"text": null
},
{
"code": "<script> // JavaScript Program to find the sum// of Binomial Coefficient. // Returns value of Binomial // Coefficient Sum function binomialCoeffSum(n) { let C = new Array(n + 1); // Loop to create 2D array using 1D array for (var i = 0; i < C.length; i++) { C[i] = new Array(2); } // Calculate value of Binomial // Coefficient in bottom up manner for (let i = 0; i <= n; i++) { for (let j = 0; j <= Math.min(i, n); j++) { // Base Cases if (j == 0 || j == i) C[i][j] = 1; // Calculate value using previously // stored values else C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; } } // Calculating the sum. let sum = 0; for (let i = 0; i <= n; i++) sum += C[n][i]; return sum; } // Driver code let n = 4; document.write(binomialCoeffSum(n)); </script>",
"e": 32599,
"s": 31440,
"text": null
},
{
"code": null,
"e": 32608,
"s": 32599,
"text": "Output: "
},
{
"code": null,
"e": 32611,
"s": 32608,
"text": "16"
},
{
"code": null,
"e": 32639,
"s": 32611,
"text": "Method 2 (Using Formula): "
},
{
"code": null,
"e": 32713,
"s": 32639,
"text": "This can be proved in 2 ways. First Proof: Using Principle of induction. "
},
{
"code": null,
"e": 33325,
"s": 32713,
"text": "For basic step, n = 0 LHS = 0C0 = (0!)/(0! * 0!) = 1/1 = 1. RHS= 20 = 1. LHS = RHSFor induction step: Let k be an integer such that k > 0 and for all r, 0 <= r <= k, where r belong to integers, the formula stand true. Therefore, kC0 + kC1 + kC2 + ....... + kCk-1 + kCk = 2kNow, we have to prove for n = k + 1, k+1C0 + k+1C1 + k+1C2 + ....... + k+1Ck + k+1Ck+1 = 2k+1LHS = k+1C0 + k+1C1 + k+1C2 + ....... + k+1Ck + k+1Ck+1 (Using nC0 = 0 and n+1Cr = nCr + nCr-1) = 1 + kC0 + kC1 + kC1 + kC2 + ...... + kCk-1 + kCk + 1 = kC0 + kC0 + kC1 + kC1 + ...... + kCk-1 + kCk-1 + kCk + kCk = 2 X ∑ nCr = 2 X 2k = 2k+1 = RHS"
},
{
"code": null,
"e": 33374,
"s": 33325,
"text": "Second Proof: Using Binomial theorem expansion "
},
{
"code": null,
"e": 33638,
"s": 33374,
"text": "Binomial expansion state, (x + y)n = nC0 xn y0 + nC1 xn-1 y1 + nC2 xn-2 y2 + ......... + nCn-1 x1 yn-1 + nCn x0 ynPut x = 1, y = 1 (1 + 1)n = nC0 1n 10 + nC1 xn-1 11 + nC2 1n-2 12 + ......... + nCn-1 11 1n-1 + nCn 10 1n2n = nC0 + nC1 + nC2 + ....... + nCn-1 + nCn"
},
{
"code": null,
"e": 33682,
"s": 33638,
"text": "Below is implementation of this approach: "
},
{
"code": null,
"e": 33686,
"s": 33682,
"text": "C++"
},
{
"code": null,
"e": 33691,
"s": 33686,
"text": "Java"
},
{
"code": null,
"e": 33699,
"s": 33691,
"text": "Python3"
},
{
"code": null,
"e": 33702,
"s": 33699,
"text": "C#"
},
{
"code": null,
"e": 33706,
"s": 33702,
"text": "PHP"
},
{
"code": null,
"e": 33717,
"s": 33706,
"text": "Javascript"
},
{
"code": "// CPP Program to find sum of Binomial// Coefficient.#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient Sum// which is 2 raised to power n.int binomialCoeffSum(int n){ return (1 << n);} /* Driver program to test above function*/int main(){ int n = 4; printf(\"%d\", binomialCoeffSum(n)); return 0;}",
"e": 34061,
"s": 33717,
"text": null
},
{
"code": "// Java Program to find sum// of Binomial Coefficient.import java.io.*; class GFG{ // Returns value of Binomial // Coefficient Sum which is // 2 raised to power n. static int binomialCoeffSum(int n) { return (1 << n); } // Driver Code public static void main (String[] args) { int n = 4; System.out.println(binomialCoeffSum(n)); }} // This code is contributed// by akt_mit.",
"e": 34487,
"s": 34061,
"text": null
},
{
"code": "# Python Program to find the sum# of Binomial Coefficient. import math # Returns value of Binomial# Coefficient Sumdef binomialCoeffSum( n): return (1 << n); # Driver program to test# above functionn = 4print(binomialCoeffSum(n)) # This code is contributed# by Gitanjali.",
"e": 34772,
"s": 34487,
"text": null
},
{
"code": "// C# Program to find sum of// Binomial Coefficient.using System; class GFG { // Returns value of Binomial Coefficient Sum // which is 2 raised to power n. static int binomialCoeffSum(int n) { return (1 << n); } /* Driver program to test above function*/ static public void Main() { int n = 4; Console.WriteLine(binomialCoeffSum(n)); }} // This code is contributed by vt_m.",
"e": 35196,
"s": 34772,
"text": null
},
{
"code": "<?php// PHP Program to find sum// of Binomial Coefficient. // Returns value of Binomial// Coefficient Sum which is// 2 raised to power n.function binomialCoeffSum($n){ return (1 << $n);} // Driver Code$n = 4;echo binomialCoeffSum($n); // This code is contributed// by akt_mit?>",
"e": 35477,
"s": 35196,
"text": null
},
{
"code": "<script> // Javascript Program to find sum of Binomial Coefficient. // Returns value of Binomial Coefficient Sum // which is 2 raised to power n. function binomialCoeffSum(n) { return (1 << n); } let n = 4; document.write(binomialCoeffSum(n)); </script>",
"e": 35778,
"s": 35477,
"text": null
},
{
"code": null,
"e": 35788,
"s": 35778,
"text": "Output: "
},
{
"code": null,
"e": 35791,
"s": 35788,
"text": "16"
},
{
"code": null,
"e": 35799,
"s": 35793,
"text": "jit_t"
},
{
"code": null,
"e": 35810,
"s": 35799,
"text": "nidhi_biet"
},
{
"code": null,
"e": 35820,
"s": 35810,
"text": "cidacoder"
},
{
"code": null,
"e": 35830,
"s": 35820,
"text": "sanjoy_62"
},
{
"code": null,
"e": 35845,
"s": 35830,
"text": "rameshtravel07"
},
{
"code": null,
"e": 35866,
"s": 35845,
"text": "binomial coefficient"
},
{
"code": null,
"e": 35880,
"s": 35866,
"text": "Combinatorial"
},
{
"code": null,
"e": 35893,
"s": 35880,
"text": "Mathematical"
},
{
"code": null,
"e": 35906,
"s": 35893,
"text": "Mathematical"
},
{
"code": null,
"e": 35920,
"s": 35906,
"text": "Combinatorial"
},
{
"code": null,
"e": 36018,
"s": 35920,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36075,
"s": 36018,
"text": "Python program to get all subsets of given size of a set"
},
{
"code": null,
"e": 36142,
"s": 36075,
"text": "Find all distinct subsets of a given set using BitMasking Approach"
},
{
"code": null,
"e": 36187,
"s": 36142,
"text": "Heap's Algorithm for generating permutations"
},
{
"code": null,
"e": 36253,
"s": 36187,
"text": "Print all distinct permutations of a given string with duplicates"
},
{
"code": null,
"e": 36285,
"s": 36253,
"text": "Make all combinations of size k"
},
{
"code": null,
"e": 36328,
"s": 36285,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 36343,
"s": 36328,
"text": "C++ Data Types"
},
{
"code": null,
"e": 36367,
"s": 36343,
"text": "Merge two sorted arrays"
}
] |
How to create fullscreen search bar using HTML , CSS and JavaScript ? - GeeksforGeeks
|
18 Mar, 2021
In this article, you will learn how to create a full-screen search Bar. Here You will be required to create two divs. One for the overlay container and the other for the overlay content container.
HTML Code: The first step is to create an HTML file. Here we will create the basic structure for the search bar. Here we will also use an icon for the search bar for that we will use the font awesome icon.
Fontawesome Icon CDN Link:
https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css
index.html
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/> <link rel="stylesheet" href="style.css"/> <script src="main.js"></script> </head> <body> <div id="myOverlay" class="overlay"> <span class="closebtn" onclick="closeSearch()" title="Close Overlay"> × </span> <div class="overlay-content"> <form action="/action_page.php"> <input type="text" placeholder="Search.." name="search" /> <button type="submit"> <i class="fa fa-search"></i> </button> </form> </div> </div> <h2>GeeksforGeeks</h2> <h2> Full Screen Search Bar </h2> <button class="openBtn" onclick="openSearch()"> Open Search Box </button> </body></html>
CSS Code: Add CSS to the file. We use CSS to give a transition effect and for the design of the search bar. It also used to align the element in the right position.
style.css
* { box-sizing: border-box;} .openBtn { background-color: dodgerblue; border: 2px solid-black; border-radius: 25px; padding: 10px 15px; font-size: 40px; cursor: pointer;} .openBtn:hover { background: green;} .overlay { height: 100%; width: 100%; display: none; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.9);} .overlay-content { position: relative; top: 50%; width: 80%; text-align: center; margin-top: 30px; margin: auto;} .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 80px; cursor: pointer; color: white;} .overlay .closebtn:hover { color: blue;} .overlay input[type="text"] { padding: 15px; font-size: 17px; border: none; float: left; width: 80%; background: white;} .overlay input[type="text"]:hover { background: #f1f1f1;} .overlay button { float: left; width: 20%; padding: 15px; background: dodger-blue; font-size: 17px; border: none; cursor: pointer;} .overlay button:hover { background: #bbb;}
JavaScript Code: Use JavaScript to turn on and off the overlay/full-screen effect.
main.js
// Open the full screen search boxfunction openSearch() { document.getElementById("myOverlay").style.display = "block";} // Close the full screen search boxfunction closeSearch() { document.getElementById("myOverlay").style.display = "none";}
Output: This output is occured when you will combine above three code sections.
CSS-Basics
HTML-Basics
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to Upload Image into Database and Display it using PHP ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?
|
[
{
"code": null,
"e": 26055,
"s": 26027,
"text": "\n18 Mar, 2021"
},
{
"code": null,
"e": 26252,
"s": 26055,
"text": "In this article, you will learn how to create a full-screen search Bar. Here You will be required to create two divs. One for the overlay container and the other for the overlay content container."
},
{
"code": null,
"e": 26458,
"s": 26252,
"text": "HTML Code: The first step is to create an HTML file. Here we will create the basic structure for the search bar. Here we will also use an icon for the search bar for that we will use the font awesome icon."
},
{
"code": null,
"e": 26485,
"s": 26458,
"text": "Fontawesome Icon CDN Link:"
},
{
"code": null,
"e": 26568,
"s": 26485,
"text": "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
},
{
"code": null,
"e": 26579,
"s": 26568,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"/> <link rel=\"stylesheet\" href=\"style.css\"/> <script src=\"main.js\"></script> </head> <body> <div id=\"myOverlay\" class=\"overlay\"> <span class=\"closebtn\" onclick=\"closeSearch()\" title=\"Close Overlay\"> × </span> <div class=\"overlay-content\"> <form action=\"/action_page.php\"> <input type=\"text\" placeholder=\"Search..\" name=\"search\" /> <button type=\"submit\"> <i class=\"fa fa-search\"></i> </button> </form> </div> </div> <h2>GeeksforGeeks</h2> <h2> Full Screen Search Bar </h2> <button class=\"openBtn\" onclick=\"openSearch()\"> Open Search Box </button> </body></html>",
"e": 27512,
"s": 26579,
"text": null
},
{
"code": null,
"e": 27678,
"s": 27512,
"text": "CSS Code: Add CSS to the file. We use CSS to give a transition effect and for the design of the search bar. It also used to align the element in the right position. "
},
{
"code": null,
"e": 27688,
"s": 27678,
"text": "style.css"
},
{
"code": "* { box-sizing: border-box;} .openBtn { background-color: dodgerblue; border: 2px solid-black; border-radius: 25px; padding: 10px 15px; font-size: 40px; cursor: pointer;} .openBtn:hover { background: green;} .overlay { height: 100%; width: 100%; display: none; position: fixed; z-index: 1; top: 0; left: 0; background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.9);} .overlay-content { position: relative; top: 50%; width: 80%; text-align: center; margin-top: 30px; margin: auto;} .overlay .closebtn { position: absolute; top: 20px; right: 45px; font-size: 80px; cursor: pointer; color: white;} .overlay .closebtn:hover { color: blue;} .overlay input[type=\"text\"] { padding: 15px; font-size: 17px; border: none; float: left; width: 80%; background: white;} .overlay input[type=\"text\"]:hover { background: #f1f1f1;} .overlay button { float: left; width: 20%; padding: 15px; background: dodger-blue; font-size: 17px; border: none; cursor: pointer;} .overlay button:hover { background: #bbb;}",
"e": 28744,
"s": 27688,
"text": null
},
{
"code": null,
"e": 28827,
"s": 28744,
"text": "JavaScript Code: Use JavaScript to turn on and off the overlay/full-screen effect."
},
{
"code": null,
"e": 28835,
"s": 28827,
"text": "main.js"
},
{
"code": "// Open the full screen search boxfunction openSearch() { document.getElementById(\"myOverlay\").style.display = \"block\";} // Close the full screen search boxfunction closeSearch() { document.getElementById(\"myOverlay\").style.display = \"none\";}",
"e": 29081,
"s": 28835,
"text": null
},
{
"code": null,
"e": 29161,
"s": 29081,
"text": "Output: This output is occured when you will combine above three code sections."
},
{
"code": null,
"e": 29172,
"s": 29161,
"text": "CSS-Basics"
},
{
"code": null,
"e": 29184,
"s": 29172,
"text": "HTML-Basics"
},
{
"code": null,
"e": 29188,
"s": 29184,
"text": "CSS"
},
{
"code": null,
"e": 29193,
"s": 29188,
"text": "HTML"
},
{
"code": null,
"e": 29204,
"s": 29193,
"text": "JavaScript"
},
{
"code": null,
"e": 29221,
"s": 29204,
"text": "Web Technologies"
},
{
"code": null,
"e": 29226,
"s": 29221,
"text": "HTML"
},
{
"code": null,
"e": 29324,
"s": 29226,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29379,
"s": 29324,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29443,
"s": 29379,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 29480,
"s": 29443,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29519,
"s": 29480,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 29580,
"s": 29519,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 29640,
"s": 29580,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 29693,
"s": 29640,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 29754,
"s": 29693,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 29778,
"s": 29754,
"text": "REST API (Introduction)"
}
] |
Program to calculate Double Integration - GeeksforGeeks
|
04 Sep, 2021
Write a program to calculate double integral numerically.
Example:
Input: Given the following integral.
where
Output: 3.915905
Explanation and Approach:
We need to decide what method we are going to use to solve the integral.In this example, we are going to use Simpson 1/3 method for both x and y integration.To do so, first, we need to decide the step size. Let h be the step size for integration with respect to x and k be the step size for integration with respect to y.We are taking h=0.1 and k=0.15 in this example.Refer for Simpson 1/3 ruleWe need to create a table which consists of the value of function f(x, y) for all possible combination of all x and y points.x\yy0y1y2....ymx0f(x0, y0)f(x0, y1)f(x0, y2)....f(x0, ym)x1f(x1, y0)f(x1, y1)f(x1, y2)....f(x1, ym)x2f(x2, y0)f(x2, y1)f(x2, y2)....f(x2, ym)x3f(x3, y0)f(x3, y1)f(x3, y2)....f(x3, ym)................................................xnf(xn, y0)f(xn, y1)f(xn, y2)....f(xn, ym)In the given problem,x0=2.3
x2=2.4
x3=3.5
y0=3.7
y1=3.85
y2=4
y3=4.15
y4=4.3
After generating the table, we apply Simpson 1/3 rule (or whatever rule is asked in the problem) on each row of the table to find integral wrt y at each x and store the values in an array ax[].We again apply Simpson 1/3 rule(or whatever rule asked) on the values of array ax[] to calculate the integral wrt x.
We need to decide what method we are going to use to solve the integral.In this example, we are going to use Simpson 1/3 method for both x and y integration.To do so, first, we need to decide the step size. Let h be the step size for integration with respect to x and k be the step size for integration with respect to y.We are taking h=0.1 and k=0.15 in this example.Refer for Simpson 1/3 rule
We need to create a table which consists of the value of function f(x, y) for all possible combination of all x and y points.x\yy0y1y2....ymx0f(x0, y0)f(x0, y1)f(x0, y2)....f(x0, ym)x1f(x1, y0)f(x1, y1)f(x1, y2)....f(x1, ym)x2f(x2, y0)f(x2, y1)f(x2, y2)....f(x2, ym)x3f(x3, y0)f(x3, y1)f(x3, y2)....f(x3, ym)................................................xnf(xn, y0)f(xn, y1)f(xn, y2)....f(xn, ym)In the given problem,x0=2.3
x2=2.4
x3=3.5
y0=3.7
y1=3.85
y2=4
y3=4.15
y4=4.3
In the given problem,
x0=2.3
x2=2.4
x3=3.5
y0=3.7
y1=3.85
y2=4
y3=4.15
y4=4.3
After generating the table, we apply Simpson 1/3 rule (or whatever rule is asked in the problem) on each row of the table to find integral wrt y at each x and store the values in an array ax[].
We again apply Simpson 1/3 rule(or whatever rule asked) on the values of array ax[] to calculate the integral wrt x.
Below is the implementation of the above code:
C++
Java
Python3
C#
// C++ program to calculate// double integral value #include <bits/stdc++.h>using namespace std; // Change the function according to your needfloat givenFunction(float x, float y){ return pow(pow(x, 4) + pow(y, 5), 0.5);} // Function to find the double integral valuefloat doubleIntegral(float h, float k, float lx, float ux, float ly, float uy){ int nx, ny; // z stores the table // ax[] stores the integral wrt y // for all x points considered float z[50][50], ax[50], answer; // Calculating the number of points // in x and y integral nx = (ux - lx) / h + 1; ny = (uy - ly) / k + 1; // Calculating the values of the table for (int i = 0; i < nx; ++i) { for (int j = 0; j < ny; ++j) { z[i][j] = givenFunction(lx + i * h, ly + j * k); } } // Calculating the integral value // wrt y at each point for x for (int i = 0; i < nx; ++i) { ax[i] = 0; for (int j = 0; j < ny; ++j) { if (j == 0 || j == ny - 1) ax[i] += z[i][j]; else if (j % 2 == 0) ax[i] += 2 * z[i][j]; else ax[i] += 4 * z[i][j]; } ax[i] *= (k / 3); } answer = 0; // Calculating the final integral value // using the integral obtained in the above step for (int i = 0; i < nx; ++i) { if (i == 0 || i == nx - 1) answer += ax[i]; else if (i % 2 == 0) answer += 2 * ax[i]; else answer += 4 * ax[i]; } answer *= (h / 3); return answer;} // Driver Codeint main(){ // lx and ux are upper and lower limit of x integral // ly and uy are upper and lower limit of y integral // h is the step size for integration wrt x // k is the step size for integration wrt y float h, k, lx, ux, ly, uy; lx = 2.3, ux = 2.5, ly = 3.7, uy = 4.3, h = 0.1, k = 0.15; printf("%f", doubleIntegral(h, k, lx, ux, ly, uy)); return 0;}
// Java program to calculate// double integral valueclass GFG{ // Change the function according to your needstatic float givenFunction(float x, float y){ return (float) Math.pow(Math.pow(x, 4) + Math.pow(y, 5), 0.5);} // Function to find the double integral valuestatic float doubleIntegral(float h, float k, float lx, float ux, float ly, float uy){ int nx, ny; // z stores the table // ax[] stores the integral wrt y // for all x points considered float z[][] = new float[50][50], ax[] = new float[50], answer; // Calculating the number of points // in x and y integral nx = (int) ((ux - lx) / h + 1); ny = (int) ((uy - ly) / k + 1); // Calculating the values of the table for (int i = 0; i < nx; ++i) { for (int j = 0; j < ny; ++j) { z[i][j] = givenFunction(lx + i * h, ly + j * k); } } // Calculating the integral value // wrt y at each point for x for (int i = 0; i < nx; ++i) { ax[i] = 0; for (int j = 0; j < ny; ++j) { if (j == 0 || j == ny - 1) ax[i] += z[i][j]; else if (j % 2 == 0) ax[i] += 2 * z[i][j]; else ax[i] += 4 * z[i][j]; } ax[i] *= (k / 3); } answer = 0; // Calculating the final integral value // using the integral obtained in the above step for (int i = 0; i < nx; ++i) { if (i == 0 || i == nx - 1) answer += ax[i]; else if (i % 2 == 0) answer += 2 * ax[i]; else answer += 4 * ax[i]; } answer *= (h / 3); return answer;} // Driver Codepublic static void main(String[] args){ // lx and ux are upper and lower limit of x integral // ly and uy are upper and lower limit of y integral // h is the step size for integration wrt x // k is the step size for integration wrt y float h, k, lx, ux, ly, uy; lx = (float) 2.3; ux = (float) 2.5; ly = (float) 3.7; uy = (float) 4.3; h = (float) 0.1; k = (float) 0.15; System.out.printf("%f", doubleIntegral(h, k, lx, ux, ly, uy));}} /* This code contributed by PrinciRaj1992 */
# Python3 program to calculate # double integral value # Change the function according# to your need def givenFunction(x, y): return pow(pow(x, 4) + pow(y, 5), 0.5) # Function to find the double integral value def doubleIntegral(h, k, lx, ux, ly, uy): # z stores the table # ax[] stores the integral wrt y # for all x points considered z = [[None for i in range(50)] for j in range(50)] ax = [None] * 50 # Calculating the number of points # in x and y integral nx = round((ux - lx) / h + 1) ny = round((uy - ly) / k + 1) # Calculating the values of the table for i in range(0, nx): for j in range(0, ny): z[i][j] = givenFunction(lx + i * h, ly + j * k) # Calculating the integral value # wrt y at each point for x for i in range(0, nx): ax[i] = 0 for j in range(0, ny): if j == 0 or j == ny - 1: ax[i] += z[i][j] elif j % 2 == 0: ax[i] += 2 * z[i][j] else: ax[i] += 4 * z[i][j] ax[i] *= (k / 3) answer = 0 # Calculating the final integral # value using the integral # obtained in the above step for i in range(0, nx): if i == 0 or i == nx - 1: answer += ax[i] elif i % 2 == 0: answer += 2 * ax[i] else: answer += 4 * ax[i] answer *= (h / 3) return answer # Driver Code if __name__ == "__main__": # lx and ux are upper and lower limit of x integral # ly and uy are upper and lower limit of y integral # h is the step size for integration wrt x # k is the step size for integration wrt y lx, ux, ly = 2.3, 2.5, 3.7 uy, h, k = 4.3, 0.1, 0.15 print(round(doubleIntegral(h, k, lx, ux, ly, uy), 6)) # This code is contributed # by Rituraj Jain
// C# program to calculate// double integral valueusing System; class GFG{ // Change the function according to your needstatic float givenFunction(float x, float y){ return (float) Math.Pow(Math.Pow(x, 4) + Math.Pow(y, 5), 0.5); } // Function to find the double integral value static float doubleIntegral(float h, float k, float lx, float ux, float ly, float uy) { int nx, ny; // z stores the table // ax[] stores the integral wrt y // for all x points considered float [, ] z = new float[50, 50]; float [] ax = new float[50]; float answer; // Calculating the number of points // in x and y integral nx = (int) ((ux - lx) / h + 1); ny = (int) ((uy - ly) / k + 1); // Calculating the values of the table for (int i = 0; i < nx; ++i) { for (int j = 0; j < ny; ++j) { z[i, j] = givenFunction(lx + i * h, ly + j * k); } } // Calculating the integral value // wrt y at each point for x for (int i = 0; i < nx; ++i) { ax[i] = 0; for (int j = 0; j < ny; ++j) { if (j == 0 || j == ny - 1) ax[i] += z[i, j]; else if (j % 2 == 0) ax[i] += 2 * z[i, j]; else ax[i] += 4 * z[i, j]; } ax[i] *= (k / 3); } answer = 0; // Calculating the final integral value // using the integral obtained in the above step for (int i = 0; i < nx; ++i) { if (i == 0 || i == nx - 1) answer += ax[i]; else if (i % 2 == 0) answer += 2 * ax[i]; else answer += 4 * ax[i]; } answer *= (h / 3); return answer; } // Driver Code public static void Main() { // lx and ux are upper and lower limit of x integral // ly and uy are upper and lower limit of y integral // h is the step size for integration wrt x // k is the step size for integration wrt y float h, k, lx, ux, ly, uy; lx = (float) 2.3; ux = (float) 2.5; ly = (float) 3.7; uy = (float) 4.3; h = (float) 0.1; k = (float) 0.15; Console.WriteLine(doubleIntegral(h, k, lx, ux, ly, uy)); }} // This code contributed by ihritik
3.915905
rituraj_jain
princiraj1992
ihritik
Akanksha_Rai
sumitgumber28
school-programming
Engineering Mathematics
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph
Arrow Symbols in LaTeX
Newton's Divided Difference Interpolation Formula
Set Notations in LaTeX
Discrete Mathematics | Hasse Diagrams
Difference between Propositional Logic and Predicate Logic
Mathematics | Graph Isomorphisms and Connectivity
Mathematics | Euler and Hamiltonian Paths
Graph measurements: length, distance, diameter, eccentricity, radius, center
|
[
{
"code": null,
"e": 25697,
"s": 25669,
"text": "\n04 Sep, 2021"
},
{
"code": null,
"e": 25755,
"s": 25697,
"text": "Write a program to calculate double integral numerically."
},
{
"code": null,
"e": 25764,
"s": 25755,
"text": "Example:"
},
{
"code": null,
"e": 25827,
"s": 25764,
"text": "Input: Given the following integral.\n\nwhere\n\nOutput: 3.915905\n"
},
{
"code": null,
"e": 25853,
"s": 25827,
"text": "Explanation and Approach:"
},
{
"code": null,
"e": 27033,
"s": 25853,
"text": "We need to decide what method we are going to use to solve the integral.In this example, we are going to use Simpson 1/3 method for both x and y integration.To do so, first, we need to decide the step size. Let h be the step size for integration with respect to x and k be the step size for integration with respect to y.We are taking h=0.1 and k=0.15 in this example.Refer for Simpson 1/3 ruleWe need to create a table which consists of the value of function f(x, y) for all possible combination of all x and y points.x\\yy0y1y2....ymx0f(x0, y0)f(x0, y1)f(x0, y2)....f(x0, ym)x1f(x1, y0)f(x1, y1)f(x1, y2)....f(x1, ym)x2f(x2, y0)f(x2, y1)f(x2, y2)....f(x2, ym)x3f(x3, y0)f(x3, y1)f(x3, y2)....f(x3, ym)................................................xnf(xn, y0)f(xn, y1)f(xn, y2)....f(xn, ym)In the given problem,x0=2.3\nx2=2.4\nx3=3.5\n\ny0=3.7\ny1=3.85\ny2=4\ny3=4.15\ny4=4.3\nAfter generating the table, we apply Simpson 1/3 rule (or whatever rule is asked in the problem) on each row of the table to find integral wrt y at each x and store the values in an array ax[].We again apply Simpson 1/3 rule(or whatever rule asked) on the values of array ax[] to calculate the integral wrt x."
},
{
"code": null,
"e": 27428,
"s": 27033,
"text": "We need to decide what method we are going to use to solve the integral.In this example, we are going to use Simpson 1/3 method for both x and y integration.To do so, first, we need to decide the step size. Let h be the step size for integration with respect to x and k be the step size for integration with respect to y.We are taking h=0.1 and k=0.15 in this example.Refer for Simpson 1/3 rule"
},
{
"code": null,
"e": 27905,
"s": 27428,
"text": "We need to create a table which consists of the value of function f(x, y) for all possible combination of all x and y points.x\\yy0y1y2....ymx0f(x0, y0)f(x0, y1)f(x0, y2)....f(x0, ym)x1f(x1, y0)f(x1, y1)f(x1, y2)....f(x1, ym)x2f(x2, y0)f(x2, y1)f(x2, y2)....f(x2, ym)x3f(x3, y0)f(x3, y1)f(x3, y2)....f(x3, ym)................................................xnf(xn, y0)f(xn, y1)f(xn, y2)....f(xn, ym)In the given problem,x0=2.3\nx2=2.4\nx3=3.5\n\ny0=3.7\ny1=3.85\ny2=4\ny3=4.15\ny4=4.3\n"
},
{
"code": null,
"e": 27927,
"s": 27905,
"text": "In the given problem,"
},
{
"code": null,
"e": 27985,
"s": 27927,
"text": "x0=2.3\nx2=2.4\nx3=3.5\n\ny0=3.7\ny1=3.85\ny2=4\ny3=4.15\ny4=4.3\n"
},
{
"code": null,
"e": 28179,
"s": 27985,
"text": "After generating the table, we apply Simpson 1/3 rule (or whatever rule is asked in the problem) on each row of the table to find integral wrt y at each x and store the values in an array ax[]."
},
{
"code": null,
"e": 28296,
"s": 28179,
"text": "We again apply Simpson 1/3 rule(or whatever rule asked) on the values of array ax[] to calculate the integral wrt x."
},
{
"code": null,
"e": 28343,
"s": 28296,
"text": "Below is the implementation of the above code:"
},
{
"code": null,
"e": 28347,
"s": 28343,
"text": "C++"
},
{
"code": null,
"e": 28352,
"s": 28347,
"text": "Java"
},
{
"code": null,
"e": 28360,
"s": 28352,
"text": "Python3"
},
{
"code": null,
"e": 28363,
"s": 28360,
"text": "C#"
},
{
"code": "// C++ program to calculate// double integral value #include <bits/stdc++.h>using namespace std; // Change the function according to your needfloat givenFunction(float x, float y){ return pow(pow(x, 4) + pow(y, 5), 0.5);} // Function to find the double integral valuefloat doubleIntegral(float h, float k, float lx, float ux, float ly, float uy){ int nx, ny; // z stores the table // ax[] stores the integral wrt y // for all x points considered float z[50][50], ax[50], answer; // Calculating the number of points // in x and y integral nx = (ux - lx) / h + 1; ny = (uy - ly) / k + 1; // Calculating the values of the table for (int i = 0; i < nx; ++i) { for (int j = 0; j < ny; ++j) { z[i][j] = givenFunction(lx + i * h, ly + j * k); } } // Calculating the integral value // wrt y at each point for x for (int i = 0; i < nx; ++i) { ax[i] = 0; for (int j = 0; j < ny; ++j) { if (j == 0 || j == ny - 1) ax[i] += z[i][j]; else if (j % 2 == 0) ax[i] += 2 * z[i][j]; else ax[i] += 4 * z[i][j]; } ax[i] *= (k / 3); } answer = 0; // Calculating the final integral value // using the integral obtained in the above step for (int i = 0; i < nx; ++i) { if (i == 0 || i == nx - 1) answer += ax[i]; else if (i % 2 == 0) answer += 2 * ax[i]; else answer += 4 * ax[i]; } answer *= (h / 3); return answer;} // Driver Codeint main(){ // lx and ux are upper and lower limit of x integral // ly and uy are upper and lower limit of y integral // h is the step size for integration wrt x // k is the step size for integration wrt y float h, k, lx, ux, ly, uy; lx = 2.3, ux = 2.5, ly = 3.7, uy = 4.3, h = 0.1, k = 0.15; printf(\"%f\", doubleIntegral(h, k, lx, ux, ly, uy)); return 0;}",
"e": 30408,
"s": 28363,
"text": null
},
{
"code": "// Java program to calculate// double integral valueclass GFG{ // Change the function according to your needstatic float givenFunction(float x, float y){ return (float) Math.pow(Math.pow(x, 4) + Math.pow(y, 5), 0.5);} // Function to find the double integral valuestatic float doubleIntegral(float h, float k, float lx, float ux, float ly, float uy){ int nx, ny; // z stores the table // ax[] stores the integral wrt y // for all x points considered float z[][] = new float[50][50], ax[] = new float[50], answer; // Calculating the number of points // in x and y integral nx = (int) ((ux - lx) / h + 1); ny = (int) ((uy - ly) / k + 1); // Calculating the values of the table for (int i = 0; i < nx; ++i) { for (int j = 0; j < ny; ++j) { z[i][j] = givenFunction(lx + i * h, ly + j * k); } } // Calculating the integral value // wrt y at each point for x for (int i = 0; i < nx; ++i) { ax[i] = 0; for (int j = 0; j < ny; ++j) { if (j == 0 || j == ny - 1) ax[i] += z[i][j]; else if (j % 2 == 0) ax[i] += 2 * z[i][j]; else ax[i] += 4 * z[i][j]; } ax[i] *= (k / 3); } answer = 0; // Calculating the final integral value // using the integral obtained in the above step for (int i = 0; i < nx; ++i) { if (i == 0 || i == nx - 1) answer += ax[i]; else if (i % 2 == 0) answer += 2 * ax[i]; else answer += 4 * ax[i]; } answer *= (h / 3); return answer;} // Driver Codepublic static void main(String[] args){ // lx and ux are upper and lower limit of x integral // ly and uy are upper and lower limit of y integral // h is the step size for integration wrt x // k is the step size for integration wrt y float h, k, lx, ux, ly, uy; lx = (float) 2.3; ux = (float) 2.5; ly = (float) 3.7; uy = (float) 4.3; h = (float) 0.1; k = (float) 0.15; System.out.printf(\"%f\", doubleIntegral(h, k, lx, ux, ly, uy));}} /* This code contributed by PrinciRaj1992 */",
"e": 32671,
"s": 30408,
"text": null
},
{
"code": "# Python3 program to calculate # double integral value # Change the function according# to your need def givenFunction(x, y): return pow(pow(x, 4) + pow(y, 5), 0.5) # Function to find the double integral value def doubleIntegral(h, k, lx, ux, ly, uy): # z stores the table # ax[] stores the integral wrt y # for all x points considered z = [[None for i in range(50)] for j in range(50)] ax = [None] * 50 # Calculating the number of points # in x and y integral nx = round((ux - lx) / h + 1) ny = round((uy - ly) / k + 1) # Calculating the values of the table for i in range(0, nx): for j in range(0, ny): z[i][j] = givenFunction(lx + i * h, ly + j * k) # Calculating the integral value # wrt y at each point for x for i in range(0, nx): ax[i] = 0 for j in range(0, ny): if j == 0 or j == ny - 1: ax[i] += z[i][j] elif j % 2 == 0: ax[i] += 2 * z[i][j] else: ax[i] += 4 * z[i][j] ax[i] *= (k / 3) answer = 0 # Calculating the final integral # value using the integral # obtained in the above step for i in range(0, nx): if i == 0 or i == nx - 1: answer += ax[i] elif i % 2 == 0: answer += 2 * ax[i] else: answer += 4 * ax[i] answer *= (h / 3) return answer # Driver Code if __name__ == \"__main__\": # lx and ux are upper and lower limit of x integral # ly and uy are upper and lower limit of y integral # h is the step size for integration wrt x # k is the step size for integration wrt y lx, ux, ly = 2.3, 2.5, 3.7 uy, h, k = 4.3, 0.1, 0.15 print(round(doubleIntegral(h, k, lx, ux, ly, uy), 6)) # This code is contributed # by Rituraj Jain",
"e": 34625,
"s": 32671,
"text": null
},
{
"code": "// C# program to calculate// double integral valueusing System; class GFG{ // Change the function according to your needstatic float givenFunction(float x, float y){ return (float) Math.Pow(Math.Pow(x, 4) + Math.Pow(y, 5), 0.5); } // Function to find the double integral value static float doubleIntegral(float h, float k, float lx, float ux, float ly, float uy) { int nx, ny; // z stores the table // ax[] stores the integral wrt y // for all x points considered float [, ] z = new float[50, 50]; float [] ax = new float[50]; float answer; // Calculating the number of points // in x and y integral nx = (int) ((ux - lx) / h + 1); ny = (int) ((uy - ly) / k + 1); // Calculating the values of the table for (int i = 0; i < nx; ++i) { for (int j = 0; j < ny; ++j) { z[i, j] = givenFunction(lx + i * h, ly + j * k); } } // Calculating the integral value // wrt y at each point for x for (int i = 0; i < nx; ++i) { ax[i] = 0; for (int j = 0; j < ny; ++j) { if (j == 0 || j == ny - 1) ax[i] += z[i, j]; else if (j % 2 == 0) ax[i] += 2 * z[i, j]; else ax[i] += 4 * z[i, j]; } ax[i] *= (k / 3); } answer = 0; // Calculating the final integral value // using the integral obtained in the above step for (int i = 0; i < nx; ++i) { if (i == 0 || i == nx - 1) answer += ax[i]; else if (i % 2 == 0) answer += 2 * ax[i]; else answer += 4 * ax[i]; } answer *= (h / 3); return answer; } // Driver Code public static void Main() { // lx and ux are upper and lower limit of x integral // ly and uy are upper and lower limit of y integral // h is the step size for integration wrt x // k is the step size for integration wrt y float h, k, lx, ux, ly, uy; lx = (float) 2.3; ux = (float) 2.5; ly = (float) 3.7; uy = (float) 4.3; h = (float) 0.1; k = (float) 0.15; Console.WriteLine(doubleIntegral(h, k, lx, ux, ly, uy)); }} // This code contributed by ihritik ",
"e": 37220,
"s": 34625,
"text": null
},
{
"code": null,
"e": 37230,
"s": 37220,
"text": "3.915905\n"
},
{
"code": null,
"e": 37243,
"s": 37230,
"text": "rituraj_jain"
},
{
"code": null,
"e": 37257,
"s": 37243,
"text": "princiraj1992"
},
{
"code": null,
"e": 37265,
"s": 37257,
"text": "ihritik"
},
{
"code": null,
"e": 37278,
"s": 37265,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 37292,
"s": 37278,
"text": "sumitgumber28"
},
{
"code": null,
"e": 37311,
"s": 37292,
"text": "school-programming"
},
{
"code": null,
"e": 37335,
"s": 37311,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 37433,
"s": 37335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37454,
"s": 37433,
"text": "Activation Functions"
},
{
"code": null,
"e": 37519,
"s": 37454,
"text": "Mathematics | Walks, Trails, Paths, Cycles and Circuits in Graph"
},
{
"code": null,
"e": 37542,
"s": 37519,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 37592,
"s": 37542,
"text": "Newton's Divided Difference Interpolation Formula"
},
{
"code": null,
"e": 37615,
"s": 37592,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 37653,
"s": 37615,
"text": "Discrete Mathematics | Hasse Diagrams"
},
{
"code": null,
"e": 37712,
"s": 37653,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 37762,
"s": 37712,
"text": "Mathematics | Graph Isomorphisms and Connectivity"
},
{
"code": null,
"e": 37804,
"s": 37762,
"text": "Mathematics | Euler and Hamiltonian Paths"
}
] |
Rexx - Signals
|
In Rexx, the signal instruction is used generally for two purposes, which are −
One is to transfer control to another part of the program. This is normally like the go-to label which is used in other programming languages.
One is to transfer control to another part of the program. This is normally like the go-to label which is used in other programming languages.
The other is to go to a specific trap label.
The other is to go to a specific trap label.
If the signal command is used in any of the following instruction commands, the pending control structures will automatically be deactivated.
if ... then ... else ...
if ... then ... else ...
do ... end
do ... end
do i = 1 to n ... end [and similar do loops]
do i = 1 to n ... end [and similar do loops]
select when ... then ... ...etc. otherwise ... end
select when ... then ... ...etc. otherwise ... end
The general syntax of the signal statement is shown as follows −
signal labelName
signal [ VALUE ] labelExpression
Let’s look at an example of how to use the signal statement.
/* Main program */
n = 100.45
if \ datatype( n, wholenumber ) then
signal msg
say 'This is a whole number'
return 0
msg :
say 'This is an incorrect number'
The output of the above program will be as shown below.
This is an incorrect number.
If you change the value of the variable n to a whole number as shown in the following program −
/* Main program */
n = 100
if \ datatype( n, wholenumber ) then
signal msg
say ' This is a whole number '
return 0
msg :
say ' This is an incorrect number '
You will get the following output −
This is a whole number
One can also transfer to the value of the label as shown in the following program −
/* Main program */
n = 1
if \ datatype( n, wholenumber ) then
signal msg
if n < 1 | n > 3 then
signal msg
signal value n
3 : say 'This is the number 3'
2 : say ' This is the number 2'
1 : say ' This is the number 1'
return n
msg :
say ' This is an incorrect number '
exit 99
The output of the above program will be shown as follows −
This is the number 1
As we have mentioned earlier, the signal instruction can also be used to transfer control to a trap label.
The general syntax of the Trap label transfer is given as follows −
signal ON conditionName [ NAME Label ]
signal OFF conditionName
Where,
conditionName − This is the condition for which the signal should be either be turned on or off.
conditionName − This is the condition for which the signal should be either be turned on or off.
Label − The optional label to which the program should be diverted to.
Label − The optional label to which the program should be diverted to.
Let’s see an example of using a trap label transfer.
/* Main program */
signal on error
signal on failure
signal on syntax
signal on novalue
beep(1)
signal off error
signal off failure
signal off syntax
signal off novalue
exit 0
error: failure: syntax: novalue:
say 'An error has occured'
In the above example, we first turn the error signals on. We then add a statement which will result in an error. We then have the error trap label to display a custom error message.
The output of the above program will be as shown follows −
An error has occurred.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2419,
"s": 2339,
"text": "In Rexx, the signal instruction is used generally for two purposes, which are −"
},
{
"code": null,
"e": 2562,
"s": 2419,
"text": "One is to transfer control to another part of the program. This is normally like the go-to label which is used in other programming languages."
},
{
"code": null,
"e": 2705,
"s": 2562,
"text": "One is to transfer control to another part of the program. This is normally like the go-to label which is used in other programming languages."
},
{
"code": null,
"e": 2750,
"s": 2705,
"text": "The other is to go to a specific trap label."
},
{
"code": null,
"e": 2795,
"s": 2750,
"text": "The other is to go to a specific trap label."
},
{
"code": null,
"e": 2937,
"s": 2795,
"text": "If the signal command is used in any of the following instruction commands, the pending control structures will automatically be deactivated."
},
{
"code": null,
"e": 2962,
"s": 2937,
"text": "if ... then ... else ..."
},
{
"code": null,
"e": 2987,
"s": 2962,
"text": "if ... then ... else ..."
},
{
"code": null,
"e": 2998,
"s": 2987,
"text": "do ... end"
},
{
"code": null,
"e": 3009,
"s": 2998,
"text": "do ... end"
},
{
"code": null,
"e": 3054,
"s": 3009,
"text": "do i = 1 to n ... end [and similar do loops]"
},
{
"code": null,
"e": 3099,
"s": 3054,
"text": "do i = 1 to n ... end [and similar do loops]"
},
{
"code": null,
"e": 3150,
"s": 3099,
"text": "select when ... then ... ...etc. otherwise ... end"
},
{
"code": null,
"e": 3201,
"s": 3150,
"text": "select when ... then ... ...etc. otherwise ... end"
},
{
"code": null,
"e": 3266,
"s": 3201,
"text": "The general syntax of the signal statement is shown as follows −"
},
{
"code": null,
"e": 3324,
"s": 3266,
"text": "signal labelName \n \nsignal [ VALUE ] labelExpression \n"
},
{
"code": null,
"e": 3385,
"s": 3324,
"text": "Let’s look at an example of how to use the signal statement."
},
{
"code": null,
"e": 3561,
"s": 3385,
"text": "/* Main program */ \nn = 100.45 \n\nif \\ datatype( n, wholenumber ) then \n signal msg \n say 'This is a whole number' \n return 0 \nmsg : \n say 'This is an incorrect number'"
},
{
"code": null,
"e": 3617,
"s": 3561,
"text": "The output of the above program will be as shown below."
},
{
"code": null,
"e": 3647,
"s": 3617,
"text": "This is an incorrect number.\n"
},
{
"code": null,
"e": 3743,
"s": 3647,
"text": "If you change the value of the variable n to a whole number as shown in the following program −"
},
{
"code": null,
"e": 3921,
"s": 3743,
"text": "/* Main program */ \nn = 100 \n\nif \\ datatype( n, wholenumber ) then \n signal msg \n say ' This is a whole number ' \n return 0 \nmsg : \n say ' This is an incorrect number ' "
},
{
"code": null,
"e": 3957,
"s": 3921,
"text": "You will get the following output −"
},
{
"code": null,
"e": 3981,
"s": 3957,
"text": "This is a whole number\n"
},
{
"code": null,
"e": 4065,
"s": 3981,
"text": "One can also transfer to the value of the label as shown in the following program −"
},
{
"code": null,
"e": 4384,
"s": 4065,
"text": "/* Main program */ \nn = 1 \n\nif \\ datatype( n, wholenumber ) then \n signal msg \n\nif n < 1 | n > 3 then \n signal msg \n signal value n \n 3 : say 'This is the number 3' \n 2 : say ' This is the number 2' \n 1 : say ' This is the number 1' \n return n \nmsg : \n say ' This is an incorrect number ' \n exit 99 "
},
{
"code": null,
"e": 4443,
"s": 4384,
"text": "The output of the above program will be shown as follows −"
},
{
"code": null,
"e": 4465,
"s": 4443,
"text": "This is the number 1\n"
},
{
"code": null,
"e": 4572,
"s": 4465,
"text": "As we have mentioned earlier, the signal instruction can also be used to transfer control to a trap label."
},
{
"code": null,
"e": 4640,
"s": 4572,
"text": "The general syntax of the Trap label transfer is given as follows −"
},
{
"code": null,
"e": 4709,
"s": 4640,
"text": "signal ON conditionName [ NAME Label ] \n \nsignal OFF conditionName\n"
},
{
"code": null,
"e": 4716,
"s": 4709,
"text": "Where,"
},
{
"code": null,
"e": 4813,
"s": 4716,
"text": "conditionName − This is the condition for which the signal should be either be turned on or off."
},
{
"code": null,
"e": 4910,
"s": 4813,
"text": "conditionName − This is the condition for which the signal should be either be turned on or off."
},
{
"code": null,
"e": 4981,
"s": 4910,
"text": "Label − The optional label to which the program should be diverted to."
},
{
"code": null,
"e": 5052,
"s": 4981,
"text": "Label − The optional label to which the program should be diverted to."
},
{
"code": null,
"e": 5105,
"s": 5052,
"text": "Let’s see an example of using a trap label transfer."
},
{
"code": null,
"e": 5354,
"s": 5105,
"text": "/* Main program */ \nsignal on error \nsignal on failure \nsignal on syntax \nsignal on novalue \nbeep(1) \nsignal off error \nsignal off failure \nsignal off syntax \nsignal off novalue \nexit 0 \nerror: failure: syntax: novalue: \nsay 'An error has occured' "
},
{
"code": null,
"e": 5536,
"s": 5354,
"text": "In the above example, we first turn the error signals on. We then add a statement which will result in an error. We then have the error trap label to display a custom error message."
},
{
"code": null,
"e": 5595,
"s": 5536,
"text": "The output of the above program will be as shown follows −"
},
{
"code": null,
"e": 5619,
"s": 5595,
"text": "An error has occurred.\n"
},
{
"code": null,
"e": 5626,
"s": 5619,
"text": " Print"
},
{
"code": null,
"e": 5637,
"s": 5626,
"text": " Add Notes"
}
] |
PHP password_verify() Function
|
The password_verify() function can verify that a password matches a hash.
boolean password_verify( string $password , string $hash )
The password_verify() function can verify that given hash matches the given password.
Note that the password_hash() function can return the algorithm, cost, and salt as part of a returned hash. Therefore, all information that needs to verify a hash that includes in it. This can allow the password_verify() function to verify a hash without need separate storage for the salt or algorithm information.
The password_verify() function can return true, if the password and hash match, or false otherwise.
<?php
$passw01 = "53nh46u74m3nt3";
$hashp02 = '$argon2i$v=19$m=1024,t=2,p=2$d1JJWnNHMkVEekZwcTFUdA$zeSi7c/Adh/1KCTHddoF39Xxwo9ystxRzHEnRA0lQeM';
$test02 = password_verify($passw01, $hashp02);
if($test02 == true) {
echo "VALID password for the informed HASH!<br>";
var_dump($test02);
} else {
echo "INVALID password for the informed HASH!<br>";
var_dump($test02);
}
?>
INVALID password for the informed HASH!<br>bool(false)
VALID password for the informed HASH!<br>bool(true)
<br><br>algo = argon2i<br>algoName = argon2i<br>memory_cost = 1024<br>time_cost = 2<br>threds = 2<br><br>
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2832,
"s": 2757,
"text": "The password_verify() function can verify that a password matches a hash. "
},
{
"code": null,
"e": 2892,
"s": 2832,
"text": "boolean password_verify( string $password , string $hash )\n"
},
{
"code": null,
"e": 2979,
"s": 2892,
"text": "The password_verify() function can verify that given hash matches the given password. "
},
{
"code": null,
"e": 3296,
"s": 2979,
"text": "Note that the password_hash() function can return the algorithm, cost, and salt as part of a returned hash. Therefore, all information that needs to verify a hash that includes in it. This can allow the password_verify() function to verify a hash without need separate storage for the salt or algorithm information. "
},
{
"code": null,
"e": 3397,
"s": 3296,
"text": "The password_verify() function can return true, if the password and hash match, or false otherwise. "
},
{
"code": null,
"e": 3822,
"s": 3397,
"text": "<?php\n $passw01 = \"53nh46u74m3nt3\";\n $hashp02 = '$argon2i$v=19$m=1024,t=2,p=2$d1JJWnNHMkVEekZwcTFUdA$zeSi7c/Adh/1KCTHddoF39Xxwo9ystxRzHEnRA0lQeM';\n\n $test02 = password_verify($passw01, $hashp02);\n \n if($test02 == true) {\n echo \"VALID password for the informed HASH!<br>\"; \n var_dump($test02);\n } else {\n echo \"INVALID password for the informed HASH!<br>\"; \n var_dump($test02); \n }\n?>"
},
{
"code": null,
"e": 3878,
"s": 3822,
"text": "INVALID password for the informed HASH!<br>bool(false)\n"
},
{
"code": null,
"e": 4038,
"s": 3878,
"text": "VALID password for the informed HASH!<br>bool(true)\n<br><br>algo = argon2i<br>algoName = argon2i<br>memory_cost = 1024<br>time_cost = 2<br>threds = 2<br><br> \n"
},
{
"code": null,
"e": 4071,
"s": 4038,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 4087,
"s": 4071,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4120,
"s": 4087,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4131,
"s": 4120,
"text": " Syed Raza"
},
{
"code": null,
"e": 4166,
"s": 4131,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4183,
"s": 4166,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4216,
"s": 4183,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4231,
"s": 4216,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 4266,
"s": 4231,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 4278,
"s": 4266,
"text": " Azaz Patel"
},
{
"code": null,
"e": 4313,
"s": 4278,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 4341,
"s": 4313,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 4348,
"s": 4341,
"text": " Print"
},
{
"code": null,
"e": 4359,
"s": 4348,
"text": " Add Notes"
}
] |
Count the Number of Binary Search Trees present in a Binary Tree - GeeksforGeeks
|
08 Jul, 2021
Given a binary tree, the task is to count the number of Binary Search Trees present in it.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes.Input:
11
/ \
8 10
/ / \
5 9 8
/ \
4 6
Output: 6 Sub-tree rooted under node 5 is a BST
5
/ \
4 6
Another BST we have is rooted under the node 8
8
/
5
/ \
4 6
Thus total 6 BSTs are present (including the leaf nodes).
Approach: A Binary Tree is a Binary Search Tree if the following are true for every node x.
The largest value in left subtree (of x) is smaller than value of x.The smallest value in right subtree (of x) is greater than value of x.
The largest value in left subtree (of x) is smaller than value of x.
The smallest value in right subtree (of x) is greater than value of x.
We traverse tree in bottom up manner. For every traversed node, we store the information of maximum and minimum of that subtree, a variable isBST to store if it is a BST and variable num_BST to store the number of Binary search tree rooted under the current node.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to count number of Binary search trees// in a given Binary Tree#include <bits/stdc++.h>using namespace std; // Binary tree nodestruct Node { struct Node* left; struct Node* right; int data; Node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Information stored in every// node during bottom up traversalstruct Info { // Stores the number of BSTs present int num_BST; // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST bool isBST;}; // Returns information about subtree such as// number of BST's it hasInfo NumberOfBST(struct Node* root){ // Base case if (root == NULL) return { 0, INT_MIN, INT_MAX, true }; // If leaf node then return from function and store // information about the leaf node if (root->left == NULL && root->right == NULL) return { 1, root->data, root->data, true }; // Store information about the left subtree Info L = NumberOfBST(root->left); // Store information about the right subtree Info R = NumberOfBST(root->right); // Create a node that has to be returned Info bst; bst.min = min(root->data, (min(L.min, R.min))); bst.max = max(root->data, (max(L.max, R.max))); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root->data > L.max && root->data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst;} // Driver codeint main(){ struct Node* root = new Node(5); root->left = new Node(9); root->right = new Node(3); root->left->left = new Node(6); root->right->right = new Node(4); root->left->left->left = new Node(8); root->left->left->right = new Node(7); cout << NumberOfBST(root).num_BST; return 0;}
// Java program to count// number of Binary search// trees in a given Binary Treeimport java.util.*; class GFG { // Binary tree node static class Node { Node left; Node right; int data; Node(int data) { this.data = data; this.left = null; this.right = null; } }; // Information stored in every // node during bottom up traversal static class Info { // Stores the number of BSTs present int num_BST; // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST boolean isBST; Info(int a, int b, int c, boolean d) { num_BST = a; max = b; min = c; isBST = d; } Info() { } }; // Returns information about subtree such as // number of BST's it has static Info NumberOfBST(Node root) { // Base case if (root == null) return new Info(0, Integer.MIN_VALUE, Integer.MAX_VALUE, true); // If leaf node then return // from function and store // information about the leaf node if (root.left == null && root.right == null) return new Info(1, root.data, root.data, true); // Store information about the left subtree Info L = NumberOfBST(root.left); // Store information about the right subtree Info R = NumberOfBST(root.right); // Create a node that has to be returned Info bst = new Info(); bst.min = Math.min(root.data, (Math.min(L.min, R.min))); bst.max = Math.max(root.data, (Math.max(L.max, R.max))); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root.data > L.max && root.data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst; } // Driver code public static void main(String args[]) { Node root = new Node(5); root.left = new Node(9); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(4); root.left.left.left = new Node(8); root.left.left.right = new Node(7); System.out.print(NumberOfBST(root).num_BST); }} // This code is contributed by Arnab Kundu
# Python program to count number of Binary search# trees in a given Binary TreeINT_MIN = -2**31INT_MAX = 2**31class newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # Returns information about subtree such as# number of BST's it hasdef NumberOfBST(root): # Base case if (root == None): return 0, INT_MIN, INT_MAX, True # If leaf node then return from function and store # information about the leaf node if (root.left == None and root.right == None): return 1, root.data, root.data, True # Store information about the left subtree L = NumberOfBST(root.left) # Store information about the right subtree R = NumberOfBST(root.right) # Create a node that has to be returned bst = [0]*4 bst[2] = min(root.data, (min(L[2], R[2]))) bst[1] = max(root.data, (max(L[1], R[1]))) # If whole tree rooted under the # current root is BST if (L[3] and R[3] and root.data > L[1] and root.data < R[2]): # Update the number of BSTs bst[3] = True bst[0] = 1 + L[0] + R[0] # If the whole tree is not a BST, # update the number of BSTs else: bst[3] = False bst[0] = L[0] + R[0] return bst # Driver codeif __name__ == '__main__': root = newNode(5) root.left = newNode(9) root.right = newNode(3) root.left.left = newNode(6) root.right.right = newNode(4) root.left.left.left = newNode(8) root.left.left.right = newNode(7) print(NumberOfBST(root)[0]) # This code is contributed by SHUBHAMSINGH10
using System; // C# program to count// number of Binary search// trees in a given Binary Tree public class GFG { // Binary tree node public class Node { public Node left; public Node right; public int data; public Node(int data) { this.data = data; this.left = null; this.right = null; } } // Information stored in every // node during bottom up traversal public class Info { // Stores the number of BSTs present public int num_BST; // Max Value in the subtree public int max; // Min value in the subtree public int min; // If subtree is BST public bool isBST; public Info(int a, int b, int c, bool d) { num_BST = a; max = b; min = c; isBST = d; } public Info() { } } // Returns information about subtree such as // number of BST's it has static Info NumberOfBST(Node root) { // Base case if (root == null) return new Info(0, Int32.MinValue, Int32.MaxValue, true); // If leaf node then return // from function and store // information about the leaf node if (root.left == null && root.right == null) return new Info(1, root.data, root.data, true); // Store information about the left subtree Info L = NumberOfBST(root.left); // Store information about the right subtree Info R = NumberOfBST(root.right); // Create a node that has to be returned Info bst = new Info(); bst.min = Math.Min(root.data, (Math.Min(L.min, R.min))); bst.max = Math.Max(root.data, (Math.Max(L.max, R.max))); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root.data > L.max && root.data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst; } // Driver code public static void Main(string[] args) { Node root = new Node(5); root.left = new Node(9); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(4); root.left.left.left = new Node(8); root.left.left.right = new Node(7); Console.Write(NumberOfBST(root).num_BST); }} // This code is contributed by Shrikant13
<script> // JavaScript program to count // number of Binary search // trees in a given Binary Tree // Binary tree node class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } // Information stored in every // node during bottom up traversal class Info { constructor(a, b, c, d) { // Stores the number of BSTs present this.num_BST = a; // Max Value in the subtree this.max = b; // Min value in the subtree this.min = c; // If subtree is BST this.isBST = d; } } // Returns information about subtree such as // number of BST's it has function NumberOfBST(root) { // Base case if (root == null) return new Info(0, -2147483648, 2147483647, true); // If leaf node then return // from function and store // information about the leaf node if (root.left == null && root.right == null) return new Info(1, root.data, root.data, true); // Store information about the left subtree var L = NumberOfBST(root.left); // Store information about the right subtree var R = NumberOfBST(root.right); // Create a node that has to be returned var bst = new Info(); bst.min = Math.min(root.data, Math.min(L.min, R.min)); bst.max = Math.max(root.data, Math.max(L.max, R.max)); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root.data > L.max && root.data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst; } // Driver code var root = new Node(5); root.left = new Node(9); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(4); root.left.left.left = new Node(8); root.left.left.right = new Node(7); document.write(NumberOfBST(root).num_BST); // This code is contributed by rdtank. </script>
4
andrew1234
SHUBHAMSINGH10
shrikanth13
Akanksha_Rai
big_endian
rdtank
Binary Tree
Marketing
Binary Search Tree
Data Structures
Tree
Data Structures
Binary Search Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
set vs unordered_set in C++ STL
Floor and Ceil from a BST
Construct BST from given preorder traversal | Set 2
Check if a triplet with given sum exists in BST
Print BST keys in the given range
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25226,
"s": 25198,
"text": "\n08 Jul, 2021"
},
{
"code": null,
"e": 25317,
"s": 25226,
"text": "Given a binary tree, the task is to count the number of Binary Search Trees present in it."
},
{
"code": null,
"e": 25329,
"s": 25317,
"text": "Examples: "
},
{
"code": null,
"e": 25337,
"s": 25329,
"text": "Input: "
},
{
"code": null,
"e": 25381,
"s": 25337,
"text": " 1\n / \\\n 2 3\n / \\ / \\\n4 5 6 7"
},
{
"code": null,
"e": 25477,
"s": 25381,
"text": "Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes.Input:"
},
{
"code": null,
"e": 25546,
"s": 25477,
"text": " 11\n / \\\n 8 10\n / / \\\n 5 9 8\n / \\\n4 6"
},
{
"code": null,
"e": 25594,
"s": 25546,
"text": "Output: 6 Sub-tree rooted under node 5 is a BST"
},
{
"code": null,
"e": 25612,
"s": 25594,
"text": " 5\n / \\\n 4 6"
},
{
"code": null,
"e": 25659,
"s": 25612,
"text": "Another BST we have is rooted under the node 8"
},
{
"code": null,
"e": 25717,
"s": 25659,
"text": " 8 \n / \n 5 \n / \\\n 4 6"
},
{
"code": null,
"e": 25775,
"s": 25717,
"text": "Thus total 6 BSTs are present (including the leaf nodes)."
},
{
"code": null,
"e": 25869,
"s": 25775,
"text": "Approach: A Binary Tree is a Binary Search Tree if the following are true for every node x. "
},
{
"code": null,
"e": 26008,
"s": 25869,
"text": "The largest value in left subtree (of x) is smaller than value of x.The smallest value in right subtree (of x) is greater than value of x."
},
{
"code": null,
"e": 26077,
"s": 26008,
"text": "The largest value in left subtree (of x) is smaller than value of x."
},
{
"code": null,
"e": 26148,
"s": 26077,
"text": "The smallest value in right subtree (of x) is greater than value of x."
},
{
"code": null,
"e": 26464,
"s": 26148,
"text": "We traverse tree in bottom up manner. For every traversed node, we store the information of maximum and minimum of that subtree, a variable isBST to store if it is a BST and variable num_BST to store the number of Binary search tree rooted under the current node.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26468,
"s": 26464,
"text": "C++"
},
{
"code": null,
"e": 26473,
"s": 26468,
"text": "Java"
},
{
"code": null,
"e": 26481,
"s": 26473,
"text": "Python3"
},
{
"code": null,
"e": 26484,
"s": 26481,
"text": "C#"
},
{
"code": null,
"e": 26495,
"s": 26484,
"text": "Javascript"
},
{
"code": "// C++ program to count number of Binary search trees// in a given Binary Tree#include <bits/stdc++.h>using namespace std; // Binary tree nodestruct Node { struct Node* left; struct Node* right; int data; Node(int data) { this->data = data; this->left = NULL; this->right = NULL; }}; // Information stored in every// node during bottom up traversalstruct Info { // Stores the number of BSTs present int num_BST; // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST bool isBST;}; // Returns information about subtree such as// number of BST's it hasInfo NumberOfBST(struct Node* root){ // Base case if (root == NULL) return { 0, INT_MIN, INT_MAX, true }; // If leaf node then return from function and store // information about the leaf node if (root->left == NULL && root->right == NULL) return { 1, root->data, root->data, true }; // Store information about the left subtree Info L = NumberOfBST(root->left); // Store information about the right subtree Info R = NumberOfBST(root->right); // Create a node that has to be returned Info bst; bst.min = min(root->data, (min(L.min, R.min))); bst.max = max(root->data, (max(L.max, R.max))); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root->data > L.max && root->data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst;} // Driver codeint main(){ struct Node* root = new Node(5); root->left = new Node(9); root->right = new Node(3); root->left->left = new Node(6); root->right->right = new Node(4); root->left->left->left = new Node(8); root->left->left->right = new Node(7); cout << NumberOfBST(root).num_BST; return 0;}",
"e": 28554,
"s": 26495,
"text": null
},
{
"code": "// Java program to count// number of Binary search// trees in a given Binary Treeimport java.util.*; class GFG { // Binary tree node static class Node { Node left; Node right; int data; Node(int data) { this.data = data; this.left = null; this.right = null; } }; // Information stored in every // node during bottom up traversal static class Info { // Stores the number of BSTs present int num_BST; // Max Value in the subtree int max; // Min value in the subtree int min; // If subtree is BST boolean isBST; Info(int a, int b, int c, boolean d) { num_BST = a; max = b; min = c; isBST = d; } Info() { } }; // Returns information about subtree such as // number of BST's it has static Info NumberOfBST(Node root) { // Base case if (root == null) return new Info(0, Integer.MIN_VALUE, Integer.MAX_VALUE, true); // If leaf node then return // from function and store // information about the leaf node if (root.left == null && root.right == null) return new Info(1, root.data, root.data, true); // Store information about the left subtree Info L = NumberOfBST(root.left); // Store information about the right subtree Info R = NumberOfBST(root.right); // Create a node that has to be returned Info bst = new Info(); bst.min = Math.min(root.data, (Math.min(L.min, R.min))); bst.max = Math.max(root.data, (Math.max(L.max, R.max))); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root.data > L.max && root.data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst; } // Driver code public static void main(String args[]) { Node root = new Node(5); root.left = new Node(9); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(4); root.left.left.left = new Node(8); root.left.left.right = new Node(7); System.out.print(NumberOfBST(root).num_BST); }} // This code is contributed by Arnab Kundu",
"e": 31199,
"s": 28554,
"text": null
},
{
"code": "# Python program to count number of Binary search# trees in a given Binary TreeINT_MIN = -2**31INT_MAX = 2**31class newNode(): def __init__(self, data): self.data = data self.left = None self.right = None # Returns information about subtree such as# number of BST's it hasdef NumberOfBST(root): # Base case if (root == None): return 0, INT_MIN, INT_MAX, True # If leaf node then return from function and store # information about the leaf node if (root.left == None and root.right == None): return 1, root.data, root.data, True # Store information about the left subtree L = NumberOfBST(root.left) # Store information about the right subtree R = NumberOfBST(root.right) # Create a node that has to be returned bst = [0]*4 bst[2] = min(root.data, (min(L[2], R[2]))) bst[1] = max(root.data, (max(L[1], R[1]))) # If whole tree rooted under the # current root is BST if (L[3] and R[3] and root.data > L[1] and root.data < R[2]): # Update the number of BSTs bst[3] = True bst[0] = 1 + L[0] + R[0] # If the whole tree is not a BST, # update the number of BSTs else: bst[3] = False bst[0] = L[0] + R[0] return bst # Driver codeif __name__ == '__main__': root = newNode(5) root.left = newNode(9) root.right = newNode(3) root.left.left = newNode(6) root.right.right = newNode(4) root.left.left.left = newNode(8) root.left.left.right = newNode(7) print(NumberOfBST(root)[0]) # This code is contributed by SHUBHAMSINGH10",
"e": 32819,
"s": 31199,
"text": null
},
{
"code": "using System; // C# program to count// number of Binary search// trees in a given Binary Tree public class GFG { // Binary tree node public class Node { public Node left; public Node right; public int data; public Node(int data) { this.data = data; this.left = null; this.right = null; } } // Information stored in every // node during bottom up traversal public class Info { // Stores the number of BSTs present public int num_BST; // Max Value in the subtree public int max; // Min value in the subtree public int min; // If subtree is BST public bool isBST; public Info(int a, int b, int c, bool d) { num_BST = a; max = b; min = c; isBST = d; } public Info() { } } // Returns information about subtree such as // number of BST's it has static Info NumberOfBST(Node root) { // Base case if (root == null) return new Info(0, Int32.MinValue, Int32.MaxValue, true); // If leaf node then return // from function and store // information about the leaf node if (root.left == null && root.right == null) return new Info(1, root.data, root.data, true); // Store information about the left subtree Info L = NumberOfBST(root.left); // Store information about the right subtree Info R = NumberOfBST(root.right); // Create a node that has to be returned Info bst = new Info(); bst.min = Math.Min(root.data, (Math.Min(L.min, R.min))); bst.max = Math.Max(root.data, (Math.Max(L.max, R.max))); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root.data > L.max && root.data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst; } // Driver code public static void Main(string[] args) { Node root = new Node(5); root.left = new Node(9); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(4); root.left.left.left = new Node(8); root.left.left.right = new Node(7); Console.Write(NumberOfBST(root).num_BST); }} // This code is contributed by Shrikant13",
"e": 35516,
"s": 32819,
"text": null
},
{
"code": "<script> // JavaScript program to count // number of Binary search // trees in a given Binary Tree // Binary tree node class Node { constructor(data) { this.data = data; this.left = null; this.right = null; } } // Information stored in every // node during bottom up traversal class Info { constructor(a, b, c, d) { // Stores the number of BSTs present this.num_BST = a; // Max Value in the subtree this.max = b; // Min value in the subtree this.min = c; // If subtree is BST this.isBST = d; } } // Returns information about subtree such as // number of BST's it has function NumberOfBST(root) { // Base case if (root == null) return new Info(0, -2147483648, 2147483647, true); // If leaf node then return // from function and store // information about the leaf node if (root.left == null && root.right == null) return new Info(1, root.data, root.data, true); // Store information about the left subtree var L = NumberOfBST(root.left); // Store information about the right subtree var R = NumberOfBST(root.right); // Create a node that has to be returned var bst = new Info(); bst.min = Math.min(root.data, Math.min(L.min, R.min)); bst.max = Math.max(root.data, Math.max(L.max, R.max)); // If whole tree rooted under the // current root is BST if (L.isBST && R.isBST && root.data > L.max && root.data < R.min) { // Update the number of BSTs bst.isBST = true; bst.num_BST = 1 + L.num_BST + R.num_BST; } // If the whole tree is not a BST, // update the number of BSTs else { bst.isBST = false; bst.num_BST = L.num_BST + R.num_BST; } return bst; } // Driver code var root = new Node(5); root.left = new Node(9); root.right = new Node(3); root.left.left = new Node(6); root.right.right = new Node(4); root.left.left.left = new Node(8); root.left.left.right = new Node(7); document.write(NumberOfBST(root).num_BST); // This code is contributed by rdtank. </script>",
"e": 37927,
"s": 35516,
"text": null
},
{
"code": null,
"e": 37929,
"s": 37927,
"text": "4"
},
{
"code": null,
"e": 37942,
"s": 37931,
"text": "andrew1234"
},
{
"code": null,
"e": 37957,
"s": 37942,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 37969,
"s": 37957,
"text": "shrikanth13"
},
{
"code": null,
"e": 37982,
"s": 37969,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 37993,
"s": 37982,
"text": "big_endian"
},
{
"code": null,
"e": 38000,
"s": 37993,
"text": "rdtank"
},
{
"code": null,
"e": 38012,
"s": 38000,
"text": "Binary Tree"
},
{
"code": null,
"e": 38022,
"s": 38012,
"text": "Marketing"
},
{
"code": null,
"e": 38041,
"s": 38022,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 38057,
"s": 38041,
"text": "Data Structures"
},
{
"code": null,
"e": 38062,
"s": 38057,
"text": "Tree"
},
{
"code": null,
"e": 38078,
"s": 38062,
"text": "Data Structures"
},
{
"code": null,
"e": 38097,
"s": 38078,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 38102,
"s": 38097,
"text": "Tree"
},
{
"code": null,
"e": 38200,
"s": 38102,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38209,
"s": 38200,
"text": "Comments"
},
{
"code": null,
"e": 38222,
"s": 38209,
"text": "Old Comments"
},
{
"code": null,
"e": 38254,
"s": 38222,
"text": "set vs unordered_set in C++ STL"
},
{
"code": null,
"e": 38280,
"s": 38254,
"text": "Floor and Ceil from a BST"
},
{
"code": null,
"e": 38332,
"s": 38280,
"text": "Construct BST from given preorder traversal | Set 2"
},
{
"code": null,
"e": 38380,
"s": 38332,
"text": "Check if a triplet with given sum exists in BST"
},
{
"code": null,
"e": 38414,
"s": 38380,
"text": "Print BST keys in the given range"
},
{
"code": null,
"e": 38463,
"s": 38414,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 38507,
"s": 38463,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 38532,
"s": 38507,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 38588,
"s": 38532,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
}
] |
How to edit a Listbox item in Tkinter?
|
Tkinter Listbox widget is generally used to create a list of items. It can store a list of numbers, characters and support many features like selecting and editing the list items.
To edit the Listbox items, we have to first select the item in a loop using listbox.curselection() function and insert a new item after deleting the previous item in the listbox. To insert a new item in the listbox, you can use listbox.insert(**items) function.
In this example, we will create a list of items in the listbox widget and a button will be used for editing the selected item in the list.
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Create a Listbox widget
lb = Listbox(win, width=100, height=10, background="purple2", foreground="white", font=('Times 13'), selectbackground="black")
lb.pack()
# Select the list item and delete the item first
# Once the list item is deleted,
# we can insert a new item in the listbox
def edit():
for item in lb.curselection():
lb.delete(item)
lb.insert("end", "foo")
# Add items in the Listbox
lb.insert("end", "item1", "item2", "item3", "item4", "item5")
# Add a Button To Edit and Delete the Listbox Item
ttk.Button(win, text="Edit", command=edit).pack()
win.mainloop()
Running the above code will allow you to select and edit the list items.
You can configure the list of items by clicking the "Edit" button.
|
[
{
"code": null,
"e": 1242,
"s": 1062,
"text": "Tkinter Listbox widget is generally used to create a list of items. It can store a list of numbers, characters and support many features like selecting and editing the list items."
},
{
"code": null,
"e": 1504,
"s": 1242,
"text": "To edit the Listbox items, we have to first select the item in a loop using listbox.curselection() function and insert a new item after deleting the previous item in the listbox. To insert a new item in the listbox, you can use listbox.insert(**items) function."
},
{
"code": null,
"e": 1643,
"s": 1504,
"text": "In this example, we will create a list of items in the listbox widget and a button will be used for editing the selected item in the list."
},
{
"code": null,
"e": 2431,
"s": 1643,
"text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a Listbox widget\nlb = Listbox(win, width=100, height=10, background=\"purple2\", foreground=\"white\", font=('Times 13'), selectbackground=\"black\")\n\nlb.pack()\n\n# Select the list item and delete the item first\n# Once the list item is deleted,\n# we can insert a new item in the listbox\ndef edit():\n for item in lb.curselection():\n lb.delete(item)\n lb.insert(\"end\", \"foo\")\n\n# Add items in the Listbox\nlb.insert(\"end\", \"item1\", \"item2\", \"item3\", \"item4\", \"item5\")\n\n# Add a Button To Edit and Delete the Listbox Item\nttk.Button(win, text=\"Edit\", command=edit).pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2504,
"s": 2431,
"text": "Running the above code will allow you to select and edit the list items."
},
{
"code": null,
"e": 2571,
"s": 2504,
"text": "You can configure the list of items by clicking the \"Edit\" button."
}
] |
Android Recyclerview GridLayoutManager column spacing
|
This example demonstrates about Android Recyclerview GridLayoutManager column spacing
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.design.widget.CoordinatorLayout android:layout_width = "match_parent"
android:layout_height = "match_parent"
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto">
<android.support.design.widget.AppBarLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content">
<android.support.v7.widget.Toolbar
android:id = "@+id/appbarlayout_tool_bar"
android:background = "@color/colorPrimary"
android:layout_width = "match_parent"
android:layout_height = "?attr/actionBarSize"
app:layout_scrollFlags = "scroll|snap|enterAlways"
app:theme = "@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme = "@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
<android.support.v7.widget.RecyclerView
android:id = "@+id/recycler_view"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layout_behavior = "@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>
In the above code, we have taken recyclerview.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
TextView text;
ArrayList<String> list = new ArrayList<>();
private RecyclerView recyclerView;
private customAdapter mAdapter;
private onClickInterface onclickInterface;
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.appbarlayout_tool_bar);
toolbar.setTitle("This is toolbar.");
setSupportActionBar(toolbar);
onclickInterface = new onClickInterface() {
@Override
public void setClick(int abc) {
list.remove(abc);
Toast.makeText(MainActivity.this,"Position is"+abc,Toast.LENGTH_LONG).show();
mAdapter.notifyDataSetChanged();
}
};
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
GridLayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),2);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
mAdapter = new customAdapter(this, list, onclickInterface);
recyclerView.setAdapter(mAdapter);
recyclerView.addItemDecoration(new SpacesItemDecoration(10));
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
list.add("sairamm");
list.add("Krishna");
list.add("prasad");
}
}
Step 4 − Add the following code to src/ customAdapter.java
package com.example.myapplication;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> {
Context context;
ArrayList<String> list;
onClickInterface onClickInterface;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
}
}
public customAdapter(Context context, ArrayList<String> list, onClickInterface onClickInterface) {
this.context = context;
this.list = list;
this.onClickInterface = onClickInterface;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {
myViewHolder.title.setText(list.get(i));
myViewHolder.title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onClickInterface.setClick(i);
}
});
}
@Override
public int getItemCount() {
return list.size();
}
}
Step 5 − Add the following code to res/layout/ list_row.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<android.support.v7.widget.CardView xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
app:cardElevation = "10dp"
app:cardCornerRadius = "20dp"
tools:context = ".MainActivity">
<LinearLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center"
android:orientation = "vertical">
<ImageView
android:id = "@+id/imageView2"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:src = "@drawable/logo" />
<TextView
android:id = "@+id/title"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center"
android:textSize = "30sp" />
<TextView
android:id = "@+id/textview2"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:gravity = "center"
android:text = "Sairamkrishan"
android:textSize = "30sp" />
</LinearLayout>
</android.support.v7.widget.CardView>
Step 6 − Add the following code to src/ onClickInterface.
package com.example.myapplication;
public interface onClickInterface {
void setClick(int abc);
}
Step 7 − Add the following code to src/ SpacesItemDecoration.java.
package com.example.myapplication;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;
public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
private int space;
public SpacesItemDecoration(int space) {
this.space = space;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
outRect.left = space;
outRect.right = space;
outRect.bottom = space;
// Add top margin only for the first item to avoid double space between items
if (parent.getChildLayoutPosition(view) = = 0) {
outRect.top = space;
} else {
outRect.top = 0;
}
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -
|
[
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates about Android Recyclerview GridLayoutManager column spacing"
},
{
"code": null,
"e": 1277,
"s": 1148,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1342,
"s": 1277,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2557,
"s": 1342,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.design.widget.CoordinatorLayout android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\">\n <android.support.design.widget.AppBarLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\">\n <android.support.v7.widget.Toolbar\n android:id = \"@+id/appbarlayout_tool_bar\"\n android:background = \"@color/colorPrimary\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"?attr/actionBarSize\"\n app:layout_scrollFlags = \"scroll|snap|enterAlways\"\n app:theme = \"@style/ThemeOverlay.AppCompat.Dark.ActionBar\"\n app:popupTheme = \"@style/ThemeOverlay.AppCompat.Light\" />\n </android.support.design.widget.AppBarLayout>\n <android.support.v7.widget.RecyclerView\n android:id = \"@+id/recycler_view\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n app:layout_behavior = \"@string/appbar_scrolling_view_behavior\"/>\n</android.support.design.widget.CoordinatorLayout>"
},
{
"code": null,
"e": 2604,
"s": 2557,
"text": "In the above code, we have taken recyclerview."
},
{
"code": null,
"e": 2661,
"s": 2604,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 5181,
"s": 2661,
"text": "package com.example.myapplication;\nimport android.annotation.TargetApi;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.v4.content.ContextCompat;\nimport android.support.v7.app.AppCompatActivity;\nimport android.support.v7.widget.DefaultItemAnimator;\nimport android.support.v7.widget.DividerItemDecoration;\nimport android.support.v7.widget.GridLayoutManager;\nimport android.support.v7.widget.LinearLayoutManager;\nimport android.support.v7.widget.RecyclerView;\nimport android.support.v7.widget.Toolbar;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n TextView text;\n ArrayList<String> list = new ArrayList<>();\n private RecyclerView recyclerView;\n private customAdapter mAdapter;\n private onClickInterface onclickInterface;\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.appbarlayout_tool_bar);\n toolbar.setTitle(\"This is toolbar.\");\n setSupportActionBar(toolbar);\n onclickInterface = new onClickInterface() {\n @Override\n public void setClick(int abc) {\n list.remove(abc);\n Toast.makeText(MainActivity.this,\"Position is\"+abc,Toast.LENGTH_LONG).show();\n mAdapter.notifyDataSetChanged();\n }\n };\n recyclerView = (RecyclerView) findViewById(R.id.recycler_view);\n GridLayoutManager mLayoutManager = new GridLayoutManager(getApplicationContext(),2);\n recyclerView.setLayoutManager(mLayoutManager);\n recyclerView.setItemAnimator(new DefaultItemAnimator());\n mAdapter = new customAdapter(this, list, onclickInterface);\n recyclerView.setAdapter(mAdapter);\n recyclerView.addItemDecoration(new SpacesItemDecoration(10));\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n list.add(\"sairamm\");\n list.add(\"Krishna\");\n list.add(\"prasad\");\n }\n}"
},
{
"code": null,
"e": 5240,
"s": 5181,
"text": "Step 4 − Add the following code to src/ customAdapter.java"
},
{
"code": null,
"e": 6838,
"s": 5240,
"text": "package com.example.myapplication;\nimport android.content.Context;\nimport android.support.annotation.NonNull;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\nimport android.widget.TextView;\nimport java.util.ArrayList;\npublic class customAdapter extends RecyclerView.Adapter<customAdapter.MyViewHolder> {\n Context context;\n ArrayList<String> list;\n onClickInterface onClickInterface;\n public class MyViewHolder extends RecyclerView.ViewHolder {\n public TextView title;\n public MyViewHolder(View view) {\n super(view);\n title = (TextView) view.findViewById(R.id.title);\n }\n }\n public customAdapter(Context context, ArrayList<String> list, onClickInterface onClickInterface) {\n this.context = context;\n this.list = list;\n this.onClickInterface = onClickInterface;\n }\n @NonNull\n @Override\n public MyViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {\n View itemView = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_row, viewGroup, false);\n return new MyViewHolder(itemView);\n }\n @Override\n public void onBindViewHolder(@NonNull MyViewHolder myViewHolder, final int i) {\n myViewHolder.title.setText(list.get(i));\n myViewHolder.title.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n onClickInterface.setClick(i);\n }\n });\n }\n @Override\n public int getItemCount() {\n return list.size();\n }\n}"
},
{
"code": null,
"e": 6899,
"s": 6838,
"text": "Step 5 − Add the following code to res/layout/ list_row.xml."
},
{
"code": null,
"e": 8245,
"s": 6899,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.v7.widget.CardView xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n app:cardElevation = \"10dp\"\n app:cardCornerRadius = \"20dp\"\n tools:context = \".MainActivity\">\n <LinearLayout\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <ImageView\n android:id = \"@+id/imageView2\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:src = \"@drawable/logo\" />\n <TextView\n android:id = \"@+id/title\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:textSize = \"30sp\" />\n <TextView\n android:id = \"@+id/textview2\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:gravity = \"center\"\n android:text = \"Sairamkrishan\"\n android:textSize = \"30sp\" />\n </LinearLayout>\n</android.support.v7.widget.CardView>"
},
{
"code": null,
"e": 8303,
"s": 8245,
"text": "Step 6 − Add the following code to src/ onClickInterface."
},
{
"code": null,
"e": 8403,
"s": 8303,
"text": "package com.example.myapplication;\npublic interface onClickInterface {\n void setClick(int abc);\n}"
},
{
"code": null,
"e": 8470,
"s": 8403,
"text": "Step 7 − Add the following code to src/ SpacesItemDecoration.java."
},
{
"code": null,
"e": 9206,
"s": 8470,
"text": "package com.example.myapplication;\nimport android.graphics.Rect;\nimport android.support.v7.widget.RecyclerView;\nimport android.view.View;\npublic class SpacesItemDecoration extends RecyclerView.ItemDecoration {\n private int space;\n public SpacesItemDecoration(int space) {\n this.space = space;\n }\n @Override\n public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {\n outRect.left = space;\n outRect.right = space;\n outRect.bottom = space;\n // Add top margin only for the first item to avoid double space between items\n if (parent.getChildLayoutPosition(view) = = 0) {\n outRect.top = space;\n } else {\n outRect.top = 0;\n }\n }\n}"
},
{
"code": null,
"e": 9556,
"s": 9206,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from an android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen -"
}
] |
How to display value of textbox in JavaScript?
|
Extract the value from text box using value and can display in paragraph using innerHTML.
Following is the code −
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>
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
Enter your Name:
<input type="text" placeholder="enter your name" id="txtInputData">
<button onclick="displayName()">Click Me</button>
<p id="show_name">
</p>
</body>
<script>
function displayName() {
var originalName = document.getElementById("txtInputData").value;
document.getElementById("show_name").innerHTML = "Your Name is :" + originalName;
}
</script>
</html>
To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VSCode editor −
This will produce the following output on console −
Now, enter the value into the text box and click the button −
After clicking the button, the output is as follows −
|
[
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Extract the value from text box using value and can display in paragraph using innerHTML."
},
{
"code": null,
"e": 1176,
"s": 1152,
"text": "Following is the code −"
},
{
"code": null,
"e": 1187,
"s": 1176,
"text": " Live Demo"
},
{
"code": null,
"e": 1992,
"s": 1187,
"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</head>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<body>\n Enter your Name:\n <input type=\"text\" placeholder=\"enter your name\" id=\"txtInputData\">\n <button onclick=\"displayName()\">Click Me</button>\n <p id=\"show_name\">\n </p>\n</body>\n<script>\n function displayName() {\n var originalName = document.getElementById(\"txtInputData\").value;\n document.getElementById(\"show_name\").innerHTML = \"Your Name is :\" + originalName;\n }\n</script>\n</html>"
},
{
"code": null,
"e": 2154,
"s": 1992,
"text": "To run the above program, save the file name “anyName.html(index.html)”. Right click on the file and select the option “Open with Live Server” in VSCode editor −"
},
{
"code": null,
"e": 2206,
"s": 2154,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2268,
"s": 2206,
"text": "Now, enter the value into the text box and click the button −"
},
{
"code": null,
"e": 2322,
"s": 2268,
"text": "After clicking the button, the output is as follows −"
}
] |
How to Create a Pivot Table in Python using Pandas? - GeeksforGeeks
|
28 Jul, 2020
Pivot table is a statistical table that summarizes a substantial table like big datasets. It is part of data processing. This summary in pivot tables may include mean, median, sum, or other statistical terms. Pivot tables are originally associated with MS Excel but we can create a pivot table in Python using Pandas using the dataframe.pivot() method.
Syntax : dataframe.pivot(self, index=None, columns=None, values=None, aggfunc)
Parameters –index: Column for making new frame’s index.columns: Column for new frame’s columns.values: Column(s) for populating new frame’s values.aggfunc: function, list of functions, dict, default numpy.mean
Example 1:Let’s first create a dataframe that includes Sales of Fruits.
# importing pandasimport pandas as pd # creating dataframedf = pd.DataFrame({'Product' : ['Carrots', 'Broccoli', 'Banana', 'Banana', 'Beans', 'Orange', 'Broccoli', 'Banana'], 'Category' : ['Vegetable', 'Vegetable', 'Fruit', 'Fruit', 'Vegetable', 'Fruit', 'Vegetable', 'Fruit'], 'Quantity' : [8, 5, 3, 4, 5, 9, 11, 8], 'Amount' : [270, 239, 617, 384, 626, 610, 62, 90]})df
Output:
Get the total sales of each product
# creating pivot table of total sales# product-wise aggfunc = 'sum' will # allow you to obtain the sum of sales# each productpivot = df.pivot_table(index =['Product'], values =['Amount'], aggfunc ='sum')print(pivot)
Output:
Get the total sales of each category
# creating pivot table of total # sales category-wise aggfunc = 'sum'# will allow you to obtain the sum of# sales each productpivot = df.pivot_table(index =['Category'], values =['Amount'], aggfunc ='sum')print(pivot)
Output:
Get the total sales of by category and product both
# creating pivot table of sales# by product and category both# aggfunc = 'sum' will allow you# to obtain the sum of sales each# productpivot = df.pivot_table(index =['Product', 'Category'], values =['Amount'], aggfunc ='sum')print (pivot)
Output –
Get the Mean, Median, Minimum sale by category
# creating pivot table of Mean, Median,# Minimum sale by category aggfunc = {'median',# 'mean', 'min'} will get median, mean and # minimum of sales respectivelypivot = df.pivot_table(index =['Category'], values =['Amount'], aggfunc ={'median', 'mean', 'min'})print (pivot)
Output –
Get the Mean, Median, Minimum sale by product
# creating pivot table of Mean, Median,# Minimum sale by product aggfunc = {'median',# 'mean', 'min'} will get median, mean and# minimum of sales respectivelypivot = df.pivot_table(index =['Product'], values =['Amount'], aggfunc ={'median', 'mean', 'min'})print (pivot)
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 25092,
"s": 25064,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 25445,
"s": 25092,
"text": "Pivot table is a statistical table that summarizes a substantial table like big datasets. It is part of data processing. This summary in pivot tables may include mean, median, sum, or other statistical terms. Pivot tables are originally associated with MS Excel but we can create a pivot table in Python using Pandas using the dataframe.pivot() method."
},
{
"code": null,
"e": 25524,
"s": 25445,
"text": "Syntax : dataframe.pivot(self, index=None, columns=None, values=None, aggfunc)"
},
{
"code": null,
"e": 25734,
"s": 25524,
"text": "Parameters –index: Column for making new frame’s index.columns: Column for new frame’s columns.values: Column(s) for populating new frame’s values.aggfunc: function, list of functions, dict, default numpy.mean"
},
{
"code": null,
"e": 25806,
"s": 25734,
"text": "Example 1:Let’s first create a dataframe that includes Sales of Fruits."
},
{
"code": "# importing pandasimport pandas as pd # creating dataframedf = pd.DataFrame({'Product' : ['Carrots', 'Broccoli', 'Banana', 'Banana', 'Beans', 'Orange', 'Broccoli', 'Banana'], 'Category' : ['Vegetable', 'Vegetable', 'Fruit', 'Fruit', 'Vegetable', 'Fruit', 'Vegetable', 'Fruit'], 'Quantity' : [8, 5, 3, 4, 5, 9, 11, 8], 'Amount' : [270, 239, 617, 384, 626, 610, 62, 90]})df",
"e": 26296,
"s": 25806,
"text": null
},
{
"code": null,
"e": 26304,
"s": 26296,
"text": "Output:"
},
{
"code": null,
"e": 26340,
"s": 26304,
"text": "Get the total sales of each product"
},
{
"code": "# creating pivot table of total sales# product-wise aggfunc = 'sum' will # allow you to obtain the sum of sales# each productpivot = df.pivot_table(index =['Product'], values =['Amount'], aggfunc ='sum')print(pivot)",
"e": 26600,
"s": 26340,
"text": null
},
{
"code": null,
"e": 26608,
"s": 26600,
"text": "Output:"
},
{
"code": null,
"e": 26645,
"s": 26608,
"text": "Get the total sales of each category"
},
{
"code": "# creating pivot table of total # sales category-wise aggfunc = 'sum'# will allow you to obtain the sum of# sales each productpivot = df.pivot_table(index =['Category'], values =['Amount'], aggfunc ='sum')print(pivot)",
"e": 26909,
"s": 26645,
"text": null
},
{
"code": null,
"e": 26917,
"s": 26909,
"text": "Output:"
},
{
"code": null,
"e": 26969,
"s": 26917,
"text": "Get the total sales of by category and product both"
},
{
"code": "# creating pivot table of sales# by product and category both# aggfunc = 'sum' will allow you# to obtain the sum of sales each# productpivot = df.pivot_table(index =['Product', 'Category'], values =['Amount'], aggfunc ='sum')print (pivot)",
"e": 27231,
"s": 26969,
"text": null
},
{
"code": null,
"e": 27240,
"s": 27231,
"text": "Output –"
},
{
"code": null,
"e": 27287,
"s": 27240,
"text": "Get the Mean, Median, Minimum sale by category"
},
{
"code": "# creating pivot table of Mean, Median,# Minimum sale by category aggfunc = {'median',# 'mean', 'min'} will get median, mean and # minimum of sales respectivelypivot = df.pivot_table(index =['Category'], values =['Amount'], aggfunc ={'median', 'mean', 'min'})print (pivot)",
"e": 27583,
"s": 27287,
"text": null
},
{
"code": null,
"e": 27592,
"s": 27583,
"text": "Output –"
},
{
"code": null,
"e": 27638,
"s": 27592,
"text": "Get the Mean, Median, Minimum sale by product"
},
{
"code": "# creating pivot table of Mean, Median,# Minimum sale by product aggfunc = {'median',# 'mean', 'min'} will get median, mean and# minimum of sales respectivelypivot = df.pivot_table(index =['Product'], values =['Amount'], aggfunc ={'median', 'mean', 'min'})print (pivot)",
"e": 27930,
"s": 27638,
"text": null
},
{
"code": null,
"e": 27938,
"s": 27930,
"text": "Output:"
},
{
"code": null,
"e": 27962,
"s": 27938,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 27976,
"s": 27962,
"text": "Python-pandas"
},
{
"code": null,
"e": 27983,
"s": 27976,
"text": "Python"
},
{
"code": null,
"e": 28081,
"s": 27983,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28099,
"s": 28081,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28134,
"s": 28099,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28156,
"s": 28134,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28188,
"s": 28156,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28218,
"s": 28188,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28260,
"s": 28218,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28286,
"s": 28260,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28323,
"s": 28286,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28366,
"s": 28323,
"text": "Python program to convert a list to string"
}
] |
Keras - RepeatVector Layers
|
RepeatVector is used to repeat the input for set number, n of times. For example, if RepeatVector with argument 16 is applied to layer having input shape as (batch_size, 32), then the output shape of the layer will be (batch_size, 16, 32)
RepeatVector has one arguments and it is as follows −
keras.layers.RepeatVector(n)
A simple example to use RepeatVector layers is as follows −
>>> from keras.models import Sequential
>>> from keras.layers import Activation, Dense, RepeatVector
>>>
>>>
>>> model = Sequential()
>>> layer_1 = Dense(16, input_shape=(8,))
>>> model.add(layer_1)
>>> layer_2 = RepeatVector(16)
>>> model.add(layer_2)
>>> layer_2.input_shape (None, 16)
>>> layer_2.output_shape
(None, 16, 16)
>>>
where, 16 is set as repeat times.
87 Lectures
11 hours
Abhilash Nelson
61 Lectures
9 hours
Abhishek And Pukhraj
57 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
7 hours
Abhishek And Pukhraj
52 Lectures
6 hours
Abhishek And Pukhraj
68 Lectures
2 hours
Mike West
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2290,
"s": 2051,
"text": "RepeatVector is used to repeat the input for set number, n of times. For example, if RepeatVector with argument 16 is applied to layer having input shape as (batch_size, 32), then the output shape of the layer will be (batch_size, 16, 32)"
},
{
"code": null,
"e": 2344,
"s": 2290,
"text": "RepeatVector has one arguments and it is as follows −"
},
{
"code": null,
"e": 2374,
"s": 2344,
"text": "keras.layers.RepeatVector(n)\n"
},
{
"code": null,
"e": 2434,
"s": 2374,
"text": "A simple example to use RepeatVector layers is as follows −"
},
{
"code": null,
"e": 2776,
"s": 2434,
"text": ">>> from keras.models import Sequential \n>>> from keras.layers import Activation, Dense, RepeatVector \n>>> \n>>> \n>>> model = Sequential() \n>>> layer_1 = Dense(16, input_shape=(8,)) \n>>> model.add(layer_1) \n>>> layer_2 = RepeatVector(16) \n>>> model.add(layer_2) \n>>> layer_2.input_shape (None, 16) \n>>> layer_2.output_shape\n(None, 16, 16)\n>>>"
},
{
"code": null,
"e": 2810,
"s": 2776,
"text": "where, 16 is set as repeat times."
},
{
"code": null,
"e": 2844,
"s": 2810,
"text": "\n 87 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 2861,
"s": 2844,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 2894,
"s": 2861,
"text": "\n 61 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 2916,
"s": 2894,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 2949,
"s": 2916,
"text": "\n 57 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 2971,
"s": 2949,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3004,
"s": 2971,
"text": "\n 52 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3026,
"s": 3004,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3059,
"s": 3026,
"text": "\n 52 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3081,
"s": 3059,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 3114,
"s": 3081,
"text": "\n 68 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3125,
"s": 3114,
"text": " Mike West"
},
{
"code": null,
"e": 3132,
"s": 3125,
"text": " Print"
},
{
"code": null,
"e": 3143,
"s": 3132,
"text": " Add Notes"
}
] |
Advance DAX Tutorial: Basket Analysis 2.0 | by Davis Zhang | Towards Data Science
|
This article aims to use DAX to analyze customer purchase behavior in Power BI and to gain insight into product potential.
Marco Russo and Alberto Ferrari have published a blog a few years ago called “Basket Analysis”, this interesting article describes in detail how to use DAX to calculate very useful measures such as the number of orders and the number of customers under any product portfolio. This article can be seen as an extension of “Basket Analysis”, which takes into account the chronological order in which customers purchase different products.
Assuming that A and B represent two different products, then “Basket Analysis” calculates P(AB), while this paper calculates P(A|B) and P(B|A), as you can compare the two figures shown below:
The figure above is the measure of “Customers with Both Products” in “Basket Analysis”, which shows that 72 customers have purchase records for both “Bottles and Cages” and “Bike Racks”. However, the data shown in the figure below takes into account the chronological order in which customers purchase products. You can find that 8 of the customers who bought Bike Racks first and then purchased Bottles and Cages later, and 14 of the customers who bought Bottles and Cages first but bought Bike Racks later.(Note: We temporarily ignore the situation of buying A and B at the same time)
The customer’s order record reflects some very useful facts that give direction to the correlation between products. In other words, “basket analysis” is very useful when analyzing supermarket data because customers often choose multiple products at the time of shopping and then go to the cashier to place an order together. In this case, all products are treated as simultaneous orders. But in fact, you can’t trace the record of different products selected by customers during the shopping process in the supermarket. But if it is in other scenarios, such as customers ordering on the e-commerce platform or the official website, if you as the store manager, you may want to know that A and B are the best-selling models, which one can bring more return customers, which one is easier to lose customers. Therefore, we need to know the repurchase % of each product. For example, all customers who purchase products A first, how many people will come back to buy products again in the future, further analysis, in these people, the purchase is still product A or other products? What is the proportion of each, this is a question worth studying.
Following the calculation process, we will finally achieve the calculation results shown in the figure below (Note: I use the same data set as “basket analysis”):
As mentioned earlier, it shows which customers who purchased the product A first and have subsequent purchase records, how much of them purchased the product B, or product C, etc.
Therefore, in order to achieve this calculation result, there are five steps here:
1. First, classify all orders for the sales table, in all orders of the customer, one or more orders with the earliest order date are classified as the first order, the rest are “non-first”:
IsFirstOrder = VARE_Date = 'Sales'[OrderDateKey]VARCUST = 'Sales'[CustomerKey]RETURNIF( SUMX( FILTER('Sales', CUST = 'Sales'[CustomerKey]&& E_Date > 'Sales'[OrderDateKey]), COUNTROWS('Sales'))>0,FALSE,TRUE)
2. Filter the order data of all products A in Sales, and then further filter which orders are marked as the customer’s first order, and we extract the customer list in this filtered table, and add a virtual column named “ROWS” to it, as shown in the following code — virtual table “VT1”.
3. Use Sales as the main table and use NATURALLEFTOUTERJOIN() to associate with the virtual table “VT1”, then use filter() to exclude those rows whose [ROWS] value is not equal to 1 so that the rest of the data (VT2) is all orders for all customers returned by “VT1”. Finally, the data is further filtered for all orders except “first-order”, and the result is named “CustDistinctValue”:
CustDistinctValue = VARFIRSTORDERPROD = IF(HASONEVALUE('Product'[Subcategory]), VALUES('Product'[Subcategory]),0)VARVT1 = SUMMARIZE( FILTER(Sales, AND(related('Product'[Subcategory]) = FIRSTORDERPROD, 'Sales'[IsFirstOrder]=TRUE)), 'Sales'[CustomerKey], "ROWS", DISTINCTCOUNT(Sales[CustomerKey]))VARVT2 = FILTER( NATURALLEFTOUTERJOIN(ALL(Sales),VT1), [ROWS] = 1)RETURNCALCULATE( DISTINCTCOUNT('Sales'[CustomerKey]), FILTER(VT2,'Sales'[IsFirstOrder] = FALSE))
4. After that, we need to make sure this data can be filtered by the product (in this case we just use sub-category). Here is basically the same as Macro’s calculation method, using the copy of the product table (Filter Product) and the main table to establish a non- Active relationship, then create a measure so that its context ignores all fields of the product table, and accepts the context from its copy (Filter Product).
CustPurchaseOthersSubcategoryAfter = VAR CustPurchaseOthersSubcategoryAfter = CALCULATE ( 'Sales'[CustDistinctValue], CALCULATETABLE ( SUMMARIZE ( Sales, Sales[CustomerKey] ), 'Sales'[IsFirstOrder] = FALSE, ALLSELECTED ('Product'), USERELATIONSHIP ( Sales[ProductCode], 'Filter Product'[Filter ProductCode] ) ))RETURNIF(NOT([SameSubCategorySelection]), CustPurchaseOthersSubcategoryAfter)
Note: “SameSubCategorySelection” is used to exclude the data of choosing the same Sub-Category. This formula also uses Macro’s method to complete:
SameSubCategorySelection = IF ( HASONEVALUE ( 'Product'[Subcategory] ) && HASONEVALUE ( 'Filter Product'[Filter Subcategory] ), IF ( VALUES ( 'Product'[Subcategory]) = VALUES ( 'Filter Product'[Filter Subcategory] ), TRUE ))
5. Now, we have figured out how many of the customers who purchased Product A first purchased each of the other products, and now we need to calculate the proportion of these customers who accounted for the total number of customers who purchased Product A first and then had a purchase record. The following is the code for calculating the denominator of this proportion.
AsFirstOrderCust = VARFIRSTORDERPROD = IF( HASONEVALUE('Product'[Subcategory]), VALUES('Product'[Subcategory]),0)VARVT1 = SUMMARIZE( FILTER(Sales, AND( RELATED('Product'[Subcategory]) = FIRSTORDERPROD, 'Sales'[IsFirstOrder]=TRUE)), 'Sales'[CustomerKey])returnCALCULATE( DISTINCTCOUNT('Sales'[CustomerKey]), VT1)-------------------------------------------------------------------------------IsLastOrder = VARE_Date = 'Sales'[OrderDateKey]VARCUST = 'Sales'[CustomerKey]RETURNIF( SUMX( FILTER('Sales', CUST = 'Sales'[CustomerKey]&& E_Date < 'Sales'[OrderDateKey]), COUNTROWS('Sales'))>0,"F","T")-------------------------------------------------------------------------------AsFirstOrderCustRepurchase = CALCULATE( 'Sales'[AsFirstOrderCust], 'Sales'[IsLastOrder] = "F")
Now we get the final result: CustPurchaseOthersSubCategoryAfter %, the name of this measure is very long, because its logic is complex, just like the calculation process above.
CustPurchaseOthersSubCategoryAfter % = DIVIDE ( 'Sales'[CustPurchaseOthersSubcategoryAfter], 'Sales'[AsFirstOrderCustRepurchase])
In the end, we will succeed in getting the final result as below and choose to visualize it using a custom-visuals called “CHORD”.
As you can see, the customers who bought road bikes first, 1853 of them bought mountain bikes later, while the interesting thing is only 200 customers bought road bikes after they have bought the mountain bikes.
I am very grateful to Gerhard’s advice before, this time I have attached the PBIX file in the article, you can download it here if you are interested in it.
|
[
{
"code": null,
"e": 294,
"s": 171,
"text": "This article aims to use DAX to analyze customer purchase behavior in Power BI and to gain insight into product potential."
},
{
"code": null,
"e": 730,
"s": 294,
"text": "Marco Russo and Alberto Ferrari have published a blog a few years ago called “Basket Analysis”, this interesting article describes in detail how to use DAX to calculate very useful measures such as the number of orders and the number of customers under any product portfolio. This article can be seen as an extension of “Basket Analysis”, which takes into account the chronological order in which customers purchase different products."
},
{
"code": null,
"e": 922,
"s": 730,
"text": "Assuming that A and B represent two different products, then “Basket Analysis” calculates P(AB), while this paper calculates P(A|B) and P(B|A), as you can compare the two figures shown below:"
},
{
"code": null,
"e": 1509,
"s": 922,
"text": "The figure above is the measure of “Customers with Both Products” in “Basket Analysis”, which shows that 72 customers have purchase records for both “Bottles and Cages” and “Bike Racks”. However, the data shown in the figure below takes into account the chronological order in which customers purchase products. You can find that 8 of the customers who bought Bike Racks first and then purchased Bottles and Cages later, and 14 of the customers who bought Bottles and Cages first but bought Bike Racks later.(Note: We temporarily ignore the situation of buying A and B at the same time)"
},
{
"code": null,
"e": 2656,
"s": 1509,
"text": "The customer’s order record reflects some very useful facts that give direction to the correlation between products. In other words, “basket analysis” is very useful when analyzing supermarket data because customers often choose multiple products at the time of shopping and then go to the cashier to place an order together. In this case, all products are treated as simultaneous orders. But in fact, you can’t trace the record of different products selected by customers during the shopping process in the supermarket. But if it is in other scenarios, such as customers ordering on the e-commerce platform or the official website, if you as the store manager, you may want to know that A and B are the best-selling models, which one can bring more return customers, which one is easier to lose customers. Therefore, we need to know the repurchase % of each product. For example, all customers who purchase products A first, how many people will come back to buy products again in the future, further analysis, in these people, the purchase is still product A or other products? What is the proportion of each, this is a question worth studying."
},
{
"code": null,
"e": 2819,
"s": 2656,
"text": "Following the calculation process, we will finally achieve the calculation results shown in the figure below (Note: I use the same data set as “basket analysis”):"
},
{
"code": null,
"e": 2999,
"s": 2819,
"text": "As mentioned earlier, it shows which customers who purchased the product A first and have subsequent purchase records, how much of them purchased the product B, or product C, etc."
},
{
"code": null,
"e": 3082,
"s": 2999,
"text": "Therefore, in order to achieve this calculation result, there are five steps here:"
},
{
"code": null,
"e": 3273,
"s": 3082,
"text": "1. First, classify all orders for the sales table, in all orders of the customer, one or more orders with the earliest order date are classified as the first order, the rest are “non-first”:"
},
{
"code": null,
"e": 3511,
"s": 3273,
"text": "IsFirstOrder = VARE_Date = 'Sales'[OrderDateKey]VARCUST = 'Sales'[CustomerKey]RETURNIF( SUMX( FILTER('Sales', CUST = 'Sales'[CustomerKey]&& E_Date > 'Sales'[OrderDateKey]), COUNTROWS('Sales'))>0,FALSE,TRUE)"
},
{
"code": null,
"e": 3799,
"s": 3511,
"text": "2. Filter the order data of all products A in Sales, and then further filter which orders are marked as the customer’s first order, and we extract the customer list in this filtered table, and add a virtual column named “ROWS” to it, as shown in the following code — virtual table “VT1”."
},
{
"code": null,
"e": 4187,
"s": 3799,
"text": "3. Use Sales as the main table and use NATURALLEFTOUTERJOIN() to associate with the virtual table “VT1”, then use filter() to exclude those rows whose [ROWS] value is not equal to 1 so that the rest of the data (VT2) is all orders for all customers returned by “VT1”. Finally, the data is further filtered for all orders except “first-order”, and the result is named “CustDistinctValue”:"
},
{
"code": null,
"e": 4702,
"s": 4187,
"text": "CustDistinctValue = VARFIRSTORDERPROD = IF(HASONEVALUE('Product'[Subcategory]), VALUES('Product'[Subcategory]),0)VARVT1 = SUMMARIZE( FILTER(Sales, AND(related('Product'[Subcategory]) = FIRSTORDERPROD, 'Sales'[IsFirstOrder]=TRUE)), 'Sales'[CustomerKey], \"ROWS\", DISTINCTCOUNT(Sales[CustomerKey]))VARVT2 = FILTER( NATURALLEFTOUTERJOIN(ALL(Sales),VT1), [ROWS] = 1)RETURNCALCULATE( DISTINCTCOUNT('Sales'[CustomerKey]), FILTER(VT2,'Sales'[IsFirstOrder] = FALSE))"
},
{
"code": null,
"e": 5130,
"s": 4702,
"text": "4. After that, we need to make sure this data can be filtered by the product (in this case we just use sub-category). Here is basically the same as Macro’s calculation method, using the copy of the product table (Filter Product) and the main table to establish a non- Active relationship, then create a measure so that its context ignores all fields of the product table, and accepts the context from its copy (Filter Product)."
},
{
"code": null,
"e": 5571,
"s": 5130,
"text": "CustPurchaseOthersSubcategoryAfter = VAR CustPurchaseOthersSubcategoryAfter = CALCULATE ( 'Sales'[CustDistinctValue], CALCULATETABLE ( SUMMARIZE ( Sales, Sales[CustomerKey] ), 'Sales'[IsFirstOrder] = FALSE, ALLSELECTED ('Product'), USERELATIONSHIP ( Sales[ProductCode], 'Filter Product'[Filter ProductCode] ) ))RETURNIF(NOT([SameSubCategorySelection]), CustPurchaseOthersSubcategoryAfter)"
},
{
"code": null,
"e": 5718,
"s": 5571,
"text": "Note: “SameSubCategorySelection” is used to exclude the data of choosing the same Sub-Category. This formula also uses Macro’s method to complete:"
},
{
"code": null,
"e": 5984,
"s": 5718,
"text": "SameSubCategorySelection = IF ( HASONEVALUE ( 'Product'[Subcategory] ) && HASONEVALUE ( 'Filter Product'[Filter Subcategory] ), IF ( VALUES ( 'Product'[Subcategory]) = VALUES ( 'Filter Product'[Filter Subcategory] ), TRUE ))"
},
{
"code": null,
"e": 6357,
"s": 5984,
"text": "5. Now, we have figured out how many of the customers who purchased Product A first purchased each of the other products, and now we need to calculate the proportion of these customers who accounted for the total number of customers who purchased Product A first and then had a purchase record. The following is the code for calculating the denominator of this proportion."
},
{
"code": null,
"e": 7219,
"s": 6357,
"text": "AsFirstOrderCust = VARFIRSTORDERPROD = IF( HASONEVALUE('Product'[Subcategory]), VALUES('Product'[Subcategory]),0)VARVT1 = SUMMARIZE( FILTER(Sales, AND( RELATED('Product'[Subcategory]) = FIRSTORDERPROD, 'Sales'[IsFirstOrder]=TRUE)), 'Sales'[CustomerKey])returnCALCULATE( DISTINCTCOUNT('Sales'[CustomerKey]), VT1)-------------------------------------------------------------------------------IsLastOrder = VARE_Date = 'Sales'[OrderDateKey]VARCUST = 'Sales'[CustomerKey]RETURNIF( SUMX( FILTER('Sales', CUST = 'Sales'[CustomerKey]&& E_Date < 'Sales'[OrderDateKey]), COUNTROWS('Sales'))>0,\"F\",\"T\")-------------------------------------------------------------------------------AsFirstOrderCustRepurchase = CALCULATE( 'Sales'[AsFirstOrderCust], 'Sales'[IsLastOrder] = \"F\")"
},
{
"code": null,
"e": 7396,
"s": 7219,
"text": "Now we get the final result: CustPurchaseOthersSubCategoryAfter %, the name of this measure is very long, because its logic is complex, just like the calculation process above."
},
{
"code": null,
"e": 7529,
"s": 7396,
"text": "CustPurchaseOthersSubCategoryAfter % = DIVIDE ( 'Sales'[CustPurchaseOthersSubcategoryAfter], 'Sales'[AsFirstOrderCustRepurchase])"
},
{
"code": null,
"e": 7660,
"s": 7529,
"text": "In the end, we will succeed in getting the final result as below and choose to visualize it using a custom-visuals called “CHORD”."
},
{
"code": null,
"e": 7872,
"s": 7660,
"text": "As you can see, the customers who bought road bikes first, 1853 of them bought mountain bikes later, while the interesting thing is only 200 customers bought road bikes after they have bought the mountain bikes."
}
] |
ReactJS – getDerivedStateFromProps() Method
|
In this article, we are going to see how to execute a function before the component is rendered.
This method is called before the rendering or before any updation of the component. This method is majorly used to update the state, before the rendering of the component, which depends upon the props received by the component. This method is called on every rerendering of the component.
static getDerivedStateFromProps(props, state)
props − Props passed to component
props − Props passed to component
state − Previous state of component
state − Previous state of component
In this example, we will build a React application which will fetch the list of users and on clicking the 'fetch user' button, the Show component will get placed in the DOM and before rendering this component, getDerivedStateFromProps method is called which updates the state according to the props passed to it.
App.jsx
import React from 'react';
class App extends React.Component {
constructor() {
super();
this.state = {
show: false,
};
}
render() {
return (
<div>
<h1>User List</h1>
<h3>Username: Rahul</h3>
<button onClick={() => this.setState({ show: true })}>
Fetch Users
</button>
{this.state.show ? <Show email="[email protected]" /> : null}
</div>
);
}
}
class Show extends React.Component {
constructor() {
super();
this.state = {
email: '',
};
}
static getDerivedStateFromProps(props, state) {
console.log('getDerivedStateFromProps method is called');
return { email: props.email };
}
render() {
return (
<div>
<h3>Email: {this.state.email}</h3>
</div>
);
}
}
export default App;
This will produce the following result.
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "In this article, we are going to see how to execute a function before the component is rendered."
},
{
"code": null,
"e": 1448,
"s": 1159,
"text": "This method is called before the rendering or before any updation of the component. This method is majorly used to update the state, before the rendering of the component, which depends upon the props received by the component. This method is called on every rerendering of the component."
},
{
"code": null,
"e": 1494,
"s": 1448,
"text": "static getDerivedStateFromProps(props, state)"
},
{
"code": null,
"e": 1528,
"s": 1494,
"text": "props − Props passed to component"
},
{
"code": null,
"e": 1562,
"s": 1528,
"text": "props − Props passed to component"
},
{
"code": null,
"e": 1598,
"s": 1562,
"text": "state − Previous state of component"
},
{
"code": null,
"e": 1634,
"s": 1598,
"text": "state − Previous state of component"
},
{
"code": null,
"e": 1947,
"s": 1634,
"text": "In this example, we will build a React application which will fetch the list of users and on clicking the 'fetch user' button, the Show component will get placed in the DOM and before rendering this component, getDerivedStateFromProps method is called which updates the state according to the props passed to it."
},
{
"code": null,
"e": 1955,
"s": 1947,
"text": "App.jsx"
},
{
"code": null,
"e": 2878,
"s": 1955,
"text": "import React from 'react';\n\nclass App extends React.Component {\n constructor() {\n super();\n this.state = {\n show: false,\n };\n }\n render() {\n return (\n <div>\n <h1>User List</h1>\n <h3>Username: Rahul</h3>\n <button onClick={() => this.setState({ show: true })}>\n Fetch Users\n </button>\n {this.state.show ? <Show email=\"[email protected]\" /> : null}\n </div>\n );\n }\n}\nclass Show extends React.Component {\n constructor() {\n super();\n this.state = {\n email: '',\n };\n }\n static getDerivedStateFromProps(props, state) {\n console.log('getDerivedStateFromProps method is called');\n return { email: props.email };\n }\n render() {\n return (\n <div>\n <h3>Email: {this.state.email}</h3>\n </div>\n );\n }\n}\nexport default App;"
},
{
"code": null,
"e": 2918,
"s": 2878,
"text": "This will produce the following result."
}
] |
Merge Without Extra Space | Practice | GeeksforGeeks
|
Given two sorted arrays arr1[] of size N and arr2[] of size M. Each array is sorted in non-decreasing order. Merge the two arrays into one sorted array in non-decreasing order without using any extra space.
Example 1:
Input:
N = 4, M = 5
arr1[] = {1, 3, 5, 7}
arr2[] = {0, 2, 6, 8, 9}
Output: 0 1 2 3 5 6 7 8 9
Explanation: Since you can't use any
extra space, modify the given arrays
to form
arr1[] = {0, 1, 2, 3}
arr2[] = {5, 6, 7, 8, 9}
Example 2:
Input:
N = 2, M = 3
arr1[] = {10, 12}
arr2[] = {5, 18, 20}
Output: 5 10 12 18 20
Explanation: Since you can't use any
extra space, modify the given arrays
to form
arr1[] = {5, 10}
arr2[] = {12, 18, 20}
Your Task:
You don't need to read input or print anything. Complete the function merge() which takes the two arrays arr1[], arr2[] and their sizes n and m, as input parameters. The function does not return anything. Use the given arrays to sort and merge arr1[] and arr2[] in-place.
Note: The generated output will print all the elements of arr1[] followed by all the elements of arr2[].
Expected Time Complexity: O((n+m)*log(n+m))
Expected Auxiliary Space: O(1)
Constraints:
1 <= N, M <= 5*104
0 <= arr1i, arr2i <= 106
0
shashankchauhansc75 days ago
def merge(self, arr1, arr2, n, m): i = n-1 j = 0 while i >= 0 and j < m:
if arr1[i] > arr2[j]: arr1[i], arr2[j] = arr2[j], arr1[i]
else: break
i -= 1 j += 1
arr1.sort() arr2.sort()
0
anmolbansal25 days ago
public void merge(int arr1[], int arr2[], int n, int m) { // code here int ans[]=new int[n+m]; for(int i=0;i<n;i++){ ans[i]=arr1[i]; } for(int i=n,j=0;i<m+n;i++){ ans[i]=arr2[j++]; } Arrays.sort(ans); for(int i=0;i<n;i++){ arr1[i]=ans[i]; } for(int i=0,j=n;i<m;i++){ arr2[i]=ans[j++]; } }
+1
2019kucp10855 days ago
void merge(int arr1[], int arr2[], int n, int m) {
int i=n-1;
int j=0;
while(i>=0 && j<m)
{
if(arr1[i]>arr2[j])
{
swap(arr1[i],arr2[j]);
i--;
j++;
}
else
break;
}
sort(arr1,arr1+n);
sort(arr2,arr2+m);
}
-1
jy9041476 days ago
java solution jitu yadav
public void merge(int arr1[], int arr2[], int n, int m) { int ans[]=new int[n+m]; for(int i=0;i<n;i++){ ans[i]=arr1[i]; } for(int i=n,j=0;i<m+n;i++){ ans[i]=arr2[j++]; } Arrays.sort(ans); for(int i=0;i<n;i++){ arr1[i]=ans[i]; } for(int i=0,j=n;i<m;i++){ arr2[i]=ans[j++]; } }
+1
aishaparween5461 week ago
public void merge(int arr1[], int arr2[], int n, int m) { // code here int i=n-1,j=0; while(i>=0 && j<m){ if(arr1[i]<arr2[j]){ break; } else{ int temp=arr1[i]; arr1[i]=arr2[j]; arr2[j]=temp; i--; j++; } } Arrays.sort(arr1);Arrays.sort(arr2);
0
rajsaurabh9011 week ago
void merge(int arr1[], int arr2[], int n, int m) { // code here int p2; int a=(n+m); while(a>1){ int p1=0; a=(a+1)/2; p2=a; while(p2<n+m){ if(p1<n && p2<n){ if(arr1[p1]<arr1[p2]){ p1++;p2++; } else{ swap(arr1[p1],arr1[p2]); p1++;p2++; } } else if(p1<n && p2>n-1){ int b=p2-n; if(arr1[p1]<arr2[b]){ p1++;p2++; } else{ swap(arr1[p1],arr2[b]); p1++;p2++; } } else if(p1>n-1 && p2>n-1){ int b2=p2-n; int b1=p1-n; if(arr2[b1]<arr2[b2]){ p1++;p2++; } else{ swap(arr2[b1],arr2[b2]); p1++;p2++; } } } }}};
-5
jeetsorathiya1 week ago
easy solution :
class Solution {
public void merge(int arr1[], int arr2[], int n, int m) { // code here int ans[] = new int[n+m]; for(int i=0;i<n;i++) { ans[i]=arr1[i]; } for(int i=n,j=0;i<m+n;i++) { ans[i]=arr2[j++]; } Arrays.sort(ans); for(int i=0;i<n;i++) { arr1[i]=ans[i]; } for(int i=0,j=n;i<m;i++) { arr2[i]=ans[j++]; } }}
0
21f10050132 weeks ago
Running successfully in Jupyter Notebook , with same input jupyter ans GforG compiler shows different output.
def merge(self,arr1,arr2, n, m):
# code here
i,j=0,0
while i<n and j<m:
#print(i,j)
if arr1[i]<arr2[j]:
i+=1
#j+=1
elif arr1[i]==arr2[j]:
i+=1
j+=1
else:
(arr1[i],arr2[j])=(arr2[j],arr1[i])
i+=1
#j+=1
arr2=sorted(arr2)
return
-1
aniket752 weeks ago
public void merge(int arr1[], int arr2[], int n, int m) { // use merge sort concept int merge[] = new int[n+m]; int i = 0; int j=0; int k=0; while(i<n && j<m){ if(arr1[i]<arr2[j]){ merge[k] = arr1[i]; i++; k++; } else{ merge[k] = arr2[j]; j++; k++; } } while(i<n){ merge[k] = arr1[i]; i++; k++; } while(j<m){ merge[k] = arr2[j]; j++; k++; } // this loop use to avoid extra space for(i=0;i<n;i++){ arr1[i]=merge[i]; } for(i=0,j=n;i<m;i++){ arr2[i]=merge[j++]; } }
-1
yedurusrinivasreddy99882 weeks ago
Simple Python Code
def merge(self, arr1, arr2, n, m):
# code here
res=[]
for i in arr1:
res.append(i)
for j in arr2:
res.append(j)
res.sort()
arr1.clear()
arr2.clear()
for i in range(n):
arr1.append(res[i])
for j in range(n,m+n):
arr2.append(res[j])
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.
|
[
{
"code": null,
"e": 445,
"s": 238,
"text": "Given two sorted arrays arr1[] of size N and arr2[] of size M. Each array is sorted in non-decreasing order. Merge the two arrays into one sorted array in non-decreasing order without using any extra space."
},
{
"code": null,
"e": 457,
"s": 445,
"text": "\nExample 1:"
},
{
"code": null,
"e": 683,
"s": 457,
"text": "Input:\nN = 4, M = 5\narr1[] = {1, 3, 5, 7}\narr2[] = {0, 2, 6, 8, 9}\nOutput: 0 1 2 3 5 6 7 8 9\nExplanation: Since you can't use any \nextra space, modify the given arrays\nto form \narr1[] = {0, 1, 2, 3}\narr2[] = {5, 6, 7, 8, 9}\n\n"
},
{
"code": null,
"e": 694,
"s": 683,
"text": "Example 2:"
},
{
"code": null,
"e": 897,
"s": 694,
"text": "Input:\nN = 2, M = 3\narr1[] = {10, 12}\narr2[] = {5, 18, 20}\nOutput: 5 10 12 18 20\nExplanation: Since you can't use any\nextra space, modify the given arrays\nto form \narr1[] = {5, 10}\narr2[] = {12, 18, 20}"
},
{
"code": null,
"e": 1288,
"s": 899,
"text": "Your Task:\nYou don't need to read input or print anything. Complete the function merge() which takes the two arrays arr1[], arr2[] and their sizes n and m, as input parameters. The function does not return anything. Use the given arrays to sort and merge arr1[] and arr2[] in-place. \nNote: The generated output will print all the elements of arr1[] followed by all the elements of arr2[]."
},
{
"code": null,
"e": 1364,
"s": 1288,
"text": "\nExpected Time Complexity: O((n+m)*log(n+m))\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1422,
"s": 1364,
"text": "\nConstraints:\n1 <= N, M <= 5*104\n0 <= arr1i, arr2i <= 106"
},
{
"code": null,
"e": 1426,
"s": 1424,
"text": "0"
},
{
"code": null,
"e": 1455,
"s": 1426,
"text": "shashankchauhansc75 days ago"
},
{
"code": null,
"e": 1551,
"s": 1455,
"text": " def merge(self, arr1, arr2, n, m): i = n-1 j = 0 while i >= 0 and j < m:"
},
{
"code": null,
"e": 1634,
"s": 1551,
"text": " if arr1[i] > arr2[j]: arr1[i], arr2[j] = arr2[j], arr1[i]"
},
{
"code": null,
"e": 1671,
"s": 1634,
"text": " else: break"
},
{
"code": null,
"e": 1706,
"s": 1671,
"text": " i -= 1 j += 1"
},
{
"code": null,
"e": 1743,
"s": 1706,
"text": " arr1.sort() arr2.sort()"
},
{
"code": null,
"e": 1745,
"s": 1743,
"text": "0"
},
{
"code": null,
"e": 1768,
"s": 1745,
"text": "anmolbansal25 days ago"
},
{
"code": null,
"e": 2152,
"s": 1768,
"text": "public void merge(int arr1[], int arr2[], int n, int m) { // code here int ans[]=new int[n+m]; for(int i=0;i<n;i++){ ans[i]=arr1[i]; } for(int i=n,j=0;i<m+n;i++){ ans[i]=arr2[j++]; } Arrays.sort(ans); for(int i=0;i<n;i++){ arr1[i]=ans[i]; } for(int i=0,j=n;i<m;i++){ arr2[i]=ans[j++]; } }"
},
{
"code": null,
"e": 2155,
"s": 2152,
"text": "+1"
},
{
"code": null,
"e": 2178,
"s": 2155,
"text": "2019kucp10855 days ago"
},
{
"code": null,
"e": 2508,
"s": 2178,
"text": "\tvoid merge(int arr1[], int arr2[], int n, int m) {\n\t int i=n-1;\n\t int j=0;\n\t \n\t while(i>=0 && j<m)\n\t {\n\t if(arr1[i]>arr2[j])\n\t {\n\t swap(arr1[i],arr2[j]);\n\t i--;\n\t j++;\n\t }\n\t else\n\t break;\n\t }\n\t sort(arr1,arr1+n);\n\t sort(arr2,arr2+m);\n\t}"
},
{
"code": null,
"e": 2511,
"s": 2508,
"text": "-1"
},
{
"code": null,
"e": 2530,
"s": 2511,
"text": "jy9041476 days ago"
},
{
"code": null,
"e": 2555,
"s": 2530,
"text": "java solution jitu yadav"
},
{
"code": null,
"e": 2959,
"s": 2555,
"text": " public void merge(int arr1[], int arr2[], int n, int m) { int ans[]=new int[n+m]; for(int i=0;i<n;i++){ ans[i]=arr1[i]; } for(int i=n,j=0;i<m+n;i++){ ans[i]=arr2[j++]; } Arrays.sort(ans); for(int i=0;i<n;i++){ arr1[i]=ans[i]; } for(int i=0,j=n;i<m;i++){ arr2[i]=ans[j++]; } }"
},
{
"code": null,
"e": 2962,
"s": 2959,
"text": "+1"
},
{
"code": null,
"e": 2988,
"s": 2962,
"text": "aishaparween5461 week ago"
},
{
"code": null,
"e": 3309,
"s": 2988,
"text": " public void merge(int arr1[], int arr2[], int n, int m) { // code here int i=n-1,j=0; while(i>=0 && j<m){ if(arr1[i]<arr2[j]){ break; } else{ int temp=arr1[i]; arr1[i]=arr2[j]; arr2[j]=temp; i--; j++; } } Arrays.sort(arr1);Arrays.sort(arr2);"
},
{
"code": null,
"e": 3311,
"s": 3309,
"text": "0"
},
{
"code": null,
"e": 3335,
"s": 3311,
"text": "rajsaurabh9011 week ago"
},
{
"code": null,
"e": 4358,
"s": 3335,
"text": " void merge(int arr1[], int arr2[], int n, int m) { // code here int p2; int a=(n+m); while(a>1){ int p1=0; a=(a+1)/2; p2=a; while(p2<n+m){ if(p1<n && p2<n){ if(arr1[p1]<arr1[p2]){ p1++;p2++; } else{ swap(arr1[p1],arr1[p2]); p1++;p2++; } } else if(p1<n && p2>n-1){ int b=p2-n; if(arr1[p1]<arr2[b]){ p1++;p2++; } else{ swap(arr1[p1],arr2[b]); p1++;p2++; } } else if(p1>n-1 && p2>n-1){ int b2=p2-n; int b1=p1-n; if(arr2[b1]<arr2[b2]){ p1++;p2++; } else{ swap(arr2[b1],arr2[b2]); p1++;p2++; } } } }}};"
},
{
"code": null,
"e": 4361,
"s": 4358,
"text": "-5"
},
{
"code": null,
"e": 4385,
"s": 4361,
"text": "jeetsorathiya1 week ago"
},
{
"code": null,
"e": 4401,
"s": 4385,
"text": "easy solution :"
},
{
"code": null,
"e": 4420,
"s": 4403,
"text": "class Solution {"
},
{
"code": null,
"e": 4872,
"s": 4420,
"text": " public void merge(int arr1[], int arr2[], int n, int m) { // code here int ans[] = new int[n+m]; for(int i=0;i<n;i++) { ans[i]=arr1[i]; } for(int i=n,j=0;i<m+n;i++) { ans[i]=arr2[j++]; } Arrays.sort(ans); for(int i=0;i<n;i++) { arr1[i]=ans[i]; } for(int i=0,j=n;i<m;i++) { arr2[i]=ans[j++]; } }}"
},
{
"code": null,
"e": 4874,
"s": 4872,
"text": "0"
},
{
"code": null,
"e": 4896,
"s": 4874,
"text": "21f10050132 weeks ago"
},
{
"code": null,
"e": 5006,
"s": 4896,
"text": "Running successfully in Jupyter Notebook , with same input jupyter ans GforG compiler shows different output."
},
{
"code": null,
"e": 5440,
"s": 5008,
"text": "def merge(self,arr1,arr2, n, m): \n # code here\n i,j=0,0\n while i<n and j<m:\n #print(i,j)\n if arr1[i]<arr2[j]:\n i+=1\n #j+=1\n elif arr1[i]==arr2[j]:\n i+=1\n j+=1\n else:\n (arr1[i],arr2[j])=(arr2[j],arr1[i])\n i+=1\n #j+=1\n arr2=sorted(arr2)\n return\n"
},
{
"code": null,
"e": 5443,
"s": 5440,
"text": "-1"
},
{
"code": null,
"e": 5463,
"s": 5443,
"text": "aniket752 weeks ago"
},
{
"code": null,
"e": 6210,
"s": 5463,
"text": " public void merge(int arr1[], int arr2[], int n, int m) { // use merge sort concept int merge[] = new int[n+m]; int i = 0; int j=0; int k=0; while(i<n && j<m){ if(arr1[i]<arr2[j]){ merge[k] = arr1[i]; i++; k++; } else{ merge[k] = arr2[j]; j++; k++; } } while(i<n){ merge[k] = arr1[i]; i++; k++; } while(j<m){ merge[k] = arr2[j]; j++; k++; } // this loop use to avoid extra space for(i=0;i<n;i++){ arr1[i]=merge[i]; } for(i=0,j=n;i<m;i++){ arr2[i]=merge[j++]; } }"
},
{
"code": null,
"e": 6213,
"s": 6210,
"text": "-1"
},
{
"code": null,
"e": 6248,
"s": 6213,
"text": "yedurusrinivasreddy99882 weeks ago"
},
{
"code": null,
"e": 6267,
"s": 6248,
"text": "Simple Python Code"
},
{
"code": null,
"e": 6606,
"s": 6267,
"text": "def merge(self, arr1, arr2, n, m): \n # code here\n res=[]\n for i in arr1:\n res.append(i)\n for j in arr2:\n res.append(j)\n res.sort()\n arr1.clear()\n arr2.clear()\n for i in range(n):\n arr1.append(res[i])\n for j in range(n,m+n):\n arr2.append(res[j])"
},
{
"code": null,
"e": 6752,
"s": 6606,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 6788,
"s": 6752,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6798,
"s": 6788,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6808,
"s": 6798,
"text": "\nContest\n"
},
{
"code": null,
"e": 6871,
"s": 6808,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7019,
"s": 6871,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 7227,
"s": 7019,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 7333,
"s": 7227,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
std::greater in C++ with Examples
|
22 Apr, 2020
The std::greater is a functional object which is used for performing comparisons. It is defined as a Function object class for the greater-than inequality comparison. This can be used for changing the functionality of the given function. This can also be used with various standard algorithms such as sort, priority queue, etc.
Header File:
#include <functional.h>
Template Class:
template <class T> struct greater;
Parameter: T is a type of the arguments to compare by the functional call.
Return Value: It returns boolean variable as shown below:
True: If two element say(a & b) such that a > b.
False: If a < b.
Below is the illustration of std::greater in C++:
Program 1:
// C++ program to illustrate std::greater #include <algorithm>#include <functional>#include <iostream>using namespace std; // Function to print array elementsvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) { cout << arr[i] << ' '; }} // Driver Codeint main(){ int arr[] = { 60, 10, 80, 40, 30, 20, 50, 90, 70 }; int n = sizeof(arr) / sizeof(arr[0]); // To sort the array in decreasing order // use greater <int>() as an third arguments sort(arr, arr + 9, greater<int>()); // Print array elements printArray(arr, n); return 0;}
90 80 70 60 50 40 30 20 10
Program 2:
// C++ program to illustrate std::greater #include <functional>#include <iostream>#include <queue>using namespace std; // Function to print elements of priority_queuevoid showpq(priority_queue<int, vector<int>, greater<int> > pq){ priority_queue<int, vector<int>, greater<int> > g; g = pq; // While priority_queue is not empty while (!g.empty()) { // Print the top element cout << g.top() << ' '; // Pop the top element g.pop(); }} // Driver Codeint main(){ // priority_queue use to implement // Max Heap, but using function // greater <int> () it implements // Min Heap priority_queue<int, vector<int>, greater<int> > gquiz; // Inserting Elements gquiz.push(10); gquiz.push(30); gquiz.push(20); gquiz.push(5); gquiz.push(1); // Print elements of priority queue cout << "The priority queue gquiz is : "; showpq(gquiz); return 0;}
The priority queue gquiz is : 1 5 10 20 30
C++
C++ Programs
Write From Home
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set in C++ Standard Template Library (STL)
Inheritance in C++
unordered_map in C++ STL
vector erase() and clear() in C++
C++ Classes and Objects
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
Program to print ASCII Value of a character
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 380,
"s": 52,
"text": "The std::greater is a functional object which is used for performing comparisons. It is defined as a Function object class for the greater-than inequality comparison. This can be used for changing the functionality of the given function. This can also be used with various standard algorithms such as sort, priority queue, etc."
},
{
"code": null,
"e": 393,
"s": 380,
"text": "Header File:"
},
{
"code": null,
"e": 418,
"s": 393,
"text": "#include <functional.h>\n"
},
{
"code": null,
"e": 434,
"s": 418,
"text": "Template Class:"
},
{
"code": null,
"e": 470,
"s": 434,
"text": "template <class T> struct greater;\n"
},
{
"code": null,
"e": 545,
"s": 470,
"text": "Parameter: T is a type of the arguments to compare by the functional call."
},
{
"code": null,
"e": 603,
"s": 545,
"text": "Return Value: It returns boolean variable as shown below:"
},
{
"code": null,
"e": 652,
"s": 603,
"text": "True: If two element say(a & b) such that a > b."
},
{
"code": null,
"e": 669,
"s": 652,
"text": "False: If a < b."
},
{
"code": null,
"e": 719,
"s": 669,
"text": "Below is the illustration of std::greater in C++:"
},
{
"code": null,
"e": 730,
"s": 719,
"text": "Program 1:"
},
{
"code": "// C++ program to illustrate std::greater #include <algorithm>#include <functional>#include <iostream>using namespace std; // Function to print array elementsvoid printArray(int arr[], int n){ for (int i = 0; i < n; i++) { cout << arr[i] << ' '; }} // Driver Codeint main(){ int arr[] = { 60, 10, 80, 40, 30, 20, 50, 90, 70 }; int n = sizeof(arr) / sizeof(arr[0]); // To sort the array in decreasing order // use greater <int>() as an third arguments sort(arr, arr + 9, greater<int>()); // Print array elements printArray(arr, n); return 0;}",
"e": 1339,
"s": 730,
"text": null
},
{
"code": null,
"e": 1367,
"s": 1339,
"text": "90 80 70 60 50 40 30 20 10\n"
},
{
"code": null,
"e": 1378,
"s": 1367,
"text": "Program 2:"
},
{
"code": "// C++ program to illustrate std::greater #include <functional>#include <iostream>#include <queue>using namespace std; // Function to print elements of priority_queuevoid showpq(priority_queue<int, vector<int>, greater<int> > pq){ priority_queue<int, vector<int>, greater<int> > g; g = pq; // While priority_queue is not empty while (!g.empty()) { // Print the top element cout << g.top() << ' '; // Pop the top element g.pop(); }} // Driver Codeint main(){ // priority_queue use to implement // Max Heap, but using function // greater <int> () it implements // Min Heap priority_queue<int, vector<int>, greater<int> > gquiz; // Inserting Elements gquiz.push(10); gquiz.push(30); gquiz.push(20); gquiz.push(5); gquiz.push(1); // Print elements of priority queue cout << \"The priority queue gquiz is : \"; showpq(gquiz); return 0;}",
"e": 2418,
"s": 1378,
"text": null
},
{
"code": null,
"e": 2462,
"s": 2418,
"text": "The priority queue gquiz is : 1 5 10 20 30\n"
},
{
"code": null,
"e": 2466,
"s": 2462,
"text": "C++"
},
{
"code": null,
"e": 2479,
"s": 2466,
"text": "C++ Programs"
},
{
"code": null,
"e": 2495,
"s": 2479,
"text": "Write From Home"
},
{
"code": null,
"e": 2499,
"s": 2495,
"text": "CPP"
},
{
"code": null,
"e": 2597,
"s": 2499,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2640,
"s": 2597,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 2659,
"s": 2640,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 2684,
"s": 2659,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 2718,
"s": 2684,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 2742,
"s": 2718,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 2777,
"s": 2742,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 2811,
"s": 2777,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 2855,
"s": 2811,
"text": "Program to print ASCII Value of a character"
},
{
"code": null,
"e": 2914,
"s": 2855,
"text": "How to return multiple values from a function in C or C++?"
}
] |
Express.js | app.route() Function
|
10 Jun, 2020
The app.route() function returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors).
Syntax:
app.route( path )
Installation of express module:
You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
You can visit the link to Install express module. You can install this package by using this command.npm install express
npm install express
After installing express module, you can check your express version in command prompt using the command.npm version express
npm version express
After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js
node index.js
Filename: index.js
var express = require('express');var app = express();var PORT = 3000; app.route('/user').get((req, res, next) => { res.send('GET request called');}).post((req, res, next) => {res.send('POST request called');}).all((req, res, next) => {res.send('Other requests called');}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);});
Steps to run the program:
The project structure will look like this:Make sure you have installed express module using following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000
Now, if me make POST request to /user we get POST request called, similarly if me make GET request to /user we get GET request called and so on.
The project structure will look like this:
Make sure you have installed express module using following command:npm install express
npm install express
Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000
node index.js
Output:
Server listening on PORT 3000
Now, if me make POST request to /user we get POST request called, similarly if me make GET request to /user we get GET request called and so on.
So this is how you can use the express app.route() function which returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware.
Express.js
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jun, 2020"
},
{
"code": null,
"e": 233,
"s": 28,
"text": "The app.route() function returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware. Use app.route() to avoid duplicate route names (and thus typo errors)."
},
{
"code": null,
"e": 241,
"s": 233,
"text": "Syntax:"
},
{
"code": null,
"e": 259,
"s": 241,
"text": "app.route( path )"
},
{
"code": null,
"e": 291,
"s": 259,
"text": "Installation of express module:"
},
{
"code": null,
"e": 682,
"s": 291,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 803,
"s": 682,
"text": "You can visit the link to Install express module. You can install this package by using this command.npm install express"
},
{
"code": null,
"e": 823,
"s": 803,
"text": "npm install express"
},
{
"code": null,
"e": 947,
"s": 823,
"text": "After installing express module, you can check your express version in command prompt using the command.npm version express"
},
{
"code": null,
"e": 967,
"s": 947,
"text": "npm version express"
},
{
"code": null,
"e": 1115,
"s": 967,
"text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js"
},
{
"code": null,
"e": 1129,
"s": 1115,
"text": "node index.js"
},
{
"code": null,
"e": 1148,
"s": 1129,
"text": "Filename: index.js"
},
{
"code": "var express = require('express');var app = express();var PORT = 3000; app.route('/user').get((req, res, next) => { res.send('GET request called');}).post((req, res, next) => {res.send('POST request called');}).all((req, res, next) => {res.send('Other requests called');}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});",
"e": 1540,
"s": 1148,
"text": null
},
{
"code": null,
"e": 1566,
"s": 1540,
"text": "Steps to run the program:"
},
{
"code": null,
"e": 1928,
"s": 1566,
"text": "The project structure will look like this:Make sure you have installed express module using following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow, if me make POST request to /user we get POST request called, similarly if me make GET request to /user we get GET request called and so on."
},
{
"code": null,
"e": 1971,
"s": 1928,
"text": "The project structure will look like this:"
},
{
"code": null,
"e": 2059,
"s": 1971,
"text": "Make sure you have installed express module using following command:npm install express"
},
{
"code": null,
"e": 2079,
"s": 2059,
"text": "npm install express"
},
{
"code": null,
"e": 2168,
"s": 2079,
"text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2182,
"s": 2168,
"text": "node index.js"
},
{
"code": null,
"e": 2190,
"s": 2182,
"text": "Output:"
},
{
"code": null,
"e": 2221,
"s": 2190,
"text": "Server listening on PORT 3000\n"
},
{
"code": null,
"e": 2366,
"s": 2221,
"text": "Now, if me make POST request to /user we get POST request called, similarly if me make GET request to /user we get GET request called and so on."
},
{
"code": null,
"e": 2541,
"s": 2366,
"text": "So this is how you can use the express app.route() function which returns an instance of a single route, which you can then use to handle HTTP verbs with optional middleware."
},
{
"code": null,
"e": 2552,
"s": 2541,
"text": "Express.js"
},
{
"code": null,
"e": 2560,
"s": 2552,
"text": "Node.js"
},
{
"code": null,
"e": 2577,
"s": 2560,
"text": "Web Technologies"
}
] |
Python program to implement Full Adder
|
09 Jun, 2021
Prerequisite : Full Adder in Digital LogicGiven three inputs of Full Adder A, B,C-IN. The task is to implement the Full Adder circuit and Print output i.e sum and C-Out of three inputs.
Full Adder : A Full Adder is a logical circuit that performs an addition operation on three one-bit binary numbers. The full adder produces a sum of the three inputs and carry value.
Logical Expression :
SUM = C-IN XOR ( A XOR B )
C-0UT= A B + B C-IN + A C-IN
Truth Table :
Examples :
Input : 0 1 1
Output: Sum=0, C-Out=1
According to logical expression Sum= C-IN XOR (A XOR B ) i.e 1 XOR (0 XOR 1) =0 , C-Out= A B + B C-IN + A C-IN i.e., 0 AND 1 + 1 AND 1 + 0 AND 1 = 1
Input : 1 0 0
Output: Sum=1, C-Out=0
Approach :
We take three inputs A ,B and C-in .
Applying C-IN XOR (A XOR B ) gives the value of sum
Applying A B + B C-IN + A C-IN gives the value of C-Out
Below is the implementation :
Python3
# python program to implement full adder # Function to print sum and C-Outdef getResult(A, B, C): # Calculating value of sum Sum = C ^ (A ^ B) C # Calculating value of C-Out C_Out = Bin&(not(A ^ B))| not(A)&B # printing the values print("Sum = ", Sum) print("C-Out = ", C_Out) # Driver codeA = 0B = 0C = 1# passing three inputs of fulladder as arguments to get result functiongetResult(A, B, C)
Output :
Sum = 1
C-Out = 0
simranarora5sos
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n09 Jun, 2021"
},
{
"code": null,
"e": 239,
"s": 53,
"text": "Prerequisite : Full Adder in Digital LogicGiven three inputs of Full Adder A, B,C-IN. The task is to implement the Full Adder circuit and Print output i.e sum and C-Out of three inputs."
},
{
"code": null,
"e": 423,
"s": 239,
"text": "Full Adder : A Full Adder is a logical circuit that performs an addition operation on three one-bit binary numbers. The full adder produces a sum of the three inputs and carry value. "
},
{
"code": null,
"e": 444,
"s": 423,
"text": "Logical Expression :"
},
{
"code": null,
"e": 504,
"s": 444,
"text": "SUM = C-IN XOR ( A XOR B )\nC-0UT= A B + B C-IN + A C-IN"
},
{
"code": null,
"e": 519,
"s": 504,
"text": "Truth Table : "
},
{
"code": null,
"e": 530,
"s": 519,
"text": "Examples :"
},
{
"code": null,
"e": 567,
"s": 530,
"text": "Input : 0 1 1\nOutput: Sum=0, C-Out=1"
},
{
"code": null,
"e": 720,
"s": 567,
"text": "According to logical expression Sum= C-IN XOR (A XOR B ) i.e 1 XOR (0 XOR 1) =0 , C-Out= A B + B C-IN + A C-IN i.e., 0 AND 1 + 1 AND 1 + 0 AND 1 = 1 "
},
{
"code": null,
"e": 757,
"s": 720,
"text": "Input : 1 0 0\nOutput: Sum=1, C-Out=0"
},
{
"code": null,
"e": 768,
"s": 757,
"text": "Approach :"
},
{
"code": null,
"e": 805,
"s": 768,
"text": "We take three inputs A ,B and C-in ."
},
{
"code": null,
"e": 857,
"s": 805,
"text": "Applying C-IN XOR (A XOR B ) gives the value of sum"
},
{
"code": null,
"e": 914,
"s": 857,
"text": "Applying A B + B C-IN + A C-IN gives the value of C-Out"
},
{
"code": null,
"e": 944,
"s": 914,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 952,
"s": 944,
"text": "Python3"
},
{
"code": "# python program to implement full adder # Function to print sum and C-Outdef getResult(A, B, C): # Calculating value of sum Sum = C ^ (A ^ B) C # Calculating value of C-Out C_Out = Bin&(not(A ^ B))| not(A)&B # printing the values print(\"Sum = \", Sum) print(\"C-Out = \", C_Out) # Driver codeA = 0B = 0C = 1# passing three inputs of fulladder as arguments to get result functiongetResult(A, B, C)",
"e": 1374,
"s": 952,
"text": null
},
{
"code": null,
"e": 1383,
"s": 1374,
"text": "Output :"
},
{
"code": null,
"e": 1403,
"s": 1383,
"text": "Sum = 1\nC-Out = 0"
},
{
"code": null,
"e": 1419,
"s": 1403,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1454,
"s": 1419,
"text": "Digital Electronics & Logic Design"
}
] |
Sqrt (or Square Root) Decomposition Technique | Set 1 (Introduction)
|
24 May, 2022
Sqrt (or Square Root) Decomposition Technique is one of the most common query optimization technique used by competitive programmers. This technique helps us to reduce Time Complexity by a factor of sqrt(n). The key concept of this technique is to decompose given array into small chunks specifically of size sqrt(n).Let’s say we have an array of n elements and we decompose this array into small chunks of size sqrt(n). We will be having exactly sqrt(n) such chunks provided that n is a perfect square. Therefore, now our array on n elements is decomposed into sqrt(n) blocks, where each block contains sqrt(n) elements (assuming size of array is perfect square).Let’s consider these chunks or blocks as an individual array each of which contains sqrt(n) elements and you have computed your desired answer(according to your problem) individually for all the chunks. Now, you need to answer certain queries asking you the answer for the elements in range l to r(l and r are starting and ending indices of the array) in the original n sized array.The naive approach is simply to iterate over each element in range l to r and calculate its corresponding answer. Therefore, the Time Complexity per query will be O(n).Sqrt Decomposition Trick : As we have already precomputed the answer for all individual chunks and now we need to answer the queries in range l to r. Now we can simply combine the answers of the chunks that lie in between the range l to r in the original array. So, if we see carefully here we are jumping sqrt(n) steps at a time instead of jumping 1 step at a time as done in naive approach. Let’s just analyze its Time Complexity and implementation considering the below problem :-
Problem :
Given an array of n elements. We need to answer q
queries telling the sum of elements in range l to
r in the array. Also the array is not static i.e
the values are changed via some point update query.
Range Sum Queries are of form : Q l r ,
where l is the starting index r is the ending
index
Point update Query is of form : U idx val,
where idx is the index to update val is the
updated value
Let us consider that we have an array of 9 elements. A[] = {1, 5, 2, 4, 6, 1, 3, 5, 7}Let’s decompose this array into sqrt(9) blocks, where each block will contain the sum of elements lying in it. Therefore now our decomposed array would look like this :
Till now we have constructed the decomposed array of sqrt(9) blocks and now we need to print the sum of elements in a given range. So first let’s see two basic types of overlap that a range query can have on our array :-
Range Query of type 1 (Given Range is on Block Boundaries) :
In this type the query, the range may totally cover the continuous sqrt blocks. So we can easily answer the sum of values in this range as the sum of completely overlapped blocks. So answer for above query in the described image will be : ans = 11 + 15 = 26 Time Complexity: In the worst case our range can be 0 to n-1(where n is the size of array and assuming n to be a perfect square). In this case all the blocks are completely overlapped by our query range. Therefore,to answer this query we need to iterate over all the decomposed blocks for the array and we know that the number of blocks = sqrt(n). Hence, the complexity for this type of query will be O(sqrt(n)) in worst case.
Range Query of type 2 (Given Range is NOT on boundaries)
We can deal these type of queries by summing the data from the completely overlapped decomposed blocks lying in the query range and then summing elements one by one from the original array whose corresponding block is not completely overlapped by the query range. So answer for above query in the described image will be : ans = 5 + 2 + 11 + 3 = 21 Time Complexity: Let’s consider a query [l = 1 and r = n-2] (n is the size of the array and has a 0 based indexing). Therefore, for this query exactly ( sqrt(n) – 2 ) blocks will be completely overlapped where as the first and last block will be partially overlapped with just one element left outside the overlapping range. So, the completely overlapped blocks can be summed up in ( sqrt(n) – 2 ) ~ sqrt(n) iterations, whereas first and last block are needed to be traversed one by one separately. But as we know that the number of elements in each block is at max sqrt(n), to sum up last block individually we need to make, (sqrt(n)-1) ~ sqrt(n) iterations and same for the last block. So, the overall Complexity = O(sqrt(n)) + O(sqrt(n)) + O(sqrt(n)) = O(3*sqrt(N)) = O(sqrt(n))
Update Queries(Point update) :
In this query we simply find the block in which the given index lies, then subtract its previous value and add the new updated value as per the point update query. Time Complexity : O(1)
Implementation :
The implementation of the above trick is given below
C++
Java
Python 3
C#
Javascript
// C++ program to demonstrate working of Square Root// Decomposition.#include "iostream"#include "math.h"using namespace std; #define MAXN 10000#define SQRSIZE 100 int arr[MAXN]; // original arrayint block[SQRSIZE]; // decomposed arrayint blk_sz; // block size // Time Complexity : O(1)void update(int idx, int val){ int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))int query(int l, int r){ int sum = 0; while (l<r and l%blk_sz!=0 and l!=0) { // traversing first block in range sum += arr[l]; l++; } while (l+blk_sz-1 <= r) { // traversing completely overlapped blocks in range sum += block[l/blk_sz]; l += blk_sz; } while (l<=r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]void preprocess(int input[], int n){ // initiating block pointer int blk_idx = -1; // calculating size of block blk_sz = sqrt(n); // building the decomposed array for (int i=0; i<n; i++) { arr[i] = input[i]; if (i%blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver codeint main(){ // We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = sizeof(input)/sizeof(input[0]); preprocess(input, n); cout << "query(3,8) : " << query(3, 8) << endl; cout << "query(1,6) : " << query(1, 6) << endl; update(8, 0); cout << "query(8,8) : " << query(8, 8) << endl; return 0;}
// Java program to demonstrate working of// Square Root Decomposition.import java.util.*; class GFG{ static int MAXN = 10000;static int SQRSIZE = 100; static int []arr = new int[MAXN]; // original arraystatic int []block = new int[SQRSIZE]; // decomposed arraystatic int blk_sz; // block size // Time Complexity : O(1)static void update(int idx, int val){ int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))static int query(int l, int r){ int sum = 0; while (l < r && l % blk_sz != 0 && l != 0) { // traversing first block in range sum += arr[l]; l++; } while (l+blk_sz-1 <= r) { // traversing completely // overlapped blocks in range sum += block[l / blk_sz]; l += blk_sz; } while (l <= r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]static void preprocess(int input[], int n){ // initiating block pointer int blk_idx = -1; // calculating size of block blk_sz = (int) Math.sqrt(n); // building the decomposed array for (int i = 0; i < n; i++) { arr[i] = input[i]; if (i % blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver codepublic static void main(String[] args){ // We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = input.length; preprocess(input, n); System.out.println("query(3, 8) : " + query(3, 8)); System.out.println("query(1, 6) : " + query(1, 6)); update(8, 0); System.out.println("query(8, 8) : " + query(8, 8));}} // This code is contributed by PrinciRaj1992
# Python 3 program to demonstrate working of Square Root# Decomposition.from math import sqrt MAXN = 10000SQRSIZE = 100 arr = [0]*(MAXN) # original arrayblock = [0]*(SQRSIZE) # decomposed arrayblk_sz = 0 # block size # Time Complexity : O(1)def update(idx, val): blockNumber = idx // blk_sz block[blockNumber] += val - arr[idx] arr[idx] = val # Time Complexity : O(sqrt(n))def query(l, r): sum = 0 while (l < r and l % blk_sz != 0 and l != 0): # traversing first block in range sum += arr[l] l += 1 while (l + blk_sz - 1 <= r): # traversing completely overlapped blocks in range sum += block[l//blk_sz] l += blk_sz while (l <= r): # traversing last block in range sum += arr[l] l += 1 return sum # Fills values in input[]def preprocess(input, n): # initiating block pointer blk_idx = -1 # calculating size of block global blk_sz blk_sz = int(sqrt(n)) # building the decomposed array for i in range(n): arr[i] = input[i]; if (i % blk_sz == 0): # entering next block # incrementing block pointer blk_idx += 1; block[blk_idx] += arr[i] # Driver code # We have used separate array for input because# the purpose of this code is to explain SQRT# decomposition in competitive programming where# we have multiple inputs.input= [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]n = len(input) preprocess(input, n) print("query(3,8) : ",query(3, 8))print("query(1,6) : ",query(1, 6))update(8, 0)print("query(8,8) : ",query(8, 8)) # This code is contributed by Sanjit_Prasad
// C# program to demonstrate working of// Square Root Decomposition.using System; class GFG{static int MAXN = 10000;static int SQRSIZE = 100; static int []arr = new int[MAXN]; // original arraystatic int []block = new int[SQRSIZE]; // decomposed arraystatic int blk_sz; // block size // Time Complexity : O(1)static void update(int idx, int val){ int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))static int query(int l, int r){ int sum = 0; while (l < r && l % blk_sz != 0 && l != 0) { // traversing first block in range sum += arr[l]; l++; } while (l + blk_sz - 1 <= r) { // traversing completely // overlapped blocks in range sum += block[l / blk_sz]; l += blk_sz; } while (l <= r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]static void preprocess(int []input, int n){ // initiating block pointer int blk_idx = -1; // calculating size of block blk_sz = (int) Math.Sqrt(n); // building the decomposed array for (int i = 0; i < n; i++) { arr[i] = input[i]; if (i % blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver codepublic static void Main(String[] args){ // We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. int []input = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = input.Length; preprocess(input, n); Console.WriteLine("query(3, 8) : " + query(3, 8)); Console.WriteLine("query(1, 6) : " + query(1, 6)); update(8, 0); Console.WriteLine("query(8, 8) : " + query(8, 8));}} // This code is contributed by 29AjayKumar
<script>// Javascript program to demonstrate working of// Square Root Decomposition. let MAXN = 10000;let SQRSIZE = 100; let arr = new Array(MAXN);for(let i = 0; i < MAXN; i++){ arr[i] = 0;} let block = new Array(SQRSIZE);for(let i = 0; i < SQRSIZE; i++){ block[i] = 0;} let blk_sz; // Time Complexity : O(1)function update(idx,val){ let blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))function query(l, r){ let sum = 0; while (l < r && l % blk_sz != 0 && l != 0) { // traversing first block in range sum += arr[l]; l++; } while (l+blk_sz-1 <= r) { // traversing completely // overlapped blocks in range sum += block[l / blk_sz]; l += blk_sz; } while (l <= r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]function preprocess(input, n){ // initiating block pointer let blk_idx = -1; // calculating size of block blk_sz = Math.floor( Math.sqrt(n)); // building the decomposed array for (let i = 0; i < n; i++) { arr[i] = input[i]; if (i % blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver code// We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. let input = [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]; let n = input.length; preprocess(input, n); document.write("query(3, 8) : " + query(3, 8)+"<br>"); document.write("query(1, 6) : " + query(1, 6)+"<br>"); update(8, 0); document.write("query(8, 8) : " + query(8, 8)+"<br>"); // This code is contributed by rag2127</script>
query(3,8) : 26
query(1,6) : 21
query(8,8) : 0
Time Complexity: O(n)
Auxiliary Space: O(MAXN)Note : The above code works even if n is not perfect square. In the case, the last block will contain even less number of elements than sqrt(n), thus reducing the number of iterations. Let’s say n = 10. In this case we will have 4 blocks first three block of size 3 and last block of size 1.This article is contributed by Nitish 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 [email protected]. 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.
princiraj1992
29AjayKumar
ApurvaRaj
rag2127
simmytarika5
rishavnitro
aryanveer
array-range-queries
Competitive Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Fast I/O for Competitive Programming
Bits manipulation (Important tactics)
Top 10 Algorithms and Data Structures for Competitive Programming
What is Competitive Programming and How to Prepare for It?
Algorithm Library | C++ Magicians STL Algorithm
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 May, 2022"
},
{
"code": null,
"e": 1754,
"s": 54,
"text": "Sqrt (or Square Root) Decomposition Technique is one of the most common query optimization technique used by competitive programmers. This technique helps us to reduce Time Complexity by a factor of sqrt(n). The key concept of this technique is to decompose given array into small chunks specifically of size sqrt(n).Let’s say we have an array of n elements and we decompose this array into small chunks of size sqrt(n). We will be having exactly sqrt(n) such chunks provided that n is a perfect square. Therefore, now our array on n elements is decomposed into sqrt(n) blocks, where each block contains sqrt(n) elements (assuming size of array is perfect square).Let’s consider these chunks or blocks as an individual array each of which contains sqrt(n) elements and you have computed your desired answer(according to your problem) individually for all the chunks. Now, you need to answer certain queries asking you the answer for the elements in range l to r(l and r are starting and ending indices of the array) in the original n sized array.The naive approach is simply to iterate over each element in range l to r and calculate its corresponding answer. Therefore, the Time Complexity per query will be O(n).Sqrt Decomposition Trick : As we have already precomputed the answer for all individual chunks and now we need to answer the queries in range l to r. Now we can simply combine the answers of the chunks that lie in between the range l to r in the original array. So, if we see carefully here we are jumping sqrt(n) steps at a time instead of jumping 1 step at a time as done in naive approach. Let’s just analyze its Time Complexity and implementation considering the below problem :- "
},
{
"code": null,
"e": 2167,
"s": 1754,
"text": "Problem :\nGiven an array of n elements. We need to answer q \nqueries telling the sum of elements in range l to \nr in the array. Also the array is not static i.e \nthe values are changed via some point update query.\n\nRange Sum Queries are of form : Q l r , \nwhere l is the starting index r is the ending \nindex\n\nPoint update Query is of form : U idx val, \nwhere idx is the index to update val is the \nupdated value"
},
{
"code": null,
"e": 2423,
"s": 2167,
"text": "Let us consider that we have an array of 9 elements. A[] = {1, 5, 2, 4, 6, 1, 3, 5, 7}Let’s decompose this array into sqrt(9) blocks, where each block will contain the sum of elements lying in it. Therefore now our decomposed array would look like this : "
},
{
"code": null,
"e": 2646,
"s": 2423,
"text": "Till now we have constructed the decomposed array of sqrt(9) blocks and now we need to print the sum of elements in a given range. So first let’s see two basic types of overlap that a range query can have on our array :- "
},
{
"code": null,
"e": 2707,
"s": 2646,
"text": "Range Query of type 1 (Given Range is on Block Boundaries) :"
},
{
"code": null,
"e": 3396,
"s": 2709,
"text": "In this type the query, the range may totally cover the continuous sqrt blocks. So we can easily answer the sum of values in this range as the sum of completely overlapped blocks. So answer for above query in the described image will be : ans = 11 + 15 = 26 Time Complexity: In the worst case our range can be 0 to n-1(where n is the size of array and assuming n to be a perfect square). In this case all the blocks are completely overlapped by our query range. Therefore,to answer this query we need to iterate over all the decomposed blocks for the array and we know that the number of blocks = sqrt(n). Hence, the complexity for this type of query will be O(sqrt(n)) in worst case. "
},
{
"code": null,
"e": 3453,
"s": 3396,
"text": "Range Query of type 2 (Given Range is NOT on boundaries)"
},
{
"code": null,
"e": 4587,
"s": 3455,
"text": "We can deal these type of queries by summing the data from the completely overlapped decomposed blocks lying in the query range and then summing elements one by one from the original array whose corresponding block is not completely overlapped by the query range. So answer for above query in the described image will be : ans = 5 + 2 + 11 + 3 = 21 Time Complexity: Let’s consider a query [l = 1 and r = n-2] (n is the size of the array and has a 0 based indexing). Therefore, for this query exactly ( sqrt(n) – 2 ) blocks will be completely overlapped where as the first and last block will be partially overlapped with just one element left outside the overlapping range. So, the completely overlapped blocks can be summed up in ( sqrt(n) – 2 ) ~ sqrt(n) iterations, whereas first and last block are needed to be traversed one by one separately. But as we know that the number of elements in each block is at max sqrt(n), to sum up last block individually we need to make, (sqrt(n)-1) ~ sqrt(n) iterations and same for the last block. So, the overall Complexity = O(sqrt(n)) + O(sqrt(n)) + O(sqrt(n)) = O(3*sqrt(N)) = O(sqrt(n)) "
},
{
"code": null,
"e": 4618,
"s": 4587,
"text": "Update Queries(Point update) :"
},
{
"code": null,
"e": 4807,
"s": 4618,
"text": "In this query we simply find the block in which the given index lies, then subtract its previous value and add the new updated value as per the point update query. Time Complexity : O(1) "
},
{
"code": null,
"e": 4824,
"s": 4807,
"text": "Implementation :"
},
{
"code": null,
"e": 4879,
"s": 4824,
"text": "The implementation of the above trick is given below "
},
{
"code": null,
"e": 4883,
"s": 4879,
"text": "C++"
},
{
"code": null,
"e": 4888,
"s": 4883,
"text": "Java"
},
{
"code": null,
"e": 4897,
"s": 4888,
"text": "Python 3"
},
{
"code": null,
"e": 4900,
"s": 4897,
"text": "C#"
},
{
"code": null,
"e": 4911,
"s": 4900,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate working of Square Root// Decomposition.#include \"iostream\"#include \"math.h\"using namespace std; #define MAXN 10000#define SQRSIZE 100 int arr[MAXN]; // original arrayint block[SQRSIZE]; // decomposed arrayint blk_sz; // block size // Time Complexity : O(1)void update(int idx, int val){ int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))int query(int l, int r){ int sum = 0; while (l<r and l%blk_sz!=0 and l!=0) { // traversing first block in range sum += arr[l]; l++; } while (l+blk_sz-1 <= r) { // traversing completely overlapped blocks in range sum += block[l/blk_sz]; l += blk_sz; } while (l<=r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]void preprocess(int input[], int n){ // initiating block pointer int blk_idx = -1; // calculating size of block blk_sz = sqrt(n); // building the decomposed array for (int i=0; i<n; i++) { arr[i] = input[i]; if (i%blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver codeint main(){ // We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = sizeof(input)/sizeof(input[0]); preprocess(input, n); cout << \"query(3,8) : \" << query(3, 8) << endl; cout << \"query(1,6) : \" << query(1, 6) << endl; update(8, 0); cout << \"query(8,8) : \" << query(8, 8) << endl; return 0;}",
"e": 6791,
"s": 4911,
"text": null
},
{
"code": "// Java program to demonstrate working of// Square Root Decomposition.import java.util.*; class GFG{ static int MAXN = 10000;static int SQRSIZE = 100; static int []arr = new int[MAXN]; // original arraystatic int []block = new int[SQRSIZE]; // decomposed arraystatic int blk_sz; // block size // Time Complexity : O(1)static void update(int idx, int val){ int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))static int query(int l, int r){ int sum = 0; while (l < r && l % blk_sz != 0 && l != 0) { // traversing first block in range sum += arr[l]; l++; } while (l+blk_sz-1 <= r) { // traversing completely // overlapped blocks in range sum += block[l / blk_sz]; l += blk_sz; } while (l <= r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]static void preprocess(int input[], int n){ // initiating block pointer int blk_idx = -1; // calculating size of block blk_sz = (int) Math.sqrt(n); // building the decomposed array for (int i = 0; i < n; i++) { arr[i] = input[i]; if (i % blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver codepublic static void main(String[] args){ // We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. int input[] = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = input.length; preprocess(input, n); System.out.println(\"query(3, 8) : \" + query(3, 8)); System.out.println(\"query(1, 6) : \" + query(1, 6)); update(8, 0); System.out.println(\"query(8, 8) : \" + query(8, 8));}} // This code is contributed by PrinciRaj1992",
"e": 8893,
"s": 6791,
"text": null
},
{
"code": "# Python 3 program to demonstrate working of Square Root# Decomposition.from math import sqrt MAXN = 10000SQRSIZE = 100 arr = [0]*(MAXN) # original arrayblock = [0]*(SQRSIZE) # decomposed arrayblk_sz = 0 # block size # Time Complexity : O(1)def update(idx, val): blockNumber = idx // blk_sz block[blockNumber] += val - arr[idx] arr[idx] = val # Time Complexity : O(sqrt(n))def query(l, r): sum = 0 while (l < r and l % blk_sz != 0 and l != 0): # traversing first block in range sum += arr[l] l += 1 while (l + blk_sz - 1 <= r): # traversing completely overlapped blocks in range sum += block[l//blk_sz] l += blk_sz while (l <= r): # traversing last block in range sum += arr[l] l += 1 return sum # Fills values in input[]def preprocess(input, n): # initiating block pointer blk_idx = -1 # calculating size of block global blk_sz blk_sz = int(sqrt(n)) # building the decomposed array for i in range(n): arr[i] = input[i]; if (i % blk_sz == 0): # entering next block # incrementing block pointer blk_idx += 1; block[blk_idx] += arr[i] # Driver code # We have used separate array for input because# the purpose of this code is to explain SQRT# decomposition in competitive programming where# we have multiple inputs.input= [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]n = len(input) preprocess(input, n) print(\"query(3,8) : \",query(3, 8))print(\"query(1,6) : \",query(1, 6))update(8, 0)print(\"query(8,8) : \",query(8, 8)) # This code is contributed by Sanjit_Prasad",
"e": 10604,
"s": 8893,
"text": null
},
{
"code": "// C# program to demonstrate working of// Square Root Decomposition.using System; class GFG{static int MAXN = 10000;static int SQRSIZE = 100; static int []arr = new int[MAXN]; // original arraystatic int []block = new int[SQRSIZE]; // decomposed arraystatic int blk_sz; // block size // Time Complexity : O(1)static void update(int idx, int val){ int blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))static int query(int l, int r){ int sum = 0; while (l < r && l % blk_sz != 0 && l != 0) { // traversing first block in range sum += arr[l]; l++; } while (l + blk_sz - 1 <= r) { // traversing completely // overlapped blocks in range sum += block[l / blk_sz]; l += blk_sz; } while (l <= r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]static void preprocess(int []input, int n){ // initiating block pointer int blk_idx = -1; // calculating size of block blk_sz = (int) Math.Sqrt(n); // building the decomposed array for (int i = 0; i < n; i++) { arr[i] = input[i]; if (i % blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver codepublic static void Main(String[] args){ // We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. int []input = {1, 5, 2, 4, 6, 1, 3, 5, 7, 10}; int n = input.Length; preprocess(input, n); Console.WriteLine(\"query(3, 8) : \" + query(3, 8)); Console.WriteLine(\"query(1, 6) : \" + query(1, 6)); update(8, 0); Console.WriteLine(\"query(8, 8) : \" + query(8, 8));}} // This code is contributed by 29AjayKumar",
"e": 12697,
"s": 10604,
"text": null
},
{
"code": "<script>// Javascript program to demonstrate working of// Square Root Decomposition. let MAXN = 10000;let SQRSIZE = 100; let arr = new Array(MAXN);for(let i = 0; i < MAXN; i++){ arr[i] = 0;} let block = new Array(SQRSIZE);for(let i = 0; i < SQRSIZE; i++){ block[i] = 0;} let blk_sz; // Time Complexity : O(1)function update(idx,val){ let blockNumber = idx / blk_sz; block[blockNumber] += val - arr[idx]; arr[idx] = val;} // Time Complexity : O(sqrt(n))function query(l, r){ let sum = 0; while (l < r && l % blk_sz != 0 && l != 0) { // traversing first block in range sum += arr[l]; l++; } while (l+blk_sz-1 <= r) { // traversing completely // overlapped blocks in range sum += block[l / blk_sz]; l += blk_sz; } while (l <= r) { // traversing last block in range sum += arr[l]; l++; } return sum;} // Fills values in input[]function preprocess(input, n){ // initiating block pointer let blk_idx = -1; // calculating size of block blk_sz = Math.floor( Math.sqrt(n)); // building the decomposed array for (let i = 0; i < n; i++) { arr[i] = input[i]; if (i % blk_sz == 0) { // entering next block // incrementing block pointer blk_idx++; } block[blk_idx] += arr[i]; }} // Driver code// We have used separate array for input because // the purpose of this code is to explain SQRT // decomposition in competitive programming where // we have multiple inputs. let input = [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]; let n = input.length; preprocess(input, n); document.write(\"query(3, 8) : \" + query(3, 8)+\"<br>\"); document.write(\"query(1, 6) : \" + query(1, 6)+\"<br>\"); update(8, 0); document.write(\"query(8, 8) : \" + query(8, 8)+\"<br>\"); // This code is contributed by rag2127</script>",
"e": 14700,
"s": 12697,
"text": null
},
{
"code": null,
"e": 14748,
"s": 14700,
"text": "query(3,8) : 26\nquery(1,6) : 21\nquery(8,8) : 0\n"
},
{
"code": null,
"e": 14770,
"s": 14748,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 15506,
"s": 14770,
"text": "Auxiliary Space: O(MAXN)Note : The above code works even if n is not perfect square. In the case, the last block will contain even less number of elements than sqrt(n), thus reducing the number of iterations. Let’s say n = 10. In this case we will have 4 blocks first three block of size 3 and last block of size 1.This article is contributed by Nitish 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 [email protected]. 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": 15520,
"s": 15506,
"text": "princiraj1992"
},
{
"code": null,
"e": 15532,
"s": 15520,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15542,
"s": 15532,
"text": "ApurvaRaj"
},
{
"code": null,
"e": 15550,
"s": 15542,
"text": "rag2127"
},
{
"code": null,
"e": 15563,
"s": 15550,
"text": "simmytarika5"
},
{
"code": null,
"e": 15575,
"s": 15563,
"text": "rishavnitro"
},
{
"code": null,
"e": 15585,
"s": 15575,
"text": "aryanveer"
},
{
"code": null,
"e": 15605,
"s": 15585,
"text": "array-range-queries"
},
{
"code": null,
"e": 15629,
"s": 15605,
"text": "Competitive Programming"
},
{
"code": null,
"e": 15727,
"s": 15629,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15770,
"s": 15727,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 15813,
"s": 15770,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 15854,
"s": 15813,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 15881,
"s": 15854,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 15959,
"s": 15881,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 15996,
"s": 15959,
"text": "Fast I/O for Competitive Programming"
},
{
"code": null,
"e": 16034,
"s": 15996,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 16100,
"s": 16034,
"text": "Top 10 Algorithms and Data Structures for Competitive Programming"
},
{
"code": null,
"e": 16159,
"s": 16100,
"text": "What is Competitive Programming and How to Prepare for It?"
}
] |
Sum of numbers from 1 to N which are in Lucas Sequence
|
22 Jun, 2022
Given a number N. The task is to find the sum of numbers from 1 to N, which are present in the Lucas Sequence.
The Lucas numbers are in the following integer sequence:
2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123 ......
Examples:
Input : N = 10
Output : 17
Input : N = 5
Output : 10
Approach:
Loop through all the Lucas numbers which are less than the given value N.
Initialize a sum variable with 0.
Keep on adding these lucas numbers to get the required sum.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find sum of numbers from// 1 to N which are in Lucas Sequence#include <bits/stdc++.h>using namespace std; // Function to return the// required sumint LucasSum(int N){ // Generate lucas number and keep on // adding them int sum = 0; int a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; int c = a + b; a = b; b = c; } return sum;} // Driver codeint main(){ int N = 20; cout << LucasSum(N); return 0;}
// java program to find sum of numbers from// 1 to N which are in Lucas Sequenceclass GFG{ // Function to return the// required sumstatic int LucasSum(int N){ // Generate lucas number and keep on // adding them int sum = 0; int a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; c = a + b; a = b; b = c; } return sum;} // Driver codepublic static void main(String[] args){ int N = 20; System.out.println(LucasSum(N)); }// This code is contributed by princiraj1992}
# Python3 program to find Sum of# numbers from 1 to N which are# in Lucas Sequence # Function to return the# required Sumdef LucasSum(N): # Generate lucas number and # keep on adding them Sum = 0 a = 2 b = 1 c = 0 Sum += a while (b <= N): Sum += b c = a + b a = b b = c return Sum # Driver codeN = 20print(LucasSum(N)) # This code is contributed# by mohit kumar
// C# program to find sum of numbers from// 1 to N which are in Lucas Sequenceusing System; class GFG{ // Function to return the// required sumstatic int LucasSum(int N){ // Generate lucas number and keep on // adding them int sum = 0; int a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; c = a + b; a = b; b = c; } return sum;} // Driver codepublic static void Main(String[] args){ int N = 20; Console.WriteLine(LucasSum(N));}} // This code contributed by Rajput-Ji
<?php// PHP program to find sum of numbers from// 1 to N which are in Lucas Sequence // Function to return the required sumfunction LucasSum($N){ // Generate lucas number and // keep on adding them $sum = 0; $a = 2; $b = 1; $c; $sum += $a; while ($b <= $N) { $sum += $b; $c = $a + $b; $a = $b; $b = $c; } return $sum;} // Driver code$N = 20;echo(LucasSum($N)); // This code is contributed// by Code_Mech.?>
<script> // Javascript program to find sum of numbers// from 1 to N which are in Lucas Sequence // Function to return the// required sumfunction LucasSum(N){ // Generate lucas number and keep // on adding them var sum = 0; var a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; var c = a + b; a = b; b = c; } return sum;} // Driver codevar N = 20;document.write(LucasSum(N)); // This code is contributed by rutvik_56 </script>
Output:
46
Time Complexity: O(n)Auxiliary Space: O(1)
mohit kumar 29
princiraj1992
Rajput-Ji
Code_Mech
rutvik_56
rishavnitro
series
series-sum
Mathematical
Mathematical
series
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
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
Program for factorial of a number
Program to print prime numbers from 1 to N.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "Given a number N. The task is to find the sum of numbers from 1 to N, which are present in the Lucas Sequence."
},
{
"code": null,
"e": 197,
"s": 139,
"text": "The Lucas numbers are in the following integer sequence: "
},
{
"code": null,
"e": 243,
"s": 197,
"text": "2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123 ......"
},
{
"code": null,
"e": 255,
"s": 243,
"text": "Examples: "
},
{
"code": null,
"e": 310,
"s": 255,
"text": "Input : N = 10\nOutput : 17\n\nInput : N = 5\nOutput : 10"
},
{
"code": null,
"e": 322,
"s": 310,
"text": "Approach: "
},
{
"code": null,
"e": 396,
"s": 322,
"text": "Loop through all the Lucas numbers which are less than the given value N."
},
{
"code": null,
"e": 430,
"s": 396,
"text": "Initialize a sum variable with 0."
},
{
"code": null,
"e": 490,
"s": 430,
"text": "Keep on adding these lucas numbers to get the required sum."
},
{
"code": null,
"e": 543,
"s": 490,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 547,
"s": 543,
"text": "C++"
},
{
"code": null,
"e": 552,
"s": 547,
"text": "Java"
},
{
"code": null,
"e": 560,
"s": 552,
"text": "Python3"
},
{
"code": null,
"e": 563,
"s": 560,
"text": "C#"
},
{
"code": null,
"e": 567,
"s": 563,
"text": "PHP"
},
{
"code": null,
"e": 578,
"s": 567,
"text": "Javascript"
},
{
"code": "// C++ program to find sum of numbers from// 1 to N which are in Lucas Sequence#include <bits/stdc++.h>using namespace std; // Function to return the// required sumint LucasSum(int N){ // Generate lucas number and keep on // adding them int sum = 0; int a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; int c = a + b; a = b; b = c; } return sum;} // Driver codeint main(){ int N = 20; cout << LucasSum(N); return 0;}",
"e": 1065,
"s": 578,
"text": null
},
{
"code": "// java program to find sum of numbers from// 1 to N which are in Lucas Sequenceclass GFG{ // Function to return the// required sumstatic int LucasSum(int N){ // Generate lucas number and keep on // adding them int sum = 0; int a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; c = a + b; a = b; b = c; } return sum;} // Driver codepublic static void main(String[] args){ int N = 20; System.out.println(LucasSum(N)); }// This code is contributed by princiraj1992}",
"e": 1599,
"s": 1065,
"text": null
},
{
"code": "# Python3 program to find Sum of# numbers from 1 to N which are# in Lucas Sequence # Function to return the# required Sumdef LucasSum(N): # Generate lucas number and # keep on adding them Sum = 0 a = 2 b = 1 c = 0 Sum += a while (b <= N): Sum += b c = a + b a = b b = c return Sum # Driver codeN = 20print(LucasSum(N)) # This code is contributed# by mohit kumar",
"e": 2025,
"s": 1599,
"text": null
},
{
"code": "// C# program to find sum of numbers from// 1 to N which are in Lucas Sequenceusing System; class GFG{ // Function to return the// required sumstatic int LucasSum(int N){ // Generate lucas number and keep on // adding them int sum = 0; int a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; c = a + b; a = b; b = c; } return sum;} // Driver codepublic static void Main(String[] args){ int N = 20; Console.WriteLine(LucasSum(N));}} // This code contributed by Rajput-Ji",
"e": 2562,
"s": 2025,
"text": null
},
{
"code": "<?php// PHP program to find sum of numbers from// 1 to N which are in Lucas Sequence // Function to return the required sumfunction LucasSum($N){ // Generate lucas number and // keep on adding them $sum = 0; $a = 2; $b = 1; $c; $sum += $a; while ($b <= $N) { $sum += $b; $c = $a + $b; $a = $b; $b = $c; } return $sum;} // Driver code$N = 20;echo(LucasSum($N)); // This code is contributed// by Code_Mech.?>",
"e": 3031,
"s": 2562,
"text": null
},
{
"code": "<script> // Javascript program to find sum of numbers// from 1 to N which are in Lucas Sequence // Function to return the// required sumfunction LucasSum(N){ // Generate lucas number and keep // on adding them var sum = 0; var a = 2, b = 1, c; sum += a; while (b <= N) { sum += b; var c = a + b; a = b; b = c; } return sum;} // Driver codevar N = 20;document.write(LucasSum(N)); // This code is contributed by rutvik_56 </script>",
"e": 3523,
"s": 3031,
"text": null
},
{
"code": null,
"e": 3532,
"s": 3523,
"text": "Output: "
},
{
"code": null,
"e": 3535,
"s": 3532,
"text": "46"
},
{
"code": null,
"e": 3580,
"s": 3535,
"text": "Time Complexity: O(n)Auxiliary Space: O(1) "
},
{
"code": null,
"e": 3595,
"s": 3580,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 3609,
"s": 3595,
"text": "princiraj1992"
},
{
"code": null,
"e": 3619,
"s": 3609,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 3629,
"s": 3619,
"text": "Code_Mech"
},
{
"code": null,
"e": 3639,
"s": 3629,
"text": "rutvik_56"
},
{
"code": null,
"e": 3651,
"s": 3639,
"text": "rishavnitro"
},
{
"code": null,
"e": 3658,
"s": 3651,
"text": "series"
},
{
"code": null,
"e": 3669,
"s": 3658,
"text": "series-sum"
},
{
"code": null,
"e": 3682,
"s": 3669,
"text": "Mathematical"
},
{
"code": null,
"e": 3695,
"s": 3682,
"text": "Mathematical"
},
{
"code": null,
"e": 3702,
"s": 3695,
"text": "series"
},
{
"code": null,
"e": 3800,
"s": 3702,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3824,
"s": 3800,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 3845,
"s": 3824,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 3859,
"s": 3845,
"text": "Prime Numbers"
},
{
"code": null,
"e": 3896,
"s": 3859,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 3939,
"s": 3896,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 3971,
"s": 3939,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 3998,
"s": 3971,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 4041,
"s": 3998,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 4075,
"s": 4041,
"text": "Program for factorial of a number"
}
] |
How to Improve RecyclerView Scrolling Performance in Android?
|
21 Dec, 2020
RecyclerView is the main UI component in Android which is used to represent the huge list of data. If the RecyclerView is not implemented properly then it will not smoothly scrollable and it may lead to a bad user experience. To make it scrollable smoothly we have to optimize it and follow some tips to improve its performance. In this article, we will see the steps to follow for optimizing the Scrolling performance of our RecyclerView.
Note:
If you are looking for the implementation guide of RecyclerView. Then do check out: How to implement RecyclerView in Android
In RecyclerView if you’re using ImageView to display an image from your server in your RecyclerView items then specify the constant size for your ImageView. If the size of ImageView in RecyclerView items is not fixed then RecyclerView will take some time to load and adjust the RecyclerView item size according to the size of Image. So to improve the performance of our RecyclerView we should keep the size of our ImageView to make it RecyclerView load faster.
While creating an item for RecyclerView avoid using NestedView for RecyclerView item. Nesting will reduce the performance of RecyclerView. So it is better to avoid using Nested View. Nested View means adding a Horizontal RecyclerView in a Vertical RecyclerView. This type of Nesting may reduce RecyclerView performance. Below is the image of Nested RecyclerView.
If the height of our RecyclerView items is fixed then we should use the setHasFixedsize method in our XML of our card item. This will fix the height of our RecyclerView item and prevent it from increasing or decreasing the size of our Card Layout. We can use this method in our JAVA class as well where we are declaring our RecyclerView adapter and layout manager.
recyclerView.setHasFixedSize(true)
RecyclerView is composed of so many images and if you are loading an image in all cards then loading each image from the server will take so much time. As the Garbage Collection runs on the main thread so this is the reason which results in unresponsive UI. Continuous allocation and deallocation of memory lead to the frequent GC run. This can be prevented by using the bitmap pool concept. The simple solution to tackle this problem is to use Image Loading libraries such as Picasso, Glide, Fresco, and many more. These libraries will handle all bitmap pool concept and all delegate tasks related to images.
Note: You may also refer to the Top 5 Image Loading Libraries in Android
OnBindViewHolder method is used to set data in each item of RecyclerView. This method will set the data in each RecyclerView item. We should do less work in this method. We only have to set data in this method and not to do any comparison or any heavy task. If we perform any heavy task in this method then this will degrade the performance of our RecyclerView because setting data for each item will take a specific amount of time. So to improve the performance of RecyclerView we should do less work in the OnBindViewHolder method.
Whenever you are performing actions in RecyclerView such as adding an item in RecyclerView at any position or deleting an item from a specific position of RecyclerView then you should use NotifyItemChange() method.
Java
// below method will notify the adapter // of our RecyclerView when an item // from RecyclerView is removed. adapter.notifyItemRemoved(position) // below method will be used when// we update the data of any RecyclerView // item at a fixed position. adapter.notifyItemChanged(position) // below method is used when we add // any item at a specific position// of our RecyclerView. adapter.notifyItemInserted(position) // below method is used when we add multiple // number of items in our recyclerview.// start represents the position from // which the items are added.// end represents the position upto // which we have to add items. adapter.notifyItemRangeInserted(start, end)
When we will call the notifyDataSetChanged() method it will not handle the complete reordering of the RecyclerView adapter but it will find if the item at that position is the same as before to do less work.
android
Technical Scripter 2020
Android
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Dec, 2020"
},
{
"code": null,
"e": 496,
"s": 54,
"text": "RecyclerView is the main UI component in Android which is used to represent the huge list of data. If the RecyclerView is not implemented properly then it will not smoothly scrollable and it may lead to a bad user experience. To make it scrollable smoothly we have to optimize it and follow some tips to improve its performance. In this article, we will see the steps to follow for optimizing the Scrolling performance of our RecyclerView. "
},
{
"code": null,
"e": 502,
"s": 496,
"text": "Note:"
},
{
"code": null,
"e": 627,
"s": 502,
"text": "If you are looking for the implementation guide of RecyclerView. Then do check out: How to implement RecyclerView in Android"
},
{
"code": null,
"e": 1089,
"s": 627,
"text": "In RecyclerView if you’re using ImageView to display an image from your server in your RecyclerView items then specify the constant size for your ImageView. If the size of ImageView in RecyclerView items is not fixed then RecyclerView will take some time to load and adjust the RecyclerView item size according to the size of Image. So to improve the performance of our RecyclerView we should keep the size of our ImageView to make it RecyclerView load faster. "
},
{
"code": null,
"e": 1453,
"s": 1089,
"text": "While creating an item for RecyclerView avoid using NestedView for RecyclerView item. Nesting will reduce the performance of RecyclerView. So it is better to avoid using Nested View. Nested View means adding a Horizontal RecyclerView in a Vertical RecyclerView. This type of Nesting may reduce RecyclerView performance. Below is the image of Nested RecyclerView. "
},
{
"code": null,
"e": 1818,
"s": 1453,
"text": "If the height of our RecyclerView items is fixed then we should use the setHasFixedsize method in our XML of our card item. This will fix the height of our RecyclerView item and prevent it from increasing or decreasing the size of our Card Layout. We can use this method in our JAVA class as well where we are declaring our RecyclerView adapter and layout manager."
},
{
"code": null,
"e": 1853,
"s": 1818,
"text": "recyclerView.setHasFixedSize(true)"
},
{
"code": null,
"e": 2464,
"s": 1853,
"text": "RecyclerView is composed of so many images and if you are loading an image in all cards then loading each image from the server will take so much time. As the Garbage Collection runs on the main thread so this is the reason which results in unresponsive UI. Continuous allocation and deallocation of memory lead to the frequent GC run. This can be prevented by using the bitmap pool concept. The simple solution to tackle this problem is to use Image Loading libraries such as Picasso, Glide, Fresco, and many more. These libraries will handle all bitmap pool concept and all delegate tasks related to images. "
},
{
"code": null,
"e": 2537,
"s": 2464,
"text": "Note: You may also refer to the Top 5 Image Loading Libraries in Android"
},
{
"code": null,
"e": 3071,
"s": 2537,
"text": "OnBindViewHolder method is used to set data in each item of RecyclerView. This method will set the data in each RecyclerView item. We should do less work in this method. We only have to set data in this method and not to do any comparison or any heavy task. If we perform any heavy task in this method then this will degrade the performance of our RecyclerView because setting data for each item will take a specific amount of time. So to improve the performance of RecyclerView we should do less work in the OnBindViewHolder method."
},
{
"code": null,
"e": 3287,
"s": 3071,
"text": "Whenever you are performing actions in RecyclerView such as adding an item in RecyclerView at any position or deleting an item from a specific position of RecyclerView then you should use NotifyItemChange() method. "
},
{
"code": null,
"e": 3292,
"s": 3287,
"text": "Java"
},
{
"code": "// below method will notify the adapter // of our RecyclerView when an item // from RecyclerView is removed. adapter.notifyItemRemoved(position) // below method will be used when// we update the data of any RecyclerView // item at a fixed position. adapter.notifyItemChanged(position) // below method is used when we add // any item at a specific position// of our RecyclerView. adapter.notifyItemInserted(position) // below method is used when we add multiple // number of items in our recyclerview.// start represents the position from // which the items are added.// end represents the position upto // which we have to add items. adapter.notifyItemRangeInserted(start, end)",
"e": 3983,
"s": 3292,
"text": null
},
{
"code": null,
"e": 4192,
"s": 3983,
"text": "When we will call the notifyDataSetChanged() method it will not handle the complete reordering of the RecyclerView adapter but it will find if the item at that position is the same as before to do less work. "
},
{
"code": null,
"e": 4200,
"s": 4192,
"text": "android"
},
{
"code": null,
"e": 4224,
"s": 4200,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 4232,
"s": 4224,
"text": "Android"
},
{
"code": null,
"e": 4251,
"s": 4232,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4259,
"s": 4251,
"text": "Android"
}
] |
LogManager getLogger() method in Java with Examples
|
29 Oct, 2019
The getLogger() method of java.util.logging.LogManager is used to get the specified Logger in this LogManager instance. This Logger must be a named Logger. This method will get this Logger in this LogManager if it exists. If it does not exists, then this method returns null.
Syntax:
public Logger getLogger(Logger logger)
Parameters: This method accepts a parameter logger which is the name of the Logger to be get in this LogManager instance.
Return Value: This method returns the name of this Logger in this LogManager if it exists. If it does not exists, then this method returns null.
Below programs illustrate getLogger() method:
// Java program to illustrate// LogManager getLogger() method import java.util.logging.*;import java.util.*; public class GFG { public static void main(String[] args) { // Create LogManager object LogManager logManager = LogManager.getLogManager(); String LoggerName = "GFG"; Logger logger = Logger.getLogger(LoggerName); logManager.addLogger(logger); System.out.println("\nList of Logger Names: "); Enumeration<String> listOfNames = logManager.getLoggerNames(); while (listOfNames.hasMoreElements()) System.out.println(listOfNames.nextElement()); System.out.println( "\nGet Logger Name " + LoggerName + ": " + logManager.getLogger(LoggerName)); LoggerName = "Geeks"; System.out.println( "\nGet Logger Name " + LoggerName + ": " + logManager.getLogger(LoggerName)); }}
List of Logger Names:
GFG
global
Get Logger Name GFG: java.util.logging.Logger@1540e19d
Get Logger Name Geeks: null
Reference: https://docs.oracle.com/javase/9/docs/api/java/util/logging/LogManager.html#getLogger-java.lang.String-
Java-Functions
Java-LogManager
java.util.logging package
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
ArrayList in Java
Stream In Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n29 Oct, 2019"
},
{
"code": null,
"e": 330,
"s": 54,
"text": "The getLogger() method of java.util.logging.LogManager is used to get the specified Logger in this LogManager instance. This Logger must be a named Logger. This method will get this Logger in this LogManager if it exists. If it does not exists, then this method returns null."
},
{
"code": null,
"e": 338,
"s": 330,
"text": "Syntax:"
},
{
"code": null,
"e": 378,
"s": 338,
"text": "public Logger getLogger(Logger logger)\n"
},
{
"code": null,
"e": 500,
"s": 378,
"text": "Parameters: This method accepts a parameter logger which is the name of the Logger to be get in this LogManager instance."
},
{
"code": null,
"e": 645,
"s": 500,
"text": "Return Value: This method returns the name of this Logger in this LogManager if it exists. If it does not exists, then this method returns null."
},
{
"code": null,
"e": 691,
"s": 645,
"text": "Below programs illustrate getLogger() method:"
},
{
"code": "// Java program to illustrate// LogManager getLogger() method import java.util.logging.*;import java.util.*; public class GFG { public static void main(String[] args) { // Create LogManager object LogManager logManager = LogManager.getLogManager(); String LoggerName = \"GFG\"; Logger logger = Logger.getLogger(LoggerName); logManager.addLogger(logger); System.out.println(\"\\nList of Logger Names: \"); Enumeration<String> listOfNames = logManager.getLoggerNames(); while (listOfNames.hasMoreElements()) System.out.println(listOfNames.nextElement()); System.out.println( \"\\nGet Logger Name \" + LoggerName + \": \" + logManager.getLogger(LoggerName)); LoggerName = \"Geeks\"; System.out.println( \"\\nGet Logger Name \" + LoggerName + \": \" + logManager.getLogger(LoggerName)); }}",
"e": 1672,
"s": 691,
"text": null
},
{
"code": null,
"e": 1793,
"s": 1672,
"text": "List of Logger Names: \nGFG\nglobal\n\n\nGet Logger Name GFG: java.util.logging.Logger@1540e19d\n\nGet Logger Name Geeks: null\n"
},
{
"code": null,
"e": 1908,
"s": 1793,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/util/logging/LogManager.html#getLogger-java.lang.String-"
},
{
"code": null,
"e": 1923,
"s": 1908,
"text": "Java-Functions"
},
{
"code": null,
"e": 1939,
"s": 1923,
"text": "Java-LogManager"
},
{
"code": null,
"e": 1965,
"s": 1939,
"text": "java.util.logging package"
},
{
"code": null,
"e": 1970,
"s": 1965,
"text": "Java"
},
{
"code": null,
"e": 1975,
"s": 1970,
"text": "Java"
},
{
"code": null,
"e": 2073,
"s": 1975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2124,
"s": 2073,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2155,
"s": 2124,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2174,
"s": 2155,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2204,
"s": 2174,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2222,
"s": 2204,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2237,
"s": 2222,
"text": "Stream In Java"
},
{
"code": null,
"e": 2257,
"s": 2237,
"text": "Collections in Java"
},
{
"code": null,
"e": 2281,
"s": 2257,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 2313,
"s": 2281,
"text": "Multidimensional Arrays in Java"
}
] |
jQuery UI Dialog closeOnEscape Option
|
12 Jan, 2021
closeOnEscape option if set to true and the current dialog box is focused will close the dialog on pressing Escape key(esc). By default, value is true.
Syntax:
$( ".selector" ).dialog({
closeOnEscape : true
});
Approach: First, add jQuery UI scripts needed for your project.
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
Example 1:
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src= "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").dialog({ closeOnEscape: true, }); $("#geeks").click(function () { $("#gfg").dialog("open"); }); }); </script></head> <body> <div id="gfg" title="GeeksforGeeks"> Jquery UI| closeOnEscape dialog option </div> <button id="geeks">Open Dialog</button></body> </html>
Output:
Example 2:
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src= "https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").dialog({ closeOnEscape: false, }); $("#geeks").click(function () { $("#gfg").dialog("open"); }); }); </script></head> <body> <div id="gfg" title="GeeksforGeeks"> Jquery UI| closeOnEscape dialog option </div> <button id="geeks">Open Dialog</button></body> </html>
Output:
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to add options to a select element using jQuery?
jQuery | children() with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jan, 2021"
},
{
"code": null,
"e": 180,
"s": 28,
"text": "closeOnEscape option if set to true and the current dialog box is focused will close the dialog on pressing Escape key(esc). By default, value is true."
},
{
"code": null,
"e": 188,
"s": 180,
"text": "Syntax:"
},
{
"code": null,
"e": 243,
"s": 188,
"text": "$( \".selector\" ).dialog({\n closeOnEscape : true\n});"
},
{
"code": null,
"e": 307,
"s": 243,
"text": "Approach: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 548,
"s": 307,
"text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>"
},
{
"code": null,
"e": 559,
"s": 548,
"text": "Example 1:"
},
{
"code": null,
"e": 564,
"s": 559,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src= \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").dialog({ closeOnEscape: true, }); $(\"#geeks\").click(function () { $(\"#gfg\").dialog(\"open\"); }); }); </script></head> <body> <div id=\"gfg\" title=\"GeeksforGeeks\"> Jquery UI| closeOnEscape dialog option </div> <button id=\"geeks\">Open Dialog</button></body> </html>",
"e": 1310,
"s": 564,
"text": null
},
{
"code": null,
"e": 1318,
"s": 1310,
"text": "Output:"
},
{
"code": null,
"e": 1329,
"s": 1318,
"text": "Example 2:"
},
{
"code": null,
"e": 1334,
"s": 1329,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src= \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").dialog({ closeOnEscape: false, }); $(\"#geeks\").click(function () { $(\"#gfg\").dialog(\"open\"); }); }); </script></head> <body> <div id=\"gfg\" title=\"GeeksforGeeks\"> Jquery UI| closeOnEscape dialog option </div> <button id=\"geeks\">Open Dialog</button></body> </html>",
"e": 2081,
"s": 1334,
"text": null
},
{
"code": null,
"e": 2089,
"s": 2081,
"text": "Output:"
},
{
"code": null,
"e": 2099,
"s": 2089,
"text": "jQuery-UI"
},
{
"code": null,
"e": 2104,
"s": 2099,
"text": "HTML"
},
{
"code": null,
"e": 2111,
"s": 2104,
"text": "JQuery"
},
{
"code": null,
"e": 2128,
"s": 2111,
"text": "Web Technologies"
},
{
"code": null,
"e": 2133,
"s": 2128,
"text": "HTML"
},
{
"code": null,
"e": 2231,
"s": 2133,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2279,
"s": 2231,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 2341,
"s": 2279,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2391,
"s": 2341,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2415,
"s": 2391,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2468,
"s": 2415,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2514,
"s": 2468,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 2577,
"s": 2514,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 2606,
"s": 2577,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2659,
"s": 2606,
"text": "How to add options to a select element using jQuery?"
}
] |
Max Circular Subarray Sum | Practice | GeeksforGeeks
|
Given an array arr[] of N integers arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum.
Example 1:
Input:
N = 7
arr[] = {8,-8,9,-9,10,-11,12}
Output:
22
Explanation:
Starting from the last element
of the array, i.e, 12, and
moving in a circular fashion, we
have max subarray as 12, 8, -8, 9,
-9, 10, which gives maximum sum
as 22.
Example 2:
Input:
N = 8
arr[] = {10,-3,-4,7,6,5,-4,-1}
Output:
23
Explanation: Sum of the circular
subarray with maximum sum is 23
Your Task:
The task is to complete the function circularSubarraySum() which returns a sum of the circular subarray with maximum sum.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1 <= N <= 106
-106 <= Arr[i] <= 106
0
saipraveensura12348 hours ago
can someone explain error in this code
class Solution{
public:
// arr: input array
// num: size of array
//Function to find maximum circular subarray sum.
int circularSubarraySum(int arr[], int num){
int res1=arr[0],maxending=arr[0];
int res2=arr[0],minending=arr[0];
int arrsum=0;
for(int i=1;i<num;i++)
{
arrsum=arrsum+arr[i];
maxending=max(maxending+arr[i],arr[i]);
res1=max(res1,maxending);
minending=min(minending+arr[i],arr[i]);
res2=min(minending,res2);
}
res2=arrsum-(res2);
return max(res1,res2);
// your code here
}
};
0
abhinayabhi14119 hours ago
int result=INT_MAX; int r=INT_MIN; int sum1=0,sum2=0,sum3=0; for(int i=0;i<num;i++) { sum1+=arr[i]; sum2+=arr[i]; sum3+=arr[i]; sum3=max(sum3,arr[i]); r=max(r,sum3); sum1=min(sum1,arr[i]); result=min(result,sum1); } if(r<0) return r; return max(sum2-result,r);
+1
yashurawat190321 hours ago
WELL EXPLAINED
PLS UPVOTE
int kadanes(int arr[],int n) { int currSum = 0; int maxSum = INT_MIN; for(int i=0;i<n;i++) { currSum = max(arr[i] + currSum, arr[i]); maxSum = max(maxSum,currSum); } return maxSum; } int circularSubarraySum(int arr[], int n){ // your code here int x = kadanes(arr,n); int y =0; for(int i =0;i<n;i++) { y += arr[i]; arr[i] = -arr[i];//here we are calculating min sub array } //by changing sign so that min subarray became max sub array int z = kadanes(arr,n);//z is maxsub array after changing sign if(y-(-z)==0)//and then subtract total sum (y) with negative of z { return x; } return max(x,y-(-z)); }
0
abhishek0908022 days ago
int kadanes(int arr[],int n)
{
int ans=INT_MIN; int sum=0;
for(int i=0;i<n;i++)
{
sum+=arr[i];
if(sum>ans)
ans=sum;
if(sum<0) sum=0;
}
return ans;
}
int circularSubarraySum(int arr[], int num){
int x=kadanes(arr,num); int sum=0;
for(int i=0;i<num;i++)
{ sum+=arr[i]; arr[i]=-1*arr[i];}
int y=kadanes(arr,num);
int z=sum+y;
if(z==0) return x;
return max(z,x);
}
0
ruchikajamwal03192 days ago
class Solution{ public: // arr: input array // num: size of array //Function to find maximum circular subarray sum. int circularSubarraySum(int arr[], int num){ // your code here int result=INT_MAX; int r=INT_MIN; int sum1=0,sum2=0,sum3=0; for(int i=0;i<num;i++) { sum1+=arr[i]; sum2+=arr[i]; sum3+=arr[i]; sum3=max(sum3,arr[i]); r=max(r,sum3); sum1=min(sum1,arr[i]); result=min(result,sum1); } if(r<0) return r; return max(sum2-result,r);
}};
0
mrharshkshitij90603 days ago
class Solution{
public:
int totalsum(int arr[], int n)
{
int res=arr[0];
int maxend=arr[0];
for(int i=1; i<n; i++)
{
maxend= max(maxend+arr[i], arr[i]);
res=max(res, maxend);
}
return res;
}
int circularSubarraySum(int arr[], int num)
{
int total=totalsum(arr, num);
if(total<0)
return total;
int sum=0;
for(int i=0; i<num; i++)
{
sum=sum+arr[i];
arr[i]= -arr[i];
}
int max_cir= sum+totalsum(arr, num);
return max(max_cir, total);
}
};
+2
amankrguptagumla1441 week ago
//JAVA SOLUTION
class Solution{
static int normalMaxSum(int arr[], int n)
{
int res = arr[0];
int maxEnding = arr[0];
for(int i = 1; i < n; i++)
{
maxEnding = Math.max(maxEnding + arr[i], arr[i]);
res = Math.max(maxEnding, res);
}
return res;
}
// a: input array
// n: size of array
//Function to find maximum circular subarray sum.
static int circularSubarraySum(int arr[], int n) {
// Your code here
int max_normal = normalMaxSum(arr, n);
if(max_normal < 0)
return max_normal;
int arr_sum = 0;
for(int i = 0; i < n; i++)
{
arr_sum += arr[i];
arr[i] = -arr[i];
}
int max_circular = arr_sum + normalMaxSum(arr, n);
return Math.max(max_circular, max_normal);
//return Integer.max(kadane(arr,n), reverseKadane(arr,n));
}
}
+1
ayushsunariya4581 week ago
C++ Easy Solution
Logic: So there are two case.Case 1. The first is that the subarray take only a middle part, and we know how to find the max subarray sum.Case2. The second is that the subarray take a part of head array and a part of tail array.We can transfer this case to the first one.The maximum result equals to the total sum minus the minimum subarray sum.
int circularSubarraySum(int A[], int n){
// your code here
int total = 0, maxSum = A[0], curMax = 0, minSum = A[0], curMin = 0;
for (int i=0;i<n;i++) {
curMax = max(curMax + A[i], A[i]);
maxSum = max(maxSum, curMax);
curMin = min(curMin + A[i], A[i]);
minSum = min(minSum, curMin);
total += A[i];
}
return maxSum > 0 ? max(maxSum, total - minSum) : maxSum;
}
0
prathameshmistry2 weeks ago
C++++
class Solution{ public: //Function to find maximum circular subarray sum. int circularSubarraySum(int a[], int n) { bool flag = false; int count =0;int maxx = INT_MIN; for(int i = 0; i < n; i++) { //Storing the maximum element in the array. if(a[i] > maxx) maxx = a[i]; //Counting total number of negative numbers in the array. if(a[i] < 0) count++; } if(count == n) return maxx; //Case 1:We get the maximum sum using standard Kadane's algorithm. int max_kadane = kadane(a, n); //Case 2:We now find the maximum sum that includes corner elements. int max_wrap = 0, i; for (i = 0; i < n; i++) { //Calculating total sum of array elements. max_wrap += a[i]; //Inverting the sign of array elements. a[i] = -a[i]; } //Maximum sum with corner elements will be: //Total sum of array elements-(-max subarray sum after changing //sign of array elements). max_wrap = max_wrap + kadane(a, n); //The maximum circular subarray sum will be maximum of two sums. return (max_wrap > max_kadane)? max_wrap: max_kadane; } //Standard Kadane's algorithm to find maximum subarray sum. int kadane(int a[], int n) { int max_so_far = 0, max_ending_here = 0; int i; for (i = 0; i < n; i++) { //Storing max sum till current index. max_ending_here = max_ending_here + a[i]; //If max sum till current index is negative, we update it to 0. if (max_ending_here < 0) max_ending_here = 0; //Storing the max sum so far. if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } };
0
gopikrishnaguntamukkala32 weeks ago
python code
ALL TEST CASES PASSED
def circularSubarraySum(arr,n):
##Your code here
def kadane(num):
sumtillnow=num[0]
totalsum=num[0]
for i in num[1:]:
sumtillnow=max(i,sumtillnow+i)
totalsum=max(totalsum,sumtillnow)
return totalsum
t=kadane(arr)
sum1=0
for i in range(n):
sum1+=arr[i]
arr[i]=-arr[i]
sum1+=kadane(arr)
if sum1>t and sum1!=0:
return sum1
else:
return t
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 363,
"s": 238,
"text": "Given an array arr[] of N integers arranged in a circular fashion. Your task is to find the maximum contiguous subarray sum."
},
{
"code": null,
"e": 375,
"s": 363,
"text": "\nExample 1:"
},
{
"code": null,
"e": 611,
"s": 375,
"text": "Input:\nN = 7\narr[] = {8,-8,9,-9,10,-11,12}\nOutput:\n22\nExplanation:\nStarting from the last element\nof the array, i.e, 12, and \nmoving in a circular fashion, we \nhave max subarray as 12, 8, -8, 9, \n-9, 10, which gives maximum sum \nas 22."
},
{
"code": null,
"e": 622,
"s": 611,
"text": "Example 2:"
},
{
"code": null,
"e": 744,
"s": 622,
"text": "Input:\nN = 8\narr[] = {10,-3,-4,7,6,5,-4,-1}\nOutput:\n23\nExplanation: Sum of the circular \nsubarray with maximum sum is 23\n"
},
{
"code": null,
"e": 878,
"s": 744,
"text": "\nYour Task:\nThe task is to complete the function circularSubarraySum() which returns a sum of the circular subarray with maximum sum."
},
{
"code": null,
"e": 943,
"s": 878,
"text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 993,
"s": 943,
"text": "\nConstraints:\n1 <= N <= 106\n-106 <= Arr[i] <= 106"
},
{
"code": null,
"e": 995,
"s": 993,
"text": "0"
},
{
"code": null,
"e": 1025,
"s": 995,
"text": "saipraveensura12348 hours ago"
},
{
"code": null,
"e": 1064,
"s": 1025,
"text": "can someone explain error in this code"
},
{
"code": null,
"e": 1734,
"s": 1070,
"text": "class Solution{\n public:\n // arr: input array\n // num: size of array\n //Function to find maximum circular subarray sum.\n int circularSubarraySum(int arr[], int num){\n int res1=arr[0],maxending=arr[0];\n int res2=arr[0],minending=arr[0];\n int arrsum=0;\n for(int i=1;i<num;i++)\n {\n arrsum=arrsum+arr[i];\n maxending=max(maxending+arr[i],arr[i]);\n res1=max(res1,maxending);\n minending=min(minending+arr[i],arr[i]);\n res2=min(minending,res2);\n }\n res2=arrsum-(res2);\n \n return max(res1,res2);\n \n // your code here\n }\n};"
},
{
"code": null,
"e": 1736,
"s": 1734,
"text": "0"
},
{
"code": null,
"e": 1763,
"s": 1736,
"text": "abhinayabhi14119 hours ago"
},
{
"code": null,
"e": 2130,
"s": 1763,
"text": " int result=INT_MAX; int r=INT_MIN; int sum1=0,sum2=0,sum3=0; for(int i=0;i<num;i++) { sum1+=arr[i]; sum2+=arr[i]; sum3+=arr[i]; sum3=max(sum3,arr[i]); r=max(r,sum3); sum1=min(sum1,arr[i]); result=min(result,sum1); } if(r<0) return r; return max(sum2-result,r);"
},
{
"code": null,
"e": 2133,
"s": 2130,
"text": "+1"
},
{
"code": null,
"e": 2160,
"s": 2133,
"text": "yashurawat190321 hours ago"
},
{
"code": null,
"e": 2175,
"s": 2160,
"text": "WELL EXPLAINED"
},
{
"code": null,
"e": 2186,
"s": 2175,
"text": "PLS UPVOTE"
},
{
"code": null,
"e": 2986,
"s": 2192,
"text": " int kadanes(int arr[],int n) { int currSum = 0; int maxSum = INT_MIN; for(int i=0;i<n;i++) { currSum = max(arr[i] + currSum, arr[i]); maxSum = max(maxSum,currSum); } return maxSum; } int circularSubarraySum(int arr[], int n){ // your code here int x = kadanes(arr,n); int y =0; for(int i =0;i<n;i++) { y += arr[i]; arr[i] = -arr[i];//here we are calculating min sub array } //by changing sign so that min subarray became max sub array int z = kadanes(arr,n);//z is maxsub array after changing sign if(y-(-z)==0)//and then subtract total sum (y) with negative of z { return x; } return max(x,y-(-z)); }"
},
{
"code": null,
"e": 2988,
"s": 2986,
"text": "0"
},
{
"code": null,
"e": 3013,
"s": 2988,
"text": "abhishek0908022 days ago"
},
{
"code": null,
"e": 3042,
"s": 3013,
"text": "int kadanes(int arr[],int n)"
},
{
"code": null,
"e": 3048,
"s": 3042,
"text": " {"
},
{
"code": null,
"e": 3085,
"s": 3048,
"text": " int ans=INT_MIN; int sum=0; "
},
{
"code": null,
"e": 3114,
"s": 3085,
"text": " for(int i=0;i<n;i++)"
},
{
"code": null,
"e": 3124,
"s": 3114,
"text": " {"
},
{
"code": null,
"e": 3150,
"s": 3124,
"text": " sum+=arr[i]; "
},
{
"code": null,
"e": 3174,
"s": 3150,
"text": " if(sum>ans)"
},
{
"code": null,
"e": 3196,
"s": 3174,
"text": " ans=sum; "
},
{
"code": null,
"e": 3225,
"s": 3196,
"text": " if(sum<0) sum=0;"
},
{
"code": null,
"e": 3235,
"s": 3225,
"text": " }"
},
{
"code": null,
"e": 3255,
"s": 3235,
"text": " return ans;"
},
{
"code": null,
"e": 3261,
"s": 3255,
"text": " }"
},
{
"code": null,
"e": 3310,
"s": 3261,
"text": " int circularSubarraySum(int arr[], int num){"
},
{
"code": null,
"e": 3354,
"s": 3310,
"text": " int x=kadanes(arr,num); int sum=0; "
},
{
"code": null,
"e": 3385,
"s": 3354,
"text": " for(int i=0;i<num;i++)"
},
{
"code": null,
"e": 3427,
"s": 3385,
"text": " { sum+=arr[i]; arr[i]=-1*arr[i];}"
},
{
"code": null,
"e": 3460,
"s": 3427,
"text": " int y=kadanes(arr,num); "
},
{
"code": null,
"e": 3482,
"s": 3460,
"text": " int z=sum+y; "
},
{
"code": null,
"e": 3510,
"s": 3482,
"text": " if(z==0) return x; "
},
{
"code": null,
"e": 3536,
"s": 3510,
"text": " return max(z,x); "
},
{
"code": null,
"e": 3551,
"s": 3545,
"text": " }"
},
{
"code": null,
"e": 3553,
"s": 3551,
"text": "0"
},
{
"code": null,
"e": 3581,
"s": 3553,
"text": "ruchikajamwal03192 days ago"
},
{
"code": null,
"e": 4153,
"s": 3581,
"text": "class Solution{ public: // arr: input array // num: size of array //Function to find maximum circular subarray sum. int circularSubarraySum(int arr[], int num){ // your code here int result=INT_MAX; int r=INT_MIN; int sum1=0,sum2=0,sum3=0; for(int i=0;i<num;i++) { sum1+=arr[i]; sum2+=arr[i]; sum3+=arr[i]; sum3=max(sum3,arr[i]); r=max(r,sum3); sum1=min(sum1,arr[i]); result=min(result,sum1); } if(r<0) return r; return max(sum2-result,r);"
},
{
"code": null,
"e": 4167,
"s": 4153,
"text": " }};"
},
{
"code": null,
"e": 4169,
"s": 4167,
"text": "0"
},
{
"code": null,
"e": 4198,
"s": 4169,
"text": "mrharshkshitij90603 days ago"
},
{
"code": null,
"e": 4824,
"s": 4200,
"text": "class Solution{\n public:\n int totalsum(int arr[], int n)\n {\n int res=arr[0];\n int maxend=arr[0];\n for(int i=1; i<n; i++)\n {\n maxend= max(maxend+arr[i], arr[i]);\n res=max(res, maxend);\n }\n return res;\n }\n \n int circularSubarraySum(int arr[], int num)\n {\n int total=totalsum(arr, num);\n if(total<0)\n return total;\n \n int sum=0;\n for(int i=0; i<num; i++)\n {\n sum=sum+arr[i];\n arr[i]= -arr[i];\n }\n int max_cir= sum+totalsum(arr, num);\n return max(max_cir, total);\n }\n};"
},
{
"code": null,
"e": 4829,
"s": 4826,
"text": "+2"
},
{
"code": null,
"e": 4859,
"s": 4829,
"text": "amankrguptagumla1441 week ago"
},
{
"code": null,
"e": 5725,
"s": 4859,
"text": "//JAVA SOLUTION\nclass Solution{\n static int normalMaxSum(int arr[], int n)\n {\n int res = arr[0];\n int maxEnding = arr[0];\n for(int i = 1; i < n; i++)\n {\n maxEnding = Math.max(maxEnding + arr[i], arr[i]);\n res = Math.max(maxEnding, res);\n }\n \n return res;\n }\n // a: input array\n // n: size of array\n //Function to find maximum circular subarray sum.\n static int circularSubarraySum(int arr[], int n) {\n \n // Your code here\n int max_normal = normalMaxSum(arr, n);\n if(max_normal < 0)\n return max_normal;\n int arr_sum = 0;\n for(int i = 0; i < n; i++)\n {\n arr_sum += arr[i];\n arr[i] = -arr[i];\n }\n int max_circular = arr_sum + normalMaxSum(arr, n);\n return Math.max(max_circular, max_normal);\n \n //return Integer.max(kadane(arr,n), reverseKadane(arr,n));\n }\n \n}\n"
},
{
"code": null,
"e": 5728,
"s": 5725,
"text": "+1"
},
{
"code": null,
"e": 5755,
"s": 5728,
"text": "ayushsunariya4581 week ago"
},
{
"code": null,
"e": 5773,
"s": 5755,
"text": "C++ Easy Solution"
},
{
"code": null,
"e": 6120,
"s": 5773,
"text": "Logic: So there are two case.Case 1. The first is that the subarray take only a middle part, and we know how to find the max subarray sum.Case2. The second is that the subarray take a part of head array and a part of tail array.We can transfer this case to the first one.The maximum result equals to the total sum minus the minimum subarray sum. "
},
{
"code": null,
"e": 6593,
"s": 6120,
"text": "\tint circularSubarraySum(int A[], int n){\n \n // your code here\n int total = 0, maxSum = A[0], curMax = 0, minSum = A[0], curMin = 0;\n for (int i=0;i<n;i++) {\n curMax = max(curMax + A[i], A[i]);\n maxSum = max(maxSum, curMax);\n curMin = min(curMin + A[i], A[i]);\n minSum = min(minSum, curMin);\n total += A[i];\n }\n return maxSum > 0 ? max(maxSum, total - minSum) : maxSum;\n }"
},
{
"code": null,
"e": 6595,
"s": 6593,
"text": "0"
},
{
"code": null,
"e": 6623,
"s": 6595,
"text": "prathameshmistry2 weeks ago"
},
{
"code": null,
"e": 6629,
"s": 6623,
"text": "C++++"
},
{
"code": null,
"e": 8416,
"s": 6635,
"text": "class Solution{ public: //Function to find maximum circular subarray sum. int circularSubarraySum(int a[], int n) { bool flag = false; int count =0;int maxx = INT_MIN; for(int i = 0; i < n; i++) { //Storing the maximum element in the array. if(a[i] > maxx) maxx = a[i]; //Counting total number of negative numbers in the array. if(a[i] < 0) count++; } if(count == n) return maxx; //Case 1:We get the maximum sum using standard Kadane's algorithm. int max_kadane = kadane(a, n); //Case 2:We now find the maximum sum that includes corner elements. int max_wrap = 0, i; for (i = 0; i < n; i++) { //Calculating total sum of array elements. max_wrap += a[i]; //Inverting the sign of array elements. a[i] = -a[i]; } //Maximum sum with corner elements will be: //Total sum of array elements-(-max subarray sum after changing //sign of array elements). max_wrap = max_wrap + kadane(a, n); //The maximum circular subarray sum will be maximum of two sums. return (max_wrap > max_kadane)? max_wrap: max_kadane; } //Standard Kadane's algorithm to find maximum subarray sum. int kadane(int a[], int n) { int max_so_far = 0, max_ending_here = 0; int i; for (i = 0; i < n; i++) { //Storing max sum till current index. max_ending_here = max_ending_here + a[i]; //If max sum till current index is negative, we update it to 0. if (max_ending_here < 0) max_ending_here = 0; //Storing the max sum so far. if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } };"
},
{
"code": null,
"e": 8418,
"s": 8416,
"text": "0"
},
{
"code": null,
"e": 8454,
"s": 8418,
"text": "gopikrishnaguntamukkala32 weeks ago"
},
{
"code": null,
"e": 8944,
"s": 8454,
"text": "python code\nALL TEST CASES PASSED\n\ndef circularSubarraySum(arr,n):\n ##Your code here\n def kadane(num):\n sumtillnow=num[0]\n totalsum=num[0]\n for i in num[1:]:\n sumtillnow=max(i,sumtillnow+i)\n totalsum=max(totalsum,sumtillnow)\n return totalsum\n t=kadane(arr)\n sum1=0\n for i in range(n):\n sum1+=arr[i]\n arr[i]=-arr[i]\n sum1+=kadane(arr)\n if sum1>t and sum1!=0:\n return sum1\n else:\n return t"
},
{
"code": null,
"e": 9090,
"s": 8944,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 9126,
"s": 9090,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9136,
"s": 9126,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9146,
"s": 9136,
"text": "\nContest\n"
},
{
"code": null,
"e": 9209,
"s": 9146,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9394,
"s": 9209,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9678,
"s": 9394,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 9824,
"s": 9678,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 9901,
"s": 9824,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 9942,
"s": 9901,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 9970,
"s": 9942,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 10041,
"s": 9970,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 10228,
"s": 10041,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Find longest palindrome formed by removing or shuffling chars from string
|
04 Jul, 2022
Given a string, find the longest palindrome that can be constructed by removing or shuffling characters from the string. Return only one palindrome if there are multiple palindrome strings of longest length.
Examples:
Input: abc
Output: a OR b OR c
Input: aabbcc
Output: abccba OR baccab OR cbaabc OR
any other palindromic string of length 6.
Input: abbaccd
Output: abcdcba OR ...
Input: aba
Output: aba
We can divide any palindromic string into three parts – beg, mid and end. For palindromic string of odd length say 2n + 1, ‘beg’ consists of first n characters of the string, ‘mid’ will consist of only 1 character i.e. (n + 1)th character and ‘end’ will consists of last n characters of the palindromic string. For palindromic string of even length 2n, ‘mid’ will always be empty. It should be noted that ‘end’ will be reverse of ‘beg’ in order for string to be palindrome.
The idea is to use above observation in our solution. As shuffling of characters is allowed, order of characters doesn’t matter in the input string. We first get frequency of each character in the input string. Then all characters having even occurrence (say 2n) in the input string will be part of the output string as we can easily place n characters in ‘beg’ string and the other n characters in the ‘end’ string (by preserving the palindromic order). For characters having odd occurrence (say 2n + 1), we fill ‘mid’ with one of all such characters. and remaining 2n characters are divided in halves and added at beginning and end.
Below is the implementation of above idea
C++
Java
Python3
C#
Javascript
// C++ program to find the longest palindrome by removing// or shuffling characters from the given string#include <bits/stdc++.h>using namespace std; // Function to find the longest palindrome by removing// or shuffling characters from the given stringstring findLongestPalindrome(string str){ // to stores freq of characters in a string int count[256] = { 0 }; // find freq of characters in the input string for (int i = 0; i < str.size(); i++) count[str[i]]++; // Any palindromic string consists of three parts // beg + mid + end string beg = "", mid = "", end = ""; // solution assumes only lowercase characters are // present in string. We can easily extend this // to consider any set of characters for (char ch = 'a'; ch <= 'z'; ch++) { // if the current character freq is odd if (count[ch] & 1) { // mid will contain only 1 character. It // will be overridden with next character // with odd freq mid = ch; // decrement the character freq to make // it even and consider current character // again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (int i = 0; i < count[ch]/2 ; i++) beg.push_back(ch); } } // end will be reverse of beg end = beg; reverse(end.begin(), end.end()); // return palindrome string return beg + mid + end;} // Driver codeint main(){ string str = "abbaccd"; cout << findLongestPalindrome(str); return 0;}
// Java program to find the longest palindrome by removing// or shuffling characters from the given string class GFG { // Function to find the longest palindrome by removing// or shuffling characters from the given string static String findLongestPalindrome(String str) { // to stores freq of characters in a string int count[] = new int[256]; // find freq of characters in the input string for (int i = 0; i < str.length(); i++) { count[str.charAt(i)]++; } // Any palindromic string consists of three parts // beg + mid + end String beg = "", mid = "", end = ""; // solution assumes only lowercase characters are // present in string. We can easily extend this // to consider any set of characters for (char ch = 'a'; ch <= 'z'; ch++) { // if the current character freq is odd if (count[ch] % 2 == 1) { // mid will contain only 1 character. It // will be overridden with next character // with odd freq mid = String.valueOf(ch); // decrement the character freq to make // it even and consider current character // again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (int i = 0; i < count[ch] / 2; i++) { beg += ch; } } } // end will be reverse of beg end = beg; end = reverse(end); // return palindrome string return beg + mid + end; } static String reverse(String str) { // convert String to character array // by using toCharArray String ans = ""; char[] try1 = str.toCharArray(); for (int i = try1.length - 1; i >= 0; i--) { ans += try1[i]; } return ans; } // Driver code public static void main(String[] args) { String str = "abbaccd"; System.out.println(findLongestPalindrome(str)); }}// This code is contributed by PrinciRaj1992
# Python3 program to find the longest palindrome by removing# or shuffling characters from the given string # Function to find the longest palindrome by removing# or shuffling characters from the given stringdef findLongestPalindrome(strr): # to stores freq of characters in a string count = [0]*256 # find freq of characters in the input string for i in range(len(strr)): count[ord(strr[i])] += 1 # Any palindromic consists of three parts # beg + mid + end beg = "" mid = "" end = "" # solution assumes only lowercase characters are # present in string. We can easily extend this # to consider any set of characters ch = ord('a') while ch <= ord('z'): # if the current character freq is odd if (count[ch] & 1): # mid will contain only 1 character. It # will be overridden with next character # with odd freq mid = ch # decrement the character freq to make # it even and consider current character # again count[ch] -= 1 ch -= 1 # if the current character freq is even else: # If count is n(an even number), push # n/2 characters to beg and rest # n/2 characters will form part of end # string for i in range(count[ch]//2): beg += chr(ch) ch += 1 # end will be reverse of beg end = beg end = end[::-1] # return palindrome string return beg + chr(mid) + end # Driver codestrr = "abbaccd" print(findLongestPalindrome(strr)) # This code is contributed by mohit kumar 29
// C# program to find the longest// palindrome by removing or// shuffling characters from// the given stringusing System; class GFG{ // Function to find the longest // palindrome by removing or // shuffling characters from // the given string static String findLongestPalindrome(String str) { // to stores freq of characters in a string int []count = new int[256]; // find freq of characters // in the input string for (int i = 0; i < str.Length; i++) { count[str[i]]++; } // Any palindromic string consists of // three parts beg + mid + end String beg = "", mid = "", end = ""; // solution assumes only lowercase // characters are present in string. // We can easily extend this to // consider any set of characters for (char ch = 'a'; ch <= 'z'; ch++) { // if the current character freq is odd if (count[ch] % 2 == 1) { // mid will contain only 1 character. // It will be overridden with next // character with odd freq mid = String.Join("",ch); // decrement the character freq to make // it even and consider current // character again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (int i = 0; i < count[ch] / 2; i++) { beg += ch; } } } // end will be reverse of beg end = beg; end = reverse(end); // return palindrome string return beg + mid + end; } static String reverse(String str) { // convert String to character array // by using toCharArray String ans = ""; char[] try1 = str.ToCharArray(); for (int i = try1.Length - 1; i >= 0; i--) { ans += try1[i]; } return ans; } // Driver code public static void Main() { String str = "abbaccd"; Console.WriteLine(findLongestPalindrome(str)); }} // This code is contributed by 29AjayKumar
<script> // Javascript program to find the// longest palindrome by removing// or shuffling characters from// the given string // Function to find the longest// palindrome by removing// or shuffling characters from// the given string function findLongestPalindrome(str) { // to stores freq of characters // in a string let count = new Array(256); for(let i=0;i<256;i++) { count[i]=0; } // find freq of characters in // the input string for (let i = 0; i < str.length; i++) { count[str[i].charCodeAt(0)]++; } // Any palindromic string consists // of three parts // beg + mid + end let beg = "", mid = "", end = ""; // solution assumes only // lowercase characters are // present in string. // We can easily extend this // to consider any set of characters for (let ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++) { // if the current character freq is odd if (count[ch] % 2 == 1) { // mid will contain only 1 character. It // will be overridden with next character // with odd freq mid = String.fromCharCode(ch); // decrement the character freq to make // it even and consider current character // again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (let i = 0; i < count[ch] / 2; i++) { beg += String.fromCharCode(ch); } } } // end will be reverse of beg end = beg; end = reverse(end); // return palindrome string return beg + mid + end; } function reverse(str) { // convert String to character array // by using toCharArray let ans = ""; let try1 = str.split(""); for (let i = try1.length - 1; i >= 0; i--) { ans += try1[i]; } return ans; } // Driver code let str = "abbaccd"; document.write(findLongestPalindrome(str)); // This code is contributed by unknown2108 </script>
abcdcba
Time complexity of above solution is O(n) where n is length of the string. Since, number of characters in the alphabet is constant, they do not contribute to asymptotic analysis.Auxiliary space used by the program is M where M is number of ASCII characters.
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
princiraj1992
29AjayKumar
mohit kumar 29
unknown2108
saurabh1990aror
hardikkoriintern
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
What is Data Structure: Types, Classifications and Applications
Print all the duplicates in the input string
Print all subsequences of a string
A Program to check if strings are rotations of each other or not
String class in Java | Set 1
Find if a string is interleaved of two other strings | DP-33
Remove first and last character of a string in Java
Find the smallest window in a string containing all characters of another string
Program to count occurrence of a given character in a string
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 262,
"s": 54,
"text": "Given a string, find the longest palindrome that can be constructed by removing or shuffling characters from the string. Return only one palindrome if there are multiple palindrome strings of longest length."
},
{
"code": null,
"e": 273,
"s": 262,
"text": "Examples: "
},
{
"code": null,
"e": 466,
"s": 273,
"text": "Input: abc\nOutput: a OR b OR c\n\nInput: aabbcc\nOutput: abccba OR baccab OR cbaabc OR\nany other palindromic string of length 6.\n\nInput: abbaccd\nOutput: abcdcba OR ...\n\nInput: aba\nOutput: aba"
},
{
"code": null,
"e": 940,
"s": 466,
"text": "We can divide any palindromic string into three parts – beg, mid and end. For palindromic string of odd length say 2n + 1, ‘beg’ consists of first n characters of the string, ‘mid’ will consist of only 1 character i.e. (n + 1)th character and ‘end’ will consists of last n characters of the palindromic string. For palindromic string of even length 2n, ‘mid’ will always be empty. It should be noted that ‘end’ will be reverse of ‘beg’ in order for string to be palindrome."
},
{
"code": null,
"e": 1575,
"s": 940,
"text": "The idea is to use above observation in our solution. As shuffling of characters is allowed, order of characters doesn’t matter in the input string. We first get frequency of each character in the input string. Then all characters having even occurrence (say 2n) in the input string will be part of the output string as we can easily place n characters in ‘beg’ string and the other n characters in the ‘end’ string (by preserving the palindromic order). For characters having odd occurrence (say 2n + 1), we fill ‘mid’ with one of all such characters. and remaining 2n characters are divided in halves and added at beginning and end."
},
{
"code": null,
"e": 1618,
"s": 1575,
"text": "Below is the implementation of above idea "
},
{
"code": null,
"e": 1622,
"s": 1618,
"text": "C++"
},
{
"code": null,
"e": 1627,
"s": 1622,
"text": "Java"
},
{
"code": null,
"e": 1635,
"s": 1627,
"text": "Python3"
},
{
"code": null,
"e": 1638,
"s": 1635,
"text": "C#"
},
{
"code": null,
"e": 1649,
"s": 1638,
"text": "Javascript"
},
{
"code": "// C++ program to find the longest palindrome by removing// or shuffling characters from the given string#include <bits/stdc++.h>using namespace std; // Function to find the longest palindrome by removing// or shuffling characters from the given stringstring findLongestPalindrome(string str){ // to stores freq of characters in a string int count[256] = { 0 }; // find freq of characters in the input string for (int i = 0; i < str.size(); i++) count[str[i]]++; // Any palindromic string consists of three parts // beg + mid + end string beg = \"\", mid = \"\", end = \"\"; // solution assumes only lowercase characters are // present in string. We can easily extend this // to consider any set of characters for (char ch = 'a'; ch <= 'z'; ch++) { // if the current character freq is odd if (count[ch] & 1) { // mid will contain only 1 character. It // will be overridden with next character // with odd freq mid = ch; // decrement the character freq to make // it even and consider current character // again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (int i = 0; i < count[ch]/2 ; i++) beg.push_back(ch); } } // end will be reverse of beg end = beg; reverse(end.begin(), end.end()); // return palindrome string return beg + mid + end;} // Driver codeint main(){ string str = \"abbaccd\"; cout << findLongestPalindrome(str); return 0;}",
"e": 3428,
"s": 1649,
"text": null
},
{
"code": "// Java program to find the longest palindrome by removing// or shuffling characters from the given string class GFG { // Function to find the longest palindrome by removing// or shuffling characters from the given string static String findLongestPalindrome(String str) { // to stores freq of characters in a string int count[] = new int[256]; // find freq of characters in the input string for (int i = 0; i < str.length(); i++) { count[str.charAt(i)]++; } // Any palindromic string consists of three parts // beg + mid + end String beg = \"\", mid = \"\", end = \"\"; // solution assumes only lowercase characters are // present in string. We can easily extend this // to consider any set of characters for (char ch = 'a'; ch <= 'z'; ch++) { // if the current character freq is odd if (count[ch] % 2 == 1) { // mid will contain only 1 character. It // will be overridden with next character // with odd freq mid = String.valueOf(ch); // decrement the character freq to make // it even and consider current character // again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (int i = 0; i < count[ch] / 2; i++) { beg += ch; } } } // end will be reverse of beg end = beg; end = reverse(end); // return palindrome string return beg + mid + end; } static String reverse(String str) { // convert String to character array // by using toCharArray String ans = \"\"; char[] try1 = str.toCharArray(); for (int i = try1.length - 1; i >= 0; i--) { ans += try1[i]; } return ans; } // Driver code public static void main(String[] args) { String str = \"abbaccd\"; System.out.println(findLongestPalindrome(str)); }}// This code is contributed by PrinciRaj1992",
"e": 5742,
"s": 3428,
"text": null
},
{
"code": "# Python3 program to find the longest palindrome by removing# or shuffling characters from the given string # Function to find the longest palindrome by removing# or shuffling characters from the given stringdef findLongestPalindrome(strr): # to stores freq of characters in a string count = [0]*256 # find freq of characters in the input string for i in range(len(strr)): count[ord(strr[i])] += 1 # Any palindromic consists of three parts # beg + mid + end beg = \"\" mid = \"\" end = \"\" # solution assumes only lowercase characters are # present in string. We can easily extend this # to consider any set of characters ch = ord('a') while ch <= ord('z'): # if the current character freq is odd if (count[ch] & 1): # mid will contain only 1 character. It # will be overridden with next character # with odd freq mid = ch # decrement the character freq to make # it even and consider current character # again count[ch] -= 1 ch -= 1 # if the current character freq is even else: # If count is n(an even number), push # n/2 characters to beg and rest # n/2 characters will form part of end # string for i in range(count[ch]//2): beg += chr(ch) ch += 1 # end will be reverse of beg end = beg end = end[::-1] # return palindrome string return beg + chr(mid) + end # Driver codestrr = \"abbaccd\" print(findLongestPalindrome(strr)) # This code is contributed by mohit kumar 29",
"e": 7421,
"s": 5742,
"text": null
},
{
"code": "// C# program to find the longest// palindrome by removing or// shuffling characters from// the given stringusing System; class GFG{ // Function to find the longest // palindrome by removing or // shuffling characters from // the given string static String findLongestPalindrome(String str) { // to stores freq of characters in a string int []count = new int[256]; // find freq of characters // in the input string for (int i = 0; i < str.Length; i++) { count[str[i]]++; } // Any palindromic string consists of // three parts beg + mid + end String beg = \"\", mid = \"\", end = \"\"; // solution assumes only lowercase // characters are present in string. // We can easily extend this to // consider any set of characters for (char ch = 'a'; ch <= 'z'; ch++) { // if the current character freq is odd if (count[ch] % 2 == 1) { // mid will contain only 1 character. // It will be overridden with next // character with odd freq mid = String.Join(\"\",ch); // decrement the character freq to make // it even and consider current // character again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (int i = 0; i < count[ch] / 2; i++) { beg += ch; } } } // end will be reverse of beg end = beg; end = reverse(end); // return palindrome string return beg + mid + end; } static String reverse(String str) { // convert String to character array // by using toCharArray String ans = \"\"; char[] try1 = str.ToCharArray(); for (int i = try1.Length - 1; i >= 0; i--) { ans += try1[i]; } return ans; } // Driver code public static void Main() { String str = \"abbaccd\"; Console.WriteLine(findLongestPalindrome(str)); }} // This code is contributed by 29AjayKumar",
"e": 9900,
"s": 7421,
"text": null
},
{
"code": "<script> // Javascript program to find the// longest palindrome by removing// or shuffling characters from// the given string // Function to find the longest// palindrome by removing// or shuffling characters from// the given string function findLongestPalindrome(str) { // to stores freq of characters // in a string let count = new Array(256); for(let i=0;i<256;i++) { count[i]=0; } // find freq of characters in // the input string for (let i = 0; i < str.length; i++) { count[str[i].charCodeAt(0)]++; } // Any palindromic string consists // of three parts // beg + mid + end let beg = \"\", mid = \"\", end = \"\"; // solution assumes only // lowercase characters are // present in string. // We can easily extend this // to consider any set of characters for (let ch = 'a'.charCodeAt(0); ch <= 'z'.charCodeAt(0); ch++) { // if the current character freq is odd if (count[ch] % 2 == 1) { // mid will contain only 1 character. It // will be overridden with next character // with odd freq mid = String.fromCharCode(ch); // decrement the character freq to make // it even and consider current character // again count[ch--]--; } // if the current character freq is even else { // If count is n(an even number), push // n/2 characters to beg string and rest // n/2 characters will form part of end // string for (let i = 0; i < count[ch] / 2; i++) { beg += String.fromCharCode(ch); } } } // end will be reverse of beg end = beg; end = reverse(end); // return palindrome string return beg + mid + end; } function reverse(str) { // convert String to character array // by using toCharArray let ans = \"\"; let try1 = str.split(\"\"); for (let i = try1.length - 1; i >= 0; i--) { ans += try1[i]; } return ans; } // Driver code let str = \"abbaccd\"; document.write(findLongestPalindrome(str)); // This code is contributed by unknown2108 </script>",
"e": 12373,
"s": 9900,
"text": null
},
{
"code": null,
"e": 12381,
"s": 12373,
"text": "abcdcba"
},
{
"code": null,
"e": 12639,
"s": 12381,
"text": "Time complexity of above solution is O(n) where n is length of the string. Since, number of characters in the alphabet is constant, they do not contribute to asymptotic analysis.Auxiliary space used by the program is M where M is number of ASCII characters."
},
{
"code": null,
"e": 12935,
"s": 12639,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 12949,
"s": 12935,
"text": "princiraj1992"
},
{
"code": null,
"e": 12961,
"s": 12949,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12976,
"s": 12961,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 12988,
"s": 12976,
"text": "unknown2108"
},
{
"code": null,
"e": 13004,
"s": 12988,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 13021,
"s": 13004,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 13029,
"s": 13021,
"text": "Strings"
},
{
"code": null,
"e": 13037,
"s": 13029,
"text": "Strings"
},
{
"code": null,
"e": 13135,
"s": 13037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13180,
"s": 13135,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 13244,
"s": 13180,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 13289,
"s": 13244,
"text": "Print all the duplicates in the input string"
},
{
"code": null,
"e": 13324,
"s": 13289,
"text": "Print all subsequences of a string"
},
{
"code": null,
"e": 13389,
"s": 13324,
"text": "A Program to check if strings are rotations of each other or not"
},
{
"code": null,
"e": 13418,
"s": 13389,
"text": "String class in Java | Set 1"
},
{
"code": null,
"e": 13479,
"s": 13418,
"text": "Find if a string is interleaved of two other strings | DP-33"
},
{
"code": null,
"e": 13531,
"s": 13479,
"text": "Remove first and last character of a string in Java"
},
{
"code": null,
"e": 13612,
"s": 13531,
"text": "Find the smallest window in a string containing all characters of another string"
}
] |
Javascript Short circuiting operators
|
10 Feb, 2022
Below is the example of the Short circuiting operators.
Example:<script> function gfg() { // AND short circuit document.write(false && true) document.write("</br>"); document.write(true && true) document.write("</br>"); // OR short circuit document.write(true || false) document.write("</br>"); document.write(false || true) } gfg(); </script>
<script> function gfg() { // AND short circuit document.write(false && true) document.write("</br>"); document.write(true && true) document.write("</br>"); // OR short circuit document.write(true || false) document.write("</br>"); document.write(false || true) } gfg(); </script>
Output:false
true
true
true
false
true
true
true
In JavaScript short-circuiting, an expression is evaluated from left to right until it is confirmed that the result of the remaining conditions is not going to affect the already evaluated result. If the result is clear even before the complete evaluation of the expression, it short circuits and the result will be returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing.
AND(&&) short circuit: In case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated and false is returned.
Example: Short circuiting using AND(&&) operator.
<script> // Since first operand is false and operator// is AND, Evaluation stops and false is// returned.console.log(false && true && true && false) // Whole expression will be evaluated.console.log(true && true && true)</script>
Output:
false
true
OR(||) short circuit: In case of OR, the expression is evaluated until we get one true result because the result will always be true, independent of the further conditions. If there is an expression with ||(logical OR), and the first operand itself is true, then a short circuit occurs, evaluation stops, and true is returned.
Example: Short circuiting using OR(||).
<script> // First operand is true and operator is ||, // evaluation stops and true is returned.console.log(true || false || false) // Evaluation stops at the second operand(true).console.log(false || true || true || false)</script>
Output:
true
true
JavaScript-Misc
javascript-operators
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 Feb, 2022"
},
{
"code": null,
"e": 109,
"s": 53,
"text": "Below is the example of the Short circuiting operators."
},
{
"code": null,
"e": 487,
"s": 109,
"text": "Example:<script> function gfg() { // AND short circuit document.write(false && true) document.write(\"</br>\"); document.write(true && true) document.write(\"</br>\"); // OR short circuit document.write(true || false) document.write(\"</br>\"); document.write(false || true) } gfg(); </script>"
},
{
"code": "<script> function gfg() { // AND short circuit document.write(false && true) document.write(\"</br>\"); document.write(true && true) document.write(\"</br>\"); // OR short circuit document.write(true || false) document.write(\"</br>\"); document.write(false || true) } gfg(); </script>",
"e": 857,
"s": 487,
"text": null
},
{
"code": null,
"e": 886,
"s": 857,
"text": "Output:false\ntrue\ntrue\ntrue\n"
},
{
"code": null,
"e": 908,
"s": 886,
"text": "false\ntrue\ntrue\ntrue\n"
},
{
"code": null,
"e": 1318,
"s": 908,
"text": "In JavaScript short-circuiting, an expression is evaluated from left to right until it is confirmed that the result of the remaining conditions is not going to affect the already evaluated result. If the result is clear even before the complete evaluation of the expression, it short circuits and the result will be returned. Short circuit evaluation avoids unnecessary work and leads to efficient processing."
},
{
"code": null,
"e": 1674,
"s": 1318,
"text": "AND(&&) short circuit: In case of AND, the expression is evaluated until we get one false result because the result will always be false, independent of the further conditions. If there is an expression with &&(logical AND), and the first operand itself is false, then a short circuit occurs, the further expression is not evaluated and false is returned."
},
{
"code": null,
"e": 1724,
"s": 1674,
"text": "Example: Short circuiting using AND(&&) operator."
},
{
"code": "<script> // Since first operand is false and operator// is AND, Evaluation stops and false is// returned.console.log(false && true && true && false) // Whole expression will be evaluated.console.log(true && true && true)</script>",
"e": 1956,
"s": 1724,
"text": null
},
{
"code": null,
"e": 1964,
"s": 1956,
"text": "Output:"
},
{
"code": null,
"e": 1976,
"s": 1964,
"text": "false\ntrue\n"
},
{
"code": null,
"e": 2303,
"s": 1976,
"text": "OR(||) short circuit: In case of OR, the expression is evaluated until we get one true result because the result will always be true, independent of the further conditions. If there is an expression with ||(logical OR), and the first operand itself is true, then a short circuit occurs, evaluation stops, and true is returned."
},
{
"code": null,
"e": 2343,
"s": 2303,
"text": "Example: Short circuiting using OR(||)."
},
{
"code": "<script> // First operand is true and operator is ||, // evaluation stops and true is returned.console.log(true || false || false) // Evaluation stops at the second operand(true).console.log(false || true || true || false)</script>",
"e": 2577,
"s": 2343,
"text": null
},
{
"code": null,
"e": 2585,
"s": 2577,
"text": "Output:"
},
{
"code": null,
"e": 2596,
"s": 2585,
"text": "true\ntrue\n"
},
{
"code": null,
"e": 2612,
"s": 2596,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2633,
"s": 2612,
"text": "javascript-operators"
},
{
"code": null,
"e": 2644,
"s": 2633,
"text": "JavaScript"
},
{
"code": null,
"e": 2661,
"s": 2644,
"text": "Web Technologies"
}
] |
jQuery | focusout() with Example
|
12 Feb, 2019
The focusout() is an inbuilt method in jQuery which is used to remove focus from the selected element.Syntax:
$(selector).focusout(function);
Parameter: It accepts a parameter “function” which is to be executed after execution of fadeout method.Return Value: It returns the selected element which loses its focus.jQuery code to show the working of focusout() method:
<html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $("div").focusin(function() { $(this).css("background-color", "green"); }); $("div").focusout(function() { $(this).css("background-color", "#FFFFFF"); }); }); </script> <style> div { border: 2px solid black; width: 50%; padding: 20px; } input { padding: 5px; margin: 10px; } </style></head> <body> <!-- click inside the field focusin will take place and when click outside focusout will take place --> <div> Enter name: <input type="text"> <br> </div> </body> </html>
Output:After clicking inside of the input field focusin will be in action-
After clicking outside of the input field focusout will be in action.
jQuery-Events
JavaScript
JQuery
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to Open URL in New Tab using JavaScript ?
Form validation using jQuery
How to change selected value of a drop-down list using jQuery?
How to add options to a select element using jQuery?
jQuery | children() with Examples
Scroll to the top of the page using JavaScript/jQuery
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2019"
},
{
"code": null,
"e": 138,
"s": 28,
"text": "The focusout() is an inbuilt method in jQuery which is used to remove focus from the selected element.Syntax:"
},
{
"code": null,
"e": 171,
"s": 138,
"text": "$(selector).focusout(function);\n"
},
{
"code": null,
"e": 396,
"s": 171,
"text": "Parameter: It accepts a parameter “function” which is to be executed after execution of fadeout method.Return Value: It returns the selected element which loses its focus.jQuery code to show the working of focusout() method:"
},
{
"code": "<html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- jQuery code to show the working of this method --> <script> $(document).ready(function() { $(\"div\").focusin(function() { $(this).css(\"background-color\", \"green\"); }); $(\"div\").focusout(function() { $(this).css(\"background-color\", \"#FFFFFF\"); }); }); </script> <style> div { border: 2px solid black; width: 50%; padding: 20px; } input { padding: 5px; margin: 10px; } </style></head> <body> <!-- click inside the field focusin will take place and when click outside focusout will take place --> <div> Enter name: <input type=\"text\"> <br> </div> </body> </html>",
"e": 1326,
"s": 396,
"text": null
},
{
"code": null,
"e": 1401,
"s": 1326,
"text": "Output:After clicking inside of the input field focusin will be in action-"
},
{
"code": null,
"e": 1471,
"s": 1401,
"text": "After clicking outside of the input field focusout will be in action."
},
{
"code": null,
"e": 1485,
"s": 1471,
"text": "jQuery-Events"
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": "JavaScript"
},
{
"code": null,
"e": 1503,
"s": 1496,
"text": "JQuery"
},
{
"code": null,
"e": 1601,
"s": 1503,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1662,
"s": 1601,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1734,
"s": 1662,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1774,
"s": 1734,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1815,
"s": 1774,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1861,
"s": 1815,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 1890,
"s": 1861,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1953,
"s": 1890,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 2006,
"s": 1953,
"text": "How to add options to a select element using jQuery?"
},
{
"code": null,
"e": 2040,
"s": 2006,
"text": "jQuery | children() with Examples"
}
] |
Program to print hollow Triangle pattern
|
28 Jun, 2022
Given the number of lines as N, the task is to form the given hollow Triangle pattern.Examples:
Input: N = 6
Output:
************
***** *****
**** ****
*** ***
** **
* *
Approach:
Input number of rows to print from the user as N.To iterate through rows run an outer loop from number of rows till it is greater than 1. The loop structure should look like for(i=N; i>=1; i–).To print spaces, run an inner loop from i to space (another local variable). The loop structure should look like for(k=1; k=1; j–); .Inside this loop print star.After printing all columns of a row, move to next line i.e. print new line.
Input number of rows to print from the user as N.
To iterate through rows run an outer loop from number of rows till it is greater than 1. The loop structure should look like for(i=N; i>=1; i–).
To print spaces, run an inner loop from i to space (another local variable). The loop structure should look like for(k=1; k=1; j–); .Inside this loop print star.
After printing all columns of a row, move to next line i.e. print new line.
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program for printing// the hollow triangle pattern #include <iostream>using namespace std; // Function for printing patternvoid pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { cout << "*"; } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { cout << " "; } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) cout << "*"; } cout << "\n"; } cout << "\n";} // Driver codeint main(){ // Get N int N = 6; // Print the pattern pattern(N); return 0;}
// C program for printing// the hollow triangle pattern #include <stdio.h> // Function for printing patternvoid pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { printf("*"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { printf(" "); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) printf("*"); } printf("\n"); } printf("\n");} // Driver codeint main(){ // Get N int N = 6; // Print the pattern pattern(N); return 0;}
// Java program for printing// the hollow triangle patternimport java.util.*; class solution{ // Function for printing patternstatic void pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { System.out.print("*"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { System.out.print(" "); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) System.out.print("*"); } System.out.print("\n"); } System.out.print("\n");} // Driver codepublic static void main(String args[]){ // Get N int N = 6; // Print the pattern pattern(N); }} //This code is contributed by Surendra_Gangwar
# Python 3 program for printing# the hollow triangle pattern # Function for printing patterndef pattern(N): k, space, rows = 0, 1, N # For printing stars for i in range(rows, 0, -1): for j in range(1, i + 1): print('*', end = '') if i != rows: # for printing space for k in range(1, space + 1): print(' ', end = '') # increment by 2 space += 2 for j in range(i, 0, -1): if j != rows: print('*', end = '') print() print() # Driver Code # Get NN = 6 # Print the patternpattern(N) # This code is contributed by# SamyuktaSHegde
// C# program for printing// the hollow triangle patternusing System; class GFG{ // Function for printing patternstatic void pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { Console.WriteLine("*"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { Console.Write(" "); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) Console.Write("*"); } Console.Write("\n"); } Console.Write("\n");} // Driver codepublic static void Main(){ // Get N int N = 6; // Print the pattern pattern(N);}} // This code is contributed// by Rajput-Ji
<?php// PHP program for printing// the hollow triangle pattern // Function for printing patternfunction pattern($N){ $k = 0; $space = 1; $rows = $N; // For printing stars for ($i = $rows; $i >= 1; $i--) { for ($j = 1; $j <= $i; $j++) { echo "*"; } if ($i != $rows) { // for printing space for ($k = 1; $k <= $space; $k++) { echo " "; } // increment by 2 $space = $space + 2; } for ($j = $i; $j >= 1; $j--) { if ($j != $rows) echo "*"; } echo "\n"; } echo "\n";} // Driver code // Get N$N = 6; // Print the patternpattern($N); // This code is contributed by// Archana_kumari?>
<script> // JavaScript program for printing // the hollow triangle pattern // Function for printing pattern function pattern(N) { var i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { document.write("*"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { document.write(" "); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) document.write("*"); } document.write("<br>"); } document.write("<br>"); } // Driver code // Get N var N = 6; // Print the pattern pattern(N); // This code is contributed by rdtank. </script>
***********
***** *****
**** ****
*** ***
** **
* *
Time complexity: O(n2)
Auxiliary Space: O(1)
SURENDRA_GANGWAR
Rajput-Ji
SamyuktaSHegde
archana_kumari
rdtank
krishnav4
pattern-printing
C Programs
C++ Programs
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
C Program to Swap two Numbers
Header files in C/C++ and its uses
Sorting a Map by value in C++ STL
How to return multiple values from a function in C or C++?
Shallow Copy and Deep Copy in C++
C++ program for hashing with chaining
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Given the number of lines as N, the task is to form the given hollow Triangle pattern.Examples: "
},
{
"code": null,
"e": 225,
"s": 126,
"text": "Input: N = 6\nOutput:\n************\n***** *****\n**** ****\n*** ***\n** **\n* *"
},
{
"code": null,
"e": 236,
"s": 225,
"text": "Approach: "
},
{
"code": null,
"e": 666,
"s": 236,
"text": "Input number of rows to print from the user as N.To iterate through rows run an outer loop from number of rows till it is greater than 1. The loop structure should look like for(i=N; i>=1; i–).To print spaces, run an inner loop from i to space (another local variable). The loop structure should look like for(k=1; k=1; j–); .Inside this loop print star.After printing all columns of a row, move to next line i.e. print new line."
},
{
"code": null,
"e": 716,
"s": 666,
"text": "Input number of rows to print from the user as N."
},
{
"code": null,
"e": 861,
"s": 716,
"text": "To iterate through rows run an outer loop from number of rows till it is greater than 1. The loop structure should look like for(i=N; i>=1; i–)."
},
{
"code": null,
"e": 1023,
"s": 861,
"text": "To print spaces, run an inner loop from i to space (another local variable). The loop structure should look like for(k=1; k=1; j–); .Inside this loop print star."
},
{
"code": null,
"e": 1099,
"s": 1023,
"text": "After printing all columns of a row, move to next line i.e. print new line."
},
{
"code": null,
"e": 1151,
"s": 1099,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1155,
"s": 1151,
"text": "C++"
},
{
"code": null,
"e": 1157,
"s": 1155,
"text": "C"
},
{
"code": null,
"e": 1162,
"s": 1157,
"text": "Java"
},
{
"code": null,
"e": 1170,
"s": 1162,
"text": "Python3"
},
{
"code": null,
"e": 1173,
"s": 1170,
"text": "C#"
},
{
"code": null,
"e": 1177,
"s": 1173,
"text": "PHP"
},
{
"code": null,
"e": 1188,
"s": 1177,
"text": "Javascript"
},
{
"code": "// C++ program for printing// the hollow triangle pattern #include <iostream>using namespace std; // Function for printing patternvoid pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { cout << \"*\"; } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { cout << \" \"; } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) cout << \"*\"; } cout << \"\\n\"; } cout << \"\\n\";} // Driver codeint main(){ // Get N int N = 6; // Print the pattern pattern(N); return 0;}",
"e": 1964,
"s": 1188,
"text": null
},
{
"code": "// C program for printing// the hollow triangle pattern #include <stdio.h> // Function for printing patternvoid pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { printf(\"*\"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { printf(\" \"); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) printf(\"*\"); } printf(\"\\n\"); } printf(\"\\n\");} // Driver codeint main(){ // Get N int N = 6; // Print the pattern pattern(N); return 0;}",
"e": 2717,
"s": 1964,
"text": null
},
{
"code": "// Java program for printing// the hollow triangle patternimport java.util.*; class solution{ // Function for printing patternstatic void pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { System.out.print(\"*\"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { System.out.print(\" \"); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) System.out.print(\"*\"); } System.out.print(\"\\n\"); } System.out.print(\"\\n\");} // Driver codepublic static void main(String args[]){ // Get N int N = 6; // Print the pattern pattern(N); }} //This code is contributed by Surendra_Gangwar",
"e": 3605,
"s": 2717,
"text": null
},
{
"code": "# Python 3 program for printing# the hollow triangle pattern # Function for printing patterndef pattern(N): k, space, rows = 0, 1, N # For printing stars for i in range(rows, 0, -1): for j in range(1, i + 1): print('*', end = '') if i != rows: # for printing space for k in range(1, space + 1): print(' ', end = '') # increment by 2 space += 2 for j in range(i, 0, -1): if j != rows: print('*', end = '') print() print() # Driver Code # Get NN = 6 # Print the patternpattern(N) # This code is contributed by# SamyuktaSHegde",
"e": 4268,
"s": 3605,
"text": null
},
{
"code": "// C# program for printing// the hollow triangle patternusing System; class GFG{ // Function for printing patternstatic void pattern(int N){ int i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { Console.WriteLine(\"*\"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { Console.Write(\" \"); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) Console.Write(\"*\"); } Console.Write(\"\\n\"); } Console.Write(\"\\n\");} // Driver codepublic static void Main(){ // Get N int N = 6; // Print the pattern pattern(N);}} // This code is contributed// by Rajput-Ji",
"e": 5149,
"s": 4268,
"text": null
},
{
"code": "<?php// PHP program for printing// the hollow triangle pattern // Function for printing patternfunction pattern($N){ $k = 0; $space = 1; $rows = $N; // For printing stars for ($i = $rows; $i >= 1; $i--) { for ($j = 1; $j <= $i; $j++) { echo \"*\"; } if ($i != $rows) { // for printing space for ($k = 1; $k <= $space; $k++) { echo \" \"; } // increment by 2 $space = $space + 2; } for ($j = $i; $j >= 1; $j--) { if ($j != $rows) echo \"*\"; } echo \"\\n\"; } echo \"\\n\";} // Driver code // Get N$N = 6; // Print the patternpattern($N); // This code is contributed by// Archana_kumari?>",
"e": 5939,
"s": 5149,
"text": null
},
{
"code": "<script> // JavaScript program for printing // the hollow triangle pattern // Function for printing pattern function pattern(N) { var i, j, k = 0, space = 1, rows = N; // For printing stars for (i = rows; i >= 1; i--) { for (j = 1; j <= i; j++) { document.write(\"*\"); } if (i != rows) { // for printing space for (k = 1; k <= space; k++) { document.write(\" \"); } // increment by 2 space = space + 2; } for (j = i; j >= 1; j--) { if (j != rows) document.write(\"*\"); } document.write(\"<br>\"); } document.write(\"<br>\"); } // Driver code // Get N var N = 6; // Print the pattern pattern(N); // This code is contributed by rdtank. </script>",
"e": 6876,
"s": 5939,
"text": null
},
{
"code": null,
"e": 6948,
"s": 6876,
"text": "***********\n***** *****\n**** ****\n*** ***\n** **\n* *"
},
{
"code": null,
"e": 6973,
"s": 6950,
"text": "Time complexity: O(n2)"
},
{
"code": null,
"e": 6995,
"s": 6973,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7012,
"s": 6995,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 7022,
"s": 7012,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7037,
"s": 7022,
"text": "SamyuktaSHegde"
},
{
"code": null,
"e": 7052,
"s": 7037,
"text": "archana_kumari"
},
{
"code": null,
"e": 7059,
"s": 7052,
"text": "rdtank"
},
{
"code": null,
"e": 7069,
"s": 7059,
"text": "krishnav4"
},
{
"code": null,
"e": 7086,
"s": 7069,
"text": "pattern-printing"
},
{
"code": null,
"e": 7097,
"s": 7086,
"text": "C Programs"
},
{
"code": null,
"e": 7110,
"s": 7097,
"text": "C++ Programs"
},
{
"code": null,
"e": 7129,
"s": 7110,
"text": "School Programming"
},
{
"code": null,
"e": 7146,
"s": 7129,
"text": "pattern-printing"
},
{
"code": null,
"e": 7244,
"s": 7146,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7279,
"s": 7244,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 7320,
"s": 7279,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 7379,
"s": 7320,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 7413,
"s": 7379,
"text": "C++ Program to check Prime Number"
},
{
"code": null,
"e": 7443,
"s": 7413,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 7478,
"s": 7443,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 7512,
"s": 7478,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 7571,
"s": 7512,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 7605,
"s": 7571,
"text": "Shallow Copy and Deep Copy in C++"
}
] |
How to include one CSS file in another?
|
10 May, 2022
Is it possible to include one CSS file in another? Yes, It is possible to include one CSS file in another and it can be done multiple times. Also, import multiple CSS files in the main HTML file or in the main CSS file. It can be done by using @import keyword.
Example 1:
HTML section: File name is index.html
html
<!DOCTYPE html><html> <head> <!-- linking css file with html file --> <link rel="stylesheet" href="style1.css"> </head> <body> <center> <marquee><h1>GeeksforGeeks</h1> </marquee> <div class="css1">GeeksforGeeks: It is a computer science portal. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </div> </center> </body></html>
Output: Without using CSS file
CSS section1: File name is style1.css
CSS
<!-- Including one css file into other -->@import "style2.css"; h1 { color:green; } .css1 { color:black; background-image: linear-gradient(to right, #DFF1DF, #11A00C); position:static; }
Output: Using style1.css file without importing the second CSS file (style2.css).
CSS section2: File name is style2.css
CSS
body { background:black; opacity: 0.5;}
Output:After importing the style2.css file into the style1.css file by using @import keyword.
Note: Many CSS file can be imported using one CSS file.Example 2:
HTML Section: File name is Example.html
html
<!DOCTYPE html><html> <head> <link rel="stylesheet" href="styl.css"> </head> <body> <h1>GeeksforGeeks<h1> <div include="form-input-select()"> <select required> <option value="">Example Placeholder</option> <!-- Available Options --> <option value="1">GeeksforGeeks</option> <option value="2">w3skul</option> <option value="3">tuitorial point</option> <option value="4">CodeComunity</option> <option value="5">Coders</option> </select> </div> </body></html>
Output: Without using CSS file
CSS Section1: File name is style1.css
CSS
@import "style2.css";body { border:black; justify-content: center; text-align: center;}
Output: Using style1.css file without importing style2.css file.
CSS Section2: File name is style2.css
html
h1 { color:green; text-decoration: underline overline;;}
Output:After using both CSS file (style1 and style2).
Note: There are two different ways to import a CSS file into another using @import url(“style2.css”); or @import “style2.css”; or directly import any CSS file or multiple CSS file in the HTML file directly within <style>@import “style1.css”; or .@import url(“style2.css”);</style> in head section.
CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.
rs1686740
sooda367
hardikkoriintern
Picked
Technical Scripter 2018
CSS
HTML
Technical Scripter
Web Technologies
Web technologies Questions
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to create footer to stay at the bottom of a Web page?
CSS to put icon inside an input element in a form
How to update Node.js and NPM to next version ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
REST API (Introduction)
Hide or show elements in HTML using display property
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 314,
"s": 52,
"text": "Is it possible to include one CSS file in another? Yes, It is possible to include one CSS file in another and it can be done multiple times. Also, import multiple CSS files in the main HTML file or in the main CSS file. It can be done by using @import keyword. "
},
{
"code": null,
"e": 326,
"s": 314,
"text": "Example 1: "
},
{
"code": null,
"e": 365,
"s": 326,
"text": "HTML section: File name is index.html "
},
{
"code": null,
"e": 370,
"s": 365,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <!-- linking css file with html file --> <link rel=\"stylesheet\" href=\"style1.css\"> </head> <body> <center> <marquee><h1>GeeksforGeeks</h1> </marquee> <div class=\"css1\">GeeksforGeeks: It is a computer science portal. It is an educational website. Prepare for the Recruitment drive of product based companies like Microsoft, Amazon, Adobe etc with a free online placement preparation course. </div> </center> </body></html> ",
"e": 938,
"s": 370,
"text": null
},
{
"code": null,
"e": 971,
"s": 938,
"text": "Output: Without using CSS file "
},
{
"code": null,
"e": 1010,
"s": 971,
"text": "CSS section1: File name is style1.css "
},
{
"code": null,
"e": 1014,
"s": 1010,
"text": "CSS"
},
{
"code": "<!-- Including one css file into other -->@import \"style2.css\"; h1 { color:green; } .css1 { color:black; background-image: linear-gradient(to right, #DFF1DF, #11A00C); position:static; }",
"e": 1224,
"s": 1014,
"text": null
},
{
"code": null,
"e": 1307,
"s": 1224,
"text": "Output: Using style1.css file without importing the second CSS file (style2.css). "
},
{
"code": null,
"e": 1346,
"s": 1307,
"text": "CSS section2: File name is style2.css "
},
{
"code": null,
"e": 1350,
"s": 1346,
"text": "CSS"
},
{
"code": "body { background:black; opacity: 0.5;}",
"e": 1400,
"s": 1350,
"text": null
},
{
"code": null,
"e": 1495,
"s": 1400,
"text": "Output:After importing the style2.css file into the style1.css file by using @import keyword. "
},
{
"code": null,
"e": 1563,
"s": 1495,
"text": "Note: Many CSS file can be imported using one CSS file.Example 2: "
},
{
"code": null,
"e": 1603,
"s": 1563,
"text": "HTML Section: File name is Example.html"
},
{
"code": null,
"e": 1608,
"s": 1603,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"styl.css\"> </head> <body> <h1>GeeksforGeeks<h1> <div include=\"form-input-select()\"> <select required> <option value=\"\">Example Placeholder</option> <!-- Available Options --> <option value=\"1\">GeeksforGeeks</option> <option value=\"2\">w3skul</option> <option value=\"3\">tuitorial point</option> <option value=\"4\">CodeComunity</option> <option value=\"5\">Coders</option> </select> </div> </body></html> ",
"e": 2282,
"s": 1608,
"text": null
},
{
"code": null,
"e": 2314,
"s": 2282,
"text": "Output: Without using CSS file "
},
{
"code": null,
"e": 2353,
"s": 2314,
"text": "CSS Section1: File name is style1.css "
},
{
"code": null,
"e": 2357,
"s": 2353,
"text": "CSS"
},
{
"code": "@import \"style2.css\";body { border:black; justify-content: center; text-align: center;} ",
"e": 2470,
"s": 2357,
"text": null
},
{
"code": null,
"e": 2536,
"s": 2470,
"text": "Output: Using style1.css file without importing style2.css file. "
},
{
"code": null,
"e": 2575,
"s": 2536,
"text": "CSS Section2: File name is style2.css "
},
{
"code": null,
"e": 2580,
"s": 2575,
"text": "html"
},
{
"code": "h1 { color:green; text-decoration: underline overline;;} ",
"e": 2662,
"s": 2580,
"text": null
},
{
"code": null,
"e": 2716,
"s": 2662,
"text": "Output:After using both CSS file (style1 and style2)."
},
{
"code": null,
"e": 3015,
"s": 2716,
"text": "Note: There are two different ways to import a CSS file into another using @import url(“style2.css”); or @import “style2.css”; or directly import any CSS file or multiple CSS file in the HTML file directly within <style>@import “style1.css”; or .@import url(“style2.css”);</style> in head section. "
},
{
"code": null,
"e": 3201,
"s": 3015,
"text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples."
},
{
"code": null,
"e": 3211,
"s": 3201,
"text": "rs1686740"
},
{
"code": null,
"e": 3220,
"s": 3211,
"text": "sooda367"
},
{
"code": null,
"e": 3237,
"s": 3220,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 3244,
"s": 3237,
"text": "Picked"
},
{
"code": null,
"e": 3268,
"s": 3244,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3272,
"s": 3268,
"text": "CSS"
},
{
"code": null,
"e": 3277,
"s": 3272,
"text": "HTML"
},
{
"code": null,
"e": 3296,
"s": 3277,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3313,
"s": 3296,
"text": "Web Technologies"
},
{
"code": null,
"e": 3340,
"s": 3313,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3345,
"s": 3340,
"text": "HTML"
},
{
"code": null,
"e": 3443,
"s": 3345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3491,
"s": 3443,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3553,
"s": 3491,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3603,
"s": 3553,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3661,
"s": 3603,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 3711,
"s": 3661,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 3759,
"s": 3711,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3821,
"s": 3759,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3871,
"s": 3821,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3895,
"s": 3871,
"text": "REST API (Introduction)"
}
] |
Python math function | hypot()
|
28 Aug, 2020
hypot() function is an inbuilt math function in Python that return the Euclidean norm, .
Syntax :
hypot(x, y)
Parameters :
x and y are numerical values
Returns :
Returns a float value having Euclidean norm, sqrt(x*x + y*y).
Error :
When more then two arguments are
passed, it returns a TypeError.
Note : One has to import math module before using hypot() function. Below is the demonstration of hypot() function :
Code #1 :
# Python3 program for hypot() function # Import the math moduleimport math # Use of hypot functionprint("hypot(3, 4) : ", math.hypot(3, 4)) # Neglects the negative signprint("hypot(-3, 4) : ", math.hypot(-3, 4)) print("hypot(6, 6) : ", math.hypot(6, 6))
Output :
hypot(3, 4) : 5.0
hypot(-3, 4) : 5.0
hypot(6, 6) : 8.48528137423857
Code #2 :
# Python3 program for error in hypot() function # import the math moduleimport math # Use of hypot() functionprint("hypot(3, 4, 6) : ", math.hypot(3, 4, 6))
Output :
Traceback (most recent call last):
File "/home/d8c8612ee97dd2c763e2836de644fac1.py", line 7, in
print("hypot(3, 4, 6) : ", math.hypot(3, 4, 6))
TypeError: hypot expected 2 arguments, got 3
Practical Application :Given perpendicular and base of a right angle triangle find the hypotenuse.
Using Pythagorean theorem which states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides.
Hence,
Hypotenuse = sqrt(p^2 + b^2)
Code #3 :
# Python3 program for finding Hypotenuse# in hypot() function # import the math modulefrom math import hypot # Perpendicular and basep = 3b = 4 # Calculates the hypotenuseprint("Hypotenuse is:", hypot(p, b))
Output :
Hypotenuse is: 5.0
Akanksha_Rai
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 117,
"s": 28,
"text": "hypot() function is an inbuilt math function in Python that return the Euclidean norm, ."
},
{
"code": null,
"e": 126,
"s": 117,
"text": "Syntax :"
},
{
"code": null,
"e": 139,
"s": 126,
"text": "hypot(x, y) "
},
{
"code": null,
"e": 152,
"s": 139,
"text": "Parameters :"
},
{
"code": null,
"e": 182,
"s": 152,
"text": "x and y are numerical values "
},
{
"code": null,
"e": 192,
"s": 182,
"text": "Returns :"
},
{
"code": null,
"e": 255,
"s": 192,
"text": "Returns a float value having Euclidean norm, sqrt(x*x + y*y). "
},
{
"code": null,
"e": 263,
"s": 255,
"text": "Error :"
},
{
"code": null,
"e": 329,
"s": 263,
"text": "When more then two arguments are \npassed, it returns a TypeError."
},
{
"code": null,
"e": 446,
"s": 329,
"text": "Note : One has to import math module before using hypot() function. Below is the demonstration of hypot() function :"
},
{
"code": null,
"e": 456,
"s": 446,
"text": "Code #1 :"
},
{
"code": "# Python3 program for hypot() function # Import the math moduleimport math # Use of hypot functionprint(\"hypot(3, 4) : \", math.hypot(3, 4)) # Neglects the negative signprint(\"hypot(-3, 4) : \", math.hypot(-3, 4)) print(\"hypot(6, 6) : \", math.hypot(6, 6))",
"e": 715,
"s": 456,
"text": null
},
{
"code": null,
"e": 724,
"s": 715,
"text": "Output :"
},
{
"code": null,
"e": 796,
"s": 724,
"text": "hypot(3, 4) : 5.0\nhypot(-3, 4) : 5.0\nhypot(6, 6) : 8.48528137423857\n"
},
{
"code": null,
"e": 807,
"s": 796,
"text": " Code #2 :"
},
{
"code": "# Python3 program for error in hypot() function # import the math moduleimport math # Use of hypot() functionprint(\"hypot(3, 4, 6) : \", math.hypot(3, 4, 6))",
"e": 968,
"s": 807,
"text": null
},
{
"code": null,
"e": 977,
"s": 968,
"text": "Output :"
},
{
"code": null,
"e": 1175,
"s": 977,
"text": "Traceback (most recent call last):\n File \"/home/d8c8612ee97dd2c763e2836de644fac1.py\", line 7, in \n print(\"hypot(3, 4, 6) : \", math.hypot(3, 4, 6))\nTypeError: hypot expected 2 arguments, got 3\n"
},
{
"code": null,
"e": 1275,
"s": 1175,
"text": " Practical Application :Given perpendicular and base of a right angle triangle find the hypotenuse."
},
{
"code": null,
"e": 1443,
"s": 1275,
"text": "Using Pythagorean theorem which states that the square of the hypotenuse (the side opposite the right angle) is equal to the sum of the squares of the other two sides."
},
{
"code": null,
"e": 1450,
"s": 1443,
"text": "Hence,"
},
{
"code": null,
"e": 1481,
"s": 1450,
"text": " Hypotenuse = sqrt(p^2 + b^2) "
},
{
"code": null,
"e": 1491,
"s": 1481,
"text": "Code #3 :"
},
{
"code": "# Python3 program for finding Hypotenuse# in hypot() function # import the math modulefrom math import hypot # Perpendicular and basep = 3b = 4 # Calculates the hypotenuseprint(\"Hypotenuse is:\", hypot(p, b))",
"e": 1703,
"s": 1491,
"text": null
},
{
"code": null,
"e": 1712,
"s": 1703,
"text": "Output :"
},
{
"code": null,
"e": 1732,
"s": 1712,
"text": "Hypotenuse is: 5.0\n"
},
{
"code": null,
"e": 1745,
"s": 1732,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1771,
"s": 1745,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 1778,
"s": 1771,
"text": "Python"
}
] |
AWS Lambda â Function in Java
|
In this chapter, let us understand in detail how to create a simple AWS Lambda function in Java in detail.
Before proceeding to work on creating a lambda function in AWS, we need AWS toolkit support for Eclipse. For any guidance on installation of the same, you can refer to the Environment Setup chapter in this tutorial.
Once you are done with installation, follow the steps given here −
Open Eclipse IDE and create a new project with AWS Lambda Java Project. Observe the screenshot given below for better understanding −
Once you select Next, it will redirect you the screen shown below −
Now, a default code is created for Input Type Custom. Once you click Finish button the project gets created as shown below −
Now, right click your project and export it. Select Java / JAR file from the Export wizard and click Next.
Now, if you click Next, you will be prompted save the file in the destination folder which will be asked when you click on next.
Once the file is saved, go back to AWS Console and create the AWS Lambda function for Java.
Now, upload the .jar file that we created using the Upload button as shown in the screenshot given below −
Handler is package name and class name. Look at the following example to understand handler in detail −
package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler {
@Override
public String handleRequest(Object input, Context context) {
context.getLogger().log("Input: " + input);
// TODO: implement your handler
return "Hello from Lambda!";
}
}
Observe that from the above code, the handler will be com.amazonaws.lambda.demo.LambdaFunctionHandler
Now, let us test the changes and see the output −
Interaction with AWS Lambda execution is done using the context. It provides following methods to be used inside Java −
getMemoryLimitInMB()
this will give the memory limit you specified while creating lambda function.
getFunctionName()
this will give the name of the lambda function.
getFunctionVersion()
this will give the version of the lambda function running.
getInvokedFunctionArn()
this will give the ARN used to invoke the function.
getAwsRequestId()
this will give the aws request id. This id gets created for the lambda function and it is unique. The id can be used with aws support incase if you face any issues.
getLogGroupName()
this will give the aws cloudwatch group name linked with aws lambda function created. It will be null if the iam user is not having permission for cloudwatch logging.
getClientContext()
this will give details about the app and device when used with aws mobile sdk. It will give details like version name and code, client id, title, app package name. It can be null.
getIdentity()
this will give details about the amazon cognito identity when used with aws mobile sdk. It can be null.
getRemainingTimeInMillis()
this will give the remaining time execution in milliseconds when the function is terminated after the specified timeout.
getLogger()
this will give the lambda logger linked with the context object.
Now, let us update the code given above and observe the output for some of the methods listed above. Observe the Example code given below for a better understanding −
package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<Object, String> {
@Override
public String handleRequest(Object input, Context context) {
context.getLogger().log("Input: " + input);
System.out.println("AWS Lambda function name: " + context.getFunctionName());
System.out.println("Memory Allocated: " + context.getMemoryLimitInMB());
System.out.println("Time remaining in milliseconds: " + context.getRemainingTimeInMillis());
System.out.println("Cloudwatch group name " + context.getLogGroupName());
System.out.println("AWS Lambda Request Id " + context.getAwsRequestId());
// TODO: implement your handler
return "Hello from Lambda!";
}
}
Once you run the code given above, you can find the output as given below −
You can observe the following output when you are viewing your log output −
The memory allocated for the Lambda function is 512MB. The time allocated is 25 seconds. The time remaining as displayed above is 24961, which is in milliseconds. So 25000 - 24961 which equals to 39 milliseconds is used for the execution of the Lambda function. Note that Cloudwatch group name and request id are also displayed as shown above.
Note that we have used the following command to print logs in Java −
System.out.println (“log message”)
The same is available in CloudWatch. For this, go to AWS services, select CloudWatchservices and click Logs.
Now, if you select the Lambda function, it will display the logs date wise as shown below −
You can also use Lambdalogger in Java to log the data. Observe the following example that shows the same −
package com.amazonaws.lambda.demo;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.services.lambda.runtime.LambdaLogger;
public class LambdaFunctionHandler implements RequestHandler<Object, String> {
@Override
public String handleRequest(Object input, Context context) {
LambdaLogger logger = context.getLogger();
logger.log("Input: " + input);
logger.log("AWS Lambda function name: " + context.getFunctionName()+"\n");
logger.log("Memory Allocated: " + context.getMemoryLimitInMB()+"\n");
logger.log("Time remaining in milliseconds: " + context.getRemainingTimeInMillis()+"\n");
logger.log("Cloudwatch group name " + context.getLogGroupName()+"\n");
logger.log("AWS Lambda Request Id " + context.getAwsRequestId()+"\n");
// TODO: implement your handler
return "Hello from Lambda!";
}
}
The code shown above will give you the following output −
The output in CloudWatch will be as shown below −
This section will explain how to handle errors in Java for Lambda function. Observe the following code that shows the same −
package com.amazonaws.lambda.errorhandling;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
public class LambdaFunctionHandler implements RequestHandler<Object, String> {
@Override
public String handleRequest(Object input, Context context) {
throw new RuntimeException("Error from aws lambda");
}
}
Note that the error details are displayed in json format with errorMessage Error from AWS Lambda. Also, the ErrorType and stackTrace gives more details about the error.
The output and the corresponding log output of the code given above will be as shown in the following screenshots given below −
35 Lectures
7.5 hours
Mr. Pradeep Kshetrapal
30 Lectures
3.5 hours
Priyanka Choudhary
44 Lectures
7.5 hours
Eduonix Learning Solutions
51 Lectures
6 hours
Manuj Aggarwal
41 Lectures
5 hours
AR Shankar
14 Lectures
1 hours
Zach Miller
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2513,
"s": 2406,
"text": "In this chapter, let us understand in detail how to create a simple AWS Lambda function in Java in detail."
},
{
"code": null,
"e": 2729,
"s": 2513,
"text": "Before proceeding to work on creating a lambda function in AWS, we need AWS toolkit support for Eclipse. For any guidance on installation of the same, you can refer to the Environment Setup chapter in this tutorial."
},
{
"code": null,
"e": 2796,
"s": 2729,
"text": "Once you are done with installation, follow the steps given here −"
},
{
"code": null,
"e": 2930,
"s": 2796,
"text": "Open Eclipse IDE and create a new project with AWS Lambda Java Project. Observe the screenshot given below for better understanding −"
},
{
"code": null,
"e": 2998,
"s": 2930,
"text": "Once you select Next, it will redirect you the screen shown below −"
},
{
"code": null,
"e": 3123,
"s": 2998,
"text": "Now, a default code is created for Input Type Custom. Once you click Finish button the project gets created as shown below −"
},
{
"code": null,
"e": 3230,
"s": 3123,
"text": "Now, right click your project and export it. Select Java / JAR file from the Export wizard and click Next."
},
{
"code": null,
"e": 3359,
"s": 3230,
"text": "Now, if you click Next, you will be prompted save the file in the destination folder which will be asked when you click on next."
},
{
"code": null,
"e": 3451,
"s": 3359,
"text": "Once the file is saved, go back to AWS Console and create the AWS Lambda function for Java."
},
{
"code": null,
"e": 3558,
"s": 3451,
"text": "Now, upload the .jar file that we created using the Upload button as shown in the screenshot given below −"
},
{
"code": null,
"e": 3662,
"s": 3558,
"text": "Handler is package name and class name. Look at the following example to understand handler in detail −"
},
{
"code": null,
"e": 4084,
"s": 3662,
"text": "package com.amazonaws.lambda.demo;\n\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\npublic class LambdaFunctionHandler implements RequestHandler {\n @Override\n public String handleRequest(Object input, Context context) {\n context.getLogger().log(\"Input: \" + input);\n\n // TODO: implement your handler\n return \"Hello from Lambda!\";\n }\n}"
},
{
"code": null,
"e": 4186,
"s": 4084,
"text": "Observe that from the above code, the handler will be com.amazonaws.lambda.demo.LambdaFunctionHandler"
},
{
"code": null,
"e": 4236,
"s": 4186,
"text": "Now, let us test the changes and see the output −"
},
{
"code": null,
"e": 4356,
"s": 4236,
"text": "Interaction with AWS Lambda execution is done using the context. It provides following methods to be used inside Java −"
},
{
"code": null,
"e": 4377,
"s": 4356,
"text": "getMemoryLimitInMB()"
},
{
"code": null,
"e": 4455,
"s": 4377,
"text": "this will give the memory limit you specified while creating lambda function."
},
{
"code": null,
"e": 4473,
"s": 4455,
"text": "getFunctionName()"
},
{
"code": null,
"e": 4521,
"s": 4473,
"text": "this will give the name of the lambda function."
},
{
"code": null,
"e": 4542,
"s": 4521,
"text": "getFunctionVersion()"
},
{
"code": null,
"e": 4601,
"s": 4542,
"text": "this will give the version of the lambda function running."
},
{
"code": null,
"e": 4625,
"s": 4601,
"text": "getInvokedFunctionArn()"
},
{
"code": null,
"e": 4677,
"s": 4625,
"text": "this will give the ARN used to invoke the function."
},
{
"code": null,
"e": 4695,
"s": 4677,
"text": "getAwsRequestId()"
},
{
"code": null,
"e": 4860,
"s": 4695,
"text": "this will give the aws request id. This id gets created for the lambda function and it is unique. The id can be used with aws support incase if you face any issues."
},
{
"code": null,
"e": 4878,
"s": 4860,
"text": "getLogGroupName()"
},
{
"code": null,
"e": 5045,
"s": 4878,
"text": "this will give the aws cloudwatch group name linked with aws lambda function created. It will be null if the iam user is not having permission for cloudwatch logging."
},
{
"code": null,
"e": 5064,
"s": 5045,
"text": "getClientContext()"
},
{
"code": null,
"e": 5244,
"s": 5064,
"text": "this will give details about the app and device when used with aws mobile sdk. It will give details like version name and code, client id, title, app package name. It can be null."
},
{
"code": null,
"e": 5258,
"s": 5244,
"text": "getIdentity()"
},
{
"code": null,
"e": 5362,
"s": 5258,
"text": "this will give details about the amazon cognito identity when used with aws mobile sdk. It can be null."
},
{
"code": null,
"e": 5389,
"s": 5362,
"text": "getRemainingTimeInMillis()"
},
{
"code": null,
"e": 5510,
"s": 5389,
"text": "this will give the remaining time execution in milliseconds when the function is terminated after the specified timeout."
},
{
"code": null,
"e": 5522,
"s": 5510,
"text": "getLogger()"
},
{
"code": null,
"e": 5587,
"s": 5522,
"text": "this will give the lambda logger linked with the context object."
},
{
"code": null,
"e": 5754,
"s": 5587,
"text": "Now, let us update the code given above and observe the output for some of the methods listed above. Observe the Example code given below for a better understanding −"
},
{
"code": null,
"e": 6619,
"s": 5754,
"text": "package com.amazonaws.lambda.demo;\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\npublic class LambdaFunctionHandler implements RequestHandler<Object, String> {\n @Override\n public String handleRequest(Object input, Context context) {\n context.getLogger().log(\"Input: \" + input);\n System.out.println(\"AWS Lambda function name: \" + context.getFunctionName());\n System.out.println(\"Memory Allocated: \" + context.getMemoryLimitInMB());\n System.out.println(\"Time remaining in milliseconds: \" + context.getRemainingTimeInMillis());\n System.out.println(\"Cloudwatch group name \" + context.getLogGroupName());\n System.out.println(\"AWS Lambda Request Id \" + context.getAwsRequestId());\n \n // TODO: implement your handler\n return \"Hello from Lambda!\";\n }\n}"
},
{
"code": null,
"e": 6695,
"s": 6619,
"text": "Once you run the code given above, you can find the output as given below −"
},
{
"code": null,
"e": 6771,
"s": 6695,
"text": "You can observe the following output when you are viewing your log output −"
},
{
"code": null,
"e": 7115,
"s": 6771,
"text": "The memory allocated for the Lambda function is 512MB. The time allocated is 25 seconds. The time remaining as displayed above is 24961, which is in milliseconds. So 25000 - 24961 which equals to 39 milliseconds is used for the execution of the Lambda function. Note that Cloudwatch group name and request id are also displayed as shown above."
},
{
"code": null,
"e": 7184,
"s": 7115,
"text": "Note that we have used the following command to print logs in Java −"
},
{
"code": null,
"e": 7220,
"s": 7184,
"text": "System.out.println (“log message”)\n"
},
{
"code": null,
"e": 7329,
"s": 7220,
"text": "The same is available in CloudWatch. For this, go to AWS services, select CloudWatchservices and click Logs."
},
{
"code": null,
"e": 7421,
"s": 7329,
"text": "Now, if you select the Lambda function, it will display the logs date wise as shown below −"
},
{
"code": null,
"e": 7528,
"s": 7421,
"text": "You can also use Lambdalogger in Java to log the data. Observe the following example that shows the same −"
},
{
"code": null,
"e": 8473,
"s": 7528,
"text": "package com.amazonaws.lambda.demo;\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\nimport com.amazonaws.services.lambda.runtime.LambdaLogger;\npublic class LambdaFunctionHandler implements RequestHandler<Object, String> {\n @Override\n public String handleRequest(Object input, Context context) {\n LambdaLogger logger = context.getLogger();\n logger.log(\"Input: \" + input);\n logger.log(\"AWS Lambda function name: \" + context.getFunctionName()+\"\\n\");\n logger.log(\"Memory Allocated: \" + context.getMemoryLimitInMB()+\"\\n\");\n logger.log(\"Time remaining in milliseconds: \" + context.getRemainingTimeInMillis()+\"\\n\");\n logger.log(\"Cloudwatch group name \" + context.getLogGroupName()+\"\\n\");\n logger.log(\"AWS Lambda Request Id \" + context.getAwsRequestId()+\"\\n\");\n \n // TODO: implement your handler\n return \"Hello from Lambda!\";\n }\n}"
},
{
"code": null,
"e": 8531,
"s": 8473,
"text": "The code shown above will give you the following output −"
},
{
"code": null,
"e": 8581,
"s": 8531,
"text": "The output in CloudWatch will be as shown below −"
},
{
"code": null,
"e": 8706,
"s": 8581,
"text": "This section will explain how to handle errors in Java for Lambda function. Observe the following code that shows the same −"
},
{
"code": null,
"e": 9088,
"s": 8706,
"text": "package com.amazonaws.lambda.errorhandling;\nimport com.amazonaws.services.lambda.runtime.Context;\nimport com.amazonaws.services.lambda.runtime.RequestHandler;\npublic class LambdaFunctionHandler implements RequestHandler<Object, String> {\n @Override\n public String handleRequest(Object input, Context context) {\n throw new RuntimeException(\"Error from aws lambda\");\n } \n}"
},
{
"code": null,
"e": 9257,
"s": 9088,
"text": "Note that the error details are displayed in json format with errorMessage Error from AWS Lambda. Also, the ErrorType and stackTrace gives more details about the error."
},
{
"code": null,
"e": 9385,
"s": 9257,
"text": "The output and the corresponding log output of the code given above will be as shown in the following screenshots given below −"
},
{
"code": null,
"e": 9420,
"s": 9385,
"text": "\n 35 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9444,
"s": 9420,
"text": " Mr. Pradeep Kshetrapal"
},
{
"code": null,
"e": 9479,
"s": 9444,
"text": "\n 30 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9499,
"s": 9479,
"text": " Priyanka Choudhary"
},
{
"code": null,
"e": 9534,
"s": 9499,
"text": "\n 44 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9562,
"s": 9534,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 9595,
"s": 9562,
"text": "\n 51 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 9611,
"s": 9595,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 9644,
"s": 9611,
"text": "\n 41 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 9656,
"s": 9644,
"text": " AR Shankar"
},
{
"code": null,
"e": 9689,
"s": 9656,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 9702,
"s": 9689,
"text": " Zach Miller"
},
{
"code": null,
"e": 9709,
"s": 9702,
"text": " Print"
},
{
"code": null,
"e": 9720,
"s": 9709,
"text": " Add Notes"
}
] |
How to train CNNs on ImageNet. A practical guide to using large image... | by Shivam Sharma | Towards Data Science
|
I’ll go over how to get the ImageNet dataset, and train your convolutional neural net on it. I’ve added some advice and learnings specific to training CNNs with PyTorch.
If you haven’t already, I recommend first trying to run your model on a sample image. When you’re starting out, it’s really tempting to jump to a big dataset like ImageNet to train your next state of the art model. However, I’ve found it more effective to start small and slowly scale up your experiment. First, try an image to make sure your code works. Then, try a smaller dataset like CIFAR-10. Finally, try it out on ImageNet. Do sanity checks along the way and repeat them for each “scale up”.
Also, be aware of the differences in your model for the smaller image sizes of one dataset vs the other. For example, CIFAR-10 has only 32x32 size images which are smaller than ImageNet’s variable image sizes. The average resolution of an ImageNet image is 469x387. They are usually cropped to 256x256 or 224x224 in your image preprocessing step.
In PyTorch, we don’t define an input height or width like we would in TensorFlow, so it’s your job to make sure output channel sizes along the way are appropriate in your network for a given input size. My advice is to be wary of how dimensionality reduction occurs from shallow to deeper filters in your network, especially as you change your dataset.
In general, as you increase the input resolution to a new dataset, the early receptive field should also increase in size (via increasing kernel size or adding pooling layers).
This is for two reasons:
Increasing the size of the early receptive field is a form of regularisation to guard your CNN from learning ultra specific details of images that are less generalisable.When decreasing the input resolution, this will help avoid premature shrinkage of the channel size. Applying a convolution to a 256x1x1 size tensor is kind of useless.
Increasing the size of the early receptive field is a form of regularisation to guard your CNN from learning ultra specific details of images that are less generalisable.
When decreasing the input resolution, this will help avoid premature shrinkage of the channel size. Applying a convolution to a 256x1x1 size tensor is kind of useless.
Both of these errors fail silently. These errors result in only an 8% decrease in top 1 accuracy when an ImageNet shaped ResNet is improperly applied to CIFAR-10. To correct this error, when moving from CIFAR-10 to ImageNet, the ResNet authors add an early max-pool layer, and use a larger initial kernel size (5x5 → 7x7).
I’d really recommend reading this blog post by Andrej Karpathy for a deeper intuition of this art. I’d also recommend this post by Tim Rocktaschel on advice for short term ML projects.
This is best done on a cloud environment. Unless you have access to a powerful GPU and a large SSD, I wouldn’t recommend doing this locally.
Before doing any training, spin up a Google Colab instance or an AWS SageMaker instance to use a Jupyter Notebook to experiment with your model & visualise the data being passed in. Then when you want to train your model, I’d recommend using a script and spinning up an EC2 instance with the AWS Deep Learning AMI. Attach an EBS instance to your EC2 with enough storage space for downloading & unzipping ImageNet. For 2012 ImageNet, the compressed download is 150GB. But you will need ~400GB since you need enough space to unzip the files, then delete the .tar afterwards. Using an EBS instance also means you can upgrade your EC2 without having to re-download the data.
Now to actually download ImageNet, the official instructions are to sign up as a researcher with your research institution here.
I don’t think Stanford has been maintaining this for quite some time, as you’ll never get the email invite. So, what I found is effective is to download ImageNet from Academic Torrents.
Search for ImageNet, get the desired magnet links, and use the CLI to download torrents with Transmission. Make sure your instance has internet access!
sudo yum install transmission transmission-daemon transmission-cli
Then setup your download directory
transmission-daemon --download-dir "your-download-directory-path"
And add your magnet link
transmission-remote -a "magnet-link"
Find other important commands here.
Once you have downloaded the compressed files, we’d like to extract them and put them in the correct folders so that they match what the PyTorch ImageFolder class expects as described in the documentation here.
Place ILSVRC2012_img_train.tar and ILSVRC2012_img_val.tar in the same folder as the following script to get the desired folders. Edit as necessary for your specific torrent.
I’d also recommend throwing both .tar files onto a bucket in S3 so you can get them from there next time. Don’t toss the uncompressed files since you pay for individual requests per object on S3.
I’d recommend setting up your usage of PyTorch’s DataLoader and ImageFolder in a module titled with the dataset. I’ve found that easy to help keep dataset specific augmentations in different files. Here’s an example imagenet.py for use with ResNet. Set up your default batch size, your normalising transformation, and crop that is specific to this dataset. Perhaps in another file like cifar10.py you could have the dataset loader with settings specific to cifar-10 (with different batch size, normalisation, and crop).
I would not recommend training a model on a massive dataset like ImageNet or Sports1M in a Jupyter notebook. You may have timeouts, and your instance will disconnect from stdout which leads to you not seeing the progress your model is making either. A safer option is to ssh in and train with a script in a screen.
I would also recommend using neptune.ai to track progress in a neat visual dashboard. Some people use TensorBoard or TensorBoardX for pytorch, but I’ve yet to try that out. I liked neptune.ai because it keeps my results around even after I’ve closed the instances, and lets me easily compare experiments.
Now use your data loaders with your model, your choice of an optimiser, and your choice of loss to train on ImageNet. It’ll look like some variation of the following pseudocode:
# one epochfor i, (images, target) in enumerate(train_loader): # compute output output = model(images) loss = criterion(output, target) # measure accuracy and record loss acc1, acc5 = accuracy(output, target, topk=(1, 5)) losses.update(loss.item(), images.size(0)) top1.update(acc1[0], images.size(0)) top5.update(acc5[0], images.size(0)) # compute gradient and do step optimizer.zero_grad() loss.backward() optimizer.step()
This is only for training. Use this in a loop with a validation function to alternate training and scoring on the validation set in each epoch. For more examples on how to do this, look at the official PyTorch examples here.
Remember to have a look at the data before it goes in to your network at least once. This means actually visualising it. Here’s a sample sanity check below to use to make sure everything is going well during preprocessing.
For completeness, I’ve added some code above the sanity check to generate the denormalising transformation (to view the actual image without the effects of normalisation).
Now have fun training & keep your sanity with sanity checks! 😄
|
[
{
"code": null,
"e": 342,
"s": 172,
"text": "I’ll go over how to get the ImageNet dataset, and train your convolutional neural net on it. I’ve added some advice and learnings specific to training CNNs with PyTorch."
},
{
"code": null,
"e": 841,
"s": 342,
"text": "If you haven’t already, I recommend first trying to run your model on a sample image. When you’re starting out, it’s really tempting to jump to a big dataset like ImageNet to train your next state of the art model. However, I’ve found it more effective to start small and slowly scale up your experiment. First, try an image to make sure your code works. Then, try a smaller dataset like CIFAR-10. Finally, try it out on ImageNet. Do sanity checks along the way and repeat them for each “scale up”."
},
{
"code": null,
"e": 1188,
"s": 841,
"text": "Also, be aware of the differences in your model for the smaller image sizes of one dataset vs the other. For example, CIFAR-10 has only 32x32 size images which are smaller than ImageNet’s variable image sizes. The average resolution of an ImageNet image is 469x387. They are usually cropped to 256x256 or 224x224 in your image preprocessing step."
},
{
"code": null,
"e": 1541,
"s": 1188,
"text": "In PyTorch, we don’t define an input height or width like we would in TensorFlow, so it’s your job to make sure output channel sizes along the way are appropriate in your network for a given input size. My advice is to be wary of how dimensionality reduction occurs from shallow to deeper filters in your network, especially as you change your dataset."
},
{
"code": null,
"e": 1718,
"s": 1541,
"text": "In general, as you increase the input resolution to a new dataset, the early receptive field should also increase in size (via increasing kernel size or adding pooling layers)."
},
{
"code": null,
"e": 1743,
"s": 1718,
"text": "This is for two reasons:"
},
{
"code": null,
"e": 2081,
"s": 1743,
"text": "Increasing the size of the early receptive field is a form of regularisation to guard your CNN from learning ultra specific details of images that are less generalisable.When decreasing the input resolution, this will help avoid premature shrinkage of the channel size. Applying a convolution to a 256x1x1 size tensor is kind of useless."
},
{
"code": null,
"e": 2252,
"s": 2081,
"text": "Increasing the size of the early receptive field is a form of regularisation to guard your CNN from learning ultra specific details of images that are less generalisable."
},
{
"code": null,
"e": 2420,
"s": 2252,
"text": "When decreasing the input resolution, this will help avoid premature shrinkage of the channel size. Applying a convolution to a 256x1x1 size tensor is kind of useless."
},
{
"code": null,
"e": 2743,
"s": 2420,
"text": "Both of these errors fail silently. These errors result in only an 8% decrease in top 1 accuracy when an ImageNet shaped ResNet is improperly applied to CIFAR-10. To correct this error, when moving from CIFAR-10 to ImageNet, the ResNet authors add an early max-pool layer, and use a larger initial kernel size (5x5 → 7x7)."
},
{
"code": null,
"e": 2928,
"s": 2743,
"text": "I’d really recommend reading this blog post by Andrej Karpathy for a deeper intuition of this art. I’d also recommend this post by Tim Rocktaschel on advice for short term ML projects."
},
{
"code": null,
"e": 3069,
"s": 2928,
"text": "This is best done on a cloud environment. Unless you have access to a powerful GPU and a large SSD, I wouldn’t recommend doing this locally."
},
{
"code": null,
"e": 3740,
"s": 3069,
"text": "Before doing any training, spin up a Google Colab instance or an AWS SageMaker instance to use a Jupyter Notebook to experiment with your model & visualise the data being passed in. Then when you want to train your model, I’d recommend using a script and spinning up an EC2 instance with the AWS Deep Learning AMI. Attach an EBS instance to your EC2 with enough storage space for downloading & unzipping ImageNet. For 2012 ImageNet, the compressed download is 150GB. But you will need ~400GB since you need enough space to unzip the files, then delete the .tar afterwards. Using an EBS instance also means you can upgrade your EC2 without having to re-download the data."
},
{
"code": null,
"e": 3869,
"s": 3740,
"text": "Now to actually download ImageNet, the official instructions are to sign up as a researcher with your research institution here."
},
{
"code": null,
"e": 4055,
"s": 3869,
"text": "I don’t think Stanford has been maintaining this for quite some time, as you’ll never get the email invite. So, what I found is effective is to download ImageNet from Academic Torrents."
},
{
"code": null,
"e": 4207,
"s": 4055,
"text": "Search for ImageNet, get the desired magnet links, and use the CLI to download torrents with Transmission. Make sure your instance has internet access!"
},
{
"code": null,
"e": 4274,
"s": 4207,
"text": "sudo yum install transmission transmission-daemon transmission-cli"
},
{
"code": null,
"e": 4309,
"s": 4274,
"text": "Then setup your download directory"
},
{
"code": null,
"e": 4375,
"s": 4309,
"text": "transmission-daemon --download-dir \"your-download-directory-path\""
},
{
"code": null,
"e": 4400,
"s": 4375,
"text": "And add your magnet link"
},
{
"code": null,
"e": 4437,
"s": 4400,
"text": "transmission-remote -a \"magnet-link\""
},
{
"code": null,
"e": 4473,
"s": 4437,
"text": "Find other important commands here."
},
{
"code": null,
"e": 4684,
"s": 4473,
"text": "Once you have downloaded the compressed files, we’d like to extract them and put them in the correct folders so that they match what the PyTorch ImageFolder class expects as described in the documentation here."
},
{
"code": null,
"e": 4858,
"s": 4684,
"text": "Place ILSVRC2012_img_train.tar and ILSVRC2012_img_val.tar in the same folder as the following script to get the desired folders. Edit as necessary for your specific torrent."
},
{
"code": null,
"e": 5054,
"s": 4858,
"text": "I’d also recommend throwing both .tar files onto a bucket in S3 so you can get them from there next time. Don’t toss the uncompressed files since you pay for individual requests per object on S3."
},
{
"code": null,
"e": 5574,
"s": 5054,
"text": "I’d recommend setting up your usage of PyTorch’s DataLoader and ImageFolder in a module titled with the dataset. I’ve found that easy to help keep dataset specific augmentations in different files. Here’s an example imagenet.py for use with ResNet. Set up your default batch size, your normalising transformation, and crop that is specific to this dataset. Perhaps in another file like cifar10.py you could have the dataset loader with settings specific to cifar-10 (with different batch size, normalisation, and crop)."
},
{
"code": null,
"e": 5889,
"s": 5574,
"text": "I would not recommend training a model on a massive dataset like ImageNet or Sports1M in a Jupyter notebook. You may have timeouts, and your instance will disconnect from stdout which leads to you not seeing the progress your model is making either. A safer option is to ssh in and train with a script in a screen."
},
{
"code": null,
"e": 6194,
"s": 5889,
"text": "I would also recommend using neptune.ai to track progress in a neat visual dashboard. Some people use TensorBoard or TensorBoardX for pytorch, but I’ve yet to try that out. I liked neptune.ai because it keeps my results around even after I’ve closed the instances, and lets me easily compare experiments."
},
{
"code": null,
"e": 6372,
"s": 6194,
"text": "Now use your data loaders with your model, your choice of an optimiser, and your choice of loss to train on ImageNet. It’ll look like some variation of the following pseudocode:"
},
{
"code": null,
"e": 6881,
"s": 6372,
"text": "# one epochfor i, (images, target) in enumerate(train_loader): # compute output output = model(images) loss = criterion(output, target) # measure accuracy and record loss acc1, acc5 = accuracy(output, target, topk=(1, 5)) losses.update(loss.item(), images.size(0)) top1.update(acc1[0], images.size(0)) top5.update(acc5[0], images.size(0)) # compute gradient and do step optimizer.zero_grad() loss.backward() optimizer.step()"
},
{
"code": null,
"e": 7106,
"s": 6881,
"text": "This is only for training. Use this in a loop with a validation function to alternate training and scoring on the validation set in each epoch. For more examples on how to do this, look at the official PyTorch examples here."
},
{
"code": null,
"e": 7329,
"s": 7106,
"text": "Remember to have a look at the data before it goes in to your network at least once. This means actually visualising it. Here’s a sample sanity check below to use to make sure everything is going well during preprocessing."
},
{
"code": null,
"e": 7501,
"s": 7329,
"text": "For completeness, I’ve added some code above the sanity check to generate the denormalising transformation (to view the actual image without the effects of normalisation)."
}
] |
Coding and Implementing a Relational Database using MySQL | by Craig Dickson | Towards Data Science
|
This is part 2 of a 3-part series taking you through the process of designing, coding, implementing and querying a relational database, starting from zero. See part 1 (Designing a Relational Database and Creating an Entity Relationship Diagram) here, and part 3 (Data Analysis in MySQL — Operators, Joins and More in Relational Databases) here.
All the code and information for this tutorial can be found on the associated GitHub repository. I used Lucidchart to make the diagrams shown in the article.
In part 1 of this series, we covered going from conception of the database to making a plan, and finally creating an Entity Relationship Diagram spelling out the relationships that we will need to model using our SQL code. We covered the basics of Relational Database theory, and talked about primary keys, foreign keys, cardinality and a lot of other really useful material.
It’s a good idea to read that before starting this article, but you can also read this one on its own if you prefer to dive right into the code.
Alright! Now we’re about to get to the real fun stuff, actually creating and populating our database using SQL.
Before we dive into this, we will need to get MySQL Community Server set up on our system, if it isn’t already. The installation is a little more complex than installing a typical application (at least on Windows!), but we can handle it.
First go to the download page and get the installer for your system. If you are using Windows, this guide will help you get set up. Here are guides for Mac and Linux users too (although it may vary by Linux distribution). A full walk-through is beyond the scope of this article, but you can do it. I believe in you!
Once you get this set up, we can do everything that follows in the MySQL command line client.
The command line client is great and powerful, and essential to learn. Sometimes it’s nice to make our lives easier by using a GUI client, however.
PopSQL is a good GUI application for SQL, which makes things look a little nicer, as well as providing very useful features like the ability to look over your database schema in the left-hand navigation window, alongside some basic data visualisation and convenient export features.
For professional use there is a fee, but there is also a free tier that will definitely be enough for learning and playing around with SQL. There are lots of other GUI options out there as well, so give them a try if an alternative sounds appealing. We’ll be using PopSQL for the rest of this article however, so that’s where the screenshots will come from.
To answer any further questions about the SQL statements we use here, the best step is to look at the MySQL documentation. This is the official resource produced by the developers and contains detailed and comprehensive information. While it might seem intimidating to begin with, reading the documentation is a great habit to get into. Just search for the statement or topic of interest and see what comes out. As with all things code-related, google (or a search engine of your choice) is your friend!
Once we have our environment set up, we need to create a database on our MySQL server. This is not too complicated, we just have to use the CREATE DATABASE statement. Note that all SQL statements are closed with a semicolon ‘;’. This lets the client know that this is the end of our statement, which is especially useful when writing longer and more complex statements, like nested queries, but is essential for all statements (except the USE command, which we will see next).
CREATE DATABASE school;
Nice! We just created a database with the name school. Incredible work.
Next time we log into MySQL command line client, we will need to enter our password and then choose which database we want to use. To do this we use the use command:
USE school
As simple as that. If we are using GUI software we don’t normally have to take this step every time.
Note that by convention we put the keywords (like SELECT, DELETE and CREATE DATABASE) in upper case, and the rest of the code in lower case. SQL is actually case insensitive so the code works perfectly well all in lower case or all in upper case (or in mOcKiNg SpOnGeBoB meme style if you really have to). This convention is for the humans who will read your code later, and it’s strongly recommended to follow this practice when writing any flavour of SQL.
Building our database is going to be hugely simplified by the work we have already done creating our ERD and defining the entities (which will be created in our database as tables) and their relationships. The final step we need to take before creating the tables in SQL is plan which data type each attribute will need to have. This has to be declared when creating the table, so we need to think about it before we take that step.
MySQL supports a wide range of data types, from simple integers and strings to BLOBs and JSONs. We will just be using a small subset of these in our database.
We’re going to use the following;
INT — this is an integer, a whole number. We’re mainly going to use this for our ID fields (which will be our primary keys).
VARCHAR — this is a string field of varying length, which we will use for storing text. We need to tell the RDBMS how long the VARCHAR will be, so we can define VARCHAR(20), for example, which will store up to 20 characters, or VARCHAR(60), which will store up to 60. Larger strings allow us to store more data, but take up more memory.
DATE — this is a date field, stored in YYYY-MM-DD format.
BOOLEAN — technically MySQL doesn’t store boolean (true / false) values, but it does allow them to be stored using what it calls ‘boolean literals’, which it evaluates to 1 for true and 0 for false.
With this in mind, we can start defining appropriate data types for our tables.
Here we have defined our teacher_id as an INT, first_name and last_name as VARCHAR(40), language_1 and language_2 as VARCHAR(3), dob as a DATE, tax_id as INT and phone_no as VARCHAR(20). It’s perfectly possible to choose different values or even different data types (perhaps the tax_id in your country includes text characters? Then an INT won’t work for you), this is all part of the art of database design.
To create this table in our database, we will use the following code:
CREATE TABLE teacher ( teacher_id INT PRIMARY KEY, first_name VARCHAR(40) NOT NULL, last_name VARCHAR(40) NOT NULL, language_1 VARCHAR(3) NOT NULL, language_2 VARCHAR(3), dob DATE, tax_id INT UNIQUE, phone_no VARCHAR(20) );
The SQL statement we use here is simply CREATE TABLE. This is followed by the name we want to give the table, then parentheses and the attribute names and associated data types.
We have also added some constraints to some of the attributes in our table. Contraints specify rules for data in a table, and will constrain what the RDBMS will allow us to do to that particular attribute.
We have added NOT NULL to first_name, last_name and language_1 — this means that the table will not accept a record where any of those attributes are set to NULL. Those attributes require a non-NULL value for every record. This makes sense, as our teachers will require a first name and last name, and to teach in a language school they need to be able to offer at least one language.
We have also set tax_id to be UNIQUE. This means that every record must have a different value for this attribute, which makes sense for a tax ID number, but would not make sense for our language_1 field, for example — we will likely have multiple teachers who offer the same language!
We have also set the teacher_id field as our PRIMARY KEY. In practice this is really just a combination of NOT NULL and UNIQUE, but it is important to define one primary key (which again, can be a single attribute or a combination of different attributes) for each table.
If we now try to use a SELECT * FROM table statement to see what data is in our table (we will go over this statement in more detail in part 3), we should receive ‘Empty set’ as our response (in MySQL command line client) or ‘No results found’ (in PopSQL). This shows us our table exists (otherwise we would receive an error), but is still empty. Exactly as we would expect!
Now that we have created our first table, let’s delete it!
The passion for destruction is a creative passion, too. A good way to understand how easy it is to delete something in MySQL (and why I was so concerned about doing that accidentally in the past) is to go ahead and do it. This is also the best way to overcome those concerns, as it is in fact relatively difficult to do by accident.
The relevant SQL statement is DROP TABLE.
DROP TABLE teacher;
Go ahead, do it! It’s liberating!
Notice that there is no helpful ‘are you sure you want to do this?’ dialog box which pops up. There is also no undo button, just a simple ‘Query OK’ or ‘Success’ message, and the table is gone. This is also the case when the table contains data. So SQL is a very powerful language, but it can be unforgiving. Make sure you’ve thought through what you’re doing when you’re deleting or updating tables!
Don’t forget to reinstate the Teacher table before moving on to the next sections.
Here we’re using the same data types again, the only new one is BOOLEAN for in_school. This is going to be TRUE if the class takes place on the premises of the International Language School, and FALSE if it take place elsewhere, i.e. at the offices of the client.
The code to create these tables is as follows:
CREATE TABLE client ( client_id INT PRIMARY KEY, client_name VARCHAR(40) NOT NULL, address VARCHAR(60) NOT NULL, industry VARCHAR(20));CREATE TABLE participant ( participant_id INT PRIMARY KEY, first_name VARCHAR(40) NOT NULL, last_name VARCHAR(40) NOT NULL, phone_no VARCHAR(20), client INT);CREATE TABLE course ( course_id INT PRIMARY KEY, course_name VARCHAR(40) NOT NULL, language VARCHAR(3) NOT NULL, level VARCHAR(2), course_length_weeks INT, start_date DATE, in_school BOOLEAN, teacher INT, client INT);
Now we have a table for each of our entities, great!
The next step is to establish the relationships between these by setting up our foreign keys. Happily, we thought about this and planned these way back when creating our ERD, so now we just need to put them into the correct syntax and update our tables using the ALTER TABLE statement.
ALTER TABLE participantADD FOREIGN KEY(client)REFERENCES client(client_id)ON DELETE SET NULL;ALTER TABLE courseADD FOREIGN KEY(teacher)REFERENCES teacher(teacher_id)ON DELETE SET NULL;ALTER TABLE courseADD FOREIGN KEY(client)REFERENCES client(client_id)ON DELETE SET NULL;
Note that these can be added during the CREATE TABLE step, but that calls for greater planning in the order of our statements, as we can’t create a relation between tables in MySQL until both tables are created. Using ALTER TABLE after the initial table creation helps us to keep these steps separated and can be a little more forgiving, but both methods are useful to know.
Let’s take a closer look at the first of these commands to see what we’re doing here:
ALTER TABLE participantADD FOREIGN KEY(client)REFERENCES client(client_id)ON DELETE SET NULL;
Here, we are updating the participant table, and creating a relationship (ADD FOREIGN KEY) where the attribute/column client on the participant table references the client_id attribute/column on the client table, exactly as we planned. This establishes the relationship between these tables and makes our database into a relational database. Hooray!
We also have a new constraint here — ON DELETE SET NULL. This tells MySQL what we want to do when a record in the client table is deleted — in this case the value of the client attribute for that participant will be set to NULL, but the record will remain in the participants table. The other option is ON DELETE CASCADE. If we used this here then when a record is deleted from the client table all participants linked to that client via this foreign key relationship would also be deleted.
ON DELETE SET NULL is the more conservative option here, but there are good reasons to go with ON DELETE CASCADE in many circumstances. Again, this is part of database design, considering the implications of this type of decision on your database. When we’re dealing with bigger databases then these decisions will also have effects on the performance of the database, which we also need to factor in to our decision-making.
If you remember, way back in part 1 when we were designing our database and creating our ERD, the last point we looked at was the many-to-many relationship between participants and courses. This relationship is different from the 1-to-N relationships we have encountered so far, and as such needs to be handled differently in our database.
In a 1-to-N relationship such as that between our Teacher and Course tables, it is enough to add a foreign key to the entity on the N side of the relationship. We did this above where we referenced the teacher column of our course table to the teacher_id column on our teacher table.
ALTER TABLE courseADD FOREIGN KEY(teacher)REFERENCES teacher(teacher_id)ON DELETE SET NULL;
This means that any course can only be taught by one teacher, but that a teacher may teach many courses. The foreign key perfectly enables us to capture this relationship in our database.
In the case of participants and courses, however, this won’t work. A course may be taken by multiple participants, and a participant may take multiple courses. Adding a foreign key to one, or even both, of these tables wouldn’t capture every way in which these are related without creating multiple copies of our records.
To capture an N-to-M relationship in a relational database we must create another table which connects the primary keys of the entities involved in the relationship, along with any other useful information that it makes sense to store here.
For our case, we will create a new table called takes_course:
This is our first composite key! We have set the two columns participant_id and course_id together to be the primary key for this table, as only this combination will be unique. Note that each of these is the primary key in their respective table. It is necessary that the attributes we use in this table uniquely identify the records in the respective tables, so the primary key column (or columns) is usually the best choice for this.
We are only using these two columns, as we don’t have any additional data to store here. That may not always be the case — for example we may have a table for customers and a table for salespeople, and we might like to store the total sales by each salesperson to each customer on the table that captures their relationship. That would be entirely valid and possible, but in our example all we are interested in is the fact that the participant takes the course, all the other details regarding the participant and the course are more logically stored in their respective tables.
Let’s create the table! This time we will add the constraints at the same time, as all our other tables already exist.
CREATE TABLE takes_course ( participant_id INT, course_id INT, PRIMARY KEY(participant_id, course_id), FOREIGN KEY(participant_id) REFERENCES participant(participant_id) ON DELETE CASCADE, FOREIGN KEY(course_id) REFERENCES course(course_id) ON DELETE CASCADE);
Here we have set the two columns participant_id and course_id as the primary key by including them in parentheses, separated by a comma. This is how we create a composite key in MySQL.
Also notice that this time we have used ON DELETE CASCADE. This makes sense here as if a participant is deleted from the database, we don’t need to continue to store the courses they are taking, and likewise if a course is deleted we no longer need to store the participants taking that course.
Now we have all of our tables created in a fully functioning relational database. Really great work.
Now we have our database ready, the relationships are defined and it’s waiting to get into action. We just need to add the teachers, courses, clients and participants and we have ourselves a fully-functioning relational database, which we have built from the ground up!
To populate our tables with data, we need to use the INSERT INTO statement, followed by the data we wish to insert in parentheses. For example, to populate the first row of our Teachers table, we would use the following statement:
INSERT INTO teacher VALUES(1, 'James', 'Smith', 'ENG', NULL, '1985-04-20', 12345, '+491774553676');
Which gives the following output:
The syntax here is INSERT INTO table VALUES (data we want to insert, separated by commas). It is essential that we have a value (or a NULL value) for every attribute of the record (every column of the table), or MySQL will give us an error. They also need to be in the same order as the columns in the table, and follow any constraints we have placed on the columns (i.e. no NULL values in columns set as NOT NULL, no duplicates in columns set as UNIQUE).
We can insert multiple records by including the values in a list, separated by commas, as so:
INSERT INTO teacher VALUES(1, 'James', 'Smith', 'ENG', NULL, '1985-04-20', 12345, '+491774553676'),(2, 'Stefanie', 'Martin', 'FRA', NULL, '1970-02-17', 23456, '+491234567890'), (3, 'Steve', 'Wang', 'MAN', 'ENG', '1990-11-12', 34567, '+447840921333');
It is also possible to perform a partial insert by specifying the columns we wish to populate, as below:
INSERT INTO teacher (teacher_id, first_name, last_name, language_1)VALUES (2, 'Stefanie', 'Martin', 'FRA');
Running this statement gives us:
Notice we’re using the SELECT statement to retrieve the contents of our table. This is one of the most important statements in SQL, and we will use it all the time, any time we want to retrieve data from our database.
The format here is:
SELECT *FROM teacher;
In this case SELECT * means ‘select all columns’. We could also enterSELECT teacher_id, last_name, tax_id, for example, if we were only interested in retrieving those columns.
Before we populate the rest of our data, let’s see how we can delete records from our table. We do this using the DELETE FROM statement. We need to be very careful here, as if we don’t include a condition clause (using WHERE) with our DELETE FROM statement we can delete all the data in our table.
DELETE FROM teacher WHERE teacher_id = 2;
This will delete all records where the condition ‘teacher_id = 2’ is satisfied, so just the record we created for Stefanie Martin a moment ago. Sure enough:
This is our first time seeing the WHERE clause. As we use SQL, we will find more and more uses for this, in SELECT statements, as well as DELETE and UPDATE statements. We will explore this more thoroughly in part 3 of this guide.
We can also make changes to records using the UPDATE clause. This uses syntax UPDATE table SET column_1 = value_1, column_2 = value_2, WHERE condition.
In our table, perhaps James Smith gets married and wants to take his wife’s last name. We can use the following statement in MySQL to make that change:
UPDATE teacherSET last_name = 'Jones'WHERE teacher_id = 1;
Remember that WHERE clause, or we’ll change every last name in the table to Jones! Running this statement will give us:
Now we have covered each of the CRUD functions — Creating, Reading, Updating and Deleting. We are well on our way to being able to do whatever we need to with databases!
Now that we’ve seen how to INSERT, DELETE and UPDATE records, let’s go ahead and put the rest of our data into our database. You can see the data set we will be importing in Excel format in this GitHub repository, along with all the SQL code we have used (plus a little that we haven’t) in a .SQL file there.
Here is the necessary MySQL code to populate the database with the values (remember to delete the entry for James Jones in the teacher table first!):
INSERT INTO teacher VALUES(1, 'James', 'Smith', 'ENG', NULL, '1985-04-20', 12345, '+491774553676'),(2, 'Stefanie', 'Martin', 'FRA', NULL, '1970-02-17', 23456, '+491234567890'), (3, 'Steve', 'Wang', 'MAN', 'ENG', '1990-11-12', 34567, '+447840921333'),(4, 'Friederike', 'Müller-Rossi', 'DEU', 'ITA', '1987-07-07', 45678, '+492345678901'),(5, 'Isobel', 'Ivanova', 'RUS', 'ENG', '1963-05-30', 56789, '+491772635467'),(6, 'Niamh', 'Murphy', 'ENG', 'IRI', '1995-09-08', 67890, '+491231231232');INSERT INTO client VALUES(101, 'Big Business Federation', '123 Falschungstraße, 10999 Berlin', 'NGO'),(102, 'eCommerce GmbH', '27 Ersatz Allee, 10317 Berlin', 'Retail'),(103, 'AutoMaker AG', '20 Künstlichstraße, 10023 Berlin', 'Auto'),(104, 'Banko Bank', '12 Betrugstraße, 12345 Berlin', 'Banking'),(105, 'WeMoveIt GmbH', '138 Arglistweg, 10065 Berlin', 'Logistics');INSERT INTO participant VALUES(101, 'Marina', 'Berg','491635558182', 101),(102, 'Andrea', 'Duerr', '49159555740', 101),(103, 'Philipp', 'Probst', '49155555692', 102),(104, 'René', 'Brandt', '4916355546', 102),(105, 'Susanne', 'Shuster', '49155555779', 102),(106, 'Christian', 'Schreiner', '49162555375', 101),(107, 'Harry', 'Kim', '49177555633', 101),(108, 'Jan', 'Nowak', '49151555824', 101),(109, 'Pablo', 'Garcia', '49162555176', 101),(110, 'Melanie', 'Dreschler', '49151555527', 103),(111, 'Dieter', 'Durr', '49178555311', 103),(112, 'Max', 'Mustermann', '49152555195', 104),(113, 'Maxine', 'Mustermann', '49177555355', 104),(114, 'Heiko', 'Fleischer', '49155555581', 105);INSERT INTO course VALUES(12, 'English for Logistics', 'ENG', 'A1', 10, '2020-02-01', TRUE, 1, 105),(13, 'Beginner English', 'ENG', 'A2', 40, '2019-11-12', FALSE, 6, 101),(14, 'Intermediate English', 'ENG', 'B2', 40, '2019-11-12', FALSE, 6, 101),(15, 'Advanced English', 'ENG', 'C1', 40, '2019-11-12', FALSE, 6, 101),(16, 'Mandarin für Autoindustrie', 'MAN', 'B1', 15, '2020-01-15', TRUE, 3, 103),(17, 'Français intermédiaire', 'FRA', 'B1', 18, '2020-04-03', FALSE, 2, 101),(18, 'Deutsch für Anfänger', 'DEU', 'A2', 8, '2020-02-14', TRUE, 4, 102),(19, 'Intermediate English', 'ENG', 'B2', 10, '2020-03-29', FALSE, 1, 104),(20, 'Fortgeschrittenes Russisch', 'RUS', 'C1', 4, '2020-04-08', FALSE, 5, 103);INSERT INTO takes_course VALUES(101, 15),(101, 17),(102, 17),(103, 18),(104, 18),(105, 18),(106, 13),(107, 13),(108, 13),(109, 14),(109, 15),(110, 16),(110, 20),(111, 16),(114, 12),(112, 19),(113, 19);
Nice! Now all of our tables have been populated with the data, all the relationships between the data have been defined and implemented, all the attributes have appropriate data types and constraints and the database is ready for use. Fantastic work!
In this article, we have gone from having a plan for a database, with ERD ready to go, to having a fully implemented and populated database in MySQL. We have chosen our data types, defined all our fields, created our tables and defined the relationships between them using MySQL code.
The next step is to start analysing that data. Stick around for part 3 of this guide — Data Analysis in MySQL — Operators, Joins and More in Relational Databases — to see a good selection of the powerful tools available in MySQL for extracting, manipulating and updating the data in our newly-created database.
Thanks very much for taking the time to come with me on this journey. I always welcome your feedback — please get in touch with me via my website and let me know how I could have done this more effectively! I am always open to constructive criticism, or any of your comments.
Until next time!
|
[
{
"code": null,
"e": 517,
"s": 172,
"text": "This is part 2 of a 3-part series taking you through the process of designing, coding, implementing and querying a relational database, starting from zero. See part 1 (Designing a Relational Database and Creating an Entity Relationship Diagram) here, and part 3 (Data Analysis in MySQL — Operators, Joins and More in Relational Databases) here."
},
{
"code": null,
"e": 675,
"s": 517,
"text": "All the code and information for this tutorial can be found on the associated GitHub repository. I used Lucidchart to make the diagrams shown in the article."
},
{
"code": null,
"e": 1051,
"s": 675,
"text": "In part 1 of this series, we covered going from conception of the database to making a plan, and finally creating an Entity Relationship Diagram spelling out the relationships that we will need to model using our SQL code. We covered the basics of Relational Database theory, and talked about primary keys, foreign keys, cardinality and a lot of other really useful material."
},
{
"code": null,
"e": 1196,
"s": 1051,
"text": "It’s a good idea to read that before starting this article, but you can also read this one on its own if you prefer to dive right into the code."
},
{
"code": null,
"e": 1308,
"s": 1196,
"text": "Alright! Now we’re about to get to the real fun stuff, actually creating and populating our database using SQL."
},
{
"code": null,
"e": 1546,
"s": 1308,
"text": "Before we dive into this, we will need to get MySQL Community Server set up on our system, if it isn’t already. The installation is a little more complex than installing a typical application (at least on Windows!), but we can handle it."
},
{
"code": null,
"e": 1862,
"s": 1546,
"text": "First go to the download page and get the installer for your system. If you are using Windows, this guide will help you get set up. Here are guides for Mac and Linux users too (although it may vary by Linux distribution). A full walk-through is beyond the scope of this article, but you can do it. I believe in you!"
},
{
"code": null,
"e": 1956,
"s": 1862,
"text": "Once you get this set up, we can do everything that follows in the MySQL command line client."
},
{
"code": null,
"e": 2104,
"s": 1956,
"text": "The command line client is great and powerful, and essential to learn. Sometimes it’s nice to make our lives easier by using a GUI client, however."
},
{
"code": null,
"e": 2387,
"s": 2104,
"text": "PopSQL is a good GUI application for SQL, which makes things look a little nicer, as well as providing very useful features like the ability to look over your database schema in the left-hand navigation window, alongside some basic data visualisation and convenient export features."
},
{
"code": null,
"e": 2745,
"s": 2387,
"text": "For professional use there is a fee, but there is also a free tier that will definitely be enough for learning and playing around with SQL. There are lots of other GUI options out there as well, so give them a try if an alternative sounds appealing. We’ll be using PopSQL for the rest of this article however, so that’s where the screenshots will come from."
},
{
"code": null,
"e": 3249,
"s": 2745,
"text": "To answer any further questions about the SQL statements we use here, the best step is to look at the MySQL documentation. This is the official resource produced by the developers and contains detailed and comprehensive information. While it might seem intimidating to begin with, reading the documentation is a great habit to get into. Just search for the statement or topic of interest and see what comes out. As with all things code-related, google (or a search engine of your choice) is your friend!"
},
{
"code": null,
"e": 3726,
"s": 3249,
"text": "Once we have our environment set up, we need to create a database on our MySQL server. This is not too complicated, we just have to use the CREATE DATABASE statement. Note that all SQL statements are closed with a semicolon ‘;’. This lets the client know that this is the end of our statement, which is especially useful when writing longer and more complex statements, like nested queries, but is essential for all statements (except the USE command, which we will see next)."
},
{
"code": null,
"e": 3750,
"s": 3726,
"text": "CREATE DATABASE school;"
},
{
"code": null,
"e": 3822,
"s": 3750,
"text": "Nice! We just created a database with the name school. Incredible work."
},
{
"code": null,
"e": 3988,
"s": 3822,
"text": "Next time we log into MySQL command line client, we will need to enter our password and then choose which database we want to use. To do this we use the use command:"
},
{
"code": null,
"e": 3999,
"s": 3988,
"text": "USE school"
},
{
"code": null,
"e": 4100,
"s": 3999,
"text": "As simple as that. If we are using GUI software we don’t normally have to take this step every time."
},
{
"code": null,
"e": 4558,
"s": 4100,
"text": "Note that by convention we put the keywords (like SELECT, DELETE and CREATE DATABASE) in upper case, and the rest of the code in lower case. SQL is actually case insensitive so the code works perfectly well all in lower case or all in upper case (or in mOcKiNg SpOnGeBoB meme style if you really have to). This convention is for the humans who will read your code later, and it’s strongly recommended to follow this practice when writing any flavour of SQL."
},
{
"code": null,
"e": 4991,
"s": 4558,
"text": "Building our database is going to be hugely simplified by the work we have already done creating our ERD and defining the entities (which will be created in our database as tables) and their relationships. The final step we need to take before creating the tables in SQL is plan which data type each attribute will need to have. This has to be declared when creating the table, so we need to think about it before we take that step."
},
{
"code": null,
"e": 5150,
"s": 4991,
"text": "MySQL supports a wide range of data types, from simple integers and strings to BLOBs and JSONs. We will just be using a small subset of these in our database."
},
{
"code": null,
"e": 5184,
"s": 5150,
"text": "We’re going to use the following;"
},
{
"code": null,
"e": 5309,
"s": 5184,
"text": "INT — this is an integer, a whole number. We’re mainly going to use this for our ID fields (which will be our primary keys)."
},
{
"code": null,
"e": 5646,
"s": 5309,
"text": "VARCHAR — this is a string field of varying length, which we will use for storing text. We need to tell the RDBMS how long the VARCHAR will be, so we can define VARCHAR(20), for example, which will store up to 20 characters, or VARCHAR(60), which will store up to 60. Larger strings allow us to store more data, but take up more memory."
},
{
"code": null,
"e": 5704,
"s": 5646,
"text": "DATE — this is a date field, stored in YYYY-MM-DD format."
},
{
"code": null,
"e": 5903,
"s": 5704,
"text": "BOOLEAN — technically MySQL doesn’t store boolean (true / false) values, but it does allow them to be stored using what it calls ‘boolean literals’, which it evaluates to 1 for true and 0 for false."
},
{
"code": null,
"e": 5983,
"s": 5903,
"text": "With this in mind, we can start defining appropriate data types for our tables."
},
{
"code": null,
"e": 6393,
"s": 5983,
"text": "Here we have defined our teacher_id as an INT, first_name and last_name as VARCHAR(40), language_1 and language_2 as VARCHAR(3), dob as a DATE, tax_id as INT and phone_no as VARCHAR(20). It’s perfectly possible to choose different values or even different data types (perhaps the tax_id in your country includes text characters? Then an INT won’t work for you), this is all part of the art of database design."
},
{
"code": null,
"e": 6463,
"s": 6393,
"text": "To create this table in our database, we will use the following code:"
},
{
"code": null,
"e": 6696,
"s": 6463,
"text": "CREATE TABLE teacher ( teacher_id INT PRIMARY KEY, first_name VARCHAR(40) NOT NULL, last_name VARCHAR(40) NOT NULL, language_1 VARCHAR(3) NOT NULL, language_2 VARCHAR(3), dob DATE, tax_id INT UNIQUE, phone_no VARCHAR(20) );"
},
{
"code": null,
"e": 6874,
"s": 6696,
"text": "The SQL statement we use here is simply CREATE TABLE. This is followed by the name we want to give the table, then parentheses and the attribute names and associated data types."
},
{
"code": null,
"e": 7080,
"s": 6874,
"text": "We have also added some constraints to some of the attributes in our table. Contraints specify rules for data in a table, and will constrain what the RDBMS will allow us to do to that particular attribute."
},
{
"code": null,
"e": 7465,
"s": 7080,
"text": "We have added NOT NULL to first_name, last_name and language_1 — this means that the table will not accept a record where any of those attributes are set to NULL. Those attributes require a non-NULL value for every record. This makes sense, as our teachers will require a first name and last name, and to teach in a language school they need to be able to offer at least one language."
},
{
"code": null,
"e": 7751,
"s": 7465,
"text": "We have also set tax_id to be UNIQUE. This means that every record must have a different value for this attribute, which makes sense for a tax ID number, but would not make sense for our language_1 field, for example — we will likely have multiple teachers who offer the same language!"
},
{
"code": null,
"e": 8023,
"s": 7751,
"text": "We have also set the teacher_id field as our PRIMARY KEY. In practice this is really just a combination of NOT NULL and UNIQUE, but it is important to define one primary key (which again, can be a single attribute or a combination of different attributes) for each table."
},
{
"code": null,
"e": 8398,
"s": 8023,
"text": "If we now try to use a SELECT * FROM table statement to see what data is in our table (we will go over this statement in more detail in part 3), we should receive ‘Empty set’ as our response (in MySQL command line client) or ‘No results found’ (in PopSQL). This shows us our table exists (otherwise we would receive an error), but is still empty. Exactly as we would expect!"
},
{
"code": null,
"e": 8457,
"s": 8398,
"text": "Now that we have created our first table, let’s delete it!"
},
{
"code": null,
"e": 8790,
"s": 8457,
"text": "The passion for destruction is a creative passion, too. A good way to understand how easy it is to delete something in MySQL (and why I was so concerned about doing that accidentally in the past) is to go ahead and do it. This is also the best way to overcome those concerns, as it is in fact relatively difficult to do by accident."
},
{
"code": null,
"e": 8832,
"s": 8790,
"text": "The relevant SQL statement is DROP TABLE."
},
{
"code": null,
"e": 8852,
"s": 8832,
"text": "DROP TABLE teacher;"
},
{
"code": null,
"e": 8886,
"s": 8852,
"text": "Go ahead, do it! It’s liberating!"
},
{
"code": null,
"e": 9287,
"s": 8886,
"text": "Notice that there is no helpful ‘are you sure you want to do this?’ dialog box which pops up. There is also no undo button, just a simple ‘Query OK’ or ‘Success’ message, and the table is gone. This is also the case when the table contains data. So SQL is a very powerful language, but it can be unforgiving. Make sure you’ve thought through what you’re doing when you’re deleting or updating tables!"
},
{
"code": null,
"e": 9370,
"s": 9287,
"text": "Don’t forget to reinstate the Teacher table before moving on to the next sections."
},
{
"code": null,
"e": 9634,
"s": 9370,
"text": "Here we’re using the same data types again, the only new one is BOOLEAN for in_school. This is going to be TRUE if the class takes place on the premises of the International Language School, and FALSE if it take place elsewhere, i.e. at the offices of the client."
},
{
"code": null,
"e": 9681,
"s": 9634,
"text": "The code to create these tables is as follows:"
},
{
"code": null,
"e": 10210,
"s": 9681,
"text": "CREATE TABLE client ( client_id INT PRIMARY KEY, client_name VARCHAR(40) NOT NULL, address VARCHAR(60) NOT NULL, industry VARCHAR(20));CREATE TABLE participant ( participant_id INT PRIMARY KEY, first_name VARCHAR(40) NOT NULL, last_name VARCHAR(40) NOT NULL, phone_no VARCHAR(20), client INT);CREATE TABLE course ( course_id INT PRIMARY KEY, course_name VARCHAR(40) NOT NULL, language VARCHAR(3) NOT NULL, level VARCHAR(2), course_length_weeks INT, start_date DATE, in_school BOOLEAN, teacher INT, client INT);"
},
{
"code": null,
"e": 10263,
"s": 10210,
"text": "Now we have a table for each of our entities, great!"
},
{
"code": null,
"e": 10549,
"s": 10263,
"text": "The next step is to establish the relationships between these by setting up our foreign keys. Happily, we thought about this and planned these way back when creating our ERD, so now we just need to put them into the correct syntax and update our tables using the ALTER TABLE statement."
},
{
"code": null,
"e": 10822,
"s": 10549,
"text": "ALTER TABLE participantADD FOREIGN KEY(client)REFERENCES client(client_id)ON DELETE SET NULL;ALTER TABLE courseADD FOREIGN KEY(teacher)REFERENCES teacher(teacher_id)ON DELETE SET NULL;ALTER TABLE courseADD FOREIGN KEY(client)REFERENCES client(client_id)ON DELETE SET NULL;"
},
{
"code": null,
"e": 11197,
"s": 10822,
"text": "Note that these can be added during the CREATE TABLE step, but that calls for greater planning in the order of our statements, as we can’t create a relation between tables in MySQL until both tables are created. Using ALTER TABLE after the initial table creation helps us to keep these steps separated and can be a little more forgiving, but both methods are useful to know."
},
{
"code": null,
"e": 11283,
"s": 11197,
"text": "Let’s take a closer look at the first of these commands to see what we’re doing here:"
},
{
"code": null,
"e": 11377,
"s": 11283,
"text": "ALTER TABLE participantADD FOREIGN KEY(client)REFERENCES client(client_id)ON DELETE SET NULL;"
},
{
"code": null,
"e": 11727,
"s": 11377,
"text": "Here, we are updating the participant table, and creating a relationship (ADD FOREIGN KEY) where the attribute/column client on the participant table references the client_id attribute/column on the client table, exactly as we planned. This establishes the relationship between these tables and makes our database into a relational database. Hooray!"
},
{
"code": null,
"e": 12218,
"s": 11727,
"text": "We also have a new constraint here — ON DELETE SET NULL. This tells MySQL what we want to do when a record in the client table is deleted — in this case the value of the client attribute for that participant will be set to NULL, but the record will remain in the participants table. The other option is ON DELETE CASCADE. If we used this here then when a record is deleted from the client table all participants linked to that client via this foreign key relationship would also be deleted."
},
{
"code": null,
"e": 12643,
"s": 12218,
"text": "ON DELETE SET NULL is the more conservative option here, but there are good reasons to go with ON DELETE CASCADE in many circumstances. Again, this is part of database design, considering the implications of this type of decision on your database. When we’re dealing with bigger databases then these decisions will also have effects on the performance of the database, which we also need to factor in to our decision-making."
},
{
"code": null,
"e": 12983,
"s": 12643,
"text": "If you remember, way back in part 1 when we were designing our database and creating our ERD, the last point we looked at was the many-to-many relationship between participants and courses. This relationship is different from the 1-to-N relationships we have encountered so far, and as such needs to be handled differently in our database."
},
{
"code": null,
"e": 13267,
"s": 12983,
"text": "In a 1-to-N relationship such as that between our Teacher and Course tables, it is enough to add a foreign key to the entity on the N side of the relationship. We did this above where we referenced the teacher column of our course table to the teacher_id column on our teacher table."
},
{
"code": null,
"e": 13359,
"s": 13267,
"text": "ALTER TABLE courseADD FOREIGN KEY(teacher)REFERENCES teacher(teacher_id)ON DELETE SET NULL;"
},
{
"code": null,
"e": 13547,
"s": 13359,
"text": "This means that any course can only be taught by one teacher, but that a teacher may teach many courses. The foreign key perfectly enables us to capture this relationship in our database."
},
{
"code": null,
"e": 13869,
"s": 13547,
"text": "In the case of participants and courses, however, this won’t work. A course may be taken by multiple participants, and a participant may take multiple courses. Adding a foreign key to one, or even both, of these tables wouldn’t capture every way in which these are related without creating multiple copies of our records."
},
{
"code": null,
"e": 14110,
"s": 13869,
"text": "To capture an N-to-M relationship in a relational database we must create another table which connects the primary keys of the entities involved in the relationship, along with any other useful information that it makes sense to store here."
},
{
"code": null,
"e": 14172,
"s": 14110,
"text": "For our case, we will create a new table called takes_course:"
},
{
"code": null,
"e": 14609,
"s": 14172,
"text": "This is our first composite key! We have set the two columns participant_id and course_id together to be the primary key for this table, as only this combination will be unique. Note that each of these is the primary key in their respective table. It is necessary that the attributes we use in this table uniquely identify the records in the respective tables, so the primary key column (or columns) is usually the best choice for this."
},
{
"code": null,
"e": 15189,
"s": 14609,
"text": "We are only using these two columns, as we don’t have any additional data to store here. That may not always be the case — for example we may have a table for customers and a table for salespeople, and we might like to store the total sales by each salesperson to each customer on the table that captures their relationship. That would be entirely valid and possible, but in our example all we are interested in is the fact that the participant takes the course, all the other details regarding the participant and the course are more logically stored in their respective tables."
},
{
"code": null,
"e": 15308,
"s": 15189,
"text": "Let’s create the table! This time we will add the constraints at the same time, as all our other tables already exist."
},
{
"code": null,
"e": 15574,
"s": 15308,
"text": "CREATE TABLE takes_course ( participant_id INT, course_id INT, PRIMARY KEY(participant_id, course_id), FOREIGN KEY(participant_id) REFERENCES participant(participant_id) ON DELETE CASCADE, FOREIGN KEY(course_id) REFERENCES course(course_id) ON DELETE CASCADE);"
},
{
"code": null,
"e": 15759,
"s": 15574,
"text": "Here we have set the two columns participant_id and course_id as the primary key by including them in parentheses, separated by a comma. This is how we create a composite key in MySQL."
},
{
"code": null,
"e": 16054,
"s": 15759,
"text": "Also notice that this time we have used ON DELETE CASCADE. This makes sense here as if a participant is deleted from the database, we don’t need to continue to store the courses they are taking, and likewise if a course is deleted we no longer need to store the participants taking that course."
},
{
"code": null,
"e": 16155,
"s": 16054,
"text": "Now we have all of our tables created in a fully functioning relational database. Really great work."
},
{
"code": null,
"e": 16425,
"s": 16155,
"text": "Now we have our database ready, the relationships are defined and it’s waiting to get into action. We just need to add the teachers, courses, clients and participants and we have ourselves a fully-functioning relational database, which we have built from the ground up!"
},
{
"code": null,
"e": 16656,
"s": 16425,
"text": "To populate our tables with data, we need to use the INSERT INTO statement, followed by the data we wish to insert in parentheses. For example, to populate the first row of our Teachers table, we would use the following statement:"
},
{
"code": null,
"e": 16757,
"s": 16656,
"text": "INSERT INTO teacher VALUES(1, 'James', 'Smith', 'ENG', NULL, '1985-04-20', 12345, '+491774553676');"
},
{
"code": null,
"e": 16791,
"s": 16757,
"text": "Which gives the following output:"
},
{
"code": null,
"e": 17247,
"s": 16791,
"text": "The syntax here is INSERT INTO table VALUES (data we want to insert, separated by commas). It is essential that we have a value (or a NULL value) for every attribute of the record (every column of the table), or MySQL will give us an error. They also need to be in the same order as the columns in the table, and follow any constraints we have placed on the columns (i.e. no NULL values in columns set as NOT NULL, no duplicates in columns set as UNIQUE)."
},
{
"code": null,
"e": 17341,
"s": 17247,
"text": "We can insert multiple records by including the values in a list, separated by commas, as so:"
},
{
"code": null,
"e": 17597,
"s": 17341,
"text": "INSERT INTO teacher VALUES(1, 'James', 'Smith', 'ENG', NULL, '1985-04-20', 12345, '+491774553676'),(2, 'Stefanie', 'Martin', 'FRA', NULL, '1970-02-17', 23456, '+491234567890'), (3, 'Steve', 'Wang', 'MAN', 'ENG', '1990-11-12', 34567, '+447840921333');"
},
{
"code": null,
"e": 17702,
"s": 17597,
"text": "It is also possible to perform a partial insert by specifying the columns we wish to populate, as below:"
},
{
"code": null,
"e": 17812,
"s": 17702,
"text": "INSERT INTO teacher (teacher_id, first_name, last_name, language_1)VALUES (2, 'Stefanie', 'Martin', 'FRA');"
},
{
"code": null,
"e": 17845,
"s": 17812,
"text": "Running this statement gives us:"
},
{
"code": null,
"e": 18063,
"s": 17845,
"text": "Notice we’re using the SELECT statement to retrieve the contents of our table. This is one of the most important statements in SQL, and we will use it all the time, any time we want to retrieve data from our database."
},
{
"code": null,
"e": 18083,
"s": 18063,
"text": "The format here is:"
},
{
"code": null,
"e": 18105,
"s": 18083,
"text": "SELECT *FROM teacher;"
},
{
"code": null,
"e": 18281,
"s": 18105,
"text": "In this case SELECT * means ‘select all columns’. We could also enterSELECT teacher_id, last_name, tax_id, for example, if we were only interested in retrieving those columns."
},
{
"code": null,
"e": 18579,
"s": 18281,
"text": "Before we populate the rest of our data, let’s see how we can delete records from our table. We do this using the DELETE FROM statement. We need to be very careful here, as if we don’t include a condition clause (using WHERE) with our DELETE FROM statement we can delete all the data in our table."
},
{
"code": null,
"e": 18621,
"s": 18579,
"text": "DELETE FROM teacher WHERE teacher_id = 2;"
},
{
"code": null,
"e": 18778,
"s": 18621,
"text": "This will delete all records where the condition ‘teacher_id = 2’ is satisfied, so just the record we created for Stefanie Martin a moment ago. Sure enough:"
},
{
"code": null,
"e": 19008,
"s": 18778,
"text": "This is our first time seeing the WHERE clause. As we use SQL, we will find more and more uses for this, in SELECT statements, as well as DELETE and UPDATE statements. We will explore this more thoroughly in part 3 of this guide."
},
{
"code": null,
"e": 19160,
"s": 19008,
"text": "We can also make changes to records using the UPDATE clause. This uses syntax UPDATE table SET column_1 = value_1, column_2 = value_2, WHERE condition."
},
{
"code": null,
"e": 19312,
"s": 19160,
"text": "In our table, perhaps James Smith gets married and wants to take his wife’s last name. We can use the following statement in MySQL to make that change:"
},
{
"code": null,
"e": 19371,
"s": 19312,
"text": "UPDATE teacherSET last_name = 'Jones'WHERE teacher_id = 1;"
},
{
"code": null,
"e": 19491,
"s": 19371,
"text": "Remember that WHERE clause, or we’ll change every last name in the table to Jones! Running this statement will give us:"
},
{
"code": null,
"e": 19661,
"s": 19491,
"text": "Now we have covered each of the CRUD functions — Creating, Reading, Updating and Deleting. We are well on our way to being able to do whatever we need to with databases!"
},
{
"code": null,
"e": 19970,
"s": 19661,
"text": "Now that we’ve seen how to INSERT, DELETE and UPDATE records, let’s go ahead and put the rest of our data into our database. You can see the data set we will be importing in Excel format in this GitHub repository, along with all the SQL code we have used (plus a little that we haven’t) in a .SQL file there."
},
{
"code": null,
"e": 20120,
"s": 19970,
"text": "Here is the necessary MySQL code to populate the database with the values (remember to delete the entry for James Jones in the teacher table first!):"
},
{
"code": null,
"e": 22586,
"s": 20120,
"text": "INSERT INTO teacher VALUES(1, 'James', 'Smith', 'ENG', NULL, '1985-04-20', 12345, '+491774553676'),(2, 'Stefanie', 'Martin', 'FRA', NULL, '1970-02-17', 23456, '+491234567890'), (3, 'Steve', 'Wang', 'MAN', 'ENG', '1990-11-12', 34567, '+447840921333'),(4, 'Friederike', 'Müller-Rossi', 'DEU', 'ITA', '1987-07-07', 45678, '+492345678901'),(5, 'Isobel', 'Ivanova', 'RUS', 'ENG', '1963-05-30', 56789, '+491772635467'),(6, 'Niamh', 'Murphy', 'ENG', 'IRI', '1995-09-08', 67890, '+491231231232');INSERT INTO client VALUES(101, 'Big Business Federation', '123 Falschungstraße, 10999 Berlin', 'NGO'),(102, 'eCommerce GmbH', '27 Ersatz Allee, 10317 Berlin', 'Retail'),(103, 'AutoMaker AG', '20 Künstlichstraße, 10023 Berlin', 'Auto'),(104, 'Banko Bank', '12 Betrugstraße, 12345 Berlin', 'Banking'),(105, 'WeMoveIt GmbH', '138 Arglistweg, 10065 Berlin', 'Logistics');INSERT INTO participant VALUES(101, 'Marina', 'Berg','491635558182', 101),(102, 'Andrea', 'Duerr', '49159555740', 101),(103, 'Philipp', 'Probst', '49155555692', 102),(104, 'René', 'Brandt', '4916355546', 102),(105, 'Susanne', 'Shuster', '49155555779', 102),(106, 'Christian', 'Schreiner', '49162555375', 101),(107, 'Harry', 'Kim', '49177555633', 101),(108, 'Jan', 'Nowak', '49151555824', 101),(109, 'Pablo', 'Garcia', '49162555176', 101),(110, 'Melanie', 'Dreschler', '49151555527', 103),(111, 'Dieter', 'Durr', '49178555311', 103),(112, 'Max', 'Mustermann', '49152555195', 104),(113, 'Maxine', 'Mustermann', '49177555355', 104),(114, 'Heiko', 'Fleischer', '49155555581', 105);INSERT INTO course VALUES(12, 'English for Logistics', 'ENG', 'A1', 10, '2020-02-01', TRUE, 1, 105),(13, 'Beginner English', 'ENG', 'A2', 40, '2019-11-12', FALSE, 6, 101),(14, 'Intermediate English', 'ENG', 'B2', 40, '2019-11-12', FALSE, 6, 101),(15, 'Advanced English', 'ENG', 'C1', 40, '2019-11-12', FALSE, 6, 101),(16, 'Mandarin für Autoindustrie', 'MAN', 'B1', 15, '2020-01-15', TRUE, 3, 103),(17, 'Français intermédiaire', 'FRA', 'B1', 18, '2020-04-03', FALSE, 2, 101),(18, 'Deutsch für Anfänger', 'DEU', 'A2', 8, '2020-02-14', TRUE, 4, 102),(19, 'Intermediate English', 'ENG', 'B2', 10, '2020-03-29', FALSE, 1, 104),(20, 'Fortgeschrittenes Russisch', 'RUS', 'C1', 4, '2020-04-08', FALSE, 5, 103);INSERT INTO takes_course VALUES(101, 15),(101, 17),(102, 17),(103, 18),(104, 18),(105, 18),(106, 13),(107, 13),(108, 13),(109, 14),(109, 15),(110, 16),(110, 20),(111, 16),(114, 12),(112, 19),(113, 19);"
},
{
"code": null,
"e": 22837,
"s": 22586,
"text": "Nice! Now all of our tables have been populated with the data, all the relationships between the data have been defined and implemented, all the attributes have appropriate data types and constraints and the database is ready for use. Fantastic work!"
},
{
"code": null,
"e": 23122,
"s": 22837,
"text": "In this article, we have gone from having a plan for a database, with ERD ready to go, to having a fully implemented and populated database in MySQL. We have chosen our data types, defined all our fields, created our tables and defined the relationships between them using MySQL code."
},
{
"code": null,
"e": 23433,
"s": 23122,
"text": "The next step is to start analysing that data. Stick around for part 3 of this guide — Data Analysis in MySQL — Operators, Joins and More in Relational Databases — to see a good selection of the powerful tools available in MySQL for extracting, manipulating and updating the data in our newly-created database."
},
{
"code": null,
"e": 23709,
"s": 23433,
"text": "Thanks very much for taking the time to come with me on this journey. I always welcome your feedback — please get in touch with me via my website and let me know how I could have done this more effectively! I am always open to constructive criticism, or any of your comments."
}
] |
Generate a matrix product of two NumPy arrays - GeeksforGeeks
|
29 Aug, 2020
We can multiply two matrices with the function np.matmul(a,b). When we multiply two arrays of order (m*n) and (p*q ) in order to obtained matrix product then its output contains m rows and q columns where n is n==p is a necessary condition.
Syntax: numpy.matmul(x1, x2, /, out=None, *, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj])
To multiply two matrices take the row from first array and column of second array and multiply the corresponding elements. Then add the value for the final answer. Suppose there are two matrices A and B.
A = [[A00, A01],
[A10, A11]]
B = [[B00, B01],
[B10, B11]]
Then the product is calculated as shown below
A*B = [[(A00*B00 + A01*B10), (A00*B01 + A01*B11)],
[(A10*B00 + A11+B10), (A10*B01 + A11*B11)]]
Below is the implementation.
Python3
# Importing Libraryimport numpy as np # Finding the matrix productarr1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])arr2 = np.array([[11, 12, 13], [14, 15, 16], [17, 18, 19]]) matrix_product = np.matmul(arr1, arr2)print("Matrix Product is ")print(matrix_product)print() arr1 = np.array([[2,2],[3,3]])arr2 = np.array([[1,2,3],[4,5,6]]) matrix_product = np.matmul(arr1, arr2)print("Matrix Product is ")print(matrix_product)print() arr1 = np.array([[100,200],[300,400]])arr2 = np.array([[1,2],[4,6]]) matrix_product = np.matmul(arr1, arr2)print("Matrix Product is ")print(matrix_product)
Output:
Matrix Product is
[[ 90 96 102]
[216 231 246]
[342 366 390]]
Matrix Product is
[[10 14 18]
[15 21 27]]
Matrix Product is
[[ 900 1400]
[1900 3000]]
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
Selecting rows in pandas DataFrame based on conditions
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python Classes and Objects
|
[
{
"code": null,
"e": 24212,
"s": 24184,
"text": "\n29 Aug, 2020"
},
{
"code": null,
"e": 24454,
"s": 24212,
"text": "We can multiply two matrices with the function np.matmul(a,b). When we multiply two arrays of order (m*n) and (p*q ) in order to obtained matrix product then its output contains m rows and q columns where n is n==p is a necessary condition."
},
{
"code": null,
"e": 24577,
"s": 24454,
"text": "Syntax: numpy.matmul(x1, x2, /, out=None, *, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) "
},
{
"code": null,
"e": 24781,
"s": 24577,
"text": "To multiply two matrices take the row from first array and column of second array and multiply the corresponding elements. Then add the value for the final answer. Suppose there are two matrices A and B."
},
{
"code": null,
"e": 25005,
"s": 24781,
"text": "A = [[A00, A01],\n [A10, A11]]\n \nB = [[B00, B01],\n [B10, B11]]\n\nThen the product is calculated as shown below\nA*B = [[(A00*B00 + A01*B10), (A00*B01 + A01*B11)],\n [(A10*B00 + A11+B10), (A10*B01 + A11*B11)]]\n"
},
{
"code": null,
"e": 25034,
"s": 25005,
"text": "Below is the implementation."
},
{
"code": null,
"e": 25042,
"s": 25034,
"text": "Python3"
},
{
"code": "# Importing Libraryimport numpy as np # Finding the matrix productarr1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])arr2 = np.array([[11, 12, 13], [14, 15, 16], [17, 18, 19]]) matrix_product = np.matmul(arr1, arr2)print(\"Matrix Product is \")print(matrix_product)print() arr1 = np.array([[2,2],[3,3]])arr2 = np.array([[1,2,3],[4,5,6]]) matrix_product = np.matmul(arr1, arr2)print(\"Matrix Product is \")print(matrix_product)print() arr1 = np.array([[100,200],[300,400]])arr2 = np.array([[1,2],[4,6]]) matrix_product = np.matmul(arr1, arr2)print(\"Matrix Product is \")print(matrix_product)",
"e": 25665,
"s": 25042,
"text": null
},
{
"code": null,
"e": 25673,
"s": 25665,
"text": "Output:"
},
{
"code": null,
"e": 25831,
"s": 25673,
"text": "Matrix Product is \n[[ 90 96 102]\n [216 231 246]\n [342 366 390]]\n\nMatrix Product is \n[[10 14 18]\n [15 21 27]]\n\nMatrix Product is \n[[ 900 1400]\n [1900 3000]]\n"
},
{
"code": null,
"e": 25860,
"s": 25831,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 25873,
"s": 25860,
"text": "Python-numpy"
},
{
"code": null,
"e": 25880,
"s": 25873,
"text": "Python"
},
{
"code": null,
"e": 25978,
"s": 25880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25987,
"s": 25978,
"text": "Comments"
},
{
"code": null,
"e": 26000,
"s": 25987,
"text": "Old Comments"
},
{
"code": null,
"e": 26032,
"s": 26000,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26087,
"s": 26032,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 26143,
"s": 26087,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26182,
"s": 26143,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26224,
"s": 26182,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26266,
"s": 26224,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26297,
"s": 26266,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26319,
"s": 26297,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26348,
"s": 26319,
"text": "Create a directory in Python"
}
] |
How to pass arguments in Invoke-Command in PowerShell?
|
To pass the argument in the Invoke-command, you need to use -ArgumentList parameter. For example, we need to get the notepad process information on the remote server.
Invoke-Command -ComputerName Test1-Win2k12 -
ScriptBlock{param($proc) Get-Process -Name $proc} -
ArgumentList "Notepad"
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName
------- ------ ----- ----- ------ -- -- ----------- --------------
67 8 1348 7488 0.08 104 notepad Test1-Win2k12
In the above example, we are passing "Notepad" name as the argument to the command and the same has been caught by the $proc variable inside Param().
If you have the multiple, check the below command to pass the multiple parameters.
Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{param($proc,$proc2) Get-Process -Name $proc,$proc2} -ArgumentList "Notepad","Calc"
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName
------- ------ ----- ----- ------ -- -- ----------- --------------
96 20 5980 11392 0.19 288 calc Test1-Win2k12
67 8 1344 7556 0.08 104 notepad Test1-Win2k12
Same can be achieved with the Session variable.
$sess = New-PSSession -ComputerName Test1-win2k12
Invoke-Command -Session $sess -ScriptBlock{param($proc) Get-Process $proc} -ArgumentList "Notepad"
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName
------- ------ ----- ----- ------ -- -- ----------- --------------
67 8 1348 7488 0.08 104 notepad Test1-Win2k12
|
[
{
"code": null,
"e": 1229,
"s": 1062,
"text": "To pass the argument in the Invoke-command, you need to use -ArgumentList parameter. For example, we need to get the notepad process information on the remote server."
},
{
"code": null,
"e": 1349,
"s": 1229,
"text": "Invoke-Command -ComputerName Test1-Win2k12 -\nScriptBlock{param($proc) Get-Process -Name $proc} -\nArgumentList \"Notepad\""
},
{
"code": null,
"e": 1549,
"s": 1349,
"text": "Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName\n------- ------ ----- ----- ------ -- -- ----------- --------------\n 67 8 1348 7488 0.08 104 notepad Test1-Win2k12"
},
{
"code": null,
"e": 1699,
"s": 1549,
"text": "In the above example, we are passing \"Notepad\" name as the argument to the command and the same has been caught by the $proc variable inside Param()."
},
{
"code": null,
"e": 1782,
"s": 1699,
"text": "If you have the multiple, check the below command to pass the multiple parameters."
},
{
"code": null,
"e": 1921,
"s": 1782,
"text": "Invoke-Command -ComputerName Test1-Win2k12 -ScriptBlock{param($proc,$proc2) Get-Process -Name $proc,$proc2} -ArgumentList \"Notepad\",\"Calc\""
},
{
"code": null,
"e": 2185,
"s": 1921,
"text": "Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName\n------- ------ ----- ----- ------ -- -- ----------- --------------\n 96 20 5980 11392 0.19 288 calc Test1-Win2k12\n 67 8 1344 7556 0.08 104 notepad Test1-Win2k12"
},
{
"code": null,
"e": 2233,
"s": 2185,
"text": "Same can be achieved with the Session variable."
},
{
"code": null,
"e": 2382,
"s": 2233,
"text": "$sess = New-PSSession -ComputerName Test1-win2k12\nInvoke-Command -Session $sess -ScriptBlock{param($proc) Get-Process $proc} -ArgumentList \"Notepad\""
},
{
"code": null,
"e": 2582,
"s": 2382,
"text": "Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName PSComputerName\n------- ------ ----- ----- ------ -- -- ----------- --------------\n 67 8 1348 7488 0.08 104 notepad Test1-Win2k12"
}
] |
Apache Storm - Installation
|
Let us now see how to install Apache Storm framework on your machine. There are three majo steps here −
Install Java on your system, if you don’t have it already.
Install ZooKeeper framework.
Install Apache Storm framework.
Use the following command to check whether you have Java already installed on your system.
$ java -version
If Java is already there, then you would see its version number. Else, download the latest version of JDK.
Download the latest version of JDK by using the following link − www.oracle.com
The latest version is JDK 8u 60 and the file is “jdk-8u60-linux-x64.tar.gz”. Download the file on your machine.
Generally files are being downloaded onto the downloads folder. Extract the tar setup using the following commands.
$ cd /go/to/download/path
$ tar -zxf jdk-8u60-linux-x64.gz
To make Java available to all users, move the extracted java content to “/usr/local/java” folder.
$ su
password: (type password of root user)
$ mkdir /opt/jdk
$ mv jdk-1.8.0_60 /opt/jdk/
To set path and JAVA_HOME variables, add the following commands to ~/.bashrc file.
export JAVA_HOME =/usr/jdk/jdk-1.8.0_60
export PATH=$PATH:$JAVA_HOME/bin
Now apply all the changes in to the current running system.
$ source ~/.bashrc
Use the following command to change Java alternatives.
update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_60/bin/java 100
Now verify the Java installation using the verification command (java -version) explained in Step 1.
To install ZooKeeper framework on your machine, visit the following link and download the latest version of ZooKeeper http://zookeeper.apache.org/releases.html
As of now, the latest version of ZooKeeper is 3.4.6 (ZooKeeper-3.4.6.tar.gz).
Extract the tar file using the following commands −
$ cd opt/
$ tar -zxf zookeeper-3.4.6.tar.gz
$ cd zookeeper-3.4.6
$ mkdir data
Open configuration file named “conf/zoo.cfg” using the command "vi conf/zoo.cfg" and setting all the following parameters as starting point.
$ vi conf/zoo.cfg
tickTime=2000
dataDir=/path/to/zookeeper/data
clientPort=2181
initLimit=5
syncLimit=2
Once the configuration file has been saved successfully, you can start the ZooKeeper server.
Use the following command to start the ZooKeeper server.
$ bin/zkServer.sh start
After executing this command, you will get a response as follows −
$ JMX enabled by default
$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg
$ Starting zookeeper ... STARTED
Use the following command to start the CLI.
$ bin/zkCli.sh
After executing the above command, you will be connected to the ZooKeeper server and get the following response.
Connecting to localhost:2181
................
................
................
Welcome to ZooKeeper!
................
................
WATCHER::
WatchedEvent state:SyncConnected type: None path:null
[zk: localhost:2181(CONNECTED) 0]
After connecting the server and performing all the operations, you can stop the ZooKeeper server by using the following command.
bin/zkServer.sh stop
You have successfully installed Java and ZooKeeper on your machine. Let us now see the steps to install Apache Storm framework.
To install Storm framework on your machine, visit the following link and download the latest version of Storm http://storm.apache.org/downloads.html
As of now, the latest version of Storm is “apache-storm-0.9.5.tar.gz”.
Extract the tar file using the following commands −
$ cd opt/
$ tar -zxf apache-storm-0.9.5.tar.gz
$ cd apache-storm-0.9.5
$ mkdir data
The current release of Storm contains a file at “conf/storm.yaml” that configures Storm daemons. Add the following information to that file.
$ vi conf/storm.yaml
storm.zookeeper.servers:
- "localhost"
storm.local.dir: “/path/to/storm/data(any path)”
nimbus.host: "localhost"
supervisor.slots.ports:
- 6700
- 6701
- 6702
- 6703
After applying all the changes, save and return to terminal.
$ bin/storm nimbus
$ bin/storm supervisor
$ bin/storm ui
After starting Storm user interface application, type the URL http://localhost:8080 in your favorite browser and you could see Storm cluster information and its running topology. The page should look similar to the following screenshot.
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2031,
"s": 1927,
"text": "Let us now see how to install Apache Storm framework on your machine. There are three majo steps here −"
},
{
"code": null,
"e": 2090,
"s": 2031,
"text": "Install Java on your system, if you don’t have it already."
},
{
"code": null,
"e": 2119,
"s": 2090,
"text": "Install ZooKeeper framework."
},
{
"code": null,
"e": 2151,
"s": 2119,
"text": "Install Apache Storm framework."
},
{
"code": null,
"e": 2242,
"s": 2151,
"text": "Use the following command to check whether you have Java already installed on your system."
},
{
"code": null,
"e": 2259,
"s": 2242,
"text": "$ java -version\n"
},
{
"code": null,
"e": 2366,
"s": 2259,
"text": "If Java is already there, then you would see its version number. Else, download the latest version of JDK."
},
{
"code": null,
"e": 2446,
"s": 2366,
"text": "Download the latest version of JDK by using the following link − www.oracle.com"
},
{
"code": null,
"e": 2558,
"s": 2446,
"text": "The latest version is JDK 8u 60 and the file is “jdk-8u60-linux-x64.tar.gz”. Download the file on your machine."
},
{
"code": null,
"e": 2674,
"s": 2558,
"text": "Generally files are being downloaded onto the downloads folder. Extract the tar setup using the following commands."
},
{
"code": null,
"e": 2734,
"s": 2674,
"text": "$ cd /go/to/download/path\n$ tar -zxf jdk-8u60-linux-x64.gz\n"
},
{
"code": null,
"e": 2832,
"s": 2734,
"text": "To make Java available to all users, move the extracted java content to “/usr/local/java” folder."
},
{
"code": null,
"e": 2922,
"s": 2832,
"text": "$ su\npassword: (type password of root user)\n$ mkdir /opt/jdk\n$ mv jdk-1.8.0_60 /opt/jdk/\n"
},
{
"code": null,
"e": 3005,
"s": 2922,
"text": "To set path and JAVA_HOME variables, add the following commands to ~/.bashrc file."
},
{
"code": null,
"e": 3079,
"s": 3005,
"text": "export JAVA_HOME =/usr/jdk/jdk-1.8.0_60\nexport PATH=$PATH:$JAVA_HOME/bin\n"
},
{
"code": null,
"e": 3139,
"s": 3079,
"text": "Now apply all the changes in to the current running system."
},
{
"code": null,
"e": 3159,
"s": 3139,
"text": "$ source ~/.bashrc\n"
},
{
"code": null,
"e": 3214,
"s": 3159,
"text": "Use the following command to change Java alternatives."
},
{
"code": null,
"e": 3298,
"s": 3214,
"text": "update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_60/bin/java 100\n"
},
{
"code": null,
"e": 3399,
"s": 3298,
"text": "Now verify the Java installation using the verification command (java -version) explained in Step 1."
},
{
"code": null,
"e": 3559,
"s": 3399,
"text": "To install ZooKeeper framework on your machine, visit the following link and download the latest version of ZooKeeper http://zookeeper.apache.org/releases.html"
},
{
"code": null,
"e": 3637,
"s": 3559,
"text": "As of now, the latest version of ZooKeeper is 3.4.6 (ZooKeeper-3.4.6.tar.gz)."
},
{
"code": null,
"e": 3689,
"s": 3637,
"text": "Extract the tar file using the following commands −"
},
{
"code": null,
"e": 3768,
"s": 3689,
"text": "$ cd opt/\n$ tar -zxf zookeeper-3.4.6.tar.gz\n$ cd zookeeper-3.4.6\n$ mkdir data\n"
},
{
"code": null,
"e": 3909,
"s": 3768,
"text": "Open configuration file named “conf/zoo.cfg” using the command \"vi conf/zoo.cfg\" and setting all the following parameters as starting point."
},
{
"code": null,
"e": 4014,
"s": 3909,
"text": "$ vi conf/zoo.cfg\ntickTime=2000\ndataDir=/path/to/zookeeper/data\nclientPort=2181\ninitLimit=5\nsyncLimit=2\n"
},
{
"code": null,
"e": 4107,
"s": 4014,
"text": "Once the configuration file has been saved successfully, you can start the ZooKeeper server."
},
{
"code": null,
"e": 4164,
"s": 4107,
"text": "Use the following command to start the ZooKeeper server."
},
{
"code": null,
"e": 4189,
"s": 4164,
"text": "$ bin/zkServer.sh start\n"
},
{
"code": null,
"e": 4256,
"s": 4189,
"text": "After executing this command, you will get a response as follows −"
},
{
"code": null,
"e": 4377,
"s": 4256,
"text": "$ JMX enabled by default\n$ Using config: /Users/../zookeeper-3.4.6/bin/../conf/zoo.cfg\n$ Starting zookeeper ... STARTED\n"
},
{
"code": null,
"e": 4421,
"s": 4377,
"text": "Use the following command to start the CLI."
},
{
"code": null,
"e": 4437,
"s": 4421,
"text": "$ bin/zkCli.sh\n"
},
{
"code": null,
"e": 4550,
"s": 4437,
"text": "After executing the above command, you will be connected to the ZooKeeper server and get the following response."
},
{
"code": null,
"e": 4785,
"s": 4550,
"text": "Connecting to localhost:2181\n................\n................\n................\nWelcome to ZooKeeper!\n................\n................\nWATCHER::\nWatchedEvent state:SyncConnected type: None path:null\n[zk: localhost:2181(CONNECTED) 0]\n"
},
{
"code": null,
"e": 4914,
"s": 4785,
"text": "After connecting the server and performing all the operations, you can stop the ZooKeeper server by using the following command."
},
{
"code": null,
"e": 4936,
"s": 4914,
"text": "bin/zkServer.sh stop\n"
},
{
"code": null,
"e": 5064,
"s": 4936,
"text": "You have successfully installed Java and ZooKeeper on your machine. Let us now see the steps to install Apache Storm framework."
},
{
"code": null,
"e": 5213,
"s": 5064,
"text": "To install Storm framework on your machine, visit the following link and download the latest version of Storm http://storm.apache.org/downloads.html"
},
{
"code": null,
"e": 5284,
"s": 5213,
"text": "As of now, the latest version of Storm is “apache-storm-0.9.5.tar.gz”."
},
{
"code": null,
"e": 5336,
"s": 5284,
"text": "Extract the tar file using the following commands −"
},
{
"code": null,
"e": 5421,
"s": 5336,
"text": "$ cd opt/\n$ tar -zxf apache-storm-0.9.5.tar.gz\n$ cd apache-storm-0.9.5\n$ mkdir data\n"
},
{
"code": null,
"e": 5562,
"s": 5421,
"text": "The current release of Storm contains a file at “conf/storm.yaml” that configures Storm daemons. Add the following information to that file."
},
{
"code": null,
"e": 5754,
"s": 5562,
"text": "$ vi conf/storm.yaml\nstorm.zookeeper.servers:\n - \"localhost\"\nstorm.local.dir: “/path/to/storm/data(any path)”\nnimbus.host: \"localhost\"\nsupervisor.slots.ports:\n - 6700\n - 6701\n - 6702\n - 6703\n"
},
{
"code": null,
"e": 5815,
"s": 5754,
"text": "After applying all the changes, save and return to terminal."
},
{
"code": null,
"e": 5835,
"s": 5815,
"text": "$ bin/storm nimbus\n"
},
{
"code": null,
"e": 5859,
"s": 5835,
"text": "$ bin/storm supervisor\n"
},
{
"code": null,
"e": 5875,
"s": 5859,
"text": "$ bin/storm ui\n"
},
{
"code": null,
"e": 6112,
"s": 5875,
"text": "After starting Storm user interface application, type the URL http://localhost:8080 in your favorite browser and you could see Storm cluster information and its running topology. The page should look similar to the following screenshot."
},
{
"code": null,
"e": 6147,
"s": 6112,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6166,
"s": 6147,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6201,
"s": 6166,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6222,
"s": 6201,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 6255,
"s": 6222,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6268,
"s": 6255,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6303,
"s": 6268,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6321,
"s": 6303,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6354,
"s": 6321,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6372,
"s": 6354,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6405,
"s": 6372,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6423,
"s": 6405,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6430,
"s": 6423,
"text": " Print"
},
{
"code": null,
"e": 6441,
"s": 6430,
"text": " Add Notes"
}
] |
Find a value in lowercase from a MongoDB collection with documents
|
To find a value in lowercase, use the toLowerCase() method in MongoDB. Use the method in find() to find the value in lowercase.
Let us create a collection with documents −
> db.demo172.insertOne({"SubjectName":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3838ce9e4f06af551997e1")
}
> db.demo172.insertOne({"SubjectName":"mongodb"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3838d69e4f06af551997e2")
}
> db.demo172.insertOne({"SubjectName":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3838db9e4f06af551997e3")
}
Display all documents from a collection with the help of find() method −
> db.demo172.find();
This will produce the following output −
{ "_id" : ObjectId("5e3838ce9e4f06af551997e1"), "SubjectName" : "MySQL" }
{ "_id" : ObjectId("5e3838d69e4f06af551997e2"), "SubjectName" : "mongodb" }
{ "_id" : ObjectId("5e3838db9e4f06af551997e3"), "SubjectName" : "MongoDB" }
Following is the query to find a value in lowercase −
> db.demo172.find({"SubjectName":"MONGODB".toLowerCase()});
This will produce the following output −
{ "_id" : ObjectId("5e3838d69e4f06af551997e2"), "SubjectName" : "mongodb" }
|
[
{
"code": null,
"e": 1190,
"s": 1062,
"text": "To find a value in lowercase, use the toLowerCase() method in MongoDB. Use the method in find() to find the value in lowercase."
},
{
"code": null,
"e": 1234,
"s": 1190,
"text": "Let us create a collection with documents −"
},
{
"code": null,
"e": 1641,
"s": 1234,
"text": "> db.demo172.insertOne({\"SubjectName\":\"MySQL\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3838ce9e4f06af551997e1\")\n}\n> db.demo172.insertOne({\"SubjectName\":\"mongodb\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3838d69e4f06af551997e2\")\n}\n> db.demo172.insertOne({\"SubjectName\":\"MongoDB\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e3838db9e4f06af551997e3\")\n}"
},
{
"code": null,
"e": 1714,
"s": 1641,
"text": "Display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1735,
"s": 1714,
"text": "> db.demo172.find();"
},
{
"code": null,
"e": 1776,
"s": 1735,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2002,
"s": 1776,
"text": "{ \"_id\" : ObjectId(\"5e3838ce9e4f06af551997e1\"), \"SubjectName\" : \"MySQL\" }\n{ \"_id\" : ObjectId(\"5e3838d69e4f06af551997e2\"), \"SubjectName\" : \"mongodb\" }\n{ \"_id\" : ObjectId(\"5e3838db9e4f06af551997e3\"), \"SubjectName\" : \"MongoDB\" }"
},
{
"code": null,
"e": 2056,
"s": 2002,
"text": "Following is the query to find a value in lowercase −"
},
{
"code": null,
"e": 2116,
"s": 2056,
"text": "> db.demo172.find({\"SubjectName\":\"MONGODB\".toLowerCase()});"
},
{
"code": null,
"e": 2157,
"s": 2116,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2233,
"s": 2157,
"text": "{ \"_id\" : ObjectId(\"5e3838d69e4f06af551997e2\"), \"SubjectName\" : \"mongodb\" }"
}
] |
Tryit Editor v3.7
|
Tryit basic HTML image
|
[] |
Real-time Twitter Sentiment Analysis for Brand Improvement and Topic Tracking (Chapter 3/3) | by Chulong Li | Towards Data Science
|
This tutorial will teach you 1) how to deploy all data analytics with insights on the Heroku cloud application platform and 2) how to migrate Plotly-based data visualization to analytical dashboard web app using Dash in Python.
Note: Real-time Twitter Data Collection and Data Analytics & Sentiment Analysis were completed in previous chapters.
Chapter 1: Collecting Twitter Data using Streaming Twitter API with Tweepy, MySQL, & Python
Chapter 2: Twitter Sentiment Analysis and Interactive Data Visualization using RE, TextBlob, NLTK, and Plotly
Chapter 3 (You’re here !): Deploy a Real-time Twitter Analytical Web App on Heroku using Dash & Plotly in Python
Chapter 4 (Optional): Parallelize Streaming Twitter Sentiment Analysis using Scala, Kafka and Spark Streaming
Dash is a productive Python framework for building web applications. Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python.
Dash Core Components (dcc) provide supercharged components for interactive user interfaces.
Dash Html Components (html) provide pure Python abstraction around HTML, CSS, and JavaScript.
Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud.
In order to run the real-time twitter monitoring system, we will use two scripts (or two dynos, or two apps). One is used for collecting the streaming data, and another one is used for data analysis and visualization in real-time. This approach could effectively reduce the latency of data pipeline when handling high-throughput Twitter textual data.
This part is written for beginners to how to set up new Heroku app environment from scratch. If you’re familiar with Heroku platform, you may consider to skip this part.
Two important deployment guides for references:
Dash App Deployment Guide: https://dash.plot.ly/deployment
Heroku Deployment Guide: https://devcenter.heroku.com/articles/git
Sign up your account on Heroku: Cloud Application Platform
Check your email to confirm your account, and then log in Heroku platform.
Click on New button to create new app. App name must be unique since everyone can access the web app via that name after app is published.
First, download and install the Heroku CLI. Heroku Command Line Interface (CLI) is an essential component allowing us to create and manage Heroku apps via terminal.
Then, log in to your Heroku account and follow the prompts to create a new SSH public key.
$ heroku login
Heroku uses Git to version-control the development of applications.
$ mkdir Real-time-Twitter-Monitoring-System$ cd Real-time-Twitter-Monitoring-System
$ git init # initializes an empty git repo $ virtualenv venv # creates a virtualenv called "venv" $ source venv/bin/activate # uses the virtualenv$ Heroku git: remote -a THIS-IS-YOUR-APP-NAME
virtualenv creates a fresh Python instance. You will need to reinstall your app's dependencies with this virtualenv:
$ pip install dash $ pip install plotly$ pip install gunicorn
Note: gunicorn is a new dependency for deploying the app.
Initialize the folder with a sample app (app.py), a .gitignore file, requirements.txt, and a Procfile for deployment
I. Create a file called app.py and fill in the sample demo code.
# Simple demo app onlyimport dashapp = dash.Dash(__name__)server = app.server # the Flask app
II. Create .gitignore
venv*.pyc.DS_Store.env
III. Create Procfile
web: gunicorn app:server
(Note that app refers to the filename app.py. server refers to the variable server inside that file).
IV. Create requirements.txt
Then let’s add this long dependencies. Note: Some of them may not be directly used but can be useful when you’re trying to tune your app.
Click==7.0dash==1.1.1dash-core-components==1.1.1dash-html-components==1.0.0dash-renderer==1.0.0dash-table==4.1.0Flask==1.1.1Flask-Compress==1.4.0gunicorn==19.9.0itsdangerous==1.1.0Jinja2==2.10.1MarkupSafe==1.1.1plotly==4.1.0PyYAML==5.1.2retrying==1.3.3six==1.12.0Werkzeug==0.15.5pandas==0.25.0nltk==3.4.4textblob==0.15.2tweepy==3.8.0psycopg2-binary==2.8.3Flask==1.1.1
Initialize Heroku app, add and commit code to the repo, and push to Heroku cloud using Git.
$ heroku create THIS-IS-YOUR-UNIQUE-APP-NAME$ git add .$ git commit -m 'Initial the app' $ git push heroku master # deploy code to heroku
The Heroku cloud should already set up a dyno, a cluster to run your app, for you at the beginning. If not, then create a dyno manually.
$ heroku ps:scale web=1 # run the app with a 1 heroku "dyno"
To update our app on Heroku cloud in the future, we just need to add, commit, and push again our new codes.
$ git status # view the changes $ git add .$ git commit -m 'a description of the changes' $ git push heroku master
Now we need to write some real codes.
To put our data visualization from the previous chapter on the Heroku app, we need to wrap our Plotly-based dashboard with Dash framework. All data analysis and visualizations will be processed in the file app.py , and you may check my entire code for this file here.
Start with a new app server with the Dash default CSS sheet. Note: I recommend to improve the appearance of the web app using Bootstrap.
external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets)app.title = 'Real-Time Twitter Monitor'server = app.server
The core framework of Dash web app is using app.layout as a background layout. Note: Click on two links below to understand how they work and check some typical samples as they are VERY IMPORTANT to utilize the Dash.
Dash Layout allows us to display integrated data visualization along with other text descriptions.
Dash Callbacks enables the application to update everything consistently with real-time data.
Since Dash is built on top of HTML, it uses HTML in its own way (Dash HTML Components). But some of HTML features are not allowed in the Dash.
html.Div(id='live-update-graph') describes the top part of the dashboard in the application, including descriptions for tweet number and potential impressions. html.Div(id='live-update-graph-bottom') describes the bottom part of dashboard in the web app.
dcc.Interval is the key to allow the application to update information regularly. Although the data collector, which will be explained later, on another dyno works in real-time, the analytical dashboard only analyzes and visualizes data per 10 seconds because of the utilization of aggregated data for visualization and the consideration of cost-efficiency.
app.layout = html.Div(children=[ # Parts of Title hided html.H2('This-is-your-tittle'), html.Div(id='live-update-graph'), html.Div(id='live-update-graph-bottom'), # Parts of Summary hided html.Div( dcc.Markdown("Author's Words: ...... ") ) # Timer for updating data per 10 seconds dcc.Interval( id='interval-component-slow', interval=1*10000, # in milliseconds n_intervals=0 ) ], style={'padding': '20px'})}
For each Div in the HTML of Dash, it has className , children , and style . children is a list of dcc.Graph (Graphs in Dash Core Components), dcc.Markdown, html.Div , html.H1 , and other interactive buttons (e.g. dcc.Dropdown and dcc.Slider).
html.Div( className='row', children=[ dcc.Markdown("..."), dcc.Graph(...), html.Div(...) ], style={'width': '35%', 'marginLeft': 70} )
style is important for building a good layout and ensuring proper distances among several visualization graphs, but can be time-consuming to tune the details.
Give an example of dcc.Graph below (Graphs in Dash Core Components). dcc.Graph has attributes id and figure . Under the figure , there are 'data' , containing different kinds of graphs in Plotly (e.g. go.Scatter and go.Pie), and 'layout' , which is only the layout of this graph rather than app.layout .
# import dash_core_components as dcc# import plotly.graph_objs as godcc.Graph( id='pie-chart', figure={ 'data': [ go.Pie( labels=['Positives', 'Negatives', 'Neutrals'], values=[pos_num, neg_num, neu_num], ) ], 'layout':{ 'showlegend':False, 'title':'Tweets In Last 10 Mins', 'annotations':[ # ... ] } } )
'annotations' is another important part to ensure the current labels. Note: Reference for Annotation in Dash is quite ambiguous, since parameters may need to be expressed as go.layout.Annotation, a dictionary dict(...), and sometimes a list.
In the Dash app layout, reactive and functional Python callbacks provide connections between inputs and outputs, allowing customizable declarative UIs.
Note: We skip all data analysis parts that were explained in the previous chapter, although there might be a little bit difference (or improvement). Thus, we dive directly into Dash-based data visualization parts, which are implemented through complicated Plotly graphs plotly.graph_objs (a.k.a. go).
# Multiple components can update everytime interval gets [email protected]( Output('live-update-graph', 'children'), [Input('interval-component-slow', 'n_intervals')] )def update_graph_live(n): # Lots of nested Div to ensure the proper layout # Graphs will be explained later # All codes are hided return children
All three line charts use go.Scatter along with stack groups to ensure the overlapped areas under lines in the same graph.
# import plotly.graph_objs as gogo.Scatter( x=time_series, y=result["Num of A-Brand-Name mentions", name="Neutrals", opacity=0.8, mode='lines', line=dict(width=0.5, color='rgb(131, 90, 241)'), stackgroup='one')
Pie chart was explained in the example of dcc.Graph above.
For text descriptions (e.g. Tweet Number Change per 10 Mins), we use two HTML paragraphs to embed data info. By comparing the previous 10-min interval and current 10-min interval, we could generate such a result.
html.P( 'Tweets/10 Mins Changed By', style={'fontSize': 17}),html.P( '{0:.2f}%'.format(percent) if percent <= 0 \ else '+{0:.2f}%'.format(percent), style={'fontSize': 40})
For Potential Impressions Today, we want to figure out how many people at most have a chance to see these tweets. By counting the sum of follower numbers of people who posted these tweets, we can get the potential impressions. Add a dynamic numeric unit to better display this value in a very large range.
html.P( '{0:.1f}K'.format(daily_impressions/1000) \ if daily_impressions < 1000000 else \ ('{0:.1f}M'.format(daily_impressions/1000000) if daily_impressions < 1000000000 \ else '{0:.1f}B'.format(daily_impressions/1000000000)), style={'fontSize': 40})
Counting Daily Tweet Number is an easy approach by storing and adding up tweet numbers in each app data update. And this value will be reset to zero at midnight.
html.P( '{0:.1f}K'.format(daily_tweets_num/1000), style={'fontSize': 40})
The callback function for the bottom dashboard is similar to the first one.
@app.callback(Output('live-update-graph-bottom', 'children'), [Input('interval-component-slow', 'n_intervals')])def update_graph_bottom_live(n): # Lots of nested Div to ensure the proper layout # Graphs will be explained later # All codes are hidedreturn children
Bar chart for hottest topic tracking. Set orientation as horizontal to better display bars and related word names
go.Bar( x=fd["Frequency"].loc[::-1], y=fd["Word"].loc[::-1], name="Neutrals", orientation='h', marker_color=fd['Marker_Color'].loc[::-1].to_list(), marker=dict( line=dict( color=fd['Line_Color'].loc[::-1].to_list(), width=1 ), ))
Focus the scope on State-level Map by setting 'layout': {'geo':{'scope':'usa'}}
go.Choropleth( locations=geo_dist['State'], # Spatial coordinates z = geo_dist['Log Num'].astype(float), # Color-coded data locationmode = 'USA-states', text=geo_dist['text'], # hover text geo = 'geo', colorbar_title = "Num in Log2", marker_line_color='white', colorscale = ["#fdf7ff", "#835af1"])
In order to parallel multiple graphs in a single row, you may consider using the following. width should be 1/N percentage (N = number of graph), and we may subtract 1% to give enough gaps between graphs.
style={'display': 'inline-block', 'width': '33%'}
In order to run another script connected with web (for internet connection) without paying, we need to set up another application with the exact same configuration except for app.py and gunicorn . Or you can pay for a new dyno to run in the original application.
Note: The free plan could only run around 3 weeks per month due to two-app consumption, and the web app may sleep if inactive for 30 mins although the data collector won’t.
Create a new app server scraping_server.py in the new application, and add below.
Create a new app server scraping_server.py in the new application, and add below.
from os import environfrom flask import Flaskapp = Flask(__name__)app.run(environ.get('PORT'))
2. Create a data collector file scraping.py in the new application, which is very similar to the file in the Chapter 1. However, this time we’ll use Heroku PostgreSQL rather than MySQL, which also requires us to update the SQL query a little bit. You may check the code here.
# Due to the similar code, check Chapter 1 for detailed explanation.
3. Remove app.py , and update gunicorn as below.
worker: python scraping.pyweb: python scraping_server.py
*Note: Don’t forget to create credentials.py and settings.py just like in Chapter 1.
To share the same Postgres database between applications, follow this Guide:
$ heroku addons:attach my-originating-app::DATABASE --app sushi
Heroku now allows a new data pipeline feature, so you may consider to utilize this benefit rather than using my approach of two applications connected with a PostgreSQL.
Thanks for reading! This series of articles for my real-time Twitter monitoring system is over, but the development of the new technique won’t stop. Chapter 4 will be published as an independent article in October. Hope to see you next time!
|
[
{
"code": null,
"e": 400,
"s": 172,
"text": "This tutorial will teach you 1) how to deploy all data analytics with insights on the Heroku cloud application platform and 2) how to migrate Plotly-based data visualization to analytical dashboard web app using Dash in Python."
},
{
"code": null,
"e": 517,
"s": 400,
"text": "Note: Real-time Twitter Data Collection and Data Analytics & Sentiment Analysis were completed in previous chapters."
},
{
"code": null,
"e": 609,
"s": 517,
"text": "Chapter 1: Collecting Twitter Data using Streaming Twitter API with Tweepy, MySQL, & Python"
},
{
"code": null,
"e": 719,
"s": 609,
"text": "Chapter 2: Twitter Sentiment Analysis and Interactive Data Visualization using RE, TextBlob, NLTK, and Plotly"
},
{
"code": null,
"e": 832,
"s": 719,
"text": "Chapter 3 (You’re here !): Deploy a Real-time Twitter Analytical Web App on Heroku using Dash & Plotly in Python"
},
{
"code": null,
"e": 942,
"s": 832,
"text": "Chapter 4 (Optional): Parallelize Streaming Twitter Sentiment Analysis using Scala, Kafka and Spark Streaming"
},
{
"code": null,
"e": 1163,
"s": 942,
"text": "Dash is a productive Python framework for building web applications. Written on top of Flask, Plotly.js, and React.js, Dash is ideal for building data visualization apps with highly custom user interfaces in pure Python."
},
{
"code": null,
"e": 1255,
"s": 1163,
"text": "Dash Core Components (dcc) provide supercharged components for interactive user interfaces."
},
{
"code": null,
"e": 1349,
"s": 1255,
"text": "Dash Html Components (html) provide pure Python abstraction around HTML, CSS, and JavaScript."
},
{
"code": null,
"e": 1477,
"s": 1349,
"text": "Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud."
},
{
"code": null,
"e": 1828,
"s": 1477,
"text": "In order to run the real-time twitter monitoring system, we will use two scripts (or two dynos, or two apps). One is used for collecting the streaming data, and another one is used for data analysis and visualization in real-time. This approach could effectively reduce the latency of data pipeline when handling high-throughput Twitter textual data."
},
{
"code": null,
"e": 1998,
"s": 1828,
"text": "This part is written for beginners to how to set up new Heroku app environment from scratch. If you’re familiar with Heroku platform, you may consider to skip this part."
},
{
"code": null,
"e": 2046,
"s": 1998,
"text": "Two important deployment guides for references:"
},
{
"code": null,
"e": 2105,
"s": 2046,
"text": "Dash App Deployment Guide: https://dash.plot.ly/deployment"
},
{
"code": null,
"e": 2172,
"s": 2105,
"text": "Heroku Deployment Guide: https://devcenter.heroku.com/articles/git"
},
{
"code": null,
"e": 2231,
"s": 2172,
"text": "Sign up your account on Heroku: Cloud Application Platform"
},
{
"code": null,
"e": 2306,
"s": 2231,
"text": "Check your email to confirm your account, and then log in Heroku platform."
},
{
"code": null,
"e": 2445,
"s": 2306,
"text": "Click on New button to create new app. App name must be unique since everyone can access the web app via that name after app is published."
},
{
"code": null,
"e": 2610,
"s": 2445,
"text": "First, download and install the Heroku CLI. Heroku Command Line Interface (CLI) is an essential component allowing us to create and manage Heroku apps via terminal."
},
{
"code": null,
"e": 2701,
"s": 2610,
"text": "Then, log in to your Heroku account and follow the prompts to create a new SSH public key."
},
{
"code": null,
"e": 2716,
"s": 2701,
"text": "$ heroku login"
},
{
"code": null,
"e": 2784,
"s": 2716,
"text": "Heroku uses Git to version-control the development of applications."
},
{
"code": null,
"e": 2868,
"s": 2784,
"text": "$ mkdir Real-time-Twitter-Monitoring-System$ cd Real-time-Twitter-Monitoring-System"
},
{
"code": null,
"e": 3067,
"s": 2868,
"text": "$ git init # initializes an empty git repo $ virtualenv venv # creates a virtualenv called \"venv\" $ source venv/bin/activate # uses the virtualenv$ Heroku git: remote -a THIS-IS-YOUR-APP-NAME"
},
{
"code": null,
"e": 3184,
"s": 3067,
"text": "virtualenv creates a fresh Python instance. You will need to reinstall your app's dependencies with this virtualenv:"
},
{
"code": null,
"e": 3246,
"s": 3184,
"text": "$ pip install dash $ pip install plotly$ pip install gunicorn"
},
{
"code": null,
"e": 3304,
"s": 3246,
"text": "Note: gunicorn is a new dependency for deploying the app."
},
{
"code": null,
"e": 3421,
"s": 3304,
"text": "Initialize the folder with a sample app (app.py), a .gitignore file, requirements.txt, and a Procfile for deployment"
},
{
"code": null,
"e": 3486,
"s": 3421,
"text": "I. Create a file called app.py and fill in the sample demo code."
},
{
"code": null,
"e": 3580,
"s": 3486,
"text": "# Simple demo app onlyimport dashapp = dash.Dash(__name__)server = app.server # the Flask app"
},
{
"code": null,
"e": 3602,
"s": 3580,
"text": "II. Create .gitignore"
},
{
"code": null,
"e": 3625,
"s": 3602,
"text": "venv*.pyc.DS_Store.env"
},
{
"code": null,
"e": 3646,
"s": 3625,
"text": "III. Create Procfile"
},
{
"code": null,
"e": 3671,
"s": 3646,
"text": "web: gunicorn app:server"
},
{
"code": null,
"e": 3773,
"s": 3671,
"text": "(Note that app refers to the filename app.py. server refers to the variable server inside that file)."
},
{
"code": null,
"e": 3801,
"s": 3773,
"text": "IV. Create requirements.txt"
},
{
"code": null,
"e": 3939,
"s": 3801,
"text": "Then let’s add this long dependencies. Note: Some of them may not be directly used but can be useful when you’re trying to tune your app."
},
{
"code": null,
"e": 4307,
"s": 3939,
"text": "Click==7.0dash==1.1.1dash-core-components==1.1.1dash-html-components==1.0.0dash-renderer==1.0.0dash-table==4.1.0Flask==1.1.1Flask-Compress==1.4.0gunicorn==19.9.0itsdangerous==1.1.0Jinja2==2.10.1MarkupSafe==1.1.1plotly==4.1.0PyYAML==5.1.2retrying==1.3.3six==1.12.0Werkzeug==0.15.5pandas==0.25.0nltk==3.4.4textblob==0.15.2tweepy==3.8.0psycopg2-binary==2.8.3Flask==1.1.1"
},
{
"code": null,
"e": 4399,
"s": 4307,
"text": "Initialize Heroku app, add and commit code to the repo, and push to Heroku cloud using Git."
},
{
"code": null,
"e": 4538,
"s": 4399,
"text": "$ heroku create THIS-IS-YOUR-UNIQUE-APP-NAME$ git add .$ git commit -m 'Initial the app' $ git push heroku master # deploy code to heroku "
},
{
"code": null,
"e": 4675,
"s": 4538,
"text": "The Heroku cloud should already set up a dyno, a cluster to run your app, for you at the beginning. If not, then create a dyno manually."
},
{
"code": null,
"e": 4737,
"s": 4675,
"text": "$ heroku ps:scale web=1 # run the app with a 1 heroku \"dyno\""
},
{
"code": null,
"e": 4845,
"s": 4737,
"text": "To update our app on Heroku cloud in the future, we just need to add, commit, and push again our new codes."
},
{
"code": null,
"e": 4960,
"s": 4845,
"text": "$ git status # view the changes $ git add .$ git commit -m 'a description of the changes' $ git push heroku master"
},
{
"code": null,
"e": 4998,
"s": 4960,
"text": "Now we need to write some real codes."
},
{
"code": null,
"e": 5266,
"s": 4998,
"text": "To put our data visualization from the previous chapter on the Heroku app, we need to wrap our Plotly-based dashboard with Dash framework. All data analysis and visualizations will be processed in the file app.py , and you may check my entire code for this file here."
},
{
"code": null,
"e": 5403,
"s": 5266,
"text": "Start with a new app server with the Dash default CSS sheet. Note: I recommend to improve the appearance of the web app using Bootstrap."
},
{
"code": null,
"e": 5598,
"s": 5403,
"text": "external_stylesheets=['https://codepen.io/chriddyp/pen/bWLwgP.css'] app = dash.Dash(__name__, external_stylesheets=external_stylesheets)app.title = 'Real-Time Twitter Monitor'server = app.server"
},
{
"code": null,
"e": 5815,
"s": 5598,
"text": "The core framework of Dash web app is using app.layout as a background layout. Note: Click on two links below to understand how they work and check some typical samples as they are VERY IMPORTANT to utilize the Dash."
},
{
"code": null,
"e": 5914,
"s": 5815,
"text": "Dash Layout allows us to display integrated data visualization along with other text descriptions."
},
{
"code": null,
"e": 6008,
"s": 5914,
"text": "Dash Callbacks enables the application to update everything consistently with real-time data."
},
{
"code": null,
"e": 6151,
"s": 6008,
"text": "Since Dash is built on top of HTML, it uses HTML in its own way (Dash HTML Components). But some of HTML features are not allowed in the Dash."
},
{
"code": null,
"e": 6406,
"s": 6151,
"text": "html.Div(id='live-update-graph') describes the top part of the dashboard in the application, including descriptions for tweet number and potential impressions. html.Div(id='live-update-graph-bottom') describes the bottom part of dashboard in the web app."
},
{
"code": null,
"e": 6764,
"s": 6406,
"text": "dcc.Interval is the key to allow the application to update information regularly. Although the data collector, which will be explained later, on another dyno works in real-time, the analytical dashboard only analyzes and visualizes data per 10 seconds because of the utilization of aggregated data for visualization and the consideration of cost-efficiency."
},
{
"code": null,
"e": 7273,
"s": 6764,
"text": "app.layout = html.Div(children=[ # Parts of Title hided html.H2('This-is-your-tittle'), html.Div(id='live-update-graph'), html.Div(id='live-update-graph-bottom'), # Parts of Summary hided html.Div( dcc.Markdown(\"Author's Words: ...... \") ) # Timer for updating data per 10 seconds dcc.Interval( id='interval-component-slow', interval=1*10000, # in milliseconds n_intervals=0 ) ], style={'padding': '20px'})}"
},
{
"code": null,
"e": 7516,
"s": 7273,
"text": "For each Div in the HTML of Dash, it has className , children , and style . children is a list of dcc.Graph (Graphs in Dash Core Components), dcc.Markdown, html.Div , html.H1 , and other interactive buttons (e.g. dcc.Dropdown and dcc.Slider)."
},
{
"code": null,
"e": 7713,
"s": 7516,
"text": "html.Div( className='row', children=[ dcc.Markdown(\"...\"), dcc.Graph(...), html.Div(...) ], style={'width': '35%', 'marginLeft': 70} )"
},
{
"code": null,
"e": 7872,
"s": 7713,
"text": "style is important for building a good layout and ensuring proper distances among several visualization graphs, but can be time-consuming to tune the details."
},
{
"code": null,
"e": 8176,
"s": 7872,
"text": "Give an example of dcc.Graph below (Graphs in Dash Core Components). dcc.Graph has attributes id and figure . Under the figure , there are 'data' , containing different kinds of graphs in Plotly (e.g. go.Scatter and go.Pie), and 'layout' , which is only the layout of this graph rather than app.layout ."
},
{
"code": null,
"e": 8868,
"s": 8176,
"text": "# import dash_core_components as dcc# import plotly.graph_objs as godcc.Graph( id='pie-chart', figure={ 'data': [ go.Pie( labels=['Positives', 'Negatives', 'Neutrals'], values=[pos_num, neg_num, neu_num], ) ], 'layout':{ 'showlegend':False, 'title':'Tweets In Last 10 Mins', 'annotations':[ # ... ] } } )"
},
{
"code": null,
"e": 9110,
"s": 8868,
"text": "'annotations' is another important part to ensure the current labels. Note: Reference for Annotation in Dash is quite ambiguous, since parameters may need to be expressed as go.layout.Annotation, a dictionary dict(...), and sometimes a list."
},
{
"code": null,
"e": 9262,
"s": 9110,
"text": "In the Dash app layout, reactive and functional Python callbacks provide connections between inputs and outputs, allowing customizable declarative UIs."
},
{
"code": null,
"e": 9563,
"s": 9262,
"text": "Note: We skip all data analysis parts that were explained in the previous chapter, although there might be a little bit difference (or improvement). Thus, we dive directly into Dash-based data visualization parts, which are implemented through complicated Plotly graphs plotly.graph_objs (a.k.a. go)."
},
{
"code": null,
"e": 9890,
"s": 9563,
"text": "# Multiple components can update everytime interval gets [email protected]( Output('live-update-graph', 'children'), [Input('interval-component-slow', 'n_intervals')] )def update_graph_live(n): # Lots of nested Div to ensure the proper layout # Graphs will be explained later # All codes are hided return children"
},
{
"code": null,
"e": 10013,
"s": 9890,
"text": "All three line charts use go.Scatter along with stack groups to ensure the overlapped areas under lines in the same graph."
},
{
"code": null,
"e": 10231,
"s": 10013,
"text": "# import plotly.graph_objs as gogo.Scatter( x=time_series, y=result[\"Num of A-Brand-Name mentions\", name=\"Neutrals\", opacity=0.8, mode='lines', line=dict(width=0.5, color='rgb(131, 90, 241)'), stackgroup='one')"
},
{
"code": null,
"e": 10290,
"s": 10231,
"text": "Pie chart was explained in the example of dcc.Graph above."
},
{
"code": null,
"e": 10503,
"s": 10290,
"text": "For text descriptions (e.g. Tweet Number Change per 10 Mins), we use two HTML paragraphs to embed data info. By comparing the previous 10-min interval and current 10-min interval, we could generate such a result."
},
{
"code": null,
"e": 10691,
"s": 10503,
"text": "html.P( 'Tweets/10 Mins Changed By', style={'fontSize': 17}),html.P( '{0:.2f}%'.format(percent) if percent <= 0 \\ else '+{0:.2f}%'.format(percent), style={'fontSize': 40})"
},
{
"code": null,
"e": 10997,
"s": 10691,
"text": "For Potential Impressions Today, we want to figure out how many people at most have a chance to see these tweets. By counting the sum of follower numbers of people who posted these tweets, we can get the potential impressions. Add a dynamic numeric unit to better display this value in a very large range."
},
{
"code": null,
"e": 11259,
"s": 10997,
"text": "html.P( '{0:.1f}K'.format(daily_impressions/1000) \\ if daily_impressions < 1000000 else \\ ('{0:.1f}M'.format(daily_impressions/1000000) if daily_impressions < 1000000000 \\ else '{0:.1f}B'.format(daily_impressions/1000000000)), style={'fontSize': 40})"
},
{
"code": null,
"e": 11421,
"s": 11259,
"text": "Counting Daily Tweet Number is an easy approach by storing and adding up tweet numbers in each app data update. And this value will be reset to zero at midnight."
},
{
"code": null,
"e": 11497,
"s": 11421,
"text": "html.P( '{0:.1f}K'.format(daily_tweets_num/1000), style={'fontSize': 40})"
},
{
"code": null,
"e": 11573,
"s": 11497,
"text": "The callback function for the bottom dashboard is similar to the first one."
},
{
"code": null,
"e": 11853,
"s": 11573,
"text": "@app.callback(Output('live-update-graph-bottom', 'children'), [Input('interval-component-slow', 'n_intervals')])def update_graph_bottom_live(n): # Lots of nested Div to ensure the proper layout # Graphs will be explained later # All codes are hidedreturn children"
},
{
"code": null,
"e": 11967,
"s": 11853,
"text": "Bar chart for hottest topic tracking. Set orientation as horizontal to better display bars and related word names"
},
{
"code": null,
"e": 12220,
"s": 11967,
"text": "go.Bar( x=fd[\"Frequency\"].loc[::-1], y=fd[\"Word\"].loc[::-1], name=\"Neutrals\", orientation='h', marker_color=fd['Marker_Color'].loc[::-1].to_list(), marker=dict( line=dict( color=fd['Line_Color'].loc[::-1].to_list(), width=1 ), ))"
},
{
"code": null,
"e": 12300,
"s": 12220,
"text": "Focus the scope on State-level Map by setting 'layout': {'geo':{'scope':'usa'}}"
},
{
"code": null,
"e": 12606,
"s": 12300,
"text": "go.Choropleth( locations=geo_dist['State'], # Spatial coordinates z = geo_dist['Log Num'].astype(float), # Color-coded data locationmode = 'USA-states', text=geo_dist['text'], # hover text geo = 'geo', colorbar_title = \"Num in Log2\", marker_line_color='white', colorscale = [\"#fdf7ff\", \"#835af1\"])"
},
{
"code": null,
"e": 12811,
"s": 12606,
"text": "In order to parallel multiple graphs in a single row, you may consider using the following. width should be 1/N percentage (N = number of graph), and we may subtract 1% to give enough gaps between graphs."
},
{
"code": null,
"e": 12861,
"s": 12811,
"text": "style={'display': 'inline-block', 'width': '33%'}"
},
{
"code": null,
"e": 13124,
"s": 12861,
"text": "In order to run another script connected with web (for internet connection) without paying, we need to set up another application with the exact same configuration except for app.py and gunicorn . Or you can pay for a new dyno to run in the original application."
},
{
"code": null,
"e": 13297,
"s": 13124,
"text": "Note: The free plan could only run around 3 weeks per month due to two-app consumption, and the web app may sleep if inactive for 30 mins although the data collector won’t."
},
{
"code": null,
"e": 13379,
"s": 13297,
"text": "Create a new app server scraping_server.py in the new application, and add below."
},
{
"code": null,
"e": 13461,
"s": 13379,
"text": "Create a new app server scraping_server.py in the new application, and add below."
},
{
"code": null,
"e": 13556,
"s": 13461,
"text": "from os import environfrom flask import Flaskapp = Flask(__name__)app.run(environ.get('PORT'))"
},
{
"code": null,
"e": 13832,
"s": 13556,
"text": "2. Create a data collector file scraping.py in the new application, which is very similar to the file in the Chapter 1. However, this time we’ll use Heroku PostgreSQL rather than MySQL, which also requires us to update the SQL query a little bit. You may check the code here."
},
{
"code": null,
"e": 13901,
"s": 13832,
"text": "# Due to the similar code, check Chapter 1 for detailed explanation."
},
{
"code": null,
"e": 13950,
"s": 13901,
"text": "3. Remove app.py , and update gunicorn as below."
},
{
"code": null,
"e": 14007,
"s": 13950,
"text": "worker: python scraping.pyweb: python scraping_server.py"
},
{
"code": null,
"e": 14092,
"s": 14007,
"text": "*Note: Don’t forget to create credentials.py and settings.py just like in Chapter 1."
},
{
"code": null,
"e": 14169,
"s": 14092,
"text": "To share the same Postgres database between applications, follow this Guide:"
},
{
"code": null,
"e": 14233,
"s": 14169,
"text": "$ heroku addons:attach my-originating-app::DATABASE --app sushi"
},
{
"code": null,
"e": 14403,
"s": 14233,
"text": "Heroku now allows a new data pipeline feature, so you may consider to utilize this benefit rather than using my approach of two applications connected with a PostgreSQL."
}
] |
Sports Reference API Intro. How to build awesome sports datasets | by Alex Muhr | Towards Data Science
|
This is the second installment in my weekly sports-themed series. Each week, I demonstrate applications of data science centered around sports.
Last week in my article Beating the Odds I demonstrated how to build a dataset on NBA teams using the Sports Reference API, then used the dataset to find teams which outperformed their regular season point differential. This week I want to go in-depth on how to use this API to build comprehensive datasets for your projects.
When looking around the web at sports data projects, I’ve seen a lot of people resort to downloading tables from disparate sources, either manually or through web scraping. These tables then usually need to be joined, a very tedious process that’s highly dependent on the quality of data. Building a large dataset in this fashion may take days or even weeks. Don’t be that person! Thankfully the amazing engineers at Sports Reference have built an API that facilitates fast and easy access to Sports Reference’s massive databases on the MLB, NBA, NFL, NHL, NCAAF, NCAAB, and the many Football (soccer) leagues across the world.
To begin using the Sports Reference API you will need to install it just like any other python package using pip install sportsreference.
The basic idea of the Sports Reference API is that modules are used to instantiate class objects which contain relevant data in the class properties. The basic modules that are common among all sports are Teams, Schedule, Boxscore, Roster, and Player. NCAAB and NCAAF also have modules for Rankings and Conferences. Football (soccer) uses a slightly different naming convention, but the general API structure is the same. On the backend, these modules create class objects by sending HTTP requests which query the relevant data from Sports Reference’s servers. There’s no need to worry about stuffing your hard drive full of 100 years of Baseball boxscore data (although I suppose you could use the API to do this if you really wanted to).
In the following sections, I’ll show off features of the NBA API. If you’re interested in another sport I encourage you to follow along anyway as the basic features and processes are essentially the same. The code is intended to be executed in a Jupyter Notebook, but could easily be adapted for another environment.
Let’s start by looking at the Teams module. The following commands create an instance of the Teams class and print out all of its methods and properties.
from sportsreference.nba.teams import Teamsteams2020 = Teams(year = '2020')print(dir(teams2020))
The only public property of the Teams class is ‘dataframes’. This property is a 30 x 47 dataframe where every NBA team in 2020 is represented by a row. Columns include things like points, free throw attempts, opponent offensive rebounds, etc. The ‘dataframes’ property is generally the easiest way to access high level team information. However, it’s also possible to use an instance of the Teams class as an iterator. For example, the code below prints out the name and points scored for every team. Every column of the Teams dataframe is also accessible in this way as a team property.
for team in teams2020: print(team.name, 'Points Scored:', team.points)
The Schedule module, as the name suggests, is used to access information about a team’s schedule. This is very useful as the Teams module does not contain information on win/loss records. Let’s create an instance of the class for the Milwaukee Bucks’ 2019 season and use it to return a dataframe containing basic information for each game.
from sportsreference.nba.schedule import Schedulemil2019 = Schedule('MIL', year = '2019')mil2019.dataframe.head()
Note the boxscore_index column, these boxscore indices can be used with the Boxscore class to obtain much more detailed game information. Similar to the Teams module, an instance of the Schedule class can also be used as an iterator. Lastly, there is a ‘dataframe_extended’ property of the Schedule class which returns a dataframe where every row is an instance of the Boxscore class. This provides richer data on each game but takes much longer to process due to building many instances of the Boxscore class, each requiring a separate server request.
Let’s take a closer look at the Milwaukee Bucks’ 2019 Game 1 in the Eastern Conference Finals against the Toronto Raptors. From our schedule dataframe we can find that the boxscore_index for this game is ‘201905150MIL’.
from sportsreference.nba.boxscore import Boxscoregame_data = Boxscore('201905150MIL')
By calling print(dir(game_data)) we can see that the Boxscore class has many more properties than the Teams and Schedule classes. The command game_data.dataframe will compile these properties into dataframe.
Well, that’s not exactly the type of boxscore we’re used to seeing, but there’s a lot of useful data here nonetheless. In order to construct something more closely resembling a traditional boxscore we’ll need to use the Boxscore class properties ‘home_players’ and ‘away_players’. By executing game_data.home_players we see that this returns a list of BoxscorePlayer class objects. Further, we can execute print(dir(game_data.home_players[0])) to view a list of all the available methods and properties for this subclass. As the BoxscorePlayer class has a ‘dataframe’ property, a more traditional boxscore dataframe can be constructed by concatenating each individual BoxscorePlayer dataframe. The code below does just this.
home_df = game_data.home_players[0].dataframefor player in game_data.home_players[1:]: home_df = pd.concat([home_df, player.dataframe], axis = 0)home_df['name'] = [x.name for x in game_data.home_players]home_df.set_index('name', inplace = True)home_df
By checking out the columns of this dataframe we can see that not only did we get all the traditional boxscore statistics, we also got a bunch of advanced statistics as well. This wraps up the basic use cases for the Boxscore module.
The Roster module is used to obtain information on a team’s roster of players. Let’s create an instance of the Roster class for the 2007 ‘We Believe’ Warriors.
from sportsreference.nba.roster import Rostergsw2007 = Roster('GSW', year = '2007')
As I’ve shown above, we can check the methods and properties of this class object and see that there is only one property, ‘players’. Much like the ‘home_players’ property we just looked at for the Boxscore module, the ‘players’ property is a list of Player class instances. We’ll go more in-depth on the Player module in a bit. For now, let’s simply print out the name and player id of every player on the roster using the following snippet of code.
for player in gsw2007.players: print(player.name, ':', player.player_id)
As the Roster class creates an instance of the Player class for each player on the roster, and constructing each instance requires a request to Sports Reference’s servers, it can be quite slow to use the Roster class for a simple task like this. If we wanted to print the name of every player in the league for a given season using this method we might have to wait 5+ minutes to create all the Player class instances. As an alternative, we can call the Roster class using the keyword argument slim = True. This will create an instance of the Roster class where the ‘players’ property is simply a dictionary, where keys are the player_ids and values are names. The code below demonstrates this functionality.
gsw2007slim = Roster('GSW', year = '2007', slim = True)gsw2007slim.players
Not surprisingly, the Player module is used to acquire information on individual players. Referring to the API documentation, we can see that the Player module contains an abstract class, AbstractPlayer, that is inherited by the BoxscorePlayer and Player classes that we’ve already seen in the Boxscore and Roster modules. As such, the proper way to obtain Player data is actually through the Roster and Boxscore modules. Let’s use the player_id that we pulled for Baron Davis to get his stats.
from sportsreference.nba.roster import Playerbaron_davis = Player('davisba01')baron_davis.dataframe
This simple bit of code gives us 89 columns of data for Baron Davis’ career and every one of his seasons. In addition to the ‘dataframe’ property and all of its associated columns, the Player class also contains properties such as ‘birth_date’, ‘height’, ‘weight’, ‘nationality’, and more. Further, a single career statistic, such as points, can be queried with the command baron_davis.points. Similarly, we could query Baron Davis’ total points in the 2006–07 season using the command baron_davis('2007').points. Depending on the use case, it may be easier to access player statistics in this more direct fashion and avoid dealing with a dataframe.
To wrap up this article I’ll demonstrate how to use the Teams, Roster, and Player modules to build a massive dataset of NBA player statistics. This dataset will be used in my next article where I’ll be taking a look at player development, and eventual decline, over the course of an NBA career.
The first step is to import the relevant modules and define a function that creates a player dataframe with a few extra fields that I’ve defined manually. Most important being a player’s age on January 1st of the respective season.
# Function to get player info from Player class object.def get_player_df(player): # helper function to get player age during each season. def get_age(year, bd): if year[0] == "Career": return None else: year_dt = datetime(int(year[0][0:4]) + 1, 1, 1) age_years = relativedelta(year_dt, bd).years + relativedelta(year_dt, bd).months/12 return age_years # helper function to get year for each row and denote # rows that contain career totals. def get_year(ix): if ix[0] == "Career": return "Career" elif ix[0] == "1999-00": return "2000" else: return ix[0][0:2] + ix[0][-2:] # get player df and add some extra info player_df = player.dataframe player_df['birth_date'] = player.birth_date player_df['player_id'] = player.player_id player_df['name'] = player.name player_df['year'] = [get_year(ix) for ix in player_df.index] player_df['id'] = [player_id + ' ' + year for player_id, year in zip(player_df['player_id'], player_df['year'])] player_df['age'] = [get_age(year, bd) for year, bd in zip(player_df.index, player_df['birth_date'])] player_df.set_index('id', drop = True, inplace = True) return player_df
Next, I use the function defined above to collect player data spanning entire careers for every player to play in the NBA within the last 20 years. Data is split between two dataframes, one which aggregates data at the season level and another which aggregates at the career level. This is done by using the Teams and Roster modules to iterate through every NBA roster from the year 2000 to 2020. Note that I call the Roster class using the keyword variable slim = True. Without this setting I’d have to create a Player instance for every season a player was in the NBA, increasing the running time by roughly 10x.
# initialize a list of players that we have pulled data forplayers_collected = []season_df_init = 0career_df_init = 0season_df = 0career_df = 0# iterate through years.for year in range(2020, 1999, -1): print('\n' + str(year)) # iterate through all teams in that year. for team in Teams(year = str(year)).dataframes.index: print('\n' + team + '\n') # iterate through every player on a team roster. for player_id in Roster(team, year = year, slim = True).players.keys(): # only pull player info if that player hasn't # been pulled already. if player_id not in players_collected: player = Player(player_id) player_info = get_player_df(player) player_seasons = player_info[ player_info['year'] != "Career"] player_career = player_info[ player_info['year'] == "Career"] # create season_df if not initialized if not season_df_init: season_df = player_seasons season_df_init = 1 # else concatenate to season_df else: season_df = pd.concat([season_df, player_seasons], axis = 0) if not career_df_init: career_df = player_career career_df_init = 1 # else concatenate to career_df else: career_df = pd.concat([career_df, player_career], axis = 0) # add player to players_collected players_collected.append(player_id) print(player.name)
The final step is to save the resulting dataframes to your favorite file format.
season_df.to_csv('nba_player_stats_by_season.csv')career_df.to_csv('nba_player_stats_by_career.csv')
Altogether this script should compile and save your dataset within about 30 minutes. If you understand all the code in this final section then you should be more than ready to start building your own datasets using the Sports Reference API.
Be sure to look out for my article next week when I use this dataset to analyze NBA career trajectories, and also check out my article from last week Beating the Odds.
I hope you’ve enjoyed the read and take care.
|
[
{
"code": null,
"e": 315,
"s": 171,
"text": "This is the second installment in my weekly sports-themed series. Each week, I demonstrate applications of data science centered around sports."
},
{
"code": null,
"e": 641,
"s": 315,
"text": "Last week in my article Beating the Odds I demonstrated how to build a dataset on NBA teams using the Sports Reference API, then used the dataset to find teams which outperformed their regular season point differential. This week I want to go in-depth on how to use this API to build comprehensive datasets for your projects."
},
{
"code": null,
"e": 1269,
"s": 641,
"text": "When looking around the web at sports data projects, I’ve seen a lot of people resort to downloading tables from disparate sources, either manually or through web scraping. These tables then usually need to be joined, a very tedious process that’s highly dependent on the quality of data. Building a large dataset in this fashion may take days or even weeks. Don’t be that person! Thankfully the amazing engineers at Sports Reference have built an API that facilitates fast and easy access to Sports Reference’s massive databases on the MLB, NBA, NFL, NHL, NCAAF, NCAAB, and the many Football (soccer) leagues across the world."
},
{
"code": null,
"e": 1407,
"s": 1269,
"text": "To begin using the Sports Reference API you will need to install it just like any other python package using pip install sportsreference."
},
{
"code": null,
"e": 2147,
"s": 1407,
"text": "The basic idea of the Sports Reference API is that modules are used to instantiate class objects which contain relevant data in the class properties. The basic modules that are common among all sports are Teams, Schedule, Boxscore, Roster, and Player. NCAAB and NCAAF also have modules for Rankings and Conferences. Football (soccer) uses a slightly different naming convention, but the general API structure is the same. On the backend, these modules create class objects by sending HTTP requests which query the relevant data from Sports Reference’s servers. There’s no need to worry about stuffing your hard drive full of 100 years of Baseball boxscore data (although I suppose you could use the API to do this if you really wanted to)."
},
{
"code": null,
"e": 2464,
"s": 2147,
"text": "In the following sections, I’ll show off features of the NBA API. If you’re interested in another sport I encourage you to follow along anyway as the basic features and processes are essentially the same. The code is intended to be executed in a Jupyter Notebook, but could easily be adapted for another environment."
},
{
"code": null,
"e": 2618,
"s": 2464,
"text": "Let’s start by looking at the Teams module. The following commands create an instance of the Teams class and print out all of its methods and properties."
},
{
"code": null,
"e": 2715,
"s": 2618,
"text": "from sportsreference.nba.teams import Teamsteams2020 = Teams(year = '2020')print(dir(teams2020))"
},
{
"code": null,
"e": 3303,
"s": 2715,
"text": "The only public property of the Teams class is ‘dataframes’. This property is a 30 x 47 dataframe where every NBA team in 2020 is represented by a row. Columns include things like points, free throw attempts, opponent offensive rebounds, etc. The ‘dataframes’ property is generally the easiest way to access high level team information. However, it’s also possible to use an instance of the Teams class as an iterator. For example, the code below prints out the name and points scored for every team. Every column of the Teams dataframe is also accessible in this way as a team property."
},
{
"code": null,
"e": 3377,
"s": 3303,
"text": "for team in teams2020: print(team.name, 'Points Scored:', team.points)"
},
{
"code": null,
"e": 3717,
"s": 3377,
"text": "The Schedule module, as the name suggests, is used to access information about a team’s schedule. This is very useful as the Teams module does not contain information on win/loss records. Let’s create an instance of the class for the Milwaukee Bucks’ 2019 season and use it to return a dataframe containing basic information for each game."
},
{
"code": null,
"e": 3831,
"s": 3717,
"text": "from sportsreference.nba.schedule import Schedulemil2019 = Schedule('MIL', year = '2019')mil2019.dataframe.head()"
},
{
"code": null,
"e": 4384,
"s": 3831,
"text": "Note the boxscore_index column, these boxscore indices can be used with the Boxscore class to obtain much more detailed game information. Similar to the Teams module, an instance of the Schedule class can also be used as an iterator. Lastly, there is a ‘dataframe_extended’ property of the Schedule class which returns a dataframe where every row is an instance of the Boxscore class. This provides richer data on each game but takes much longer to process due to building many instances of the Boxscore class, each requiring a separate server request."
},
{
"code": null,
"e": 4604,
"s": 4384,
"text": "Let’s take a closer look at the Milwaukee Bucks’ 2019 Game 1 in the Eastern Conference Finals against the Toronto Raptors. From our schedule dataframe we can find that the boxscore_index for this game is ‘201905150MIL’."
},
{
"code": null,
"e": 4690,
"s": 4604,
"text": "from sportsreference.nba.boxscore import Boxscoregame_data = Boxscore('201905150MIL')"
},
{
"code": null,
"e": 4898,
"s": 4690,
"text": "By calling print(dir(game_data)) we can see that the Boxscore class has many more properties than the Teams and Schedule classes. The command game_data.dataframe will compile these properties into dataframe."
},
{
"code": null,
"e": 5623,
"s": 4898,
"text": "Well, that’s not exactly the type of boxscore we’re used to seeing, but there’s a lot of useful data here nonetheless. In order to construct something more closely resembling a traditional boxscore we’ll need to use the Boxscore class properties ‘home_players’ and ‘away_players’. By executing game_data.home_players we see that this returns a list of BoxscorePlayer class objects. Further, we can execute print(dir(game_data.home_players[0])) to view a list of all the available methods and properties for this subclass. As the BoxscorePlayer class has a ‘dataframe’ property, a more traditional boxscore dataframe can be constructed by concatenating each individual BoxscorePlayer dataframe. The code below does just this."
},
{
"code": null,
"e": 5878,
"s": 5623,
"text": "home_df = game_data.home_players[0].dataframefor player in game_data.home_players[1:]: home_df = pd.concat([home_df, player.dataframe], axis = 0)home_df['name'] = [x.name for x in game_data.home_players]home_df.set_index('name', inplace = True)home_df"
},
{
"code": null,
"e": 6112,
"s": 5878,
"text": "By checking out the columns of this dataframe we can see that not only did we get all the traditional boxscore statistics, we also got a bunch of advanced statistics as well. This wraps up the basic use cases for the Boxscore module."
},
{
"code": null,
"e": 6272,
"s": 6112,
"text": "The Roster module is used to obtain information on a team’s roster of players. Let’s create an instance of the Roster class for the 2007 ‘We Believe’ Warriors."
},
{
"code": null,
"e": 6356,
"s": 6272,
"text": "from sportsreference.nba.roster import Rostergsw2007 = Roster('GSW', year = '2007')"
},
{
"code": null,
"e": 6807,
"s": 6356,
"text": "As I’ve shown above, we can check the methods and properties of this class object and see that there is only one property, ‘players’. Much like the ‘home_players’ property we just looked at for the Boxscore module, the ‘players’ property is a list of Player class instances. We’ll go more in-depth on the Player module in a bit. For now, let’s simply print out the name and player id of every player on the roster using the following snippet of code."
},
{
"code": null,
"e": 6883,
"s": 6807,
"text": "for player in gsw2007.players: print(player.name, ':', player.player_id)"
},
{
"code": null,
"e": 7592,
"s": 6883,
"text": "As the Roster class creates an instance of the Player class for each player on the roster, and constructing each instance requires a request to Sports Reference’s servers, it can be quite slow to use the Roster class for a simple task like this. If we wanted to print the name of every player in the league for a given season using this method we might have to wait 5+ minutes to create all the Player class instances. As an alternative, we can call the Roster class using the keyword argument slim = True. This will create an instance of the Roster class where the ‘players’ property is simply a dictionary, where keys are the player_ids and values are names. The code below demonstrates this functionality."
},
{
"code": null,
"e": 7667,
"s": 7592,
"text": "gsw2007slim = Roster('GSW', year = '2007', slim = True)gsw2007slim.players"
},
{
"code": null,
"e": 8162,
"s": 7667,
"text": "Not surprisingly, the Player module is used to acquire information on individual players. Referring to the API documentation, we can see that the Player module contains an abstract class, AbstractPlayer, that is inherited by the BoxscorePlayer and Player classes that we’ve already seen in the Boxscore and Roster modules. As such, the proper way to obtain Player data is actually through the Roster and Boxscore modules. Let’s use the player_id that we pulled for Baron Davis to get his stats."
},
{
"code": null,
"e": 8262,
"s": 8162,
"text": "from sportsreference.nba.roster import Playerbaron_davis = Player('davisba01')baron_davis.dataframe"
},
{
"code": null,
"e": 8912,
"s": 8262,
"text": "This simple bit of code gives us 89 columns of data for Baron Davis’ career and every one of his seasons. In addition to the ‘dataframe’ property and all of its associated columns, the Player class also contains properties such as ‘birth_date’, ‘height’, ‘weight’, ‘nationality’, and more. Further, a single career statistic, such as points, can be queried with the command baron_davis.points. Similarly, we could query Baron Davis’ total points in the 2006–07 season using the command baron_davis('2007').points. Depending on the use case, it may be easier to access player statistics in this more direct fashion and avoid dealing with a dataframe."
},
{
"code": null,
"e": 9207,
"s": 8912,
"text": "To wrap up this article I’ll demonstrate how to use the Teams, Roster, and Player modules to build a massive dataset of NBA player statistics. This dataset will be used in my next article where I’ll be taking a look at player development, and eventual decline, over the course of an NBA career."
},
{
"code": null,
"e": 9439,
"s": 9207,
"text": "The first step is to import the relevant modules and define a function that creates a player dataframe with a few extra fields that I’ve defined manually. Most important being a player’s age on January 1st of the respective season."
},
{
"code": null,
"e": 10837,
"s": 9439,
"text": "# Function to get player info from Player class object.def get_player_df(player): # helper function to get player age during each season. def get_age(year, bd): if year[0] == \"Career\": return None else: year_dt = datetime(int(year[0][0:4]) + 1, 1, 1) age_years = relativedelta(year_dt, bd).years + relativedelta(year_dt, bd).months/12 return age_years # helper function to get year for each row and denote # rows that contain career totals. def get_year(ix): if ix[0] == \"Career\": return \"Career\" elif ix[0] == \"1999-00\": return \"2000\" else: return ix[0][0:2] + ix[0][-2:] # get player df and add some extra info player_df = player.dataframe player_df['birth_date'] = player.birth_date player_df['player_id'] = player.player_id player_df['name'] = player.name player_df['year'] = [get_year(ix) for ix in player_df.index] player_df['id'] = [player_id + ' ' + year for player_id, year in zip(player_df['player_id'], player_df['year'])] player_df['age'] = [get_age(year, bd) for year, bd in zip(player_df.index, player_df['birth_date'])] player_df.set_index('id', drop = True, inplace = True) return player_df"
},
{
"code": null,
"e": 11452,
"s": 10837,
"text": "Next, I use the function defined above to collect player data spanning entire careers for every player to play in the NBA within the last 20 years. Data is split between two dataframes, one which aggregates data at the season level and another which aggregates at the career level. This is done by using the Teams and Roster modules to iterate through every NBA roster from the year 2000 to 2020. Note that I call the Roster class using the keyword variable slim = True. Without this setting I’d have to create a Player instance for every season a player was in the NBA, increasing the running time by roughly 10x."
},
{
"code": null,
"e": 13348,
"s": 11452,
"text": "# initialize a list of players that we have pulled data forplayers_collected = []season_df_init = 0career_df_init = 0season_df = 0career_df = 0# iterate through years.for year in range(2020, 1999, -1): print('\\n' + str(year)) # iterate through all teams in that year. for team in Teams(year = str(year)).dataframes.index: print('\\n' + team + '\\n') # iterate through every player on a team roster. for player_id in Roster(team, year = year, slim = True).players.keys(): # only pull player info if that player hasn't # been pulled already. if player_id not in players_collected: player = Player(player_id) player_info = get_player_df(player) player_seasons = player_info[ player_info['year'] != \"Career\"] player_career = player_info[ player_info['year'] == \"Career\"] # create season_df if not initialized if not season_df_init: season_df = player_seasons season_df_init = 1 # else concatenate to season_df else: season_df = pd.concat([season_df, player_seasons], axis = 0) if not career_df_init: career_df = player_career career_df_init = 1 # else concatenate to career_df else: career_df = pd.concat([career_df, player_career], axis = 0) # add player to players_collected players_collected.append(player_id) print(player.name)"
},
{
"code": null,
"e": 13429,
"s": 13348,
"text": "The final step is to save the resulting dataframes to your favorite file format."
},
{
"code": null,
"e": 13530,
"s": 13429,
"text": "season_df.to_csv('nba_player_stats_by_season.csv')career_df.to_csv('nba_player_stats_by_career.csv')"
},
{
"code": null,
"e": 13771,
"s": 13530,
"text": "Altogether this script should compile and save your dataset within about 30 minutes. If you understand all the code in this final section then you should be more than ready to start building your own datasets using the Sports Reference API."
},
{
"code": null,
"e": 13939,
"s": 13771,
"text": "Be sure to look out for my article next week when I use this dataset to analyze NBA career trajectories, and also check out my article from last week Beating the Odds."
}
] |
Maximum path sum in a triangle. - GeeksforGeeks
|
07 Apr, 2022
We have given numbers in form of triangle, by starting at the top of the triangle and moving to adjacent numbers on the row below, find the maximum total from top to bottom. Examples :
Input :
3
7 4
2 4 6
8 5 9 3
Output : 23
Explanation : 3 + 7 + 4 + 9 = 23
Input :
8
-4 4
2 2 6
1 1 1 1
Output : 19
Explanation : 8 + 4 + 6 + 1 = 19
Method1: We can go through the brute force by checking every possible path but that is much time taking so we should try to solve this problem with the help of dynamic programming which reduces the time complexity.
Implementation of Recursive Approach:
C++
Python3
Javascript
// C++ program for// Recursive implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int i, int j, int row, int col){ if(j == col ){ return 0; } if(i == row-1 ){ return tri[i][j] ; } return tri[i][j] + max(maxPathSum(tri, i+1, j, row, col), maxPathSum(tri, i+1, j+1, row, col)) ;} /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; cout << maxPathSum(tri, 0, 0, 3, 3); return 0;}
# Python program for# Recursive implementation of# Max sum problem in a triangleN = 3 # Function for finding maximum sumdef maxPathSum(tri, i, j, row, col): if(j == col ): return 0 if(i == row-1 ): return tri[i][j] return tri[i][j] + max(maxPathSum(tri, i+1, j, row, col), maxPathSum(tri, i+1, j+1, row, col)) # Driver program to test above functionstri = [ [1, 0, 0],[4, 8, 0],[1, 5, 3] ]print(maxPathSum(tri, 0, 0, 3, 3)) # This code is contributed by shinjanpatra
<script> // JavaScript program for// Recursive implementation of// Max sum problem in a triangle const N = 3 // Function for finding maximum sumfunction maxPathSum(tri, i, j, row, col){ if(j == col ){ return 0; } if(i == row-1 ){ return tri[i][j] ; } return tri[i][j] + Math.max(maxPathSum(tri, i+1, j, row, col), maxPathSum(tri, i+1, j+1, row, col)) ;} /* Driver program to test above functions */let tri = [ [1, 0, 0],[4, 8, 0],[1, 5, 3] ];document.write(maxPathSum(tri, 0, 0, 3, 3)); // This code is contributed by shinjanpatra </script>
14
Complexity Analysis:
Time Complexity: O(2N*N)
Space Complexity: O(N)
If we should left shift every element and put 0 at each empty position to make it a regular matrix, then our problem looks like minimum cost path. So, after converting our input triangle elements into a regular matrix we should apply the dynamic programmic concept to find the maximum path sum.
Method 2: DP Top-Down
Since there are overlapping subproblems, we can avoid the repeated work done in method 1 by storing the min-cost path calculated so far using top-down approach
C++
// C++ program for Dynamic// Programming implementation (Top-Down) of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int i, int j, int row, int col, vector<vector<int>> &dp){ if(j == col ){ return 0; } if(i == row-1 ){ return tri[i][j] ; } if(dp[i][j] != -1){ return -1 ; } return dp[i][j] = tri[i][j] + max(maxPathSum(tri, i+1, j, row, col, dp), maxPathSum(tri, i+1, j+1, row, col, dp)) ;} /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; vector<vector<int>> dp(N, vector<int>(N, -1) ) ; cout << maxPathSum(tri, 0, 0, N, N, dp); return 0;}
14
Complexity Analysis:
Time Complexity: O(m*n) where m = no of rows and n = no of columns
Space Complexity: O(n2)
Method 3: DP(Bottom – UP)
Since there are overlapping subproblems, we can avoid the repeated work done in method 1 by storing the min-cost path calculated so far using bottom-up approach thus reducing stack space
C++
// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int n, vector<vector<int>> &dp){ // loop for bottom-up calculation for(int j = 0; j < n; j++ ){ dp[n-1][j] = tri[n-1][j] ; } for(int i = n-2; i >= 0; i--){ for(int j = i; j >= 0; j-- ){ dp[i][j] = tri[i][j] + max(dp[i+1][j] , dp[i+1][j+1]) ; } } return dp[0][0] ; } /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; vector<vector<int>> dp(N, vector<int>(N, -1) ) ; cout << maxPathSum(tri, N, dp); return 0;}
14
Complexity Analysis:
Time Complexity: O(m*n) where m = no of rows and n = no of columns
Space Complexity: O(n2)
Method 4: Space Optimization (Without Changning input matrix)
We do not need a 2d matrix we only need a 1d array that stores the minimum of the immediate next column and thus we can reducing space
C++
// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int n, vector<vector<int>> &dp){ vector<int> front(n, -1) , curr(n, -1) ; for(int j = 0; j < n; j++ ){ front[j] = tri[n-1][j] ; } for(int i = n-2; i >= 0; i--){ for(int j = i; j >= 0; j-- ){ curr[j] = tri[i][j] + max(front[j] , front[j+1]) ; } front = curr ; } return front[0] ; } /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; vector<vector<int>> dp(N, vector<int>(N, -1) ) ; cout << maxPathSum(tri, N, dp); return 0;}
14
Complexity Analysis:
Time Complexity: O(m*n) where m = no of rows and n = no of columns
Space Complexity: O(n)
Method 5: Space Optimization (Changing input matrix)
Applying, DP in bottom-up manner we should solve our problem as: Example:
3
7 4
2 4 6
8 5 9 3
Step 1 :
3 0 0 0
7 4 0 0
2 4 6 0
8 5 9 3
Step 2 :
3 0 0 0
7 4 0 0
10 13 15 0
Step 3 :
3 0 0 0
20 19 0 0
Step 4:
23 0 0 0
output : 23
C++
Java
Python3
C#
PHP
Javascript
// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int m, int n){ // loop for bottom-up calculation for (int i=m-1; i>=0; i--) { for (int j=0; j<=i; j++) { // for each element, check both // elements just below the number // and below right to the number // add the maximum of them to it if (tri[i+1][j] > tri[i+1][j+1]) tri[i][j] += tri[i+1][j]; else tri[i][j] += tri[i+1][j+1]; } } // return the top element // which stores the maximum sum return tri[0][0];} /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; cout << maxPathSum(tri, 2, 2); return 0;}
// Java Program for Dynamic// Programming implementation of// Max sum problem in a triangleimport java.io.*; class GFG { static int N = 3; // Function for finding maximum sum static int maxPathSum(int tri[][], int m, int n) { // loop for bottom-up calculation for (int i = m - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { // for each element, check both // elements just below the number // and below right to the number // add the maximum of them to it if (tri[i + 1][j] > tri[i + 1][j + 1]) tri[i][j] += tri[i + 1][j]; else tri[i][j] += tri[i + 1][j + 1]; } } // return the top element // which stores the maximum sum return tri[0][0]; } /* Driver program to test above functions */ public static void main (String[] args) { int tri[][] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; System.out.println ( maxPathSum(tri, 2, 2)); }} // This code is contributed by vt_m
# Python program for# Dynamic Programming# implementation of Max# sum problem in a# triangle N = 3 # Function for finding maximum sumdef maxPathSum(tri, m, n): # loop for bottom-up calculation for i in range(m-1, -1, -1): for j in range(i+1): # for each element, check both # elements just below the number # and below right to the number # add the maximum of them to it if (tri[i+1][j] > tri[i+1][j+1]): tri[i][j] += tri[i+1][j] else: tri[i][j] += tri[i+1][j+1] # return the top element # which stores the maximum sum return tri[0][0] # Driver program to test above function tri = [[1, 0, 0], [4, 8, 0], [1, 5, 3]]print(maxPathSum(tri, 2, 2)) # This code is contributed# by Soumen Ghosh.
// C# Program for Dynamic Programming// implementation of Max sum problem// in a triangleusing System; class GFG { // Function for finding maximum sum static int maxPathSum(int [,]tri, int m, int n) { // loop for bottom-up calculation for (int i = m - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { // for each element, // check both elements // just below the number // and below right to // the number add the // maximum of them to it if (tri[i + 1,j] > tri[i + 1,j + 1]) tri[i,j] += tri[i + 1,j]; else tri[i,j] += tri[i + 1,j + 1]; } } // return the top element // which stores the maximum sum return tri[0,0]; } /* Driver program to test above functions */ public static void Main () { int [,]tri = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; Console.Write ( maxPathSum(tri, 2, 2)); }} // This code is contributed by nitin mittal.
<?php// PHP program for Dynamic// Programming implementation of// Max sum problem in a triangle // Function for finding// maximum sumfunction maxPathSum($tri, $m, $n){ // loop for bottom-up // calculation for ( $i = $m - 1; $i >= 0; $i--) { for ($j = 0; $j <= $i; $j++) { // for each element, check // both elements just below // the number and below right // to the number add the maximum // of them to it if ($tri[$i + 1][$j] > $tri[$i + 1] [$j + 1]) $tri[$i][$j] += $tri[$i + 1][$j]; else $tri[$i][$j] += $tri[$i + 1] [$j + 1]; } } // return the top element // which stores the maximum sum return $tri[0][0];} // Driver Code$tri= array(array(1, 0, 0), array(4, 8, 0), array(1, 5, 3));echo maxPathSum($tri, 2, 2); // This code is contributed by ajit?>
<script>// Javascript Program for Dynamic// Programming implementation of// Max sum problem in a triangle let N = 3; // Function for finding maximum sum function maxPathSum(tri, m, n) { // loop for bottom-up calculation for (let i = m - 1; i >= 0; i--) { for (let j = 0; j <= i; j++) { // for each element, check both // elements just below the number // and below right to the number // add the maximum of them to it if (tri[i + 1][j] > tri[i + 1][j + 1]) tri[i][j] += tri[i + 1][j]; else tri[i][j] += tri[i + 1][j + 1]; } } // return the top element // which stores the maximum sum return tri[0][0]; } // Driver code let tri = [[1, 0, 0], [4, 8, 0], [1, 5, 3]]; document.write( maxPathSum(tri, 2, 2)); // This code is contributed by susmitakundugoaldanga. </script>
14
Complexity Analysis:
Time Complexity: O(m*n) where m = no of rows and n = no of columns
Space Complexity: O(1)
This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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.
jit_t
nitin mittal
susmitakundugoaldanga
prasanna1995
shinjanpatra
triangle
Dynamic Programming
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Matrix Chain Multiplication | DP-8
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Sieve of Eratosthenes
Edit Distance | DP-5
Minimum number of jumps to reach end
Efficient program to print all prime factors of a given number
Overlapping Subproblems Property in Dynamic Programming | DP-1
Find minimum number of coins that make a given value
|
[
{
"code": null,
"e": 25024,
"s": 24996,
"text": "\n07 Apr, 2022"
},
{
"code": null,
"e": 25211,
"s": 25024,
"text": "We have given numbers in form of triangle, by starting at the top of the triangle and moving to adjacent numbers on the row below, find the maximum total from top to bottom. Examples : "
},
{
"code": null,
"e": 25373,
"s": 25211,
"text": "Input : \n 3\n 7 4\n 2 4 6\n8 5 9 3\nOutput : 23\nExplanation : 3 + 7 + 4 + 9 = 23 \n\nInput :\n 8\n -4 4\n 2 2 6\n1 1 1 1\nOutput : 19\nExplanation : 8 + 4 + 6 + 1 = 19 "
},
{
"code": null,
"e": 25591,
"s": 25375,
"text": "Method1: We can go through the brute force by checking every possible path but that is much time taking so we should try to solve this problem with the help of dynamic programming which reduces the time complexity. "
},
{
"code": null,
"e": 25629,
"s": 25591,
"text": "Implementation of Recursive Approach:"
},
{
"code": null,
"e": 25633,
"s": 25629,
"text": "C++"
},
{
"code": null,
"e": 25641,
"s": 25633,
"text": "Python3"
},
{
"code": null,
"e": 25652,
"s": 25641,
"text": "Javascript"
},
{
"code": "// C++ program for// Recursive implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int i, int j, int row, int col){ if(j == col ){ return 0; } if(i == row-1 ){ return tri[i][j] ; } return tri[i][j] + max(maxPathSum(tri, i+1, j, row, col), maxPathSum(tri, i+1, j+1, row, col)) ;} /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; cout << maxPathSum(tri, 0, 0, 3, 3); return 0;}",
"e": 26323,
"s": 25652,
"text": null
},
{
"code": "# Python program for# Recursive implementation of# Max sum problem in a triangleN = 3 # Function for finding maximum sumdef maxPathSum(tri, i, j, row, col): if(j == col ): return 0 if(i == row-1 ): return tri[i][j] return tri[i][j] + max(maxPathSum(tri, i+1, j, row, col), maxPathSum(tri, i+1, j+1, row, col)) # Driver program to test above functionstri = [ [1, 0, 0],[4, 8, 0],[1, 5, 3] ]print(maxPathSum(tri, 0, 0, 3, 3)) # This code is contributed by shinjanpatra",
"e": 26853,
"s": 26323,
"text": null
},
{
"code": "<script> // JavaScript program for// Recursive implementation of// Max sum problem in a triangle const N = 3 // Function for finding maximum sumfunction maxPathSum(tri, i, j, row, col){ if(j == col ){ return 0; } if(i == row-1 ){ return tri[i][j] ; } return tri[i][j] + Math.max(maxPathSum(tri, i+1, j, row, col), maxPathSum(tri, i+1, j+1, row, col)) ;} /* Driver program to test above functions */let tri = [ [1, 0, 0],[4, 8, 0],[1, 5, 3] ];document.write(maxPathSum(tri, 0, 0, 3, 3)); // This code is contributed by shinjanpatra </script>",
"e": 27465,
"s": 26853,
"text": null
},
{
"code": null,
"e": 27468,
"s": 27465,
"text": "14"
},
{
"code": null,
"e": 27489,
"s": 27468,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 27514,
"s": 27489,
"text": "Time Complexity: O(2N*N)"
},
{
"code": null,
"e": 27538,
"s": 27514,
"text": "Space Complexity: O(N)"
},
{
"code": null,
"e": 27834,
"s": 27538,
"text": "If we should left shift every element and put 0 at each empty position to make it a regular matrix, then our problem looks like minimum cost path. So, after converting our input triangle elements into a regular matrix we should apply the dynamic programmic concept to find the maximum path sum. "
},
{
"code": null,
"e": 27856,
"s": 27834,
"text": "Method 2: DP Top-Down"
},
{
"code": null,
"e": 28016,
"s": 27856,
"text": "Since there are overlapping subproblems, we can avoid the repeated work done in method 1 by storing the min-cost path calculated so far using top-down approach"
},
{
"code": null,
"e": 28020,
"s": 28016,
"text": "C++"
},
{
"code": "// C++ program for Dynamic// Programming implementation (Top-Down) of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int i, int j, int row, int col, vector<vector<int>> &dp){ if(j == col ){ return 0; } if(i == row-1 ){ return tri[i][j] ; } if(dp[i][j] != -1){ return -1 ; } return dp[i][j] = tri[i][j] + max(maxPathSum(tri, i+1, j, row, col, dp), maxPathSum(tri, i+1, j+1, row, col, dp)) ;} /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; vector<vector<int>> dp(N, vector<int>(N, -1) ) ; cout << maxPathSum(tri, 0, 0, N, N, dp); return 0;}",
"e": 28871,
"s": 28020,
"text": null
},
{
"code": null,
"e": 28874,
"s": 28871,
"text": "14"
},
{
"code": null,
"e": 28895,
"s": 28874,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 28963,
"s": 28895,
"text": "Time Complexity: O(m*n) where m = no of rows and n = no of columns"
},
{
"code": null,
"e": 28987,
"s": 28963,
"text": "Space Complexity: O(n2)"
},
{
"code": null,
"e": 29013,
"s": 28987,
"text": "Method 3: DP(Bottom – UP)"
},
{
"code": null,
"e": 29200,
"s": 29013,
"text": "Since there are overlapping subproblems, we can avoid the repeated work done in method 1 by storing the min-cost path calculated so far using bottom-up approach thus reducing stack space"
},
{
"code": null,
"e": 29204,
"s": 29200,
"text": "C++"
},
{
"code": "// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int n, vector<vector<int>> &dp){ // loop for bottom-up calculation for(int j = 0; j < n; j++ ){ dp[n-1][j] = tri[n-1][j] ; } for(int i = n-2; i >= 0; i--){ for(int j = i; j >= 0; j-- ){ dp[i][j] = tri[i][j] + max(dp[i+1][j] , dp[i+1][j+1]) ; } } return dp[0][0] ; } /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; vector<vector<int>> dp(N, vector<int>(N, -1) ) ; cout << maxPathSum(tri, N, dp); return 0;}",
"e": 30039,
"s": 29204,
"text": null
},
{
"code": null,
"e": 30042,
"s": 30039,
"text": "14"
},
{
"code": null,
"e": 30063,
"s": 30042,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 30130,
"s": 30063,
"text": "Time Complexity: O(m*n) where m = no of rows and n = no of columns"
},
{
"code": null,
"e": 30154,
"s": 30130,
"text": "Space Complexity: O(n2)"
},
{
"code": null,
"e": 30216,
"s": 30154,
"text": "Method 4: Space Optimization (Without Changning input matrix)"
},
{
"code": null,
"e": 30352,
"s": 30216,
"text": "We do not need a 2d matrix we only need a 1d array that stores the minimum of the immediate next column and thus we can reducing space"
},
{
"code": null,
"e": 30356,
"s": 30352,
"text": "C++"
},
{
"code": "// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int n, vector<vector<int>> &dp){ vector<int> front(n, -1) , curr(n, -1) ; for(int j = 0; j < n; j++ ){ front[j] = tri[n-1][j] ; } for(int i = n-2; i >= 0; i--){ for(int j = i; j >= 0; j-- ){ curr[j] = tri[i][j] + max(front[j] , front[j+1]) ; } front = curr ; } return front[0] ; } /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; vector<vector<int>> dp(N, vector<int>(N, -1) ) ; cout << maxPathSum(tri, N, dp); return 0;}",
"e": 31231,
"s": 30356,
"text": null
},
{
"code": null,
"e": 31234,
"s": 31231,
"text": "14"
},
{
"code": null,
"e": 31255,
"s": 31234,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 31322,
"s": 31255,
"text": "Time Complexity: O(m*n) where m = no of rows and n = no of columns"
},
{
"code": null,
"e": 31345,
"s": 31322,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 31398,
"s": 31345,
"text": "Method 5: Space Optimization (Changing input matrix)"
},
{
"code": null,
"e": 31475,
"s": 31398,
"text": " Applying, DP in bottom-up manner we should solve our problem as: Example: "
},
{
"code": null,
"e": 31649,
"s": 31475,
"text": " 3\n 7 4\n 2 4 6\n8 5 9 3\n\nStep 1 :\n3 0 0 0\n7 4 0 0\n2 4 6 0\n8 5 9 3\n\nStep 2 :\n3 0 0 0\n7 4 0 0\n10 13 15 0\n\nStep 3 :\n3 0 0 0\n20 19 0 0\n\nStep 4:\n23 0 0 0\n\noutput : 23"
},
{
"code": null,
"e": 31655,
"s": 31651,
"text": "C++"
},
{
"code": null,
"e": 31660,
"s": 31655,
"text": "Java"
},
{
"code": null,
"e": 31668,
"s": 31660,
"text": "Python3"
},
{
"code": null,
"e": 31671,
"s": 31668,
"text": "C#"
},
{
"code": null,
"e": 31675,
"s": 31671,
"text": "PHP"
},
{
"code": null,
"e": 31686,
"s": 31675,
"text": "Javascript"
},
{
"code": "// C++ program for Dynamic// Programming implementation of// Max sum problem in a triangle#include<bits/stdc++.h>using namespace std;#define N 3 // Function for finding maximum sumint maxPathSum(int tri[][N], int m, int n){ // loop for bottom-up calculation for (int i=m-1; i>=0; i--) { for (int j=0; j<=i; j++) { // for each element, check both // elements just below the number // and below right to the number // add the maximum of them to it if (tri[i+1][j] > tri[i+1][j+1]) tri[i][j] += tri[i+1][j]; else tri[i][j] += tri[i+1][j+1]; } } // return the top element // which stores the maximum sum return tri[0][0];} /* Driver program to test above functions */int main(){ int tri[N][N] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; cout << maxPathSum(tri, 2, 2); return 0;}",
"e": 32652,
"s": 31686,
"text": null
},
{
"code": "// Java Program for Dynamic// Programming implementation of// Max sum problem in a triangleimport java.io.*; class GFG { static int N = 3; // Function for finding maximum sum static int maxPathSum(int tri[][], int m, int n) { // loop for bottom-up calculation for (int i = m - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { // for each element, check both // elements just below the number // and below right to the number // add the maximum of them to it if (tri[i + 1][j] > tri[i + 1][j + 1]) tri[i][j] += tri[i + 1][j]; else tri[i][j] += tri[i + 1][j + 1]; } } // return the top element // which stores the maximum sum return tri[0][0]; } /* Driver program to test above functions */ public static void main (String[] args) { int tri[][] = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; System.out.println ( maxPathSum(tri, 2, 2)); }} // This code is contributed by vt_m",
"e": 33839,
"s": 32652,
"text": null
},
{
"code": "# Python program for# Dynamic Programming# implementation of Max# sum problem in a# triangle N = 3 # Function for finding maximum sumdef maxPathSum(tri, m, n): # loop for bottom-up calculation for i in range(m-1, -1, -1): for j in range(i+1): # for each element, check both # elements just below the number # and below right to the number # add the maximum of them to it if (tri[i+1][j] > tri[i+1][j+1]): tri[i][j] += tri[i+1][j] else: tri[i][j] += tri[i+1][j+1] # return the top element # which stores the maximum sum return tri[0][0] # Driver program to test above function tri = [[1, 0, 0], [4, 8, 0], [1, 5, 3]]print(maxPathSum(tri, 2, 2)) # This code is contributed# by Soumen Ghosh.",
"e": 34661,
"s": 33839,
"text": null
},
{
"code": "// C# Program for Dynamic Programming// implementation of Max sum problem// in a triangleusing System; class GFG { // Function for finding maximum sum static int maxPathSum(int [,]tri, int m, int n) { // loop for bottom-up calculation for (int i = m - 1; i >= 0; i--) { for (int j = 0; j <= i; j++) { // for each element, // check both elements // just below the number // and below right to // the number add the // maximum of them to it if (tri[i + 1,j] > tri[i + 1,j + 1]) tri[i,j] += tri[i + 1,j]; else tri[i,j] += tri[i + 1,j + 1]; } } // return the top element // which stores the maximum sum return tri[0,0]; } /* Driver program to test above functions */ public static void Main () { int [,]tri = { {1, 0, 0}, {4, 8, 0}, {1, 5, 3} }; Console.Write ( maxPathSum(tri, 2, 2)); }} // This code is contributed by nitin mittal.",
"e": 35965,
"s": 34661,
"text": null
},
{
"code": "<?php// PHP program for Dynamic// Programming implementation of// Max sum problem in a triangle // Function for finding// maximum sumfunction maxPathSum($tri, $m, $n){ // loop for bottom-up // calculation for ( $i = $m - 1; $i >= 0; $i--) { for ($j = 0; $j <= $i; $j++) { // for each element, check // both elements just below // the number and below right // to the number add the maximum // of them to it if ($tri[$i + 1][$j] > $tri[$i + 1] [$j + 1]) $tri[$i][$j] += $tri[$i + 1][$j]; else $tri[$i][$j] += $tri[$i + 1] [$j + 1]; } } // return the top element // which stores the maximum sum return $tri[0][0];} // Driver Code$tri= array(array(1, 0, 0), array(4, 8, 0), array(1, 5, 3));echo maxPathSum($tri, 2, 2); // This code is contributed by ajit?>",
"e": 36967,
"s": 35965,
"text": null
},
{
"code": "<script>// Javascript Program for Dynamic// Programming implementation of// Max sum problem in a triangle let N = 3; // Function for finding maximum sum function maxPathSum(tri, m, n) { // loop for bottom-up calculation for (let i = m - 1; i >= 0; i--) { for (let j = 0; j <= i; j++) { // for each element, check both // elements just below the number // and below right to the number // add the maximum of them to it if (tri[i + 1][j] > tri[i + 1][j + 1]) tri[i][j] += tri[i + 1][j]; else tri[i][j] += tri[i + 1][j + 1]; } } // return the top element // which stores the maximum sum return tri[0][0]; } // Driver code let tri = [[1, 0, 0], [4, 8, 0], [1, 5, 3]]; document.write( maxPathSum(tri, 2, 2)); // This code is contributed by susmitakundugoaldanga. </script>",
"e": 38070,
"s": 36967,
"text": null
},
{
"code": null,
"e": 38073,
"s": 38070,
"text": "14"
},
{
"code": null,
"e": 38094,
"s": 38073,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 38161,
"s": 38094,
"text": "Time Complexity: O(m*n) where m = no of rows and n = no of columns"
},
{
"code": null,
"e": 38184,
"s": 38161,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 38620,
"s": 38184,
"text": "This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. 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": 38626,
"s": 38620,
"text": "jit_t"
},
{
"code": null,
"e": 38639,
"s": 38626,
"text": "nitin mittal"
},
{
"code": null,
"e": 38661,
"s": 38639,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 38674,
"s": 38661,
"text": "prasanna1995"
},
{
"code": null,
"e": 38687,
"s": 38674,
"text": "shinjanpatra"
},
{
"code": null,
"e": 38696,
"s": 38687,
"text": "triangle"
},
{
"code": null,
"e": 38716,
"s": 38696,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38736,
"s": 38716,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 38834,
"s": 38736,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38843,
"s": 38834,
"text": "Comments"
},
{
"code": null,
"e": 38856,
"s": 38843,
"text": "Old Comments"
},
{
"code": null,
"e": 38887,
"s": 38856,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 38920,
"s": 38887,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 38955,
"s": 38920,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 39023,
"s": 38955,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
},
{
"code": null,
"e": 39045,
"s": 39023,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 39066,
"s": 39045,
"text": "Edit Distance | DP-5"
},
{
"code": null,
"e": 39103,
"s": 39066,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 39166,
"s": 39103,
"text": "Efficient program to print all prime factors of a given number"
},
{
"code": null,
"e": 39229,
"s": 39166,
"text": "Overlapping Subproblems Property in Dynamic Programming | DP-1"
}
] |
Standing Out From the Cloud: How to Shape and Format a Word Cloud | by Andrew Jamieson | Towards Data Science
|
This blog will cover Word Clouds, their limitations, followed by some formatting examples.
Word Clouds are a straightforward way to summarize text and make the most popular words jump to your attention. They are eye-catching and easy to understand without the need for any additional explanation.
However, Word Clouds do have limitations. They are not helpful for an in-depth analysis. They may be more attractive to look at than a simple bar chart — but they provide far less information. Here are some of the problems with Word Clouds.
Font size is not an effective way to show differences. We can distinguish between large, medium, and small fonts; beyond that, it gets tricky.
We don’t know how the words are weighted — what does a large font actually mean? Does the word with the large font occur 10 times or 1000 times?
Positioning in visualization is usually very important. However, in Word Clouds, the word order is at random.
Longer words receive greater emphasis than shorter words because their length takes up more space.
We don’t learn anything about the context of the words. In some cases, the opposite meaning is highlighted — for example, the phrase “not good” would be represented on a Word Cloud as “good” after the stopword of “not” is removed.
Despite these limitations, Word Clouds have become incredibly popular, primarily because they are easy to create. The popularity and drawbacks of Word Clouds mean that they have many detractors — my favorite Word Cloud (or “Tag Cloud”) insult is that they are “the new mullets”... ouch.
You didn’t read this blog to learn about how terrible Word Clouds are. There are plenty of other blogs for that. Words Clouds are an excellent tool for drawing attention. They are handy as an introduction and to break up heavy text passages. So, how do you make your Word Cloud jump out from the cloud?
For these examples, I will use an Emoji from OpenMoji and text about emojis from Wikipedia to form the cloud.
“A yellow face with simple, open eyes and a thin, closed smile. Conveys a wide range of positive, happy, and friendly sentiments. Its tone can also be patronizing, passive-aggressive, or ironic, as if saying This is fine when it’s really not.”
https://emojipedia.org/slightly-smiling-face/
Here are the libraries to use
from PIL import Imagefrom wordcloud import WordCloud, STOPWORDS, ImageColorGeneratorimport matplotlib.pyplot as plt%matplotlib inlineimport numpy as np
# Default WordCloudwordcloud = WordCloud().generate(emoji_text) plt.figure(figsize=(10,6))plt.imshow(wordcloud)plt.axis(“off”)plt.show()
wordcloud = WordCloud(max_font_size=80, max_words=1000, background_color=”black”, colormap=’Paired’).generate(emoji_text)# Use the lasst four lines from above (plt) to plot the Word Cloudplt...
Here we have changed some of the default parameters — using background_color, max_font_size, and colormap — any Matplotlib palette will work and setting the font.
In this example, I’m also using font_path to choose a custom font. You set this to the file location of your chosen font. For example:
font_path = “/Users/You/Fonts/Comfortaa-Bold.ttf”
WordCloud also has a built-in list of stopwords that you can ignore, adjust, or use like this:
stopwords = set(STOPWORDS)
You can create a shape for your word cloud by using a mask. First, upload a png image and convert it to an array. Wordcloud will draw words in positions where the image is not white. In the array, 255 is white, and 1 is black.
mask2 = np.array(Image.open("paint1a.png"))emo2 = WordCloud(font_path = font_path, background_color="white", max_words=100, mask=mask2, stopwords=stopwords, min_font_size=10, colormap='Dark2')# Generate a wordcloudemo2.generate(emoji_text)# plt ...
If your image has a transparent background, it will throw an error.
ValueError: bad transparency mask
The mask needs the white value to be 255 and not 0. You can inspect your image by looking at the array.
emoji_mask = np.array(Image.open(“1F642_color.png”))emoji_maskarray([[0, 0, 0, ..., 0, 0, 0],...,[0, 0, 0, ..., 0, 0, 0]], dtype=uint8)# replace 0 with 255emoji_mask[emoji_mask == 0] = 255emoji_maskarray([[255, 255, 255, ..., 255, 255, 255],...,[255, 255, 255, ..., 255, 255, 255]], dtype=uint8)
You can also use the ImageColorGenerator function to set the colormap to match the image. (The dark patches are the eyes and mouth of our emoji. You may need to reduce max_font_size to improve the look of image details )
# note — need to set max font size, or font extends over the colorsmask = np.array(Image.open(“paint1.png”))emo_clr = WordCloud(background_color=”white”, mode=”RGBA”, max_words=3000, max_font_size=18, mask=mask).generate(emoji_text)# create coloring from imageimage_colors = ImageColorGenerator(mask)plt.figure(figsize=[7,7])plt.imshow(emo_clr.recolor(color_func=image_colors), interpolation=”bilinear”)plt.axis(“off”)plt.show()
The emoji does show how the color effect works, but it isn’t a great example. The yellow color barely shows up on the white background, and it is impossible to read the words. In order to show the definition of the eyes and mouth, this Word Cloud uses a massive max word count and a small maximum font. I recommend that you experiment with color and make the fonts as large as possible while maintaining the borders of each color. Some images work better than others — colors in straight lines work better than colors with curves.
Some images will generate an error when you use color.
NotImplementedError: Gray-scale images TODO
The color function looks for a three-channel array, representing values for red, green, and blue (RGB). Some images only have one channel. You can solve this by adding two extra channels to the array — see Matthew Arthur’s blog post for a great example of how to do this.
Alternatively, I found that by opening the image in Paint or Paintbrush and resaving the image, it transforms into the expected format.
Check your image by inspecting the shape like this:
test = np.array(Image.open(“1F642_color.png”))test.shape(618, 618) # -> error example(618, 618, 3) # -> RGB example
Here’s a similar example, where I adjusted the NumPy array so that the emoji's eyes and mouth are left blank.
mask2 = np.array(Image.open(“paint1.png”))mask3 = np.where(mask2==0, 255, mask2)emo = WordCloud(background_color=”white”, max_words=500, mask=mask3, stopwords=stopwords, colormap=’Dark2')emo.generate(emoji_text)
Finally, you can also experiment with a reverse image. Here we plot the word cloud around a shadow rather than inside a shape. I tweaked this image in MS Paint, reversing the colors, so I had a black outline around a white circle. Finally, I opened it in Python and loaded it as a Word Cloud — the code is the same.
Once you have Word Cloud outline, you can drop the original image on top, like this.
Word Clouds are an excellent way to draw attention to your work. They can be a good lead-in to more in-depth analysis. There are many different ways that you can adjust your Word Cloud and make it unique to your project, rather than restricting yourself to the defaults. I hope that this blog's examples will give you a starting point to create your own Word Clouds.
|
[
{
"code": null,
"e": 263,
"s": 172,
"text": "This blog will cover Word Clouds, their limitations, followed by some formatting examples."
},
{
"code": null,
"e": 469,
"s": 263,
"text": "Word Clouds are a straightforward way to summarize text and make the most popular words jump to your attention. They are eye-catching and easy to understand without the need for any additional explanation."
},
{
"code": null,
"e": 710,
"s": 469,
"text": "However, Word Clouds do have limitations. They are not helpful for an in-depth analysis. They may be more attractive to look at than a simple bar chart — but they provide far less information. Here are some of the problems with Word Clouds."
},
{
"code": null,
"e": 853,
"s": 710,
"text": "Font size is not an effective way to show differences. We can distinguish between large, medium, and small fonts; beyond that, it gets tricky."
},
{
"code": null,
"e": 998,
"s": 853,
"text": "We don’t know how the words are weighted — what does a large font actually mean? Does the word with the large font occur 10 times or 1000 times?"
},
{
"code": null,
"e": 1108,
"s": 998,
"text": "Positioning in visualization is usually very important. However, in Word Clouds, the word order is at random."
},
{
"code": null,
"e": 1207,
"s": 1108,
"text": "Longer words receive greater emphasis than shorter words because their length takes up more space."
},
{
"code": null,
"e": 1438,
"s": 1207,
"text": "We don’t learn anything about the context of the words. In some cases, the opposite meaning is highlighted — for example, the phrase “not good” would be represented on a Word Cloud as “good” after the stopword of “not” is removed."
},
{
"code": null,
"e": 1725,
"s": 1438,
"text": "Despite these limitations, Word Clouds have become incredibly popular, primarily because they are easy to create. The popularity and drawbacks of Word Clouds mean that they have many detractors — my favorite Word Cloud (or “Tag Cloud”) insult is that they are “the new mullets”... ouch."
},
{
"code": null,
"e": 2028,
"s": 1725,
"text": "You didn’t read this blog to learn about how terrible Word Clouds are. There are plenty of other blogs for that. Words Clouds are an excellent tool for drawing attention. They are handy as an introduction and to break up heavy text passages. So, how do you make your Word Cloud jump out from the cloud?"
},
{
"code": null,
"e": 2138,
"s": 2028,
"text": "For these examples, I will use an Emoji from OpenMoji and text about emojis from Wikipedia to form the cloud."
},
{
"code": null,
"e": 2382,
"s": 2138,
"text": "“A yellow face with simple, open eyes and a thin, closed smile. Conveys a wide range of positive, happy, and friendly sentiments. Its tone can also be patronizing, passive-aggressive, or ironic, as if saying This is fine when it’s really not.”"
},
{
"code": null,
"e": 2428,
"s": 2382,
"text": "https://emojipedia.org/slightly-smiling-face/"
},
{
"code": null,
"e": 2458,
"s": 2428,
"text": "Here are the libraries to use"
},
{
"code": null,
"e": 2610,
"s": 2458,
"text": "from PIL import Imagefrom wordcloud import WordCloud, STOPWORDS, ImageColorGeneratorimport matplotlib.pyplot as plt%matplotlib inlineimport numpy as np"
},
{
"code": null,
"e": 2748,
"s": 2610,
"text": "# Default WordCloudwordcloud = WordCloud().generate(emoji_text) plt.figure(figsize=(10,6))plt.imshow(wordcloud)plt.axis(“off”)plt.show()"
},
{
"code": null,
"e": 2942,
"s": 2748,
"text": "wordcloud = WordCloud(max_font_size=80, max_words=1000, background_color=”black”, colormap=’Paired’).generate(emoji_text)# Use the lasst four lines from above (plt) to plot the Word Cloudplt..."
},
{
"code": null,
"e": 3105,
"s": 2942,
"text": "Here we have changed some of the default parameters — using background_color, max_font_size, and colormap — any Matplotlib palette will work and setting the font."
},
{
"code": null,
"e": 3240,
"s": 3105,
"text": "In this example, I’m also using font_path to choose a custom font. You set this to the file location of your chosen font. For example:"
},
{
"code": null,
"e": 3290,
"s": 3240,
"text": "font_path = “/Users/You/Fonts/Comfortaa-Bold.ttf”"
},
{
"code": null,
"e": 3385,
"s": 3290,
"text": "WordCloud also has a built-in list of stopwords that you can ignore, adjust, or use like this:"
},
{
"code": null,
"e": 3412,
"s": 3385,
"text": "stopwords = set(STOPWORDS)"
},
{
"code": null,
"e": 3639,
"s": 3412,
"text": "You can create a shape for your word cloud by using a mask. First, upload a png image and convert it to an array. Wordcloud will draw words in positions where the image is not white. In the array, 255 is white, and 1 is black."
},
{
"code": null,
"e": 3902,
"s": 3639,
"text": "mask2 = np.array(Image.open(\"paint1a.png\"))emo2 = WordCloud(font_path = font_path, background_color=\"white\", max_words=100, mask=mask2, stopwords=stopwords, min_font_size=10, colormap='Dark2')# Generate a wordcloudemo2.generate(emoji_text)# plt ..."
},
{
"code": null,
"e": 3970,
"s": 3902,
"text": "If your image has a transparent background, it will throw an error."
},
{
"code": null,
"e": 4004,
"s": 3970,
"text": "ValueError: bad transparency mask"
},
{
"code": null,
"e": 4108,
"s": 4004,
"text": "The mask needs the white value to be 255 and not 0. You can inspect your image by looking at the array."
},
{
"code": null,
"e": 4404,
"s": 4108,
"text": "emoji_mask = np.array(Image.open(“1F642_color.png”))emoji_maskarray([[0, 0, 0, ..., 0, 0, 0],...,[0, 0, 0, ..., 0, 0, 0]], dtype=uint8)# replace 0 with 255emoji_mask[emoji_mask == 0] = 255emoji_maskarray([[255, 255, 255, ..., 255, 255, 255],...,[255, 255, 255, ..., 255, 255, 255]], dtype=uint8)"
},
{
"code": null,
"e": 4625,
"s": 4404,
"text": "You can also use the ImageColorGenerator function to set the colormap to match the image. (The dark patches are the eyes and mouth of our emoji. You may need to reduce max_font_size to improve the look of image details )"
},
{
"code": null,
"e": 5054,
"s": 4625,
"text": "# note — need to set max font size, or font extends over the colorsmask = np.array(Image.open(“paint1.png”))emo_clr = WordCloud(background_color=”white”, mode=”RGBA”, max_words=3000, max_font_size=18, mask=mask).generate(emoji_text)# create coloring from imageimage_colors = ImageColorGenerator(mask)plt.figure(figsize=[7,7])plt.imshow(emo_clr.recolor(color_func=image_colors), interpolation=”bilinear”)plt.axis(“off”)plt.show()"
},
{
"code": null,
"e": 5585,
"s": 5054,
"text": "The emoji does show how the color effect works, but it isn’t a great example. The yellow color barely shows up on the white background, and it is impossible to read the words. In order to show the definition of the eyes and mouth, this Word Cloud uses a massive max word count and a small maximum font. I recommend that you experiment with color and make the fonts as large as possible while maintaining the borders of each color. Some images work better than others — colors in straight lines work better than colors with curves."
},
{
"code": null,
"e": 5640,
"s": 5585,
"text": "Some images will generate an error when you use color."
},
{
"code": null,
"e": 5684,
"s": 5640,
"text": "NotImplementedError: Gray-scale images TODO"
},
{
"code": null,
"e": 5956,
"s": 5684,
"text": "The color function looks for a three-channel array, representing values for red, green, and blue (RGB). Some images only have one channel. You can solve this by adding two extra channels to the array — see Matthew Arthur’s blog post for a great example of how to do this."
},
{
"code": null,
"e": 6092,
"s": 5956,
"text": "Alternatively, I found that by opening the image in Paint or Paintbrush and resaving the image, it transforms into the expected format."
},
{
"code": null,
"e": 6144,
"s": 6092,
"text": "Check your image by inspecting the shape like this:"
},
{
"code": null,
"e": 6260,
"s": 6144,
"text": "test = np.array(Image.open(“1F642_color.png”))test.shape(618, 618) # -> error example(618, 618, 3) # -> RGB example"
},
{
"code": null,
"e": 6370,
"s": 6260,
"text": "Here’s a similar example, where I adjusted the NumPy array so that the emoji's eyes and mouth are left blank."
},
{
"code": null,
"e": 6582,
"s": 6370,
"text": "mask2 = np.array(Image.open(“paint1.png”))mask3 = np.where(mask2==0, 255, mask2)emo = WordCloud(background_color=”white”, max_words=500, mask=mask3, stopwords=stopwords, colormap=’Dark2')emo.generate(emoji_text)"
},
{
"code": null,
"e": 6898,
"s": 6582,
"text": "Finally, you can also experiment with a reverse image. Here we plot the word cloud around a shadow rather than inside a shape. I tweaked this image in MS Paint, reversing the colors, so I had a black outline around a white circle. Finally, I opened it in Python and loaded it as a Word Cloud — the code is the same."
},
{
"code": null,
"e": 6983,
"s": 6898,
"text": "Once you have Word Cloud outline, you can drop the original image on top, like this."
}
] |
CSS - @ Rules
|
This chapter will cover the following important @ rules −
The @import: rule imports another style sheet into the current style sheet.
The @import: rule imports another style sheet into the current style sheet.
The @charset rule indicates the character set the style sheet uses.
The @charset rule indicates the character set the style sheet uses.
The @font-face rule is used to exhaustively describe a font face for use in a document.
The @font-face rule is used to exhaustively describe a font face for use in a document.
The !important rule indicates that a user-defined rule should take precedence over the author's style sheets.
The !important rule indicates that a user-defined rule should take precedence over the author's style sheets.
NOTE − There are other @ rules which we will cover in subsequent chapters.
The @import rule allows you to import styles from another style sheet. It should appear right at the start of the style sheet before any of the rules, and its value is a URL.
It can be written in one of the two following ways −
<style type = "text/css">
<!--
@import "mystyle.css";
or
@import url("mystyle.css");
.......other CSS rules .....
-->
</style>
The significance of the @import rule is that it allows you to develop your style sheets with a modular approach. You can create various style sheets and then include them wherever you need them.
If you are writing your document using a character set other than ASCII or ISO-8859-1 you might want to set the @charset rule at the top of your style sheet to indicate what character set the style sheet is written in.
The @charset rule must be written right at the beginning of the style sheet without even a space before it. The value is held in quotes and should be one of the standard character-sets. For example −
<style type = "text/css">
<!--
@charset "iso-8859-1"
.......other CSS rules .....
-->
</style>
The @font-face rule is used to exhaustively describe a font face for use in a document. @font-face may also be used to define the location of a font for download, although this may run into implementation-specific limits.
In general, @font-face is extremely complicated, and its use is not recommended for any except those who are expert in font metrics.
Here is an example −
<style type = "text/css">
<!--
@font-face {
font-family: "Scarborough Light";
src: url("http://www.font.site/s/scarbo-lt");
}
@font-face {
font-family: Santiago;
src: local ("Santiago"),
url("http://www.font.site/s/santiago.tt")
format("truetype");
unicode-range: U+??,U+100-220;
font-size: all;
font-family: sans-serif;
}
-->
</style>
Cascading Style Sheets cascade. It means that the styles are applied in the same order as they are read by the browser. The first style is applied and then the second and so on.
The !important rule provides a way to make your CSS cascade. It also includes the rules that are to be applied always. A rule having a !important property will always be applied, no matter where that rule appears in the CSS document.
For example, in the following style sheet, the paragraph text will be black, even though the first style property applied is red:
<style type = "text/css">
<!--
p { color: #ff0000; }
p { color: #000000; }
-->
</style>
So, if you wanted to make sure that a property always applied, you would add the !important property to the tag. So, to make the paragraph text always red, you should write it as follows −
<html>
<head>
<style type = "text/css">
p { color: #ff0000 !important; }
p { color: #000000; }
</style>
</head>
<body>
<p>Tutorialspoint.com</p>
</body>
</html>
Here you have made p { color: #ff0000 !important; } mandatory, now this rule will always apply even you have defined another rule p { color: #000000; }
It will produce the following result −
Tutorialspoint.com
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2684,
"s": 2626,
"text": "This chapter will cover the following important @ rules −"
},
{
"code": null,
"e": 2760,
"s": 2684,
"text": "The @import: rule imports another style sheet into the current style sheet."
},
{
"code": null,
"e": 2836,
"s": 2760,
"text": "The @import: rule imports another style sheet into the current style sheet."
},
{
"code": null,
"e": 2904,
"s": 2836,
"text": "The @charset rule indicates the character set the style sheet uses."
},
{
"code": null,
"e": 2972,
"s": 2904,
"text": "The @charset rule indicates the character set the style sheet uses."
},
{
"code": null,
"e": 3060,
"s": 2972,
"text": "The @font-face rule is used to exhaustively describe a font face for use in a document."
},
{
"code": null,
"e": 3148,
"s": 3060,
"text": "The @font-face rule is used to exhaustively describe a font face for use in a document."
},
{
"code": null,
"e": 3258,
"s": 3148,
"text": "The !important rule indicates that a user-defined rule should take precedence over the author's style sheets."
},
{
"code": null,
"e": 3368,
"s": 3258,
"text": "The !important rule indicates that a user-defined rule should take precedence over the author's style sheets."
},
{
"code": null,
"e": 3443,
"s": 3368,
"text": "NOTE − There are other @ rules which we will cover in subsequent chapters."
},
{
"code": null,
"e": 3618,
"s": 3443,
"text": "The @import rule allows you to import styles from another style sheet. It should appear right at the start of the style sheet before any of the rules, and its value is a URL."
},
{
"code": null,
"e": 3671,
"s": 3618,
"text": "It can be written in one of the two following ways −"
},
{
"code": null,
"e": 3828,
"s": 3671,
"text": "<style type = \"text/css\">\n <!--\n @import \"mystyle.css\";\n or\n @import url(\"mystyle.css\");\n .......other CSS rules .....\n -->\n</style>"
},
{
"code": null,
"e": 4023,
"s": 3828,
"text": "The significance of the @import rule is that it allows you to develop your style sheets with a modular approach. You can create various style sheets and then include them wherever you need them."
},
{
"code": null,
"e": 4242,
"s": 4023,
"text": "If you are writing your document using a character set other than ASCII or ISO-8859-1 you might want to set the @charset rule at the top of your style sheet to indicate what character set the style sheet is written in."
},
{
"code": null,
"e": 4442,
"s": 4242,
"text": "The @charset rule must be written right at the beginning of the style sheet without even a space before it. The value is held in quotes and should be one of the standard character-sets. For example −"
},
{
"code": null,
"e": 4555,
"s": 4442,
"text": "<style type = \"text/css\">\n <!--\n @charset \"iso-8859-1\"\n .......other CSS rules .....\n -->\n</style>"
},
{
"code": null,
"e": 4777,
"s": 4555,
"text": "The @font-face rule is used to exhaustively describe a font face for use in a document. @font-face may also be used to define the location of a font for download, although this may run into implementation-specific limits."
},
{
"code": null,
"e": 4910,
"s": 4777,
"text": "In general, @font-face is extremely complicated, and its use is not recommended for any except those who are expert in font metrics."
},
{
"code": null,
"e": 4931,
"s": 4910,
"text": "Here is an example −"
},
{
"code": null,
"e": 5378,
"s": 4931,
"text": "<style type = \"text/css\">\n <!--\n @font-face {\n font-family: \"Scarborough Light\";\n src: url(\"http://www.font.site/s/scarbo-lt\");\n }\n @font-face {\n font-family: Santiago;\n src: local (\"Santiago\"),\n url(\"http://www.font.site/s/santiago.tt\")\n format(\"truetype\");\n unicode-range: U+??,U+100-220;\n font-size: all;\n font-family: sans-serif;\n }\n -->\n</style>"
},
{
"code": null,
"e": 5556,
"s": 5378,
"text": "Cascading Style Sheets cascade. It means that the styles are applied in the same order as they are read by the browser. The first style is applied and then the second and so on."
},
{
"code": null,
"e": 5790,
"s": 5556,
"text": "The !important rule provides a way to make your CSS cascade. It also includes the rules that are to be applied always. A rule having a !important property will always be applied, no matter where that rule appears in the CSS document."
},
{
"code": null,
"e": 5920,
"s": 5790,
"text": "For example, in the following style sheet, the paragraph text will be black, even though the first style property applied is red:"
},
{
"code": null,
"e": 6026,
"s": 5920,
"text": "<style type = \"text/css\">\n <!--\n p { color: #ff0000; }\n p { color: #000000; }\n -->\n</style>"
},
{
"code": null,
"e": 6215,
"s": 6026,
"text": "So, if you wanted to make sure that a property always applied, you would add the !important property to the tag. So, to make the paragraph text always red, you should write it as follows −"
},
{
"code": null,
"e": 6426,
"s": 6215,
"text": "<html>\n <head>\n <style type = \"text/css\">\n p { color: #ff0000 !important; }\n p { color: #000000; }\n </style>\n </head>\n\n <body>\n <p>Tutorialspoint.com</p>\n </body>\n</html> "
},
{
"code": null,
"e": 6578,
"s": 6426,
"text": "Here you have made p { color: #ff0000 !important; } mandatory, now this rule will always apply even you have defined another rule p { color: #000000; }"
},
{
"code": null,
"e": 6617,
"s": 6578,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 6636,
"s": 6617,
"text": "Tutorialspoint.com"
},
{
"code": null,
"e": 6671,
"s": 6636,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6685,
"s": 6671,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6720,
"s": 6685,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6737,
"s": 6720,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6772,
"s": 6737,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6803,
"s": 6772,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6838,
"s": 6803,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6869,
"s": 6838,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6904,
"s": 6869,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 6935,
"s": 6904,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 6968,
"s": 6935,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6999,
"s": 6968,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7006,
"s": 6999,
"text": " Print"
},
{
"code": null,
"e": 7017,
"s": 7006,
"text": " Add Notes"
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks
|
28 Jun, 2021
Consider two relations R1(A, B) with the tuples (1, 5), (3, 7) and R1(A, C) = (1, 7), (4, 9). Assume that R(A,B,C) is the full natural outer join of R1 and R2. Consider the following tuples of the form (A,B,C)
a = (1, 5, null),
b = (1, null, 7),
c = (3, null, 9),
d = (4, 7, null),
e = (1, 5, 7),
f = (3, 7, null),
g = (4, null, 9).
Which one of the following statements is correct?(A) R contains a, b, e, f, g but not c, d(B) R contains a, b, c, d, e, f, g(C) R contains e, f, g but not a, b(D) R contains e but not f, gAnswer: (C)Explanation:
Below is R1
A | B
-----------
1 | 5
3 | 7
Below is R2
A | C
-----------
1 | 7
4 | 9
Full outer join of above two is
A | B | C
-------------------
1 | 5 | 7
3 | 7 | NULL
4 | NULL | 9
So the full outer join contains e = (1, 5, 7), f = (3, 7, null), g = (4, null, 9).Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE CS 1997 | Question 25
GATE | GATE CS 2012 | Question 54
GATE | GATE-CS-2014-(Set-1) | Question 65
GATE | GATE CS 2019 | Question 50
GATE | GATE CS 2008 | Question 69
GATE | GATE CS 2018 | Question 45
GATE | GATE CS 2020 | Question 16
GATE | GATE CS 2011 | Question 65
GATE | GATE CS 2011 | Question 43
GATE | GATE CS 2010 | Question 33
|
[
{
"code": null,
"e": 24177,
"s": 24149,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24387,
"s": 24177,
"text": "Consider two relations R1(A, B) with the tuples (1, 5), (3, 7) and R1(A, C) = (1, 7), (4, 9). Assume that R(A,B,C) is the full natural outer join of R1 and R2. Consider the following tuples of the form (A,B,C)"
},
{
"code": null,
"e": 24530,
"s": 24387,
"text": " a = (1, 5, null),\n b = (1, null, 7), \n c = (3, null, 9), \n d = (4, 7, null), \n e = (1, 5, 7), \n f = (3, 7, null), \n g = (4, null, 9). "
},
{
"code": null,
"e": 24742,
"s": 24530,
"text": "Which one of the following statements is correct?(A) R contains a, b, e, f, g but not c, d(B) R contains a, b, c, d, e, f, g(C) R contains e, f, g but not a, b(D) R contains e but not f, gAnswer: (C)Explanation:"
},
{
"code": null,
"e": 25007,
"s": 24742,
"text": "Below is R1 \n A | B\n -----------\n 1 | 5\n 3 | 7\n\n\nBelow is R2\n A | C\n -----------\n 1 | 7\n 4 | 9 \n\n\nFull outer join of above two is \n\n A | B | C\n -------------------\n 1 | 5 | 7\n 3 | 7 | NULL\n 4 | NULL | 9"
},
{
"code": null,
"e": 25111,
"s": 25007,
"text": "So the full outer join contains e = (1, 5, 7), f = (3, 7, null), g = (4, null, 9).Quiz of this Question"
},
{
"code": null,
"e": 25132,
"s": 25111,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 25158,
"s": 25132,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 25163,
"s": 25158,
"text": "GATE"
},
{
"code": null,
"e": 25261,
"s": 25163,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25270,
"s": 25261,
"text": "Comments"
},
{
"code": null,
"e": 25283,
"s": 25270,
"text": "Old Comments"
},
{
"code": null,
"e": 25317,
"s": 25283,
"text": "GATE | GATE CS 1997 | Question 25"
},
{
"code": null,
"e": 25351,
"s": 25317,
"text": "GATE | GATE CS 2012 | Question 54"
},
{
"code": null,
"e": 25393,
"s": 25351,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 65"
},
{
"code": null,
"e": 25427,
"s": 25393,
"text": "GATE | GATE CS 2019 | Question 50"
},
{
"code": null,
"e": 25461,
"s": 25427,
"text": "GATE | GATE CS 2008 | Question 69"
},
{
"code": null,
"e": 25495,
"s": 25461,
"text": "GATE | GATE CS 2018 | Question 45"
},
{
"code": null,
"e": 25529,
"s": 25495,
"text": "GATE | GATE CS 2020 | Question 16"
},
{
"code": null,
"e": 25563,
"s": 25529,
"text": "GATE | GATE CS 2011 | Question 65"
},
{
"code": null,
"e": 25597,
"s": 25563,
"text": "GATE | GATE CS 2011 | Question 43"
}
] |
Conditional Random Field Tutorial in PyTorch 🔥 | by Freddy Boulton | Towards Data Science
|
Let’s say I have two identical dice, but one is fair and the other is loaded such that number 6 appears with 80% probability, while numbers 1–5 are equally likely with 4% probability. If I gave you a sequence of 15 rolls, could you predict which dice I used for each roll?
A simple model would be to predict I used the biased dice whenever a 6 comes up and say I used the fair dice for all other numbers. In fact, if I was equally likely to use either dice for any roll, then this simple rule is the best you could do.
But what if after using the fair dice, I have an 90% chance of using the biased dice on the next roll? If the next roll is a 3, your model will predict I used the fair dice when the biased dice is the more probable choice. We can verify this with Bayes’ theorem:
The takeaway is that making the most likely choice at each time step is only a viable strategy when I’m equally likely to use either dice. In the far more likely scenario that previous choices of dice affect what my future choices will be, you’re going to have to take the interdependence of the rolls into account in order to be successful.
A Conditional Random Field* (CRF) is a standard model for predicting the most likely sequence of labels that correspond to a sequence of inputs. There are plenty of tutorials on CRFs but the ones I’ve seen fall into one of two camps: 1) all theory without showing how to implement or 2) code for a complex machine learning problem with little explanation of what’s going on.
I don’t fault those authors for picking either theory or code. CRF’s are a deep topic in a broader and deeper subject called probabilistic graphical models so covering theory and implementation in depth will take a book, not a blog post, but this makes learning about CRFs harder than it needs to be.
My goal for this tutorial is to cover just enough theory so that you can dive into the resources in category 1 with an idea of what to expect and to show how to implement a CRF on a simple problem you can replicate on your own laptop. This will hopefully equip you with the intuition needed to adapt this simple toy CRF for a more complicated problem.
Our theoretical discussion will be divided into three parts: 1) specifying model parameters, 2) how to estimate these parameters, and 3) using these parameters to make predictions. These three broad categories apply to any statistical model, even a simple logistic regression, so in that sense CRFs aren’t anything special. But that doesn’t mean that CRFs are as simple as logistic regression models. We’ll see that things will get a bit more complicated once we tackle the fact we’re making a sequence of predictions as opposed to a single prediction.
Specifying model parameters
In this simple problem, the only parameters we need to worry about are the costs associated with transitioning from one dice to the next in consecutive rolls. There are six numbers that we need to worry about and we’ll store them in a 2x3 matrix called the transition matrix:
The first column corresponds to transitions from the fair dice in the previous roll to the fair dice (value in row 1) and biased dice (value in row 2) in the current roll. So the first entry in the first column encodes the cost of predicting that I use the fair dice on the next roll given that I used the fair dice on the current roll. If the data show that I’m unlikely to use fair dice in consecutive rolls, the model will learn this cost should be high and vice versa. The same logic applies to the second column.
The second and third columns of the matrix assume we know which dice we used in the previous roll. Therefore we have to treat the first roll as a special case. We’ll store the corresponding costs in the third column.
Parameter Estimation
Let’s say I give you a set of rolls X and their corresponding dice labels Y. We will find the transition matrix T that minimizes the negative log likelihood over the training data. I’ll show you what the likelihood and negative log likelihood look like for a single sequence of dice rolls. To get it for the entire data set, you’d average over all the sequences.
P(x_i | y_i) is the probability of observing a given dice roll given the current dice label. To give an example, P(x_i | y_i) = 1/6 if y_i = dice is fair. The other term, T(y_i | y_{i-1}), is the cost of having transitioned from the previous dice label to the current one. We can just read this cost off the transition matrix.
Notice how in the denominator we’re computing the sum over all possible sequences of labels y`. In a traditional logistic regression for a classification problem of two classes, we’d have two terms in the denominator. But now we’re dealing with sequences and for a sequence of length 15, there are a total of 215 possible sequences of labels so the number of terms in the denominator is huge. The “secret sauce” of the CRF is that it exploits how the current dice label only depends on the previous one to compute that huge sum efficiently.
This secret sauce algorithm is called the forward-backward algorithm*. Covering this in depth is out of the scope for this blog post but I’ll point you to helpful resources below.
Sequence Prediction
Once we estimate our transition matrix, we can use it to find the most likely sequence of dice labels for a given sequence of dice rolls. The naive way to do this is to compute the likelihood for all possible sequences but this will be intractable for even sequences of moderate length. Just like we did for parameter estimation, we’ll have to use a special algorithm to find the most likely sequence efficiently. This algorithm is closely related to the forward-backward algorithm and it’s called the Viterbi algorithm.
PyTorch is a deep learning library in Python built for training deep learning models. Although we’re not doing deep learning, PyTorch’s automatic differentiation library will help us train our CRF model via gradient descent without us having to compute any gradients by hand. This will save us a lot of work. Using PyTorch will force us to implement the forward part of the forward-backward algorithm and the Viterbi algorithms, which is more instructive than using a specialized CRF python package.
Let’s start by envisioning what the result needs to look like. We need a method for computing the log likelihood for an arbitrary sequence of rolls, given the dice labels. Here is one way it could look:
This method does three main things: 1) maps the value on the dice to a likelihood, 2) computes the numerator of the log likelihood term, 3) computes the denominator of the log likelihood term.
Let’s first tackle the _data_to_likelihood method, which will help us do step 1. What we’ll do is we’ll create a matrix of dimension 6 x 2 where the first column is the likelihood of rolls 1–6 for the fair dice, and the second column is the likelihood of rolls 1–6 for the biased dice. This is what this matrix looks like for our problem:
array([[-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -0.22314355]])
Now, if we see a roll of 4, we can just select the fourth row of the matrix. The first entry of that vector is the likelihood of a four for the fair dice (log(1/6)) and the second entry is the likelihood of a four for the biased dice (log(0.04)). This is what the code looks like:
Next, we’ll write the methods to compute the numerator and denominator of the log likelihood.
That’s it! We have all the code we need to start learning our transition matrix. But if we want to make predictions after training our model, we’ll have to code the Viterbi algorithm:
There’s more to our implementation but I’ve only included the big functions we discussed in the theory section.
I evaluated the model on some data I simulated using the following probabilities:
P(first dice in sequence is fair) = 0.5P(current dice is fair | previous dice is fair) = 0.8P(current dice is biased | previous dice is biased) = 0.35
P(first dice in sequence is fair) = 0.5
P(current dice is fair | previous dice is fair) = 0.8
P(current dice is biased | previous dice is biased) = 0.35
Check out the notebook I made to see how I generated the model and trained the CRF.
The first thing we’ll do is look at what the estimated transition matrix looks like. The model learned that I am more likely to roll the fair dice on the current roll if I used the fair dice on the previous roll (-1.38 < -0.87). The model also learned that I am more likely to use the fair dice after using the biased dice, but not by a lot (-0.59 < -0.41). The model assigns equal cost to both dice in the first roll (-0.51 ~ -0.54).
array([[-0.86563134, -0.40748784, -0.54984874], [-1.3820231 , -0.59524935, -0.516026 ]], dtype=float32)
Next, we’ll see what the predictions looks like for a particular sequence of rolls:
# observed dice rollsarray([2, 3, 4, 5, 5, 5, 1, 5, 3, 2, 5, 5, 5, 3, 5])# corresponding labels. 0 means fairarray([0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1])# predictionsarray([0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0])
The model recognizes long sequences of 6’s (these are the 5’s since we’re starting from 0) as coming from the biased dice, which makes sense. Notice that the model doesn’t assign every 6 to the biased dice, though (eighth roll). This is because prior to that 6, we’re pretty confident we’re at the fair dice (we rolled a 2) and transitioning to the biased dice from the fair dice is less likely. I’m ok with that mistake — I’d say our model is successful!
I’ve shown you a little bit of the theory behind CRF’s as well as how one can be implemented for a simple problem. There’s certainly a lot more to them than I’ve been able to cover here, so I encourage you to check out the sources I’ve linked below.
Further Reading:
An Introduction to Conditional Random Fields: Overview of CRFs, Hidden Markov Models, as well as derivation of forward-backward and Viterbi algorithms.
Using CRFs for named entity recognition in PyTorch: Inspiration for this post. Shows how a CRF can be applied to a more complex application in NLP.
*To be precise, we’re covering a linear-chain CRF, which is a special case of the CRF in which the sequences of inputs and outputs are arranged in a linear sequence. Like I said before, this topic is deep.
*Since we’re using PyTorch to compute gradients for us, we technically only need the forward part of the forward-backward algorithm .
|
[
{
"code": null,
"e": 444,
"s": 171,
"text": "Let’s say I have two identical dice, but one is fair and the other is loaded such that number 6 appears with 80% probability, while numbers 1–5 are equally likely with 4% probability. If I gave you a sequence of 15 rolls, could you predict which dice I used for each roll?"
},
{
"code": null,
"e": 690,
"s": 444,
"text": "A simple model would be to predict I used the biased dice whenever a 6 comes up and say I used the fair dice for all other numbers. In fact, if I was equally likely to use either dice for any roll, then this simple rule is the best you could do."
},
{
"code": null,
"e": 953,
"s": 690,
"text": "But what if after using the fair dice, I have an 90% chance of using the biased dice on the next roll? If the next roll is a 3, your model will predict I used the fair dice when the biased dice is the more probable choice. We can verify this with Bayes’ theorem:"
},
{
"code": null,
"e": 1295,
"s": 953,
"text": "The takeaway is that making the most likely choice at each time step is only a viable strategy when I’m equally likely to use either dice. In the far more likely scenario that previous choices of dice affect what my future choices will be, you’re going to have to take the interdependence of the rolls into account in order to be successful."
},
{
"code": null,
"e": 1670,
"s": 1295,
"text": "A Conditional Random Field* (CRF) is a standard model for predicting the most likely sequence of labels that correspond to a sequence of inputs. There are plenty of tutorials on CRFs but the ones I’ve seen fall into one of two camps: 1) all theory without showing how to implement or 2) code for a complex machine learning problem with little explanation of what’s going on."
},
{
"code": null,
"e": 1971,
"s": 1670,
"text": "I don’t fault those authors for picking either theory or code. CRF’s are a deep topic in a broader and deeper subject called probabilistic graphical models so covering theory and implementation in depth will take a book, not a blog post, but this makes learning about CRFs harder than it needs to be."
},
{
"code": null,
"e": 2323,
"s": 1971,
"text": "My goal for this tutorial is to cover just enough theory so that you can dive into the resources in category 1 with an idea of what to expect and to show how to implement a CRF on a simple problem you can replicate on your own laptop. This will hopefully equip you with the intuition needed to adapt this simple toy CRF for a more complicated problem."
},
{
"code": null,
"e": 2876,
"s": 2323,
"text": "Our theoretical discussion will be divided into three parts: 1) specifying model parameters, 2) how to estimate these parameters, and 3) using these parameters to make predictions. These three broad categories apply to any statistical model, even a simple logistic regression, so in that sense CRFs aren’t anything special. But that doesn’t mean that CRFs are as simple as logistic regression models. We’ll see that things will get a bit more complicated once we tackle the fact we’re making a sequence of predictions as opposed to a single prediction."
},
{
"code": null,
"e": 2904,
"s": 2876,
"text": "Specifying model parameters"
},
{
"code": null,
"e": 3180,
"s": 2904,
"text": "In this simple problem, the only parameters we need to worry about are the costs associated with transitioning from one dice to the next in consecutive rolls. There are six numbers that we need to worry about and we’ll store them in a 2x3 matrix called the transition matrix:"
},
{
"code": null,
"e": 3698,
"s": 3180,
"text": "The first column corresponds to transitions from the fair dice in the previous roll to the fair dice (value in row 1) and biased dice (value in row 2) in the current roll. So the first entry in the first column encodes the cost of predicting that I use the fair dice on the next roll given that I used the fair dice on the current roll. If the data show that I’m unlikely to use fair dice in consecutive rolls, the model will learn this cost should be high and vice versa. The same logic applies to the second column."
},
{
"code": null,
"e": 3915,
"s": 3698,
"text": "The second and third columns of the matrix assume we know which dice we used in the previous roll. Therefore we have to treat the first roll as a special case. We’ll store the corresponding costs in the third column."
},
{
"code": null,
"e": 3936,
"s": 3915,
"text": "Parameter Estimation"
},
{
"code": null,
"e": 4299,
"s": 3936,
"text": "Let’s say I give you a set of rolls X and their corresponding dice labels Y. We will find the transition matrix T that minimizes the negative log likelihood over the training data. I’ll show you what the likelihood and negative log likelihood look like for a single sequence of dice rolls. To get it for the entire data set, you’d average over all the sequences."
},
{
"code": null,
"e": 4626,
"s": 4299,
"text": "P(x_i | y_i) is the probability of observing a given dice roll given the current dice label. To give an example, P(x_i | y_i) = 1/6 if y_i = dice is fair. The other term, T(y_i | y_{i-1}), is the cost of having transitioned from the previous dice label to the current one. We can just read this cost off the transition matrix."
},
{
"code": null,
"e": 5167,
"s": 4626,
"text": "Notice how in the denominator we’re computing the sum over all possible sequences of labels y`. In a traditional logistic regression for a classification problem of two classes, we’d have two terms in the denominator. But now we’re dealing with sequences and for a sequence of length 15, there are a total of 215 possible sequences of labels so the number of terms in the denominator is huge. The “secret sauce” of the CRF is that it exploits how the current dice label only depends on the previous one to compute that huge sum efficiently."
},
{
"code": null,
"e": 5347,
"s": 5167,
"text": "This secret sauce algorithm is called the forward-backward algorithm*. Covering this in depth is out of the scope for this blog post but I’ll point you to helpful resources below."
},
{
"code": null,
"e": 5367,
"s": 5347,
"text": "Sequence Prediction"
},
{
"code": null,
"e": 5888,
"s": 5367,
"text": "Once we estimate our transition matrix, we can use it to find the most likely sequence of dice labels for a given sequence of dice rolls. The naive way to do this is to compute the likelihood for all possible sequences but this will be intractable for even sequences of moderate length. Just like we did for parameter estimation, we’ll have to use a special algorithm to find the most likely sequence efficiently. This algorithm is closely related to the forward-backward algorithm and it’s called the Viterbi algorithm."
},
{
"code": null,
"e": 6388,
"s": 5888,
"text": "PyTorch is a deep learning library in Python built for training deep learning models. Although we’re not doing deep learning, PyTorch’s automatic differentiation library will help us train our CRF model via gradient descent without us having to compute any gradients by hand. This will save us a lot of work. Using PyTorch will force us to implement the forward part of the forward-backward algorithm and the Viterbi algorithms, which is more instructive than using a specialized CRF python package."
},
{
"code": null,
"e": 6591,
"s": 6388,
"text": "Let’s start by envisioning what the result needs to look like. We need a method for computing the log likelihood for an arbitrary sequence of rolls, given the dice labels. Here is one way it could look:"
},
{
"code": null,
"e": 6784,
"s": 6591,
"text": "This method does three main things: 1) maps the value on the dice to a likelihood, 2) computes the numerator of the log likelihood term, 3) computes the denominator of the log likelihood term."
},
{
"code": null,
"e": 7123,
"s": 6784,
"text": "Let’s first tackle the _data_to_likelihood method, which will help us do step 1. What we’ll do is we’ll create a matrix of dimension 6 x 2 where the first column is the likelihood of rolls 1–6 for the fair dice, and the second column is the likelihood of rolls 1–6 for the biased dice. This is what this matrix looks like for our problem:"
},
{
"code": null,
"e": 7329,
"s": 7123,
"text": "array([[-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -3.21887582], [-1.79175947, -0.22314355]])"
},
{
"code": null,
"e": 7610,
"s": 7329,
"text": "Now, if we see a roll of 4, we can just select the fourth row of the matrix. The first entry of that vector is the likelihood of a four for the fair dice (log(1/6)) and the second entry is the likelihood of a four for the biased dice (log(0.04)). This is what the code looks like:"
},
{
"code": null,
"e": 7704,
"s": 7610,
"text": "Next, we’ll write the methods to compute the numerator and denominator of the log likelihood."
},
{
"code": null,
"e": 7888,
"s": 7704,
"text": "That’s it! We have all the code we need to start learning our transition matrix. But if we want to make predictions after training our model, we’ll have to code the Viterbi algorithm:"
},
{
"code": null,
"e": 8000,
"s": 7888,
"text": "There’s more to our implementation but I’ve only included the big functions we discussed in the theory section."
},
{
"code": null,
"e": 8082,
"s": 8000,
"text": "I evaluated the model on some data I simulated using the following probabilities:"
},
{
"code": null,
"e": 8233,
"s": 8082,
"text": "P(first dice in sequence is fair) = 0.5P(current dice is fair | previous dice is fair) = 0.8P(current dice is biased | previous dice is biased) = 0.35"
},
{
"code": null,
"e": 8273,
"s": 8233,
"text": "P(first dice in sequence is fair) = 0.5"
},
{
"code": null,
"e": 8327,
"s": 8273,
"text": "P(current dice is fair | previous dice is fair) = 0.8"
},
{
"code": null,
"e": 8386,
"s": 8327,
"text": "P(current dice is biased | previous dice is biased) = 0.35"
},
{
"code": null,
"e": 8470,
"s": 8386,
"text": "Check out the notebook I made to see how I generated the model and trained the CRF."
},
{
"code": null,
"e": 8905,
"s": 8470,
"text": "The first thing we’ll do is look at what the estimated transition matrix looks like. The model learned that I am more likely to roll the fair dice on the current roll if I used the fair dice on the previous roll (-1.38 < -0.87). The model also learned that I am more likely to use the fair dice after using the biased dice, but not by a lot (-0.59 < -0.41). The model assigns equal cost to both dice in the first roll (-0.51 ~ -0.54)."
},
{
"code": null,
"e": 9016,
"s": 8905,
"text": "array([[-0.86563134, -0.40748784, -0.54984874], [-1.3820231 , -0.59524935, -0.516026 ]], dtype=float32)"
},
{
"code": null,
"e": 9100,
"s": 9016,
"text": "Next, we’ll see what the predictions looks like for a particular sequence of rolls:"
},
{
"code": null,
"e": 9327,
"s": 9100,
"text": "# observed dice rollsarray([2, 3, 4, 5, 5, 5, 1, 5, 3, 2, 5, 5, 5, 3, 5])# corresponding labels. 0 means fairarray([0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1])# predictionsarray([0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0])"
},
{
"code": null,
"e": 9783,
"s": 9327,
"text": "The model recognizes long sequences of 6’s (these are the 5’s since we’re starting from 0) as coming from the biased dice, which makes sense. Notice that the model doesn’t assign every 6 to the biased dice, though (eighth roll). This is because prior to that 6, we’re pretty confident we’re at the fair dice (we rolled a 2) and transitioning to the biased dice from the fair dice is less likely. I’m ok with that mistake — I’d say our model is successful!"
},
{
"code": null,
"e": 10033,
"s": 9783,
"text": "I’ve shown you a little bit of the theory behind CRF’s as well as how one can be implemented for a simple problem. There’s certainly a lot more to them than I’ve been able to cover here, so I encourage you to check out the sources I’ve linked below."
},
{
"code": null,
"e": 10050,
"s": 10033,
"text": "Further Reading:"
},
{
"code": null,
"e": 10202,
"s": 10050,
"text": "An Introduction to Conditional Random Fields: Overview of CRFs, Hidden Markov Models, as well as derivation of forward-backward and Viterbi algorithms."
},
{
"code": null,
"e": 10350,
"s": 10202,
"text": "Using CRFs for named entity recognition in PyTorch: Inspiration for this post. Shows how a CRF can be applied to a more complex application in NLP."
},
{
"code": null,
"e": 10556,
"s": 10350,
"text": "*To be precise, we’re covering a linear-chain CRF, which is a special case of the CRF in which the sequences of inputs and outputs are arranged in a linear sequence. Like I said before, this topic is deep."
}
] |
What is Label Smoothing?. A technique to make your model less... | by Wanshun Wong | Towards Data Science
|
When using deep learning models for classification tasks, we usually encounter the following problems: overfitting, and overconfidence. Overfitting is well studied and can be tackled with early stopping, dropout, weight regularization etc. On the other hand, we have less tools to tackle overconfidence. Label smoothing is a regularization technique that addresses both problems.
A classification model is calibrated if its predicted probabilities of outcomes reflect their accuracy. For example, consider 100 examples within our dataset, each with predicted probability 0.9 by our model. If our model is calibrated, then 90 examples should be classified correctly. Similarly, among another 100 examples with predicted probabilities 0.6, we would expect only 60 examples being correctly classified.
Model calibration is important for
model interpretability and reliability
deciding decision thresholds for downstream applications
integrating our model into an ensemble or a machine learning pipeline
An overconfident model is not calibrated and its predicted probabilities are consistently higher than the accuracy. For example, it may predict 0.9 for inputs where the accuracy is only 0.6. Notice that models with small test errors can still be overconfident, and therefore can benefit from label smoothing.
Label smoothing replaces one-hot encoded label vector y_hot with a mixture of y_hot and the uniform distribution:
y_ls = (1 - α) * y_hot + α / K
where K is the number of label classes, and α is a hyperparameter that determines the amount of smoothing. If α = 0, we obtain the original one-hot encoded y_hot. If α = 1, we get the uniform distribution.
Label smoothing is used when the loss function is cross entropy, and the model applies the softmax function to the penultimate layer’s logit vectors z to compute its output probabilities p. In this setting, the gradient of the cross entropy loss function with respect to the logits is simply
∇CE = p - y = softmax(z) - y
where y is the label distribution. In particular, we can see that
Gradient descent will try to make p as close to y as possible.The gradient is bounded between -1 and 1.
Gradient descent will try to make p as close to y as possible.
The gradient is bounded between -1 and 1.
One-hot encoded labels encourages largest possible logit gaps to be fed into the softmax function. Intuitively, large logit gaps combined with the bounded gradient will make the model less adaptive and too confident about its predictions.
In contrast, smoothed labels encourages small logit gaps, as demonstrated by the example below. It is shown in [3] that this results in better model calibration and prevents overconfident predictions.
Suppose we have K = 3 classes, and our label belongs to the 1st class. Let [a, b, c] be our logit vector.
If we do not use label smoothing, the label vector is the one-hot encoded vector [1, 0, 0]. Our model will make a ≫ b and a ≫ c. For example, applying softmax to the logit vector [10, 0, 0] gives [0.9999, 0, 0] rounded to 4 decimal places.
If we use label smoothing with α = 0.1, the smoothed label vector ≈ [0.9333, 0.0333, 0.0333]. The logit vector [3.3322, 0, 0] approximates the smoothed label vector to 4 decimal places after softmax, and it has a smaller gap. This is why we call label smoothing a regularization technique as it restrains the largest logit from becoming much bigger than the rest.
Tensorflow: Label smoothing is already implemented in Tensorflow within the cross entropy loss functions. See e.g BinaryCrossentropy and CategoricalCrossentropy.
PyTorch: See the example from OpenNMT.
Q: When do we use label smoothing?
A: Whenever a classification neural network suffers from overfitting and/or overconfidence, we can try label smoothing.
Q: How do we choose α?
A: Just like other regularization hyperparameters, there is no formula for choosing α. It is usually done by trial and error, and α = 0.1 is a good place to start.
Q: Can we use distributions other than uniform distribution in label smoothing?
A: Technically yes. In [4] the theoretical groundwork is developed for arbitrary distributions. That being said, the vast majority of empirical studies on label smoothing use uniform distribution.
Q: Is label smoothing used outside deep learning?
A: Not really. Most popular non-deep learning methods do not use the softmax function. Thus label smoothing is usually not applicable.
[3] studies how and why label smoothing works, provides a new visualization scheme, and analyzes the performance of label smoothing for different tasks. The section of Knowledge Distillation is especially interesting.[5] and [4] discuss how label smoothing affects the loss function and also its connection to KL divergence.[1] Chapter 7.5.1 covers how label smoothing helps dealing with noisy labels.[2] introduces temperature scaling which is a simple yet effective way to calibrate a neural network.
[3] studies how and why label smoothing works, provides a new visualization scheme, and analyzes the performance of label smoothing for different tasks. The section of Knowledge Distillation is especially interesting.
[5] and [4] discuss how label smoothing affects the loss function and also its connection to KL divergence.
[1] Chapter 7.5.1 covers how label smoothing helps dealing with noisy labels.
[2] introduces temperature scaling which is a simple yet effective way to calibrate a neural network.
I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press.C. Guo, G. Pleiss, Y. Sun, and K. Weinberger. On Calibration of Modern Neural Networks (2017), ICML 2017.R. Müller, S. Kornblith, and G. Hinton. When Does Label Smoothing Help? (2019), NeurIPS 2019.G. Pereyra, G. Tucker, J. Chorowski, Ł. Kaiser, and G. Hinton. Regularizing Neural Networks by Penalizing Confident Output Distributions (2017), arXiv.C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens, and Z. Wojna. Rethinking the Inception Architecture for Computer Vision (2016), CVPR 2016.
I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press.
C. Guo, G. Pleiss, Y. Sun, and K. Weinberger. On Calibration of Modern Neural Networks (2017), ICML 2017.
R. Müller, S. Kornblith, and G. Hinton. When Does Label Smoothing Help? (2019), NeurIPS 2019.
G. Pereyra, G. Tucker, J. Chorowski, Ł. Kaiser, and G. Hinton. Regularizing Neural Networks by Penalizing Confident Output Distributions (2017), arXiv.
C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens, and Z. Wojna. Rethinking the Inception Architecture for Computer Vision (2016), CVPR 2016.
|
[
{
"code": null,
"e": 552,
"s": 172,
"text": "When using deep learning models for classification tasks, we usually encounter the following problems: overfitting, and overconfidence. Overfitting is well studied and can be tackled with early stopping, dropout, weight regularization etc. On the other hand, we have less tools to tackle overconfidence. Label smoothing is a regularization technique that addresses both problems."
},
{
"code": null,
"e": 971,
"s": 552,
"text": "A classification model is calibrated if its predicted probabilities of outcomes reflect their accuracy. For example, consider 100 examples within our dataset, each with predicted probability 0.9 by our model. If our model is calibrated, then 90 examples should be classified correctly. Similarly, among another 100 examples with predicted probabilities 0.6, we would expect only 60 examples being correctly classified."
},
{
"code": null,
"e": 1006,
"s": 971,
"text": "Model calibration is important for"
},
{
"code": null,
"e": 1045,
"s": 1006,
"text": "model interpretability and reliability"
},
{
"code": null,
"e": 1102,
"s": 1045,
"text": "deciding decision thresholds for downstream applications"
},
{
"code": null,
"e": 1172,
"s": 1102,
"text": "integrating our model into an ensemble or a machine learning pipeline"
},
{
"code": null,
"e": 1481,
"s": 1172,
"text": "An overconfident model is not calibrated and its predicted probabilities are consistently higher than the accuracy. For example, it may predict 0.9 for inputs where the accuracy is only 0.6. Notice that models with small test errors can still be overconfident, and therefore can benefit from label smoothing."
},
{
"code": null,
"e": 1595,
"s": 1481,
"text": "Label smoothing replaces one-hot encoded label vector y_hot with a mixture of y_hot and the uniform distribution:"
},
{
"code": null,
"e": 1626,
"s": 1595,
"text": "y_ls = (1 - α) * y_hot + α / K"
},
{
"code": null,
"e": 1832,
"s": 1626,
"text": "where K is the number of label classes, and α is a hyperparameter that determines the amount of smoothing. If α = 0, we obtain the original one-hot encoded y_hot. If α = 1, we get the uniform distribution."
},
{
"code": null,
"e": 2124,
"s": 1832,
"text": "Label smoothing is used when the loss function is cross entropy, and the model applies the softmax function to the penultimate layer’s logit vectors z to compute its output probabilities p. In this setting, the gradient of the cross entropy loss function with respect to the logits is simply"
},
{
"code": null,
"e": 2153,
"s": 2124,
"text": "∇CE = p - y = softmax(z) - y"
},
{
"code": null,
"e": 2219,
"s": 2153,
"text": "where y is the label distribution. In particular, we can see that"
},
{
"code": null,
"e": 2323,
"s": 2219,
"text": "Gradient descent will try to make p as close to y as possible.The gradient is bounded between -1 and 1."
},
{
"code": null,
"e": 2386,
"s": 2323,
"text": "Gradient descent will try to make p as close to y as possible."
},
{
"code": null,
"e": 2428,
"s": 2386,
"text": "The gradient is bounded between -1 and 1."
},
{
"code": null,
"e": 2667,
"s": 2428,
"text": "One-hot encoded labels encourages largest possible logit gaps to be fed into the softmax function. Intuitively, large logit gaps combined with the bounded gradient will make the model less adaptive and too confident about its predictions."
},
{
"code": null,
"e": 2868,
"s": 2667,
"text": "In contrast, smoothed labels encourages small logit gaps, as demonstrated by the example below. It is shown in [3] that this results in better model calibration and prevents overconfident predictions."
},
{
"code": null,
"e": 2974,
"s": 2868,
"text": "Suppose we have K = 3 classes, and our label belongs to the 1st class. Let [a, b, c] be our logit vector."
},
{
"code": null,
"e": 3214,
"s": 2974,
"text": "If we do not use label smoothing, the label vector is the one-hot encoded vector [1, 0, 0]. Our model will make a ≫ b and a ≫ c. For example, applying softmax to the logit vector [10, 0, 0] gives [0.9999, 0, 0] rounded to 4 decimal places."
},
{
"code": null,
"e": 3578,
"s": 3214,
"text": "If we use label smoothing with α = 0.1, the smoothed label vector ≈ [0.9333, 0.0333, 0.0333]. The logit vector [3.3322, 0, 0] approximates the smoothed label vector to 4 decimal places after softmax, and it has a smaller gap. This is why we call label smoothing a regularization technique as it restrains the largest logit from becoming much bigger than the rest."
},
{
"code": null,
"e": 3740,
"s": 3578,
"text": "Tensorflow: Label smoothing is already implemented in Tensorflow within the cross entropy loss functions. See e.g BinaryCrossentropy and CategoricalCrossentropy."
},
{
"code": null,
"e": 3779,
"s": 3740,
"text": "PyTorch: See the example from OpenNMT."
},
{
"code": null,
"e": 3814,
"s": 3779,
"text": "Q: When do we use label smoothing?"
},
{
"code": null,
"e": 3934,
"s": 3814,
"text": "A: Whenever a classification neural network suffers from overfitting and/or overconfidence, we can try label smoothing."
},
{
"code": null,
"e": 3957,
"s": 3934,
"text": "Q: How do we choose α?"
},
{
"code": null,
"e": 4121,
"s": 3957,
"text": "A: Just like other regularization hyperparameters, there is no formula for choosing α. It is usually done by trial and error, and α = 0.1 is a good place to start."
},
{
"code": null,
"e": 4201,
"s": 4121,
"text": "Q: Can we use distributions other than uniform distribution in label smoothing?"
},
{
"code": null,
"e": 4398,
"s": 4201,
"text": "A: Technically yes. In [4] the theoretical groundwork is developed for arbitrary distributions. That being said, the vast majority of empirical studies on label smoothing use uniform distribution."
},
{
"code": null,
"e": 4448,
"s": 4398,
"text": "Q: Is label smoothing used outside deep learning?"
},
{
"code": null,
"e": 4583,
"s": 4448,
"text": "A: Not really. Most popular non-deep learning methods do not use the softmax function. Thus label smoothing is usually not applicable."
},
{
"code": null,
"e": 5086,
"s": 4583,
"text": "[3] studies how and why label smoothing works, provides a new visualization scheme, and analyzes the performance of label smoothing for different tasks. The section of Knowledge Distillation is especially interesting.[5] and [4] discuss how label smoothing affects the loss function and also its connection to KL divergence.[1] Chapter 7.5.1 covers how label smoothing helps dealing with noisy labels.[2] introduces temperature scaling which is a simple yet effective way to calibrate a neural network."
},
{
"code": null,
"e": 5304,
"s": 5086,
"text": "[3] studies how and why label smoothing works, provides a new visualization scheme, and analyzes the performance of label smoothing for different tasks. The section of Knowledge Distillation is especially interesting."
},
{
"code": null,
"e": 5412,
"s": 5304,
"text": "[5] and [4] discuss how label smoothing affects the loss function and also its connection to KL divergence."
},
{
"code": null,
"e": 5490,
"s": 5412,
"text": "[1] Chapter 7.5.1 covers how label smoothing helps dealing with noisy labels."
},
{
"code": null,
"e": 5592,
"s": 5490,
"text": "[2] introduces temperature scaling which is a simple yet effective way to calibrate a neural network."
},
{
"code": null,
"e": 6156,
"s": 5592,
"text": "I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press.C. Guo, G. Pleiss, Y. Sun, and K. Weinberger. On Calibration of Modern Neural Networks (2017), ICML 2017.R. Müller, S. Kornblith, and G. Hinton. When Does Label Smoothing Help? (2019), NeurIPS 2019.G. Pereyra, G. Tucker, J. Chorowski, Ł. Kaiser, and G. Hinton. Regularizing Neural Networks by Penalizing Confident Output Distributions (2017), arXiv.C. Szegedy, V. Vanhoucke, S. Ioffe, J. Shlens, and Z. Wojna. Rethinking the Inception Architecture for Computer Vision (2016), CVPR 2016."
},
{
"code": null,
"e": 6233,
"s": 6156,
"text": "I. Goodfellow, Y. Bengio, and A. Courville. Deep Learning (2016), MIT Press."
},
{
"code": null,
"e": 6339,
"s": 6233,
"text": "C. Guo, G. Pleiss, Y. Sun, and K. Weinberger. On Calibration of Modern Neural Networks (2017), ICML 2017."
},
{
"code": null,
"e": 6434,
"s": 6339,
"text": "R. Müller, S. Kornblith, and G. Hinton. When Does Label Smoothing Help? (2019), NeurIPS 2019."
},
{
"code": null,
"e": 6586,
"s": 6434,
"text": "G. Pereyra, G. Tucker, J. Chorowski, Ł. Kaiser, and G. Hinton. Regularizing Neural Networks by Penalizing Confident Output Distributions (2017), arXiv."
}
] |
How to create a Calendar with CSS?
|
To create a calendar with CSS, the code is as follows −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
* {
box-sizing: border-box;
}
.calender {
border: 1px solid darkorchid;
}
.month {
padding: 50px;
width: 100%;
background: #874de6;
text-align: center;
border: 1px solid rgba(139, 0, 139, 0.671);
}
.month ul {
margin: 0;
padding: 0;
list-style-type: none;
}
.month ul li {
font-size: 30px;
text-transform: uppercase;
letter-spacing: 6px;
color: yellow;
}
.month .lastMonth {
float: left;
padding-top: 10px;
}
.month .nextMonth {
float: right;
padding-top: 10px;
}
.Days {
margin: 0;
padding: 10px 0;
background-color: rgb(169, 210, 248);
border: 1px solid rgba(0, 0, 139, 0.514);
}
.Days li {
font-weight: bold;
display: inline-block;
width: 13.6%;
color: rgb(0, 0, 0);
text-align: center;
}
.daysNumber {
padding: 10px 0;
background: rgb(235, 255, 182);
margin: 0;
font-weight: bold;
}
.daysNumber li {
list-style-type: none;
display: inline-block;
width: 13.6%;
text-align: center;
margin-bottom: 5px;
font-size: 12px;
color: rgb(0, 0, 0);
}
.daysNumber li .today {
padding: 5px;
background: #17003b;
font-weight: bolder;
border-radius: 50%;
color: rgb(229, 255, 0) !important;
}
</style>
</head>
<body>
<h1 style="text-align: center;">CSS Calendar Example</h1>
<div class="calender">
<div class="month">
<ul>
<li class="lastMonth">❮</li>
<li class="nextMonth">❯</li>
<li>
March<br />
<span>2020</span>
</li>
</ul>
</div>
<ul class="Days">
<li>Mo</li>
<li>Tu</li>
<li>We</li>
<li>Th</li>
<li>Fr</li>
<li>Sa</li>
<li>Su</li>
</ul>
<ul class="daysNumber">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
<li>11</li>
<li>12</li>
<li>13</li>
<li>14</li>
<li>15</li>
<li>16</li>
<li>17</li>
<li>18</li>
<li>19</li>
<li>20</li>
<li>21</li>
<li><span class="today">22</span></li>
<li>23</li>
<li>24</li>
<li>25</li>
<li>26</li>
<li>27</li>
<li>28</li>
<li>29</li>
<li>30</li>
<li>31</li>
</ul>
</div>
</body>
</html>
The above code will produce the following output −
|
[
{
"code": null,
"e": 1118,
"s": 1062,
"text": "To create a calendar with CSS, the code is as follows −"
},
{
"code": null,
"e": 1129,
"s": 1118,
"text": " Live Demo"
},
{
"code": null,
"e": 3455,
"s": 1129,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n * {\n box-sizing: border-box;\n }\n .calender {\n border: 1px solid darkorchid;\n }\n .month {\n padding: 50px;\n width: 100%;\n background: #874de6;\n text-align: center;\n border: 1px solid rgba(139, 0, 139, 0.671);\n }\n .month ul {\n margin: 0;\n padding: 0;\n list-style-type: none;\n }\n .month ul li {\n font-size: 30px;\n text-transform: uppercase;\n letter-spacing: 6px;\n color: yellow;\n }\n .month .lastMonth {\n float: left;\n padding-top: 10px;\n }\n .month .nextMonth {\n float: right;\n padding-top: 10px;\n }\n .Days {\n margin: 0;\n padding: 10px 0;\n background-color: rgb(169, 210, 248);\n border: 1px solid rgba(0, 0, 139, 0.514);\n }\n .Days li {\n font-weight: bold;\n display: inline-block;\n width: 13.6%;\n color: rgb(0, 0, 0);\n text-align: center;\n }\n .daysNumber {\n padding: 10px 0;\n background: rgb(235, 255, 182);\n margin: 0;\n font-weight: bold;\n }\n .daysNumber li {\n list-style-type: none;\n display: inline-block;\n width: 13.6%;\n text-align: center;\n margin-bottom: 5px;\n font-size: 12px;\n color: rgb(0, 0, 0);\n }\n .daysNumber li .today {\n padding: 5px;\n background: #17003b;\n font-weight: bolder;\n border-radius: 50%;\n color: rgb(229, 255, 0) !important;\n }\n</style>\n</head>\n<body>\n<h1 style=\"text-align: center;\">CSS Calendar Example</h1>\n<div class=\"calender\">\n<div class=\"month\">\n<ul>\n<li class=\"lastMonth\">❮</li>\n<li class=\"nextMonth\">❯</li>\n<li>\nMarch<br />\n<span>2020</span>\n</li>\n</ul>\n</div>\n<ul class=\"Days\">\n<li>Mo</li>\n<li>Tu</li>\n<li>We</li>\n<li>Th</li>\n<li>Fr</li>\n<li>Sa</li>\n<li>Su</li>\n</ul>\n<ul class=\"daysNumber\">\n<li>1</li>\n<li>2</li>\n<li>3</li>\n<li>4</li>\n<li>5</li>\n<li>6</li>\n<li>7</li>\n<li>8</li>\n<li>9</li>\n<li>10</li>\n<li>11</li>\n<li>12</li>\n<li>13</li>\n<li>14</li>\n<li>15</li>\n<li>16</li>\n<li>17</li>\n<li>18</li>\n<li>19</li>\n<li>20</li>\n<li>21</li>\n<li><span class=\"today\">22</span></li>\n<li>23</li>\n<li>24</li>\n<li>25</li>\n<li>26</li>\n<li>27</li>\n<li>28</li>\n<li>29</li>\n<li>30</li>\n<li>31</li>\n</ul>\n</div>\n</body>\n</html>"
},
{
"code": null,
"e": 3506,
"s": 3455,
"text": "The above code will produce the following output −"
}
] |
Replace two substrings (of a string) with each other - GeeksforGeeks
|
17 Dec, 2021
Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A or B, replace it, and then continue with the rest of the string. For example, when matching A = “aa” with S = “aaa”, A[0, 1] will be given preference over A[1, 2].
Note that A and B will have the same length and A != B.
Examples:
Input: S = “aab”, A = “aa”, B = “bb” Output: bbb We match the first two characters with A and replacing it with B we get bbb. Then we continue the algorithm starting at index 3 and we don’t find any more matches.
Input: S = “aabbaabb”, A = “aa”, B = “bb” Output: bbaabbaa We replace all the occurrences of “aa” with “bb” and “bb” with “aa”, so the resultant string is “bbaabbaa”.
Approach: Go through every possible sub-string from S of length len(A). if any sub-string matches A or B then update the string as required and print the updated string in the end.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the resultant stringstring updateString(string S, string A, string B){ int l = A.length(); // Iterate through all positions i for (int i = 0; i + l <= S.length(); i++) { // Current sub-string of // length = len(A) = len(B) string curr = S.substr(i, i + l); // If current sub-string gets // equal to A or B if (curr == A) { // Update S after replacing A string new_string = ""; new_string += S.substr(0, i) + B + S.substr(i + l, S.length()); S = new_string; i += l - 1; } else if(curr == B) { // Update S after replacing B string new_string = ""; new_string += S.substr(0, i) + A + S.substr(i + l, S.length()); S = new_string; i += l - 1; } else { //do nothing } } // Return the updated string return S;} // Driver codeint main(){ string S = "aaxb"; string A = "aa"; string B = "bb"; cout << (updateString(S, A, B)) << endl;} // This code is contributed by// Surendra_Gangwar
// Java implementation of the approachclass GFG { // Function to return the resultant string static String updateString(String S, String A, String B) { int l = A.length(); // Iterate through all positions i for (int i = 0; i + l <= S.length(); i++) { // Current sub-string of length = len(A) = len(B) String curr = S.substring(i, i + l); // If current sub-string gets equal to A or B if (curr.equals(A)) { // Update S after replacing A String new_string = S.substring(0, i) + B + S.substring(i + l, S.length()); S = new_string; i += l - 1; } else { // Update S after replacing B String new_string = S.substring(0, i) + A + S.substring(i + l, S.length()); S = new_string; i += l - 1; } } // Return the updated string return S; } // Driver code public static void main(String[] args) { String S = "aab"; String A = "aa"; String B = "bb"; System.out.println(updateString(S, A, B)); }}
# Python3 implementation of the approach # Function to return the resultant stringdef updateString(S, A, B): l = len(A) # Iterate through all positions i i = 0 while i + l <= len(S): # Current sub-string of # length = len(A) = len(B) curr = S[i:i+l] # If current sub-string gets # equal to A or B if curr == A: # Update S after replacing A new_string = S[0:i] + B + S[i + l:len(S)] S = new_string i += l - 1 else: # Update S after replacing B new_string = S[0:i] + A + S[i + l:len(S)] S = new_string i += l - 1 i += 1 # Return the updated string return S # Driver codeif __name__ == "__main__": S = "aab" A = "aa" B = "bb" print(updateString(S, A, B)) # This code is contributed by Rituraj Jain
// C# implementation of the approachusing System; class GFG{ // Function to return the resultant string static string updateString(string S, string A, string B) { int l = A.Length; // Iterate through all positions i for (int i = 0; i + l <= S.Length; i++) { // Current sub-string of length = len(A) = len(B) string curr = S.Substring(i, l); // If current sub-string gets equal to A or B if (curr.Equals(A)) { // Update S after replacing A string new_string = S.Substring(0, i) + B + S.Substring(i + l); S = new_string; i += l - 1; } else { // Update S after replacing B string new_string = S.Substring(0, i) + A + S.Substring(i + l); S = new_string; i += l - 1; } } // Return the updated string return S; } // Driver code public static void Main() { string S = "aab"; string A = "aa"; string B = "bb"; Console.WriteLine(updateString(S, A, B)); }} // This code is contributed by Ryuga
<?php// PHP implementation of the approach// Function to return the resultant stringfunction updateString($S, $A, $B){ $l = strlen($A); // Iterate through all positions i for ($i = 0; $i + $l <= strlen($S); $i++) { // Current sub-string of length = len(A) = len(B) $curr = substr($S, $i, $i + $l); // If current sub-string gets equal to A or B if (strcmp($curr, $A) == 0) { // Update S after replacing A $new_string = substr($S, 0, $i) . $B . substr($S, $i + $l, strlen($S)); $S = $new_string; $i += $l - 1; } else { // Update S after replacing B $new_string = substr($S, 0, $i) . $A . substr($S, $i + $l, strlen($S)); $S = $new_string; $i += $l - 1; } } // Return the updated string return $S;} // Driver code$S = "aab";$A = "aa";$B = "bb"; echo(updateString($S, $A, $B)); // This code is contributed by Code_Mech.
<script> // Javascript implementation of the approach // Function to return the resultant stringfunction updateString(S, A, B){ let l = A.length; // Iterate through all positions i for(let i = 0; i + l <= S.length; i++) { // Current sub-string of length = len(A) = len(B) let curr = S.substring(i, i + l); // If current sub-string gets equal to A or B if (curr == A) { // Update S after replacing A let new_string = S.substring(0, i) + B + S.substring(i + l); S = new_string; i += l - 1; } else { // Update S after replacing B let new_string = S.substring(0, i) + A + S.substring(i + l); S = new_string; i += l - 1; } } // Return the updated string return S;} // Driver codelet S = "aab";let A = "aa";let B = "bb"; document.write(updateString(S, A, B)); // This code is contributed by mukesh07 </script>
bbb
ankthon
rituraj_jain
SURENDRA_GANGWAR
Code_Mech
mukesh07
shobhittewari
substring
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to validate HTML tag using Regular Expression
Build a DFA to accept Binary strings that starts or ends with "01"
How to validate time in 24-hour format using Regular Expression
How to validate pin code of India using Regular Expression
How to check Aadhaar number is valid or not using Regular Expression
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 25328,
"s": 25300,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 25794,
"s": 25328,
"text": "Given 3 strings S, A and B. The task is to replace every sub-string of S equal to A with B and every sub-string of S equal to B with A. It is possible that two or more sub-strings matching A or B overlap. To avoid confusion about this situation, you should find the leftmost sub-string that matches A or B, replace it, and then continue with the rest of the string. For example, when matching A = “aa” with S = “aaa”, A[0, 1] will be given preference over A[1, 2]. "
},
{
"code": null,
"e": 25850,
"s": 25794,
"text": "Note that A and B will have the same length and A != B."
},
{
"code": null,
"e": 25861,
"s": 25850,
"text": "Examples: "
},
{
"code": null,
"e": 26074,
"s": 25861,
"text": "Input: S = “aab”, A = “aa”, B = “bb” Output: bbb We match the first two characters with A and replacing it with B we get bbb. Then we continue the algorithm starting at index 3 and we don’t find any more matches."
},
{
"code": null,
"e": 26243,
"s": 26074,
"text": "Input: S = “aabbaabb”, A = “aa”, B = “bb” Output: bbaabbaa We replace all the occurrences of “aa” with “bb” and “bb” with “aa”, so the resultant string is “bbaabbaa”. "
},
{
"code": null,
"e": 26424,
"s": 26243,
"text": "Approach: Go through every possible sub-string from S of length len(A). if any sub-string matches A or B then update the string as required and print the updated string in the end."
},
{
"code": null,
"e": 26476,
"s": 26424,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26480,
"s": 26476,
"text": "C++"
},
{
"code": null,
"e": 26485,
"s": 26480,
"text": "Java"
},
{
"code": null,
"e": 26493,
"s": 26485,
"text": "Python3"
},
{
"code": null,
"e": 26496,
"s": 26493,
"text": "C#"
},
{
"code": null,
"e": 26500,
"s": 26496,
"text": "PHP"
},
{
"code": null,
"e": 26511,
"s": 26500,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the resultant stringstring updateString(string S, string A, string B){ int l = A.length(); // Iterate through all positions i for (int i = 0; i + l <= S.length(); i++) { // Current sub-string of // length = len(A) = len(B) string curr = S.substr(i, i + l); // If current sub-string gets // equal to A or B if (curr == A) { // Update S after replacing A string new_string = \"\"; new_string += S.substr(0, i) + B + S.substr(i + l, S.length()); S = new_string; i += l - 1; } else if(curr == B) { // Update S after replacing B string new_string = \"\"; new_string += S.substr(0, i) + A + S.substr(i + l, S.length()); S = new_string; i += l - 1; } else { //do nothing } } // Return the updated string return S;} // Driver codeint main(){ string S = \"aaxb\"; string A = \"aa\"; string B = \"bb\"; cout << (updateString(S, A, B)) << endl;} // This code is contributed by// Surendra_Gangwar",
"e": 27816,
"s": 26511,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function to return the resultant string static String updateString(String S, String A, String B) { int l = A.length(); // Iterate through all positions i for (int i = 0; i + l <= S.length(); i++) { // Current sub-string of length = len(A) = len(B) String curr = S.substring(i, i + l); // If current sub-string gets equal to A or B if (curr.equals(A)) { // Update S after replacing A String new_string = S.substring(0, i) + B + S.substring(i + l, S.length()); S = new_string; i += l - 1; } else { // Update S after replacing B String new_string = S.substring(0, i) + A + S.substring(i + l, S.length()); S = new_string; i += l - 1; } } // Return the updated string return S; } // Driver code public static void main(String[] args) { String S = \"aab\"; String A = \"aa\"; String B = \"bb\"; System.out.println(updateString(S, A, B)); }}",
"e": 29079,
"s": 27816,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function to return the resultant stringdef updateString(S, A, B): l = len(A) # Iterate through all positions i i = 0 while i + l <= len(S): # Current sub-string of # length = len(A) = len(B) curr = S[i:i+l] # If current sub-string gets # equal to A or B if curr == A: # Update S after replacing A new_string = S[0:i] + B + S[i + l:len(S)] S = new_string i += l - 1 else: # Update S after replacing B new_string = S[0:i] + A + S[i + l:len(S)] S = new_string i += l - 1 i += 1 # Return the updated string return S # Driver codeif __name__ == \"__main__\": S = \"aab\" A = \"aa\" B = \"bb\" print(updateString(S, A, B)) # This code is contributed by Rituraj Jain",
"e": 29999,
"s": 29079,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to return the resultant string static string updateString(string S, string A, string B) { int l = A.Length; // Iterate through all positions i for (int i = 0; i + l <= S.Length; i++) { // Current sub-string of length = len(A) = len(B) string curr = S.Substring(i, l); // If current sub-string gets equal to A or B if (curr.Equals(A)) { // Update S after replacing A string new_string = S.Substring(0, i) + B + S.Substring(i + l); S = new_string; i += l - 1; } else { // Update S after replacing B string new_string = S.Substring(0, i) + A + S.Substring(i + l); S = new_string; i += l - 1; } } // Return the updated string return S; } // Driver code public static void Main() { string S = \"aab\"; string A = \"aa\"; string B = \"bb\"; Console.WriteLine(updateString(S, A, B)); }} // This code is contributed by Ryuga",
"e": 31274,
"s": 29999,
"text": null
},
{
"code": "<?php// PHP implementation of the approach// Function to return the resultant stringfunction updateString($S, $A, $B){ $l = strlen($A); // Iterate through all positions i for ($i = 0; $i + $l <= strlen($S); $i++) { // Current sub-string of length = len(A) = len(B) $curr = substr($S, $i, $i + $l); // If current sub-string gets equal to A or B if (strcmp($curr, $A) == 0) { // Update S after replacing A $new_string = substr($S, 0, $i) . $B . substr($S, $i + $l, strlen($S)); $S = $new_string; $i += $l - 1; } else { // Update S after replacing B $new_string = substr($S, 0, $i) . $A . substr($S, $i + $l, strlen($S)); $S = $new_string; $i += $l - 1; } } // Return the updated string return $S;} // Driver code$S = \"aab\";$A = \"aa\";$B = \"bb\"; echo(updateString($S, $A, $B)); // This code is contributed by Code_Mech.",
"e": 32315,
"s": 31274,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the resultant stringfunction updateString(S, A, B){ let l = A.length; // Iterate through all positions i for(let i = 0; i + l <= S.length; i++) { // Current sub-string of length = len(A) = len(B) let curr = S.substring(i, i + l); // If current sub-string gets equal to A or B if (curr == A) { // Update S after replacing A let new_string = S.substring(0, i) + B + S.substring(i + l); S = new_string; i += l - 1; } else { // Update S after replacing B let new_string = S.substring(0, i) + A + S.substring(i + l); S = new_string; i += l - 1; } } // Return the updated string return S;} // Driver codelet S = \"aab\";let A = \"aa\";let B = \"bb\"; document.write(updateString(S, A, B)); // This code is contributed by mukesh07 </script>",
"e": 33377,
"s": 32315,
"text": null
},
{
"code": null,
"e": 33381,
"s": 33377,
"text": "bbb"
},
{
"code": null,
"e": 33391,
"s": 33383,
"text": "ankthon"
},
{
"code": null,
"e": 33404,
"s": 33391,
"text": "rituraj_jain"
},
{
"code": null,
"e": 33421,
"s": 33404,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 33431,
"s": 33421,
"text": "Code_Mech"
},
{
"code": null,
"e": 33440,
"s": 33431,
"text": "mukesh07"
},
{
"code": null,
"e": 33454,
"s": 33440,
"text": "shobhittewari"
},
{
"code": null,
"e": 33464,
"s": 33454,
"text": "substring"
},
{
"code": null,
"e": 33482,
"s": 33464,
"text": "Pattern Searching"
},
{
"code": null,
"e": 33490,
"s": 33482,
"text": "Strings"
},
{
"code": null,
"e": 33498,
"s": 33490,
"text": "Strings"
},
{
"code": null,
"e": 33516,
"s": 33498,
"text": "Pattern Searching"
},
{
"code": null,
"e": 33614,
"s": 33516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33623,
"s": 33614,
"text": "Comments"
},
{
"code": null,
"e": 33636,
"s": 33623,
"text": "Old Comments"
},
{
"code": null,
"e": 33686,
"s": 33636,
"text": "How to validate HTML tag using Regular Expression"
},
{
"code": null,
"e": 33753,
"s": 33686,
"text": "Build a DFA to accept Binary strings that starts or ends with \"01\""
},
{
"code": null,
"e": 33817,
"s": 33753,
"text": "How to validate time in 24-hour format using Regular Expression"
},
{
"code": null,
"e": 33876,
"s": 33817,
"text": "How to validate pin code of India using Regular Expression"
},
{
"code": null,
"e": 33945,
"s": 33876,
"text": "How to check Aadhaar number is valid or not using Regular Expression"
},
{
"code": null,
"e": 33970,
"s": 33945,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 34016,
"s": 33970,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 34050,
"s": 34016,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 34065,
"s": 34050,
"text": "C++ Data Types"
}
] |
HTML DOM Style display Property
|
The HTML DOM Style display property is used for setting or returning the display type of an element. Elements are mostly block or inline. You can also hide the element using display:none.
Following is the syntax for −
Setting the display property −
object.style.display = value
The above property value is explained as follows −
Let us look at an example for the display property −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#DIV1{
padding:10px;
background-color:lightblue;
display:flex;
flex-direction:right;
}
#flexSpan{
width:70px;
background-color:red;
margin:20px;
padding:10px;
}
</style>
<script>
function changeDisplay() {
document.getElementById("DIV1").style.display = "block";
document.getElementById("flexSpan").style.display = "block";
document.getElementById("Sample").innerHTML="The display is now changed to block for both the div and its inner Span elements";
}
</script>
</head>
<body>
<div id="DIV1">
<span id="flexSpan">WORLD1</span>
<span id="flexSpan">WORLD2</span>
</div>
<p>Change the display property of the above div and its inner elements by clicking the below button</p>
<button onclick="changeDisplay()">Change Display</button>
<p id="Sample"></p>
</body>
</html>
On clicking the “Change Display” −
|
[
{
"code": null,
"e": 1250,
"s": 1062,
"text": "The HTML DOM Style display property is used for setting or returning the display type of an element. Elements are mostly block or inline. You can also hide the element using display:none."
},
{
"code": null,
"e": 1280,
"s": 1250,
"text": "Following is the syntax for −"
},
{
"code": null,
"e": 1311,
"s": 1280,
"text": "Setting the display property −"
},
{
"code": null,
"e": 1340,
"s": 1311,
"text": "object.style.display = value"
},
{
"code": null,
"e": 1391,
"s": 1340,
"text": "The above property value is explained as follows −"
},
{
"code": null,
"e": 1444,
"s": 1391,
"text": "Let us look at an example for the display property −"
},
{
"code": null,
"e": 1455,
"s": 1444,
"text": " Live Demo"
},
{
"code": null,
"e": 2378,
"s": 1455,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n #DIV1{\n padding:10px;\n background-color:lightblue;\n display:flex;\n flex-direction:right;\n }\n #flexSpan{\n width:70px;\n background-color:red;\n margin:20px;\n padding:10px;\n }\n</style>\n<script>\n function changeDisplay() {\n document.getElementById(\"DIV1\").style.display = \"block\";\n document.getElementById(\"flexSpan\").style.display = \"block\";\n document.getElementById(\"Sample\").innerHTML=\"The display is now changed to block for both the div and its inner Span elements\";\n }\n</script>\n</head>\n<body>\n <div id=\"DIV1\">\n <span id=\"flexSpan\">WORLD1</span>\n <span id=\"flexSpan\">WORLD2</span>\n </div>\n <p>Change the display property of the above div and its inner elements by clicking the below button</p>\n <button onclick=\"changeDisplay()\">Change Display</button>\n <p id=\"Sample\"></p>\n</body>\n</html>"
},
{
"code": null,
"e": 2413,
"s": 2378,
"text": "On clicking the “Change Display” −"
}
] |
How to use lastIndexOf () in Android textview?
|
This example demonstrate about How to use lastIndexOf () in Android textview.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter name"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and returns last index of “sai”.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
if (name.getText().toString().length() >= 0) {
int index = name.getText().toString().lastIndexOf("sai");
text.setText(String.valueOf(index));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
In the above result, enter the string as “Krishna sai sai” and it returned last index of sai as 12.
Click here to download the project code
|
[
{
"code": null,
"e": 1140,
"s": 1062,
"text": "This example demonstrate about How to use lastIndexOf () in Android textview."
},
{
"code": null,
"e": 1269,
"s": 1140,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1334,
"s": 1269,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2224,
"s": 1334,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2353,
"s": 2224,
"text": "In the above code, we have taken name as Edit text, when user click on button it will take data and returns last index of “sai”."
},
{
"code": null,
"e": 2410,
"s": 2353,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3525,
"s": 2410,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n int index = name.getText().toString().lastIndexOf(\"sai\");\n text.setText(String.valueOf(index));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3872,
"s": 3525,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3972,
"s": 3872,
"text": "In the above result, enter the string as “Krishna sai sai” and it returned last index of sai as 12."
},
{
"code": null,
"e": 4012,
"s": 3972,
"text": "Click here to download the project code"
}
] |
TestNG - Basic Annotations - AfterMethod
|
@AfterMethod annotated method will be run after each test method i.e say there are three test methods (i.e test cases), then @AfterMethod annotated method will be called thrice after each test method.
The following is a list of attributes supported by the @AfterMethod annotation:
alwaysRun
For before methods (AfterClass, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to.
For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped.
dependsOnGroups
The list of groups this method depends on.
dependsOnMethods
The list of methods this method depends on.
enabled
Whether methods on this class/method are enabled.
groups
The list of groups this class/method belongs to.
inheritGroups
If true, this method will belong to groups specified in the @Test annotation at the class level.
onlyForGroups
Only for @BeforeMethod and @AfterMethod. If specified, then this setup/teardown method will only be invoked if the corresponding test method belongs to one of the listed groups.
Create a java class to be tested, say, MessageUtil.java in /work/testng/src.
/*
* This class prints the given message on console.
*/
public class MessageUtil {
private String message;
//Constructor
//@param message to be printed
public MessageUtil(String message) {
this.message = message;
}
// prints the message
public String printMessage() {
System.out.println(message);
return message;
}
}
Create a java test class, say, TestAnnotationAfterMethod.java in /work/testng/src.
Create a java test class, say, TestAnnotationAfterMethod.java in /work/testng/src.
Add a test method testMethod() to your test class.
Add a test method testMethod() to your test class.
Add an Annotation @Test to method testMethod().
Add an Annotation @Test to method testMethod().
Add a method afterMethod to the test class with annotation @AfterMethod.
Add a method afterMethod to the test class with annotation @AfterMethod.
Implement the test condition and check the behaviour of @AfterMethod annotation.
Implement the test condition and check the behaviour of @AfterMethod annotation.
Following are the TestAnnotationAfterMethod.java contents:
import org.testng.Assert;
import org.testng.annotations.Test;
import org.testng.annotations.AfterMethod;
public class TestAnnotationAfterMethod {
@AfterMethod
public void afterMethod(){
System.out.println("executing afterMethod after each method");
}
@Test
public void testMethodOne(){
Assert.assertEquals("Test method one", (new MessageUtil("executing testMethodOne method")).printMessage());
}
@Test
public void testMethodTwo(){
Assert.assertEquals("Test method two", (new MessageUtil("executing testMethodTwo method")).printMessage());
}
}
Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database).
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="5" name="Test">
<classes>
<class name="TestAnnotationAfterMethod"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Compile the test case using javac.
/work/testng/src$ javac TestAnnotationAfterMethod.java MessageUtil.java
Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the @AfterMethod is called after all other test cases.
/work/testng/src$ java org.testng.TestNG testng.xml
Verify the output.
executing testMethodOne method
executing afterMethod after each method
executing testMethodTwo method
executing afterMethod after each method
===============================================
Suite
Total tests run: 2, Passes: 0, Failures: 2, Skips: 0
===============================================
38 Lectures
4.5 hours
Lets Kode It
15 Lectures
1.5 hours
Quaatso Learning
28 Lectures
3 hours
Dezlearn Education
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2261,
"s": 2060,
"text": "@AfterMethod annotated method will be run after each test method i.e say there are three test methods (i.e test cases), then @AfterMethod annotated method will be called thrice after each test method."
},
{
"code": null,
"e": 2341,
"s": 2261,
"text": "The following is a list of attributes supported by the @AfterMethod annotation:"
},
{
"code": null,
"e": 2351,
"s": 2341,
"text": "alwaysRun"
},
{
"code": null,
"e": 2551,
"s": 2351,
"text": "For before methods (AfterClass, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to."
},
{
"code": null,
"e": 2724,
"s": 2551,
"text": "For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped."
},
{
"code": null,
"e": 2740,
"s": 2724,
"text": "dependsOnGroups"
},
{
"code": null,
"e": 2783,
"s": 2740,
"text": "The list of groups this method depends on."
},
{
"code": null,
"e": 2800,
"s": 2783,
"text": "dependsOnMethods"
},
{
"code": null,
"e": 2844,
"s": 2800,
"text": "The list of methods this method depends on."
},
{
"code": null,
"e": 2852,
"s": 2844,
"text": "enabled"
},
{
"code": null,
"e": 2902,
"s": 2852,
"text": "Whether methods on this class/method are enabled."
},
{
"code": null,
"e": 2909,
"s": 2902,
"text": "groups"
},
{
"code": null,
"e": 2958,
"s": 2909,
"text": "The list of groups this class/method belongs to."
},
{
"code": null,
"e": 2972,
"s": 2958,
"text": "inheritGroups"
},
{
"code": null,
"e": 3069,
"s": 2972,
"text": "If true, this method will belong to groups specified in the @Test annotation at the class level."
},
{
"code": null,
"e": 3083,
"s": 3069,
"text": "onlyForGroups"
},
{
"code": null,
"e": 3261,
"s": 3083,
"text": "Only for @BeforeMethod and @AfterMethod. If specified, then this setup/teardown method will only be invoked if the corresponding test method belongs to one of the listed groups."
},
{
"code": null,
"e": 3338,
"s": 3261,
"text": "Create a java class to be tested, say, MessageUtil.java in /work/testng/src."
},
{
"code": null,
"e": 3701,
"s": 3338,
"text": "/*\n* This class prints the given message on console.\n*/\n\npublic class MessageUtil {\n\n private String message;\n\n //Constructor\n //@param message to be printed\n public MessageUtil(String message) {\n this.message = message;\n }\n\n // prints the message\n public String printMessage() {\n System.out.println(message);\n return message;\n }\n}"
},
{
"code": null,
"e": 3784,
"s": 3701,
"text": "Create a java test class, say, TestAnnotationAfterMethod.java in /work/testng/src."
},
{
"code": null,
"e": 3867,
"s": 3784,
"text": "Create a java test class, say, TestAnnotationAfterMethod.java in /work/testng/src."
},
{
"code": null,
"e": 3918,
"s": 3867,
"text": "Add a test method testMethod() to your test class."
},
{
"code": null,
"e": 3969,
"s": 3918,
"text": "Add a test method testMethod() to your test class."
},
{
"code": null,
"e": 4017,
"s": 3969,
"text": "Add an Annotation @Test to method testMethod()."
},
{
"code": null,
"e": 4065,
"s": 4017,
"text": "Add an Annotation @Test to method testMethod()."
},
{
"code": null,
"e": 4138,
"s": 4065,
"text": "Add a method afterMethod to the test class with annotation @AfterMethod."
},
{
"code": null,
"e": 4211,
"s": 4138,
"text": "Add a method afterMethod to the test class with annotation @AfterMethod."
},
{
"code": null,
"e": 4292,
"s": 4211,
"text": "Implement the test condition and check the behaviour of @AfterMethod annotation."
},
{
"code": null,
"e": 4373,
"s": 4292,
"text": "Implement the test condition and check the behaviour of @AfterMethod annotation."
},
{
"code": null,
"e": 4432,
"s": 4373,
"text": "Following are the TestAnnotationAfterMethod.java contents:"
},
{
"code": null,
"e": 5040,
"s": 4432,
"text": " import org.testng.Assert;\n import org.testng.annotations.Test;\n import org.testng.annotations.AfterMethod;\n\n public class TestAnnotationAfterMethod {\n @AfterMethod\n public void afterMethod(){\n System.out.println(\"executing afterMethod after each method\");\n }\n @Test\n public void testMethodOne(){\n Assert.assertEquals(\"Test method one\", (new MessageUtil(\"executing testMethodOne method\")).printMessage());\n }\n @Test\n public void testMethodTwo(){\n Assert.assertEquals(\"Test method two\", (new MessageUtil(\"executing testMethodTwo method\")).printMessage());\n }\n }"
},
{
"code": null,
"e": 5499,
"s": 5040,
"text": "Next, let's create testng.xml file in /work/testng/src, to execute test case(s). This file captures your entire testing in XML. This file makes it easy to describe all your test suites and their parameters in one file, which you can check in your code repository or e-mail to coworkers. It also makes it easy to extract subsets of your tests or split several runtime configurations (e.g., testngdatabase.xml would run only tests that exercise your database)."
},
{
"code": null,
"e": 5800,
"s": 5499,
"text": " <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE suite SYSTEM \"https://testng.org/testng-1.0.dtd\">\n <suite name=\"Suite\">\n <test thread-count=\"5\" name=\"Test\">\n <classes>\n <class name=\"TestAnnotationAfterMethod\"/>\n </classes>\n </test> <!-- Test -->\n </suite> <!-- Suite -->"
},
{
"code": null,
"e": 5835,
"s": 5800,
"text": "Compile the test case using javac."
},
{
"code": null,
"e": 5908,
"s": 5835,
"text": "/work/testng/src$ javac TestAnnotationAfterMethod.java MessageUtil.java\n"
},
{
"code": null,
"e": 6055,
"s": 5908,
"text": "Now, run the testng.xml, which will run the test case defined in <test> tag. As you can see the @AfterMethod is called after all other test cases."
},
{
"code": null,
"e": 6108,
"s": 6055,
"text": "/work/testng/src$ java org.testng.TestNG testng.xml\n"
},
{
"code": null,
"e": 6127,
"s": 6108,
"text": "Verify the output."
},
{
"code": null,
"e": 6426,
"s": 6127,
"text": "executing testMethodOne method\nexecuting afterMethod after each method\nexecuting testMethodTwo method\nexecuting afterMethod after each method\n\n===============================================\nSuite\nTotal tests run: 2, Passes: 0, Failures: 2, Skips: 0\n===============================================\n"
},
{
"code": null,
"e": 6461,
"s": 6426,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6475,
"s": 6461,
"text": " Lets Kode It"
},
{
"code": null,
"e": 6510,
"s": 6475,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6528,
"s": 6510,
"text": " Quaatso Learning"
},
{
"code": null,
"e": 6561,
"s": 6528,
"text": "\n 28 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6581,
"s": 6561,
"text": " Dezlearn Education"
},
{
"code": null,
"e": 6588,
"s": 6581,
"text": " Print"
},
{
"code": null,
"e": 6599,
"s": 6588,
"text": " Add Notes"
}
] |
24-hour time in Python
|
Suppose we have a string s. Here s is representing a 12-hour clock time with suffixes am or pm, we have to find its 24-hour equivalent.
So, if the input is like "08:40pm", then the output will be "20:40"
To solve this, we will follow these steps −
hour := (convert the substring of s [from index 0 to 2] as integer) mod 12
hour := (convert the substring of s [from index 0 to 2] as integer) mod 12
minutes := convert the substring of s [from index 3 to 5] as integer
minutes := convert the substring of s [from index 3 to 5] as integer
if s[5] is same as 'p', thenhour := hour + 12
if s[5] is same as 'p', then
hour := hour + 12
hour := hour + 12
return the result as hour:minutes
return the result as hour:minutes
Let us see the following implementation to get better understanding −
Live Demo
class Solution:
def solve(self, s):
hour = int(s[:2]) % 12
minutes = int(s[3:5])
if s[5] == 'p':
hour += 12
return "{:02}:{:02}".format(hour, minutes)
ob = Solution()
print(ob.solve("08:40pm"))
"08:40pm"
20:40
|
[
{
"code": null,
"e": 1198,
"s": 1062,
"text": "Suppose we have a string s. Here s is representing a 12-hour clock time with suffixes am or pm, we have to find its 24-hour equivalent."
},
{
"code": null,
"e": 1266,
"s": 1198,
"text": "So, if the input is like \"08:40pm\", then the output will be \"20:40\""
},
{
"code": null,
"e": 1310,
"s": 1266,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1385,
"s": 1310,
"text": "hour := (convert the substring of s [from index 0 to 2] as integer) mod 12"
},
{
"code": null,
"e": 1460,
"s": 1385,
"text": "hour := (convert the substring of s [from index 0 to 2] as integer) mod 12"
},
{
"code": null,
"e": 1529,
"s": 1460,
"text": "minutes := convert the substring of s [from index 3 to 5] as integer"
},
{
"code": null,
"e": 1598,
"s": 1529,
"text": "minutes := convert the substring of s [from index 3 to 5] as integer"
},
{
"code": null,
"e": 1644,
"s": 1598,
"text": "if s[5] is same as 'p', thenhour := hour + 12"
},
{
"code": null,
"e": 1673,
"s": 1644,
"text": "if s[5] is same as 'p', then"
},
{
"code": null,
"e": 1691,
"s": 1673,
"text": "hour := hour + 12"
},
{
"code": null,
"e": 1709,
"s": 1691,
"text": "hour := hour + 12"
},
{
"code": null,
"e": 1743,
"s": 1709,
"text": "return the result as hour:minutes"
},
{
"code": null,
"e": 1777,
"s": 1743,
"text": "return the result as hour:minutes"
},
{
"code": null,
"e": 1847,
"s": 1777,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1858,
"s": 1847,
"text": " Live Demo"
},
{
"code": null,
"e": 2088,
"s": 1858,
"text": "class Solution:\n def solve(self, s):\n hour = int(s[:2]) % 12\n minutes = int(s[3:5])\n if s[5] == 'p':\n hour += 12\n return \"{:02}:{:02}\".format(hour, minutes)\nob = Solution()\nprint(ob.solve(\"08:40pm\"))"
},
{
"code": null,
"e": 2098,
"s": 2088,
"text": "\"08:40pm\""
},
{
"code": null,
"e": 2104,
"s": 2098,
"text": "20:40"
}
] |
How to set subtitle for action bar in android?
|
This example demonstrates How to set subtitle for action bar in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:gravity = "center"
android:layout_height = "match_parent"
tools:context = ".MainActivity">
<TextView
android:id = "@+id/text"
android:textSize = "30sp"
android:layout_width = "match_parent"
android:layout_height = "match_parent" />
</LinearLayout>
In the above code, we have taken text view to show status bar sub tittle.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
getSupportActionBar().setSubtitle("sairam");
textView.setText(" subtittle is sairam");
}
}
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –
Click here to download the project code
|
[
{
"code": null,
"e": 1135,
"s": 1062,
"text": "This example demonstrates How to set subtitle for action bar in android."
},
{
"code": null,
"e": 1264,
"s": 1135,
"text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1329,
"s": 1264,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1889,
"s": 1329,
"text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:gravity = \"center\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/text\"\n android:textSize = \"30sp\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\" />\n</LinearLayout>"
},
{
"code": null,
"e": 1963,
"s": 1889,
"text": "In the above code, we have taken text view to show status bar sub tittle."
},
{
"code": null,
"e": 2020,
"s": 1963,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2909,
"s": 2020,
"text": "package com.example.myapplication;\nimport android.app.ActivityManager;\nimport android.app.admin.DevicePolicyManager;\nimport android.content.ComponentName;\nimport android.content.Context;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView textView;\n @RequiresApi(api = Build.VERSION_CODES.N)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n textView = findViewById(R.id.text);\n getSupportActionBar().setSubtitle(\"sairam\");\n textView.setText(\" subtittle is sairam\");\n }\n}"
},
{
"code": null,
"e": 3256,
"s": 2909,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –"
},
{
"code": null,
"e": 3296,
"s": 3256,
"text": "Click here to download the project code"
}
] |
Passing Hashes to Subroutines in Perl
|
When you supply a hash to a Perl subroutine or operator that accepts a list, then the hash is automatically translated into a list of key/value pairs. For example −
Live Demo
#!/usr/bin/perl
# Function definition
sub PrintHash {
my (%hash) = @_;
foreach my $key ( keys %hash ) {
my $value = $hash{$key};
print "$key : $value\n";
}
}
%hash = ('name' => 'Tom', 'age' => 19);
# Function call with hash parameter
PrintHash(%hash);
When the above program is executed, it produces the following result −
name : Tom
age : 19
|
[
{
"code": null,
"e": 1227,
"s": 1062,
"text": "When you supply a hash to a Perl subroutine or operator that accepts a list, then the hash is automatically translated into a list of key/value pairs. For example −"
},
{
"code": null,
"e": 1238,
"s": 1227,
"text": " Live Demo"
},
{
"code": null,
"e": 1511,
"s": 1238,
"text": "#!/usr/bin/perl\n# Function definition\nsub PrintHash {\n my (%hash) = @_;\n foreach my $key ( keys %hash ) {\n my $value = $hash{$key};\n print \"$key : $value\\n\";\n }\n}\n%hash = ('name' => 'Tom', 'age' => 19);\n# Function call with hash parameter\nPrintHash(%hash);"
},
{
"code": null,
"e": 1582,
"s": 1511,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 1602,
"s": 1582,
"text": "name : Tom\nage : 19"
}
] |
Unpacking a Tuple in Python
|
Python offers immutable data types known as tuples. In this article, we will learn about packing an unpacking tuple type in Python 3.x. Or earlier.
Python offers a very powerful tuple assignment tool that maps right hand side arguments into left hand side arguments. THis act of mapping together is known as unpacking of a tuple of values into a norml variable. WHereas in packing, we put values into a regular tuple by means of regular assignment.
Now let’s take a look at its implementation −
Live Demo
# Packing tuple varibles under one varible name
tup = ("Tutorialspoint", "Python", "Unpacking a tuple")
# Packing tuple varibles into a group of arguments
(website, language, topic) = tup
# print college name
print(website,"\t",language," ",topic)
Tutorialspoint Python Unpacking a tuple
During the unpacking of tuple, the total number of variables on the left-hand side should be equivalent to the total number of values in given tuple tup.
Python gives the syntax to pass optional arguments (*arguments) for tuple unpacking of arbitrary length. All values will be assigned to every variable in the order of their specification and all remaining values will be assigned to *arguments . Let’s consider the following code.
Live Demo
# Packing tuple variables under one variable name
tup = ("Tutorialspoint", "Python","3.x.",":Data
Structure","Unpacking a tuple")
# Packing tuple variables into a group of arguments
(website,*language, topic) = tup
# print college name
print(website,"\t",*language," ",topic)
Tutorialspoint Python 3.x. :Data Structure Unpacking a tuple
In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments.
“*_” is used to specify the arbitrary number of arguments in the tuple.
Live Demo
# Packing tuple varibles under one varible name
tup = ("Tutorialspoint", "Python","3.x.","Data Structure:","Unpacking a tuple")
# UnPacking tuple variables into a group of arguments and skipping unwanted arguments
(website,*_,typ,topic) = tup
# print college name
print(website,"\t",typ," ",topic)
Tutorialspoint Data Structure: Unpacking a tuple
In case we want to skip only one argument then we can replace “*_” by “_”
In this article, we learnt how we can pack and unpack tuples in a variety of Ways.
|
[
{
"code": null,
"e": 1210,
"s": 1062,
"text": "Python offers immutable data types known as tuples. In this article, we will learn about packing an unpacking tuple type in Python 3.x. Or earlier."
},
{
"code": null,
"e": 1511,
"s": 1210,
"text": "Python offers a very powerful tuple assignment tool that maps right hand side arguments into left hand side arguments. THis act of mapping together is known as unpacking of a tuple of values into a norml variable. WHereas in packing, we put values into a regular tuple by means of regular assignment."
},
{
"code": null,
"e": 1557,
"s": 1511,
"text": "Now let’s take a look at its implementation −"
},
{
"code": null,
"e": 1568,
"s": 1557,
"text": " Live Demo"
},
{
"code": null,
"e": 1825,
"s": 1568,
"text": "# Packing tuple varibles under one varible name\ntup = (\"Tutorialspoint\", \"Python\", \"Unpacking a tuple\")\n # Packing tuple varibles into a group of arguments\n (website, language, topic) = tup\n # print college name\nprint(website,\"\\t\",language,\" \",topic)"
},
{
"code": null,
"e": 1871,
"s": 1825,
"text": "Tutorialspoint Python Unpacking a tuple"
},
{
"code": null,
"e": 2025,
"s": 1871,
"text": "During the unpacking of tuple, the total number of variables on the left-hand side should be equivalent to the total number of values in given tuple tup."
},
{
"code": null,
"e": 2305,
"s": 2025,
"text": "Python gives the syntax to pass optional arguments (*arguments) for tuple unpacking of arbitrary length. All values will be assigned to every variable in the order of their specification and all remaining values will be assigned to *arguments . Let’s consider the following code."
},
{
"code": null,
"e": 2316,
"s": 2305,
"text": " Live Demo"
},
{
"code": null,
"e": 2601,
"s": 2316,
"text": "# Packing tuple variables under one variable name\ntup = (\"Tutorialspoint\", \"Python\",\"3.x.\",\":Data\nStructure\",\"Unpacking a tuple\")\n # Packing tuple variables into a group of arguments\n (website,*language, topic) = tup\n # print college name\nprint(website,\"\\t\",*language,\" \",topic)"
},
{
"code": null,
"e": 2662,
"s": 2601,
"text": "Tutorialspoint Python 3.x. :Data Structure Unpacking a tuple"
},
{
"code": null,
"e": 2880,
"s": 2662,
"text": "In python tuples can be unpacked using a function in function tuple is passed and in function, values are unpacked into a normal variable. The following code explains how to deal with an arbitrary number of arguments."
},
{
"code": null,
"e": 2952,
"s": 2880,
"text": "“*_” is used to specify the arbitrary number of arguments in the tuple."
},
{
"code": null,
"e": 2963,
"s": 2952,
"text": " Live Demo"
},
{
"code": null,
"e": 3261,
"s": 2963,
"text": "# Packing tuple varibles under one varible name\ntup = (\"Tutorialspoint\", \"Python\",\"3.x.\",\"Data Structure:\",\"Unpacking a tuple\")\n# UnPacking tuple variables into a group of arguments and skipping unwanted arguments\n(website,*_,typ,topic) = tup\n# print college name\nprint(website,\"\\t\",typ,\" \",topic)"
},
{
"code": null,
"e": 3316,
"s": 3261,
"text": "Tutorialspoint Data Structure: Unpacking a tuple"
},
{
"code": null,
"e": 3390,
"s": 3316,
"text": "In case we want to skip only one argument then we can replace “*_” by “_”"
},
{
"code": null,
"e": 3473,
"s": 3390,
"text": "In this article, we learnt how we can pack and unpack tuples in a variety of Ways."
}
] |
How to multiply a matrix columns and rows with the same matrix rows and columns in R?
|
To multiply a rows or columns of a matrix, we need to use %*% symbol that perform the multiplication for matrices in R. If we have a matrix M with 5 rows and 5 columns then row 1 of M can be multiplied with column 1 of M using M[1,]%*%M[,1], similarly, we can multiply other rows and columns.
Live Demo
M<−matrix(1:100,ncol=10)
M
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 11 21 31 41 51 61 71 81 91
[2,] 2 12 22 32 42 52 62 72 82 92
[3,] 3 13 23 33 43 53 63 73 83 93
[4,] 4 14 24 34 44 54 64 74 84 94
[5,] 5 15 25 35 45 55 65 75 85 95
[6,] 6 16 26 36 46 56 66 76 86 96
[7,] 7 17 27 37 47 57 67 77 87 97
[8,] 8 18 28 38 48 58 68 78 88 98
[9,] 9 19 29 39 49 59 69 79 89 99
[10,] 10 20 30 40 50 60 70 80 90 100
M[1,]%*%M[,1]
[,1]
[1,] 3355
M[1,]%*%M[,2]
[,1]
[1,] 7955
M[1,]%*%M[,3]
[,1]
[1,] 12555
M[1,]%*%M[,5]
[,1]
[1,] 21755
M[1,]%*%M[,7]
[,1]
[1,] 30955
M[1,]%*%M[,8]
[,1]
[1,] 35555
M[1,]%*%M[,10]
[,1]
[1,] 44755
M[2,]%*%M[,1]
[,1]
[1,] 3410
M[5,]%*%M[,3]
[,1]
[1,] 13575
M[9,]%*%M[,5]
[,1]
[1,] 25395
M[2,]%*%M[,10]
[,1]
[1,] 45710
M[3,]%*%M[,4]
[,1]
[1,] 17865
M[3,]%*%M[,6]
[,1]
[1,] 27465
M[3,]%*%M[,8]
[,1]
[1,] 37065
M[3,]%*%M[,10]
[,1]
[1,] 46665
M[4,]%*%M[,5]
[,1]
[1,] 23120
M[4,]%*%M[,8]
[,1]
[1,] 37820
M[4,]%*%M[,9]
[,1]
[1,] 42720
M[4,]%*%M[,10]
[,1]
[1,] 47620
M[5,]%*%M[,5]
[,1]
[1,] 23575
M[5,]%*%M[,8]
[,1]
[1,] 38575
M[5,]%*%M[,10]
[,1]
[1,] 48575
M[5,]%*%M[,1]
[,1]
[1,] 3575
M[6,]%*%M[,6]
[,1]
[1,] 29130
M[6,]%*%M[,10]
[,1]
[1,] 49530
M[6,]%*%M[,3]
[,1]
[1,] 13830
M[6,]%*%M[,1]
[,1]
[1,] 3630
M[7,]%*%M[,7]
[,1]
[1,] 34885
M[7,]%*%M[,10]
[,1]
[1,] 50485
M[7,]%*%M[,9]
[,1]
[1,] 45285
M[7,]%*%M[,2]
[,1]
[1,] 8885
M[8,]%*%M[,3]
[,1]
[1,] 14340
M[8,]%*%M[,4]
[,1]
[1,] 19640
M[8,]%*%M[,8]
[,1]
[1,] 40840
M[8,]%*%M[,10]
[,1]
[1,] 51440
M[,1]%*%M[9,]
[,1]
[1,] 3795
M[,1]%*%M[5,]
[,1]
[1,] 3575
M[,2]%*%M[5,]
[,1]
[1,] 8575
M[,4]%*%M[10,]
[,1]
[1,] 20350
M[,5]%*%M[9,]
[,1]
[1,] 25395
|
[
{
"code": null,
"e": 1355,
"s": 1062,
"text": "To multiply a rows or columns of a matrix, we need to use %*% symbol that perform the multiplication for matrices in R. If we have a matrix M with 5 rows and 5 columns then row 1 of M can be multiplied with column 1 of M using M[1,]%*%M[,1], similarly, we can multiply other rows and columns."
},
{
"code": null,
"e": 1366,
"s": 1355,
"text": " Live Demo"
},
{
"code": null,
"e": 1393,
"s": 1366,
"text": "M<−matrix(1:100,ncol=10)\nM"
},
{
"code": null,
"e": 2987,
"s": 1393,
"text": "[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]\n[1,] 1 11 21 31 41 51 61 71 81 91\n[2,] 2 12 22 32 42 52 62 72 82 92\n[3,] 3 13 23 33 43 53 63 73 83 93\n[4,] 4 14 24 34 44 54 64 74 84 94\n[5,] 5 15 25 35 45 55 65 75 85 95\n[6,] 6 16 26 36 46 56 66 76 86 96\n[7,] 7 17 27 37 47 57 67 77 87 97\n[8,] 8 18 28 38 48 58 68 78 88 98\n[9,] 9 19 29 39 49 59 69 79 89 99\n[10,] 10 20 30 40 50 60 70 80 90 100\nM[1,]%*%M[,1]\n[,1]\n[1,] 3355\nM[1,]%*%M[,2]\n[,1]\n[1,] 7955\nM[1,]%*%M[,3]\n[,1]\n[1,] 12555\nM[1,]%*%M[,5]\n[,1]\n[1,] 21755\nM[1,]%*%M[,7]\n[,1]\n[1,] 30955\nM[1,]%*%M[,8]\n[,1]\n[1,] 35555\nM[1,]%*%M[,10]\n[,1]\n[1,] 44755\nM[2,]%*%M[,1]\n[,1]\n[1,] 3410\nM[5,]%*%M[,3]\n[,1]\n[1,] 13575\nM[9,]%*%M[,5]\n[,1]\n[1,] 25395\nM[2,]%*%M[,10]\n[,1]\n[1,] 45710\nM[3,]%*%M[,4]\n[,1]\n[1,] 17865\nM[3,]%*%M[,6]\n[,1]\n[1,] 27465\nM[3,]%*%M[,8]\n[,1]\n[1,] 37065\nM[3,]%*%M[,10]\n[,1]\n[1,] 46665\nM[4,]%*%M[,5]\n[,1]\n[1,] 23120\nM[4,]%*%M[,8]\n[,1]\n[1,] 37820\nM[4,]%*%M[,9]\n[,1]\n[1,] 42720\nM[4,]%*%M[,10]\n[,1]\n[1,] 47620\nM[5,]%*%M[,5]\n[,1]\n[1,] 23575\nM[5,]%*%M[,8]\n[,1]\n[1,] 38575\nM[5,]%*%M[,10]\n[,1]\n[1,] 48575\nM[5,]%*%M[,1]\n[,1]\n[1,] 3575\nM[6,]%*%M[,6]\n[,1]\n[1,] 29130\nM[6,]%*%M[,10]\n[,1]\n[1,] 49530\nM[6,]%*%M[,3]\n[,1]\n[1,] 13830\nM[6,]%*%M[,1]\n[,1]\n[1,] 3630\nM[7,]%*%M[,7]\n[,1]\n[1,] 34885\nM[7,]%*%M[,10]\n[,1]\n[1,] 50485\nM[7,]%*%M[,9]\n[,1]\n[1,] 45285\nM[7,]%*%M[,2]\n[,1]\n[1,] 8885\nM[8,]%*%M[,3]\n[,1]\n[1,] 14340\nM[8,]%*%M[,4]\n[,1]\n[1,] 19640\nM[8,]%*%M[,8]\n[,1]\n[1,] 40840\nM[8,]%*%M[,10]\n[,1]\n[1,] 51440\nM[,1]%*%M[9,]\n[,1]\n[1,] 3795\nM[,1]%*%M[5,]\n[,1]\n[1,] 3575\nM[,2]%*%M[5,]\n[,1]\n[1,] 8575\nM[,4]%*%M[10,]\n[,1]\n[1,] 20350\nM[,5]%*%M[9,]\n[,1]\n[1,] 25395"
}
] |
How to create an HTML Document?
|
An HTML document defines the structure of HTML web page. It contains two distinct parts, the head, and the body. The head contains information about the document. The body part contains the content of the document, which gets displayed.
Just keep in mind that you should use the head part inside <head>...</head> tags. The body tag is used inside the <body>...</body> tags. Also, an HTML document begins with the <!DOCTYPE html> declaration, which is known as the DTD (Document Type Definition). This is to inform the web browser the type and version of the HTML document.
You can try to run the following code to create an HTML document. The <p> tag defines the paragraph −
<!DOCTYPE html>
<html>
<head>
<title>HTML Document</title>
</head>
<body>
<p>The content gets added here.</p>
</body>
</html>
The content gets added here.
|
[
{
"code": null,
"e": 1299,
"s": 1062,
"text": "An HTML document defines the structure of HTML web page. It contains two distinct parts, the head, and the body. The head contains information about the document. The body part contains the content of the document, which gets displayed."
},
{
"code": null,
"e": 1635,
"s": 1299,
"text": "Just keep in mind that you should use the head part inside <head>...</head> tags. The body tag is used inside the <body>...</body> tags. Also, an HTML document begins with the <!DOCTYPE html> declaration, which is known as the DTD (Document Type Definition). This is to inform the web browser the type and version of the HTML document."
},
{
"code": null,
"e": 1737,
"s": 1635,
"text": "You can try to run the following code to create an HTML document. The <p> tag defines the paragraph −"
},
{
"code": null,
"e": 1864,
"s": 1737,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<title>HTML Document</title>\n</head>\n\n<body>\n<p>The content gets added here.</p>\n</body>\n</html>"
},
{
"code": null,
"e": 1893,
"s": 1864,
"text": "The content gets added here."
}
] |
How do I call a JavaScript function on page load?
|
To call a function on page load, use −
window.onload
You can try to run the following code to implement a JavaScript function on page load
Live Demo
<!DOCTYPE html>
<html>
<body>
<script>
function alertFunction() {
alert('ok');
}
window.onload = alertFunction;
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1101,
"s": 1062,
"text": "To call a function on page load, use −"
},
{
"code": null,
"e": 1115,
"s": 1101,
"text": "window.onload"
},
{
"code": null,
"e": 1201,
"s": 1115,
"text": "You can try to run the following code to implement a JavaScript function on page load"
},
{
"code": null,
"e": 1211,
"s": 1201,
"text": "Live Demo"
},
{
"code": null,
"e": 1406,
"s": 1211,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n function alertFunction() {\n alert('ok');\n }\n window.onload = alertFunction;\n </script>\n </body>\n</html>"
}
] |
How to concatenate two or more vectors in R ? - GeeksforGeeks
|
05 Apr, 2021
In this article, we will see how to concatenate two or more vectors in R Programming Language.
To concatenate two or more vectors in r we can use the combination function in R. Let’s assume we have 3 vectors vec1, vec2, vec3 the concatenation of these vectors can be done as c(vec1, vec2, vec3). Also, we can concatenate different types of vectors at the same time using the same function.
Concatenate function:
This is a function that combines its arguments.
This method combines the arguments and results in a vector.
All the arguments are converted to a common type that is the return value type.
This function is also used to convert the array into vectors.
Syntax: c(argument, argument,..)
Parameter:
Arguments : The objects to be concatenated
Approach:
Create a number of example vectors to concatenate.
Concatenate the vectors by c function, c(vec1, vec2, vec3)
Example 1: Let’s first create an example vector and then concatenate those vectors.
In this example, we have first created a vector vec1 and vec2. Then by using the concatenate function we have concatenated both the vectors to get the result.
R
vec1 <- 1:9vec1 vec2 <-9:1vec2 c(vec1,vec2)
Output:
Example 2: Lets us now concatenate 3 vectors.
In this example, we have created 3 vectors vec1,vec2,vec3 using sample function and then concatenate the vectors into a single vector using the concatenate function
R
vec1 <- sample(0:9 , 50 , replace = TRUE)vec2 <- sample(0:4 , 25 ,replace = TRUE)vec3 <- sample(1:3 , 15 , replace = TRUE) c(vec1,vec2,vec3)
Output:
.
Example 3: In this example, we have created a character vector and a number vector and then combine both the vectors using the concatenate function of R library.
R
number <- (1, 2, 3, 4, 5)character <- ("A" , "B" , "C" , "D" , "E") c(number, character)
Output:
Picked
R Vector-Programs
R-Vectors
R Language
R Programs
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
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Replace Specific Characters in String in R
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 25242,
"s": 25214,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 25338,
"s": 25242,
"text": "In this article, we will see how to concatenate two or more vectors in R Programming Language. "
},
{
"code": null,
"e": 25633,
"s": 25338,
"text": "To concatenate two or more vectors in r we can use the combination function in R. Let’s assume we have 3 vectors vec1, vec2, vec3 the concatenation of these vectors can be done as c(vec1, vec2, vec3). Also, we can concatenate different types of vectors at the same time using the same function."
},
{
"code": null,
"e": 25655,
"s": 25633,
"text": "Concatenate function:"
},
{
"code": null,
"e": 25703,
"s": 25655,
"text": "This is a function that combines its arguments."
},
{
"code": null,
"e": 25763,
"s": 25703,
"text": "This method combines the arguments and results in a vector."
},
{
"code": null,
"e": 25843,
"s": 25763,
"text": "All the arguments are converted to a common type that is the return value type."
},
{
"code": null,
"e": 25905,
"s": 25843,
"text": "This function is also used to convert the array into vectors."
},
{
"code": null,
"e": 25938,
"s": 25905,
"text": "Syntax: c(argument, argument,..)"
},
{
"code": null,
"e": 25949,
"s": 25938,
"text": "Parameter:"
},
{
"code": null,
"e": 25992,
"s": 25949,
"text": "Arguments : The objects to be concatenated"
},
{
"code": null,
"e": 26002,
"s": 25992,
"text": "Approach:"
},
{
"code": null,
"e": 26053,
"s": 26002,
"text": "Create a number of example vectors to concatenate."
},
{
"code": null,
"e": 26112,
"s": 26053,
"text": "Concatenate the vectors by c function, c(vec1, vec2, vec3)"
},
{
"code": null,
"e": 26196,
"s": 26112,
"text": "Example 1: Let’s first create an example vector and then concatenate those vectors."
},
{
"code": null,
"e": 26355,
"s": 26196,
"text": "In this example, we have first created a vector vec1 and vec2. Then by using the concatenate function we have concatenated both the vectors to get the result."
},
{
"code": null,
"e": 26357,
"s": 26355,
"text": "R"
},
{
"code": "vec1 <- 1:9vec1 vec2 <-9:1vec2 c(vec1,vec2)",
"e": 26403,
"s": 26357,
"text": null
},
{
"code": null,
"e": 26412,
"s": 26403,
"text": "Output: "
},
{
"code": null,
"e": 26458,
"s": 26412,
"text": "Example 2: Lets us now concatenate 3 vectors."
},
{
"code": null,
"e": 26623,
"s": 26458,
"text": "In this example, we have created 3 vectors vec1,vec2,vec3 using sample function and then concatenate the vectors into a single vector using the concatenate function"
},
{
"code": null,
"e": 26625,
"s": 26623,
"text": "R"
},
{
"code": "vec1 <- sample(0:9 , 50 , replace = TRUE)vec2 <- sample(0:4 , 25 ,replace = TRUE)vec3 <- sample(1:3 , 15 , replace = TRUE) c(vec1,vec2,vec3)",
"e": 26767,
"s": 26625,
"text": null
},
{
"code": null,
"e": 26776,
"s": 26767,
"text": "Output: "
},
{
"code": null,
"e": 26778,
"s": 26776,
"text": "."
},
{
"code": null,
"e": 26940,
"s": 26778,
"text": "Example 3: In this example, we have created a character vector and a number vector and then combine both the vectors using the concatenate function of R library."
},
{
"code": null,
"e": 26942,
"s": 26940,
"text": "R"
},
{
"code": "number <- (1, 2, 3, 4, 5)character <- (\"A\" , \"B\" , \"C\" , \"D\" , \"E\") c(number, character)",
"e": 27032,
"s": 26942,
"text": null
},
{
"code": null,
"e": 27041,
"s": 27032,
"text": "Output: "
},
{
"code": null,
"e": 27048,
"s": 27041,
"text": "Picked"
},
{
"code": null,
"e": 27066,
"s": 27048,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 27076,
"s": 27066,
"text": "R-Vectors"
},
{
"code": null,
"e": 27087,
"s": 27076,
"text": "R Language"
},
{
"code": null,
"e": 27098,
"s": 27087,
"text": "R Programs"
},
{
"code": null,
"e": 27196,
"s": 27098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27248,
"s": 27196,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27286,
"s": 27248,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27321,
"s": 27286,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27379,
"s": 27321,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27428,
"s": 27379,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27486,
"s": 27428,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27535,
"s": 27486,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27585,
"s": 27535,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27628,
"s": 27585,
"text": "Replace Specific Characters in String in R"
}
] |
Python Penetration Testing - SQLi Web Attack
|
The SQL injection is a set of SQL commands that are placed in a URL string or in data structures in order to retrieve a response that we want from the databases that are connected with the web applications. This type of attacksk generally takes place on webpages developed using PHP or ASP.NET.
An SQL injection attack can be done with the following intentions −
To modify the content of the databases
To modify the content of the databases
To modify the content of the databases
To modify the content of the databases
To perform different queries that are not allowed by the application
To perform different queries that are not allowed by the application
This type of attack works when the applications does not validate the inputs properly, before passing them to an SQL statement. Injections are normally placed put in address bars, search fields, or data fields.
The easiest way to detect if a web application is vulnerable to an SQL injection attack is by using the " ‘ " character in a string and see if you get any error.
In this section, we will learn about the different types of SQLi attack. The attack can be categorize into the following two types −
In-band SQL injection (Simple SQLi)
In-band SQL injection (Simple SQLi)
Inferential SQL injection (Blind SQLi)
Inferential SQL injection (Blind SQLi)
It is the most common SQL injection. This kind of SQL injection mainly occurs when an attacker is able to use the same communication channel to both launch the attack & congregate results. The in-band SQL injections are further divided into two types −
Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database.
Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database.
Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response.
Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response.
In this kind of SQL injection attack, attacker is not able to see the result of an attack in-band because no data is transferred via the web application. This is the reason it is also called Blind SQLi. Inferential SQL injections are further of two types −
Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result.
Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result.
Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE.
Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE.
All types of SQLi can be implemented by manipulating input data to the application. In the following examples, we are writing a Python script to inject attack vectors to the application and analyze the output to verify the possibility of the attack. Here, we are going to use python module named mechanize, which gives the facility of obtaining web forms in a web page and facilitates the submission of input values too. We have also used this module for client-side validation.
The following Python script helps submit forms and analyze the response using mechanize −
First of all we need to import the mechanize module.
import mechanize
Now, provide the name of the URL for obtaining the response after submitting the form.
url = input("Enter the full url")
The following line of codes will open the url.
request = mechanize.Browser()
request.open(url)
Now, we need to select the form.
request.select_form(nr = 0)
Here, we will set the column name ‘id’.
request["id"] = "1 OR 1 = 1"
Now, we need to submit the form.
response = request.submit()
content = response.read()
print content
The above script will print the response for the POST request. We have submitted an attack vector to break the SQL query and print all the data in the table instead of one row. All the attack vectors will be saved in a text file say vectors.txt. Now, the Python script given below will get those attack vectors from the file and send them to the server one by one. It will also save the output to a file.
To begin with, let us import the mechanize module.
import mechanize
Now, provide the name of the URL for obtaining the response after submitting the form.
url = input("Enter the full url")
attack_no = 1
We need to read the attack vectors from the file.
With open (‘vectors.txt’) as v:
Now we will send request with each arrack vector
For line in v:
browser.open(url)
browser.select_form(nr = 0)
browser[“id”] = line
res = browser.submit()
content = res.read()
Now, the following line of code will write the response to the output file.
output = open(‘response/’ + str(attack_no) + ’.txt’, ’w’)
output.write(content)
output.close()
print attack_no
attack_no += 1
By checking and analyzing the responses, we can identify the possible attacks. For example, if it provides the response that include the sentence You have an error in your SQL syntax then it means the form may be affected by SQL injection.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2152,
"s": 1857,
"text": "The SQL injection is a set of SQL commands that are placed in a URL string or in data structures in order to retrieve a response that we want from the databases that are connected with the web applications. This type of attacksk generally takes place on webpages developed using PHP or ASP.NET."
},
{
"code": null,
"e": 2220,
"s": 2152,
"text": "An SQL injection attack can be done with the following intentions −"
},
{
"code": null,
"e": 2259,
"s": 2220,
"text": "To modify the content of the databases"
},
{
"code": null,
"e": 2298,
"s": 2259,
"text": "To modify the content of the databases"
},
{
"code": null,
"e": 2337,
"s": 2298,
"text": "To modify the content of the databases"
},
{
"code": null,
"e": 2376,
"s": 2337,
"text": "To modify the content of the databases"
},
{
"code": null,
"e": 2445,
"s": 2376,
"text": "To perform different queries that are not allowed by the application"
},
{
"code": null,
"e": 2514,
"s": 2445,
"text": "To perform different queries that are not allowed by the application"
},
{
"code": null,
"e": 2725,
"s": 2514,
"text": "This type of attack works when the applications does not validate the inputs properly, before passing them to an SQL statement. Injections are normally placed put in address bars, search fields, or data fields."
},
{
"code": null,
"e": 2887,
"s": 2725,
"text": "The easiest way to detect if a web application is vulnerable to an SQL injection attack is by using the \" ‘ \" character in a string and see if you get any error."
},
{
"code": null,
"e": 3020,
"s": 2887,
"text": "In this section, we will learn about the different types of SQLi attack. The attack can be categorize into the following two types −"
},
{
"code": null,
"e": 3056,
"s": 3020,
"text": "In-band SQL injection (Simple SQLi)"
},
{
"code": null,
"e": 3092,
"s": 3056,
"text": "In-band SQL injection (Simple SQLi)"
},
{
"code": null,
"e": 3131,
"s": 3092,
"text": "Inferential SQL injection (Blind SQLi)"
},
{
"code": null,
"e": 3170,
"s": 3131,
"text": "Inferential SQL injection (Blind SQLi)"
},
{
"code": null,
"e": 3423,
"s": 3170,
"text": "It is the most common SQL injection. This kind of SQL injection mainly occurs when an attacker is able to use the same communication channel to both launch the attack & congregate results. The in-band SQL injections are further divided into two types −"
},
{
"code": null,
"e": 3603,
"s": 3423,
"text": "Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database."
},
{
"code": null,
"e": 3783,
"s": 3603,
"text": "Error-based SQL injection − An error-based SQL injection technique relies on error message thrown by the database server to obtain information about the structure of the database."
},
{
"code": null,
"e": 4026,
"s": 3783,
"text": "Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response."
},
{
"code": null,
"e": 4269,
"s": 4026,
"text": "Union-based SQL injection − It is another in-band SQL injection technique that leverages the UNION SQL operator to combine the results of two or more SELECT statements into a single result, which is then returned as part of the HTTP response."
},
{
"code": null,
"e": 4526,
"s": 4269,
"text": "In this kind of SQL injection attack, attacker is not able to see the result of an attack in-band because no data is transferred via the web application. This is the reason it is also called Blind SQLi. Inferential SQL injections are further of two types −"
},
{
"code": null,
"e": 4745,
"s": 4526,
"text": "Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result."
},
{
"code": null,
"e": 4964,
"s": 4745,
"text": "Boolean-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the application to return a different result depending on whether the query returns a TRUE or FALSE result."
},
{
"code": null,
"e": 5254,
"s": 4964,
"text": "Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE."
},
{
"code": null,
"e": 5544,
"s": 5254,
"text": "Time-based blind SQLi − This kind of technique relies on sending an SQL query to the database, which forces the database to wait for a specified amount of time (in seconds) before responding. The response time will indicate to the attacker whether the result of the query is TRUE or FALSE."
},
{
"code": null,
"e": 6023,
"s": 5544,
"text": "All types of SQLi can be implemented by manipulating input data to the application. In the following examples, we are writing a Python script to inject attack vectors to the application and analyze the output to verify the possibility of the attack. Here, we are going to use python module named mechanize, which gives the facility of obtaining web forms in a web page and facilitates the submission of input values too. We have also used this module for client-side validation."
},
{
"code": null,
"e": 6113,
"s": 6023,
"text": "The following Python script helps submit forms and analyze the response using mechanize −"
},
{
"code": null,
"e": 6166,
"s": 6113,
"text": "First of all we need to import the mechanize module."
},
{
"code": null,
"e": 6184,
"s": 6166,
"text": "import mechanize\n"
},
{
"code": null,
"e": 6271,
"s": 6184,
"text": "Now, provide the name of the URL for obtaining the response after submitting the form."
},
{
"code": null,
"e": 6306,
"s": 6271,
"text": "url = input(\"Enter the full url\")\n"
},
{
"code": null,
"e": 6353,
"s": 6306,
"text": "The following line of codes will open the url."
},
{
"code": null,
"e": 6402,
"s": 6353,
"text": "request = mechanize.Browser()\nrequest.open(url)\n"
},
{
"code": null,
"e": 6435,
"s": 6402,
"text": "Now, we need to select the form."
},
{
"code": null,
"e": 6464,
"s": 6435,
"text": "request.select_form(nr = 0)\n"
},
{
"code": null,
"e": 6504,
"s": 6464,
"text": "Here, we will set the column name ‘id’."
},
{
"code": null,
"e": 6534,
"s": 6504,
"text": "request[\"id\"] = \"1 OR 1 = 1\"\n"
},
{
"code": null,
"e": 6567,
"s": 6534,
"text": "Now, we need to submit the form."
},
{
"code": null,
"e": 6635,
"s": 6567,
"text": "response = request.submit()\ncontent = response.read()\nprint content"
},
{
"code": null,
"e": 7040,
"s": 6635,
"text": "The above script will print the response for the POST request. We have submitted an attack vector to break the SQL query and print all the data in the table instead of one row. All the attack vectors will be saved in a text file say vectors.txt. Now, the Python script given below will get those attack vectors from the file and send them to the server one by one. It will also save the output to a file."
},
{
"code": null,
"e": 7091,
"s": 7040,
"text": "To begin with, let us import the mechanize module."
},
{
"code": null,
"e": 7109,
"s": 7091,
"text": "import mechanize\n"
},
{
"code": null,
"e": 7196,
"s": 7109,
"text": "Now, provide the name of the URL for obtaining the response after submitting the form."
},
{
"code": null,
"e": 7247,
"s": 7196,
"text": "url = input(\"Enter the full url\")\n attack_no = 1"
},
{
"code": null,
"e": 7297,
"s": 7247,
"text": "We need to read the attack vectors from the file."
},
{
"code": null,
"e": 7330,
"s": 7297,
"text": "With open (‘vectors.txt’) as v:\n"
},
{
"code": null,
"e": 7379,
"s": 7330,
"text": "Now we will send request with each arrack vector"
},
{
"code": null,
"e": 7517,
"s": 7379,
"text": "For line in v:\n browser.open(url)\n browser.select_form(nr = 0)\n browser[“id”] = line\n res = browser.submit()\ncontent = res.read()"
},
{
"code": null,
"e": 7593,
"s": 7517,
"text": "Now, the following line of code will write the response to the output file."
},
{
"code": null,
"e": 7719,
"s": 7593,
"text": "output = open(‘response/’ + str(attack_no) + ’.txt’, ’w’)\noutput.write(content)\noutput.close()\nprint attack_no\nattack_no += 1"
},
{
"code": null,
"e": 7959,
"s": 7719,
"text": "By checking and analyzing the responses, we can identify the possible attacks. For example, if it provides the response that include the sentence You have an error in your SQL syntax then it means the form may be affected by SQL injection."
},
{
"code": null,
"e": 7996,
"s": 7959,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 8012,
"s": 7996,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 8045,
"s": 8012,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 8064,
"s": 8045,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8099,
"s": 8064,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 8121,
"s": 8099,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 8155,
"s": 8121,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 8183,
"s": 8155,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8218,
"s": 8183,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 8232,
"s": 8218,
"text": " Lets Kode It"
},
{
"code": null,
"e": 8265,
"s": 8232,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 8282,
"s": 8265,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 8289,
"s": 8282,
"text": " Print"
},
{
"code": null,
"e": 8300,
"s": 8289,
"text": " Add Notes"
}
] |
DirectX - Compute Shaders
|
In 3D programming, compute shader is a programmable shader stage which calls for the respective buffer. It expands the feature of Microsoft Direct3Dt3d version 11. The shader technology which is included is DirectCOMPUTE technology.
Like vertex and geometry which we discussed in the last chapter, a compute shader is designed and implemented with HLSL where many similarities can be tracked. A compute shader includes high-speed general purpose computing and includes advantage of various large numbers of parallel processors on the graphics processing unit (GPU).
The compute shader includes memory sharing and thread synchronization features which allows more effective parallel programming methods when developer calls the ID3D11DeviceContext::Dispatch or ID3D11DeviceContext::DispatchIndirect method to execute commands in a compute shader.
A compute shader from Microsoft Direct3D 10 is also considered as DirectCompute 4.x.
If a user calls Direct3D 11 API and updated drivers, feature level 10 and 10.1 Direct3D hardware can equally support the required form of DirectCompute that uses the cs_4_0 and cs_4_1 profiles.
When user computes DirectCompute on this hardware, following points should be considered in mind −
The maximum number of threads should be limited to GROUP (768) per group.
The maximum number of threads should be limited to GROUP (768) per group.
The X and Y dimension of numthreads is limited to to size of 768.
The X and Y dimension of numthreads is limited to to size of 768.
The Z dimension of numthreads is always limited to 1.
The Z dimension of numthreads is always limited to 1.
The Z dimension of dispatch is limited with respect to D3D11_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION (1).
The Z dimension of dispatch is limited with respect to D3D11_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION (1).
Only one shader view can be bound to the shader (D3D11_CS_4_X_UAV_REGISTER_COUNT is 1).
Only one shader view can be bound to the shader (D3D11_CS_4_X_UAV_REGISTER_COUNT is 1).
The respective buffers namely RWStructuredBuffers and RWByteAddressBuffers are usually available as unordered-access views. A thread can only access the required region with respect to group shared memory for writing.
SV_GroupIndex or SV_DispatchThreadID is used while accessing a particular group of elements for computing shader. Groupshared memory is usually limited to 16KB per group.
A single thread is limited to 256 byte region of groupshared memory for writing.
A compute shader on Direct3D 11 is termed as DirectCompute 5.0.
When user uses a DirectCompute interface with cs_5_0 profiles, following points should be kept in mind −
The maximum number of threads is limited to (1024) per group. The count is increased 1024.
The maximum number of threads is limited to (1024) per group. The count is increased 1024.
The X and Y dimension of numthreads is limited to 1024.
The X and Y dimension of numthreads is limited to 1024.
The Z dimension of numthreads is limited to 64.
The Z dimension of numthreads is limited to 64.
The basic code snippet of creating a compute shader is given below −
ID3D11ComputeShader* g_pFinalPassCS = NULL;
pd3dDevice->CreateComputeShader( pBlobFinalPassCS->GetBufferPointer(),
pBlobFinalPassCS->GetBufferSize(), NULL, &g_pFinalPassCS );
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2531,
"s": 2298,
"text": "In 3D programming, compute shader is a programmable shader stage which calls for the respective buffer. It expands the feature of Microsoft Direct3Dt3d version 11. The shader technology which is included is DirectCOMPUTE technology."
},
{
"code": null,
"e": 2864,
"s": 2531,
"text": "Like vertex and geometry which we discussed in the last chapter, a compute shader is designed and implemented with HLSL where many similarities can be tracked. A compute shader includes high-speed general purpose computing and includes advantage of various large numbers of parallel processors on the graphics processing unit (GPU)."
},
{
"code": null,
"e": 3144,
"s": 2864,
"text": "The compute shader includes memory sharing and thread synchronization features which allows more effective parallel programming methods when developer calls the ID3D11DeviceContext::Dispatch or ID3D11DeviceContext::DispatchIndirect method to execute commands in a compute shader."
},
{
"code": null,
"e": 3229,
"s": 3144,
"text": "A compute shader from Microsoft Direct3D 10 is also considered as DirectCompute 4.x."
},
{
"code": null,
"e": 3423,
"s": 3229,
"text": "If a user calls Direct3D 11 API and updated drivers, feature level 10 and 10.1 Direct3D hardware can equally support the required form of DirectCompute that uses the cs_4_0 and cs_4_1 profiles."
},
{
"code": null,
"e": 3522,
"s": 3423,
"text": "When user computes DirectCompute on this hardware, following points should be considered in mind −"
},
{
"code": null,
"e": 3596,
"s": 3522,
"text": "The maximum number of threads should be limited to GROUP (768) per group."
},
{
"code": null,
"e": 3670,
"s": 3596,
"text": "The maximum number of threads should be limited to GROUP (768) per group."
},
{
"code": null,
"e": 3736,
"s": 3670,
"text": "The X and Y dimension of numthreads is limited to to size of 768."
},
{
"code": null,
"e": 3802,
"s": 3736,
"text": "The X and Y dimension of numthreads is limited to to size of 768."
},
{
"code": null,
"e": 3856,
"s": 3802,
"text": "The Z dimension of numthreads is always limited to 1."
},
{
"code": null,
"e": 3910,
"s": 3856,
"text": "The Z dimension of numthreads is always limited to 1."
},
{
"code": null,
"e": 4025,
"s": 3910,
"text": "The Z dimension of dispatch is limited with respect to D3D11_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION (1)."
},
{
"code": null,
"e": 4140,
"s": 4025,
"text": "The Z dimension of dispatch is limited with respect to D3D11_CS_4_X_DISPATCH_MAX_THREAD_GROUPS_IN_Z_DIMENSION (1)."
},
{
"code": null,
"e": 4228,
"s": 4140,
"text": "Only one shader view can be bound to the shader (D3D11_CS_4_X_UAV_REGISTER_COUNT is 1)."
},
{
"code": null,
"e": 4316,
"s": 4228,
"text": "Only one shader view can be bound to the shader (D3D11_CS_4_X_UAV_REGISTER_COUNT is 1)."
},
{
"code": null,
"e": 4534,
"s": 4316,
"text": "The respective buffers namely RWStructuredBuffers and RWByteAddressBuffers are usually available as unordered-access views. A thread can only access the required region with respect to group shared memory for writing."
},
{
"code": null,
"e": 4705,
"s": 4534,
"text": "SV_GroupIndex or SV_DispatchThreadID is used while accessing a particular group of elements for computing shader. Groupshared memory is usually limited to 16KB per group."
},
{
"code": null,
"e": 4786,
"s": 4705,
"text": "A single thread is limited to 256 byte region of groupshared memory for writing."
},
{
"code": null,
"e": 4850,
"s": 4786,
"text": "A compute shader on Direct3D 11 is termed as DirectCompute 5.0."
},
{
"code": null,
"e": 4955,
"s": 4850,
"text": "When user uses a DirectCompute interface with cs_5_0 profiles, following points should be kept in mind −"
},
{
"code": null,
"e": 5046,
"s": 4955,
"text": "The maximum number of threads is limited to (1024) per group. The count is increased 1024."
},
{
"code": null,
"e": 5137,
"s": 5046,
"text": "The maximum number of threads is limited to (1024) per group. The count is increased 1024."
},
{
"code": null,
"e": 5193,
"s": 5137,
"text": "The X and Y dimension of numthreads is limited to 1024."
},
{
"code": null,
"e": 5249,
"s": 5193,
"text": "The X and Y dimension of numthreads is limited to 1024."
},
{
"code": null,
"e": 5297,
"s": 5249,
"text": "The Z dimension of numthreads is limited to 64."
},
{
"code": null,
"e": 5345,
"s": 5297,
"text": "The Z dimension of numthreads is limited to 64."
},
{
"code": null,
"e": 5414,
"s": 5345,
"text": "The basic code snippet of creating a compute shader is given below −"
},
{
"code": null,
"e": 5592,
"s": 5414,
"text": "ID3D11ComputeShader* g_pFinalPassCS = NULL;\npd3dDevice->CreateComputeShader( pBlobFinalPassCS->GetBufferPointer(),\n pBlobFinalPassCS->GetBufferSize(), NULL, &g_pFinalPassCS );"
},
{
"code": null,
"e": 5599,
"s": 5592,
"text": " Print"
},
{
"code": null,
"e": 5610,
"s": 5599,
"text": " Add Notes"
}
] |
Program to find sum of elements in a given array in C++
|
In this problem, we are given an array arr[] of n integer values. Our task is to create a Program to find sum of elements in a given array in C++.
Program Description − For the given array, we will add up all elements and return the sum.
Let’s take an example to understand the problem
arr[] = {3, 1, 7, 2, 9, 10}
32
Sum = 3 + 1 + 7 + 2 + 9 + 10 = 32
To find the sum of elements of the array, we will traverse the array and
extract each element of the array and add them to sumVal which will return
the sum.
We can do by two ways,
Using recursion
Using iteration
Program to show the implement Recursive approach
Live Demo
#include <iostream>
using namespace std;
int calcArraySum(int arr[], int n){
if(n == 1){
return arr[n-1];
}
return arr[n-1] + calcArraySum(arr, n-1);
}
int main(){
int arr[] = {1, 4, 5, 7, 6};
int n = sizeof(arr)/ sizeof(arr[0]);
cout<<"The sum of elements in a given array is"<<calcArraySum(arr, n);
return 0;
}
The sum of elements in a given array is 23
Program to show the implement Iterative approach
Live Demo
#include <iostream>
using namespace std;
int calcArraySum(int arr[], int n){
int sumVal = 0;
for(int i = 0; i < n; i++){
sumVal += arr[i];
}
return sumVal;
}
int main(){
int arr[] = {1, 4, 5, 7, 6};
int n = sizeof(arr)/ sizeof(arr[0]);
cout<<"The sum of elements in a given array is"<<calcArraySum(arr, n);
return 0;
}
The sum of elements in a given array is 23
|
[
{
"code": null,
"e": 1209,
"s": 1062,
"text": "In this problem, we are given an array arr[] of n integer values. Our task is to create a Program to find sum of elements in a given array in C++."
},
{
"code": null,
"e": 1300,
"s": 1209,
"text": "Program Description − For the given array, we will add up all elements and return the sum."
},
{
"code": null,
"e": 1348,
"s": 1300,
"text": "Let’s take an example to understand the problem"
},
{
"code": null,
"e": 1376,
"s": 1348,
"text": "arr[] = {3, 1, 7, 2, 9, 10}"
},
{
"code": null,
"e": 1379,
"s": 1376,
"text": "32"
},
{
"code": null,
"e": 1413,
"s": 1379,
"text": "Sum = 3 + 1 + 7 + 2 + 9 + 10 = 32"
},
{
"code": null,
"e": 1570,
"s": 1413,
"text": "To find the sum of elements of the array, we will traverse the array and\nextract each element of the array and add them to sumVal which will return\nthe sum."
},
{
"code": null,
"e": 1593,
"s": 1570,
"text": "We can do by two ways,"
},
{
"code": null,
"e": 1609,
"s": 1593,
"text": "Using recursion"
},
{
"code": null,
"e": 1625,
"s": 1609,
"text": "Using iteration"
},
{
"code": null,
"e": 1674,
"s": 1625,
"text": "Program to show the implement Recursive approach"
},
{
"code": null,
"e": 1685,
"s": 1674,
"text": " Live Demo"
},
{
"code": null,
"e": 2025,
"s": 1685,
"text": "#include <iostream>\nusing namespace std;\nint calcArraySum(int arr[], int n){\n if(n == 1){\n return arr[n-1];\n }\n return arr[n-1] + calcArraySum(arr, n-1);\n}\nint main(){\n int arr[] = {1, 4, 5, 7, 6};\n int n = sizeof(arr)/ sizeof(arr[0]);\n cout<<\"The sum of elements in a given array is\"<<calcArraySum(arr, n);\n return 0;\n}"
},
{
"code": null,
"e": 2068,
"s": 2025,
"text": "The sum of elements in a given array is 23"
},
{
"code": null,
"e": 2117,
"s": 2068,
"text": "Program to show the implement Iterative approach"
},
{
"code": null,
"e": 2128,
"s": 2117,
"text": " Live Demo"
},
{
"code": null,
"e": 2477,
"s": 2128,
"text": "#include <iostream>\nusing namespace std;\nint calcArraySum(int arr[], int n){\n int sumVal = 0;\n for(int i = 0; i < n; i++){\n sumVal += arr[i];\n }\n return sumVal;\n}\nint main(){\n int arr[] = {1, 4, 5, 7, 6};\n int n = sizeof(arr)/ sizeof(arr[0]);\n cout<<\"The sum of elements in a given array is\"<<calcArraySum(arr, n);\n return 0;\n}"
},
{
"code": null,
"e": 2520,
"s": 2477,
"text": "The sum of elements in a given array is 23"
}
] |
Count of number of given string in 2D character array in C++
|
The following problem is an example of daily newspaper crossword, here we are given a 2-Dimensional character array and the problem statement is to find out the given word from the 2-Dimensional character array maze.The search algorithm includes finding the individual characters from Top-to-Bottom,Right-to-Left and vice-versa but not diagonally.
Input- String word-LAYS
2D String[ ] - { "LOAPYS", "KAYSOT", "LAYSST", "MLVAYS", "LAYSAA", "LAOYLS" };
Output- Count of number of given strings in 2D character array: 7
Explanation - As we are given with the string array of words and from them, we have to find the word “LAYS” which can be searched in any direction like Top-Bottom, Right-Left, Bottom-Top, and Left-Right. The counter flag in the code adds up every time the given search string is found, and the count is returned at end for the result. In the example, we can see LAYS is formed 7 times i.e.
1->LOAPYS -LAYS-> Left to Right
2 ->SAYAOL-LAYS(Right to Left)
3->LAYSST-LAYS(Left to Right)
4->MLVAYS-LAYS(Left to Right)
5->LAYSAA-LAYS(Left to Right)
6->LAOYLS-LAYS(Left to Right)
7->(Bottom to Top) in Red LAYS
Input- String word- CAMP
2D String[ ] - { "BLOOKS", "BPOOLK", "KOHPKB", "BOLKOK", "LKIOOB", "LAHYBL" }
Output-Count of number of given string in 2D character array: 0
Explanation-: As we are given with the string array of words and from them, we have to find the word “LAYS” which can be searched in any direction like Top-Bottom, Right-Left, Bottom-Top, and Left-Right. The counter flag in the code adds up every time the given search string is found, and the count is returned at end for the result. In the example, we can see BOOK is formed 0 times.
We are given with a String(word) and String array which along with some utility variables are passed into findString() for further processing.
The characters in the matrix are then traversed and a character is picked up to start the string.
For the character that has been picked up we find for the the given string recursively in all the possible direction according to the algorithm
If a match is found the counter is then incremented
After we are done with the first start character, the process is then repeated for next character
The sum of counts is then calculated with the corresponding matches
The final answer is then captured, and the result is printed.
#include <bits/stdc++.h>
using namespace std;
int utilitySearch(string word, int r, int c, string arr[], int maxR, int maxC, int index) {
int count = 0;
if (r >= 0 && r <= maxR && c >= 0) {
if (c <= maxC && word[index] == arr[r][c]) {
char res = word[index];
index = index + 1;
arr[r][c] = 0;
if (word[index] == 0) {
count = 1;
} else {
count = count + utilitySearch(word, r, c + 1, arr, maxR, maxC, index);
count = count + utilitySearch(word, r, c - 1, arr, maxR, maxC, index);
count = count + utilitySearch(word, r + 1, c, arr, maxR, maxC, index);
count = count + utilitySearch(word, r - 1, c, arr, maxR, maxC, index);
}
arr[r][c] = res;
}
}
return count;
}
int findString(string word, int r, int c, string str[], int countR, int countC) {
int count = 0;
for (int i = 0; i < countR; ++i) {
for (int j = 0; j < countC; ++j) {
count = count + utilitySearch(word, i, j, str, countR - 1, countC - 1, 0);
}
}
return count;
}
int main() {
string word = "FLOOD";
string inp[] = {"FPLIOKOD","FLOODYUT","YFLOODPU","FMLOSODT","FILPOYOD", FLOOOODE " };
string str[(sizeof(inp) / sizeof( * inp))];
for (int i = 0; i < (sizeof(inp) / sizeof( * inp)); ++i) {
str[i] = inp[i];
}
cout << "Count of number of given string in 2D character array: " << findString(word, 0, 0, str, (sizeof(inp) / sizeof( * inp)), str[0].size());
return 0;
}
If we run the above code it will generate the following output −
Count of number of given string in 2D character array: 6
|
[
{
"code": null,
"e": 1410,
"s": 1062,
"text": "The following problem is an example of daily newspaper crossword, here we are given a 2-Dimensional character array and the problem statement is to find out the given word from the 2-Dimensional character array maze.The search algorithm includes finding the individual characters from Top-to-Bottom,Right-to-Left and vice-versa but not diagonally."
},
{
"code": null,
"e": 1434,
"s": 1410,
"text": "Input- String word-LAYS"
},
{
"code": null,
"e": 1515,
"s": 1434,
"text": "2D String[ ] - { \"LOAPYS\", \"KAYSOT\", \"LAYSST\", \"MLVAYS\", \"LAYSAA\", \"LAOYLS\" };"
},
{
"code": null,
"e": 1581,
"s": 1515,
"text": "Output- Count of number of given strings in 2D character array: 7"
},
{
"code": null,
"e": 1971,
"s": 1581,
"text": "Explanation - As we are given with the string array of words and from them, we have to find the word “LAYS” which can be searched in any direction like Top-Bottom, Right-Left, Bottom-Top, and Left-Right. The counter flag in the code adds up every time the given search string is found, and the count is returned at end for the result. In the example, we can see LAYS is formed 7 times i.e."
},
{
"code": null,
"e": 2004,
"s": 1971,
"text": "1->LOAPYS -LAYS-> Left to Right"
},
{
"code": null,
"e": 2035,
"s": 2004,
"text": "2 ->SAYAOL-LAYS(Right to Left)"
},
{
"code": null,
"e": 2065,
"s": 2035,
"text": "3->LAYSST-LAYS(Left to Right)"
},
{
"code": null,
"e": 2095,
"s": 2065,
"text": "4->MLVAYS-LAYS(Left to Right)"
},
{
"code": null,
"e": 2126,
"s": 2095,
"text": "5->LAYSAA-LAYS(Left to Right) "
},
{
"code": null,
"e": 2156,
"s": 2126,
"text": "6->LAOYLS-LAYS(Left to Right)"
},
{
"code": null,
"e": 2187,
"s": 2156,
"text": "7->(Bottom to Top) in Red LAYS"
},
{
"code": null,
"e": 2212,
"s": 2187,
"text": "Input- String word- CAMP"
},
{
"code": null,
"e": 2290,
"s": 2212,
"text": "2D String[ ] - { \"BLOOKS\", \"BPOOLK\", \"KOHPKB\", \"BOLKOK\", \"LKIOOB\", \"LAHYBL\" }"
},
{
"code": null,
"e": 2354,
"s": 2290,
"text": "Output-Count of number of given string in 2D character array: 0"
},
{
"code": null,
"e": 2741,
"s": 2354,
"text": "Explanation-: As we are given with the string array of words and from them, we have to find the word “LAYS” which can be searched in any direction like Top-Bottom, Right-Left, Bottom-Top, and Left-Right. The counter flag in the code adds up every time the given search string is found, and the count is returned at end for the result. In the example, we can see BOOK is formed 0 times. "
},
{
"code": null,
"e": 2884,
"s": 2741,
"text": "We are given with a String(word) and String array which along with some utility variables are passed into findString() for further processing."
},
{
"code": null,
"e": 2982,
"s": 2884,
"text": "The characters in the matrix are then traversed and a character is picked up to start the string."
},
{
"code": null,
"e": 3126,
"s": 2982,
"text": "For the character that has been picked up we find for the the given string recursively in all the possible direction according to the algorithm"
},
{
"code": null,
"e": 3178,
"s": 3126,
"text": "If a match is found the counter is then incremented"
},
{
"code": null,
"e": 3276,
"s": 3178,
"text": "After we are done with the first start character, the process is then repeated for next character"
},
{
"code": null,
"e": 3344,
"s": 3276,
"text": "The sum of counts is then calculated with the corresponding matches"
},
{
"code": null,
"e": 3407,
"s": 3344,
"text": "The final answer is then captured, and the result is printed. "
},
{
"code": null,
"e": 4981,
"s": 3407,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint utilitySearch(string word, int r, int c, string arr[], int maxR, int maxC, int index) {\n int count = 0;\n if (r >= 0 && r <= maxR && c >= 0) {\n if (c <= maxC && word[index] == arr[r][c]) {\n char res = word[index];\n index = index + 1;\n arr[r][c] = 0;\n if (word[index] == 0) {\n count = 1;\n } else {\n count = count + utilitySearch(word, r, c + 1, arr, maxR, maxC, index);\n count = count + utilitySearch(word, r, c - 1, arr, maxR, maxC, index);\n count = count + utilitySearch(word, r + 1, c, arr, maxR, maxC, index);\n count = count + utilitySearch(word, r - 1, c, arr, maxR, maxC, index);\n }\n arr[r][c] = res;\n }\n }\n return count;\n}\n\nint findString(string word, int r, int c, string str[], int countR, int countC) {\n int count = 0;\n for (int i = 0; i < countR; ++i) {\n for (int j = 0; j < countC; ++j) {\n count = count + utilitySearch(word, i, j, str, countR - 1, countC - 1, 0);\n }\n }\n return count;\n}\n\nint main() {\n string word = \"FLOOD\";\n string inp[] = {\"FPLIOKOD\",\"FLOODYUT\",\"YFLOODPU\",\"FMLOSODT\",\"FILPOYOD\", FLOOOODE \" };\n string str[(sizeof(inp) / sizeof( * inp))];\n for (int i = 0; i < (sizeof(inp) / sizeof( * inp)); ++i) {\n str[i] = inp[i];\n }\n cout << \"Count of number of given string in 2D character array: \" << findString(word, 0, 0, str, (sizeof(inp) / sizeof( * inp)), str[0].size());\n return 0;\n}"
},
{
"code": null,
"e": 5046,
"s": 4981,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 5103,
"s": 5046,
"text": "Count of number of given string in 2D character array: 6"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.