title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
find_elements_by_tag_name() driver method - Selenium Python - GeeksforGeeks
22 Nov, 2021 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task.This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_tag_name() is discussed in this article. This method returns a list with the type of elements specified. To grab a single first element, checkout – find_element_by_tag_name() driver method – Selenium PythonSyntax – driver.find_elements_by_tag_name("tag name") Example – For instance, consider this page source: html <html> <body> <form id="loginForm"> <input name="1" type="text" /> <input name="1" type="password" /> <input name="1" type="submit" value="Login" /> </form> </body><html> Now after you have created a driver, you can grab an element using – login_form = driver.find_elements_by_tag_name('form') Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab the title of posts using the tag “h2”. Create a file called run.py to demonstrate find_elements_by_tag_name method – Python3 # Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementselements = driver.find_elements_by_tag_name("h2") # print complete elements listprint(element) Now run using – Python run.py First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output – Terminal Output – kumaripunam984122 Python-selenium selenium 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? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n22 Nov, 2021" }, { "code": null, "e": 26522, "s": 25647, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using the get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeksforgeeks, one might want to click some buttons automatically or fill a form automatically or any such automated task.This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_elements_by_tag_name() is discussed in this article. This method returns a list with the type of elements specified. To grab a single first element, checkout – find_element_by_tag_name() driver method – Selenium PythonSyntax – " }, { "code": null, "e": 26567, "s": 26522, "text": "driver.find_elements_by_tag_name(\"tag name\")" }, { "code": null, "e": 26620, "s": 26567, "text": "Example – For instance, consider this page source: " }, { "code": null, "e": 26625, "s": 26620, "text": "html" }, { "code": "<html> <body> <form id=\"loginForm\"> <input name=\"1\" type=\"text\" /> <input name=\"1\" type=\"password\" /> <input name=\"1\" type=\"submit\" value=\"Login\" /> </form> </body><html>", "e": 26804, "s": 26625, "text": null }, { "code": null, "e": 26875, "s": 26804, "text": "Now after you have created a driver, you can grab an element using – " }, { "code": null, "e": 26929, "s": 26875, "text": "login_form = driver.find_elements_by_tag_name('form')" }, { "code": null, "e": 27181, "s": 26931, "text": "Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab the title of posts using the tag “h2”. Create a file called run.py to demonstrate find_elements_by_tag_name method – " }, { "code": null, "e": 27189, "s": 27181, "text": "Python3" }, { "code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementselements = driver.find_elements_by_tag_name(\"h2\") # print complete elements listprint(element)", "e": 27562, "s": 27189, "text": null }, { "code": null, "e": 27580, "s": 27562, "text": "Now run using – " }, { "code": null, "e": 27594, "s": 27580, "text": "Python run.py" }, { "code": null, "e": 27745, "s": 27594, "text": "First, it will open the firefox window with geeksforgeeks, and then select the element and print it on the terminal as shown below. Browser Output – " }, { "code": null, "e": 27765, "s": 27745, "text": "Terminal Output – " }, { "code": null, "e": 27785, "s": 27767, "text": "kumaripunam984122" }, { "code": null, "e": 27801, "s": 27785, "text": "Python-selenium" }, { "code": null, "e": 27810, "s": 27801, "text": "selenium" }, { "code": null, "e": 27817, "s": 27810, "text": "Python" }, { "code": null, "e": 27915, "s": 27817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27947, "s": 27915, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27989, "s": 27947, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28031, "s": 27989, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28087, "s": 28031, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28114, "s": 28087, "text": "Python Classes and Objects" }, { "code": null, "e": 28145, "s": 28114, "text": "Python | os.path.join() method" }, { "code": null, "e": 28174, "s": 28145, "text": "Create a directory in Python" }, { "code": null, "e": 28196, "s": 28174, "text": "Defaultdict in Python" }, { "code": null, "e": 28232, "s": 28196, "text": "Python | Pandas dataframe.groupby()" } ]
deque max_size() function in C++ STL - GeeksforGeeks
30 Jul, 2018 The deque::max_size() is a built-in function in C++ STL which returns the maximum number of elements that a deque container can hold. Syntax: deque_name.max_size() Parameters: The function does not accept any parameters. Return Value: The function returns the maximum number of elements that a deque container can hold. Below programs illustrate the above function: Program 1: // CPP program to demonstrate the// deque::max_size() function// when deque is non-empty#include <bits/stdc++.h>using namespace std;int main(){ deque<int> dq; dq.push_back(1); dq.push_back(10); dq.push_back(100); dq.push_back(50); dq.push_back(40); dq.push_back(23); dq.push_back(6); cout << "The deque elements: "; for (auto it = dq.begin(); it != dq.end(); it++) cout << *it << " "; cout << "\nThe max-size of deque: " << dq.max_size(); return 0;} The deque elements: 1 10 100 50 40 23 6 The max-size of deque: 4611686018427387903 Program 2: // CPP program to demonstrate the// deque::max_size() function// when deque is empty#include <bits/stdc++.h>using namespace std;int main(){ deque<int> dq; cout << "The max-size of deque: " << dq.max_size(); return 0;} The max-size of deque: 4611686018427387903 cpp-deque CPP-Functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inheritance in C++ Map in C++ Standard Template Library (STL) C++ Classes and Objects Virtual Function in C++ Bitwise Operators in C/C++ Constructors in C++ Operator Overloading in C++ Templates in C++ with Examples Socket Programming in C/C++ Polymorphism in C++
[ { "code": null, "e": 25927, "s": 25899, "text": "\n30 Jul, 2018" }, { "code": null, "e": 26061, "s": 25927, "text": "The deque::max_size() is a built-in function in C++ STL which returns the maximum number of elements that a deque container can hold." }, { "code": null, "e": 26069, "s": 26061, "text": "Syntax:" }, { "code": null, "e": 26091, "s": 26069, "text": "deque_name.max_size()" }, { "code": null, "e": 26148, "s": 26091, "text": "Parameters: The function does not accept any parameters." }, { "code": null, "e": 26247, "s": 26148, "text": "Return Value: The function returns the maximum number of elements that a deque container can hold." }, { "code": null, "e": 26293, "s": 26247, "text": "Below programs illustrate the above function:" }, { "code": null, "e": 26304, "s": 26293, "text": "Program 1:" }, { "code": "// CPP program to demonstrate the// deque::max_size() function// when deque is non-empty#include <bits/stdc++.h>using namespace std;int main(){ deque<int> dq; dq.push_back(1); dq.push_back(10); dq.push_back(100); dq.push_back(50); dq.push_back(40); dq.push_back(23); dq.push_back(6); cout << \"The deque elements: \"; for (auto it = dq.begin(); it != dq.end(); it++) cout << *it << \" \"; cout << \"\\nThe max-size of deque: \" << dq.max_size(); return 0;}", "e": 26805, "s": 26304, "text": null }, { "code": null, "e": 26890, "s": 26805, "text": "The deque elements: 1 10 100 50 40 23 6 \nThe max-size of deque: 4611686018427387903\n" }, { "code": null, "e": 26901, "s": 26890, "text": "Program 2:" }, { "code": "// CPP program to demonstrate the// deque::max_size() function// when deque is empty#include <bits/stdc++.h>using namespace std;int main(){ deque<int> dq; cout << \"The max-size of deque: \" << dq.max_size(); return 0;}", "e": 27132, "s": 26901, "text": null }, { "code": null, "e": 27176, "s": 27132, "text": "The max-size of deque: 4611686018427387903\n" }, { "code": null, "e": 27186, "s": 27176, "text": "cpp-deque" }, { "code": null, "e": 27200, "s": 27186, "text": "CPP-Functions" }, { "code": null, "e": 27204, "s": 27200, "text": "C++" }, { "code": null, "e": 27208, "s": 27204, "text": "CPP" }, { "code": null, "e": 27306, "s": 27208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27325, "s": 27306, "text": "Inheritance in C++" }, { "code": null, "e": 27368, "s": 27325, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 27392, "s": 27368, "text": "C++ Classes and Objects" }, { "code": null, "e": 27416, "s": 27392, "text": "Virtual Function in C++" }, { "code": null, "e": 27443, "s": 27416, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27463, "s": 27443, "text": "Constructors in C++" }, { "code": null, "e": 27491, "s": 27463, "text": "Operator Overloading in C++" }, { "code": null, "e": 27522, "s": 27491, "text": "Templates in C++ with Examples" }, { "code": null, "e": 27550, "s": 27522, "text": "Socket Programming in C/C++" } ]
Collections.UserList in Python - GeeksforGeeks
24 Jun, 2021 Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Note: For more information, refer to Python List Python supports a List like a container called UserList present in the collections module. This class acts as a wrapper class around the List objects. This class is useful when one wants to create a list of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new behaviors for the list. This class takes a list instance as an argument and simulates a list that is kept in a regular list. The list is accessible by the data attribute of the this class.Syntax: collections.UserList([list]) Example 1: Python3 # Python program to demonstrate# userlist from collections import UserList L = [1, 2, 3, 4] # Creating a userlistuserL = UserList(L)print(userL.data) # Creating empty userlistuserL = UserList()print(userL.data) Output: [1, 2, 3, 4] [] Example 2: Python3 # Python program to demonstrate# userlist from collections import UserList # Creating a List where# deletion is not allowedclass MyList(UserList): # Function to stop deletion # from List def remove(self, s = None): raise RuntimeError("Deletion not allowed") # Function to stop pop from # List def pop(self, s = None): raise RuntimeError("Deletion not allowed") # Driver's codeL = MyList([1, 2, 3, 4]) print("Original List") # Inserting to List"L.append(5)print("After Insertion")print(L) # Deleting From ListL.remove() Output: Original List After Insertion [1, 2, 3, 4, 5] Traceback (most recent call last): File "/home/9399c9e865a7493dce58e88571472d23.py", line 33, in L.remove() File "/home/9399c9e865a7493dce58e88571472d23.py", line 15, in remove raise RuntimeError("Deletion not allowed") RuntimeError: Deletion not allowed sooda367 saurabh1990aror Python collections-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Enumerate() in Python Iterate over a list in Python Python String | replace()
[ { "code": null, "e": 41638, "s": 41610, "text": "\n24 Jun, 2021" }, { "code": null, "e": 42032, "s": 41638, "text": "Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a list is done with 0 being the first index. Note: For more information, refer to Python List " }, { "code": null, "e": 42555, "s": 42032, "text": "Python supports a List like a container called UserList present in the collections module. This class acts as a wrapper class around the List objects. This class is useful when one wants to create a list of their own with some modified functionality or with some new functionality. It can be considered as a way of adding new behaviors for the list. This class takes a list instance as an argument and simulates a list that is kept in a regular list. The list is accessible by the data attribute of the this class.Syntax: " }, { "code": null, "e": 42584, "s": 42555, "text": "collections.UserList([list])" }, { "code": null, "e": 42596, "s": 42584, "text": "Example 1: " }, { "code": null, "e": 42604, "s": 42596, "text": "Python3" }, { "code": "# Python program to demonstrate# userlist from collections import UserList L = [1, 2, 3, 4] # Creating a userlistuserL = UserList(L)print(userL.data) # Creating empty userlistuserL = UserList()print(userL.data)", "e": 42818, "s": 42604, "text": null }, { "code": null, "e": 42827, "s": 42818, "text": "Output: " }, { "code": null, "e": 42843, "s": 42827, "text": "[1, 2, 3, 4]\n[]" }, { "code": null, "e": 42855, "s": 42843, "text": "Example 2: " }, { "code": null, "e": 42863, "s": 42855, "text": "Python3" }, { "code": "# Python program to demonstrate# userlist from collections import UserList # Creating a List where# deletion is not allowedclass MyList(UserList): # Function to stop deletion # from List def remove(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Function to stop pop from # List def pop(self, s = None): raise RuntimeError(\"Deletion not allowed\") # Driver's codeL = MyList([1, 2, 3, 4]) print(\"Original List\") # Inserting to List\"L.append(5)print(\"After Insertion\")print(L) # Deleting From ListL.remove()", "e": 43436, "s": 42863, "text": null }, { "code": null, "e": 43445, "s": 43436, "text": "Output: " }, { "code": null, "e": 43491, "s": 43445, "text": "Original List\nAfter Insertion\n[1, 2, 3, 4, 5]" }, { "code": null, "e": 43761, "s": 43493, "text": "Traceback (most recent call last):\n File \"/home/9399c9e865a7493dce58e88571472d23.py\", line 33, in \n L.remove()\n File \"/home/9399c9e865a7493dce58e88571472d23.py\", line 15, in remove\n raise RuntimeError(\"Deletion not allowed\")\nRuntimeError: Deletion not allowed" }, { "code": null, "e": 43772, "s": 43763, "text": "sooda367" }, { "code": null, "e": 43788, "s": 43772, "text": "saurabh1990aror" }, { "code": null, "e": 43814, "s": 43788, "text": "Python collections-module" }, { "code": null, "e": 43821, "s": 43814, "text": "Python" }, { "code": null, "e": 43919, "s": 43821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43947, "s": 43919, "text": "Read JSON file using Python" }, { "code": null, "e": 43997, "s": 43947, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 44019, "s": 43997, "text": "Python map() function" }, { "code": null, "e": 44063, "s": 44019, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 44098, "s": 44063, "text": "Read a file line by line in Python" }, { "code": null, "e": 44130, "s": 44098, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 44172, "s": 44130, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 44194, "s": 44172, "text": "Enumerate() in Python" }, { "code": null, "e": 44224, "s": 44194, "text": "Iterate over a list in Python" } ]
FIFA Ultimate Team Machine Learning Project | by Jean-Paul Zambrano-Leon | Towards Data Science
This project follows the principles/steps outlined in the Machine Learning End-To-End guideline by ML consultant Aurélien Géron. Machine Learning (ML) is a subset of Artificial Intelligence (AI) that uses computer algorithms to find patterns in large datasets without being explicitly programmed. ML gives the computer the ability to learn and improve on its own so that it can produce the best model from the data. A lot of applications nowadays use ML such as: Product Recommendations Email Spam Detector Malware Detection Face Recognition I’ve been playing the FIFA games since I can remember. I love being able to play as my favorite football players and teams. Although the games nowadays get a bad rap for being mostly pay-to-win, I still find myself enjoying the spoils of FIFA Ultimate Team (FUT) and the competitive multiplayer. With that being said, I’ve always wondered how the developers decide on player ratings, and then I asked myself, “Could a machine do it too?”. It could very well be that the developing team at Electronic Arts (EA) use an ML model to decide the player ratings, but that didn’t stop me from building my very own. This project was my attempt at creating an ML model that can predict the overall rating of any player. I used Google Colabs to complete this project. I found a large dataset of the FIFA games on Kaggle. The dataset consists of data from FIFA 15 to FIFA 20. We will be using the latest FIFA game in the dataset which is FIFA 20. The dataset can be downloaded from Kaggle. The dataset consists of 18,278 rows and 104 columns. The columns contain features such as Player Name, Age, Height, Weight, Nationality, and many more. Since we are trying to predict the overall rating, we would only need to focus on the features that have correlations with the overall rating, but we’ll get to that later. The first thing that any ML Engineer should do is to define the problem. For this project, the problem we are facing is accurately predicting the player ratings without having to hard code an algorithm, so building a workable ML model should be our end goal. In FIFA 20, a player’s overall score is defined by the score of each player attribute such as Pace, Shooting, Passing, Dribbling, and many others. We are trying to predict the overall score based on the player’s offensive and defensive attributes. The data already comes with labeled training examples which means we are dealing with a supervised learning problem. It is also a typical regression task since we are tasked with predicting a value. More specifically, this is a multiple regression problem since the model will use multiple features to make a prediction. Now that we have defined the problem, we need to select a performance measure. I like to use the Root Mean Square Error (RMSE). This is the preferred performance measure for regression problems. The RMSE is a measure of how well the model performed. It gives an idea of how much error the system makes in its prediction. RMSE is the calculation of the residuals (prediction errors) with respect to the line of best fit. The formula can be seen below: To learn more about RMSE and how it works, I recommend reading this article. Now we are ready to start coding!!! The first thing that we need to do is to import the most common data science libraries such as numpy, scipy, and pandas. We also need to import matplotlib and seaborn so that we can plot graphs to help us visualize the data. # Common importsimport numpy as npimport pandas as pdimport osimport seaborn as snsfrom scipy import statsimport missingno as msno# To plot pretty figures%matplotlib inlineimport matplotlib as mplimport matplotlib.pyplot as pltfrom matplotlib import stylesns.set(style='ticks', color_codes=True)sns.set(style='darkgrid')import plotly.express as px# Ignore useless warnings (see SciPy issue #5998)import warningswarnings.filterwarnings(action="ignore", message="^internal gelsd")warnings.filterwarnings('always')warnings.filterwarnings('ignore') I saved the dataset to my GitHub repository which makes it easier for me to download the dataset without having to search for it on my machine. Having a function to download the data online is really useful if the data is constantly changing. It also saves the trouble of having to install the dataset on multiple machines. import urllib.requestDOWNLOAD_ROOT = "https://raw.githubusercontent.com/jpzambranoleon/ML_Projects/master/"TRAIN_PATH = os.path.join("datasets", "players_20")TRAIN_URL = DOWNLOAD_ROOT + "datasets/players_20.csv"def fetch_train_data(train_url=TRAIN_URL, train_path=TRAIN_PATH): os.makedirs(train_path, exist_ok=True) csv_path = os.path.join(train_path, "players_20.csv") urllib.request.urlretrieve(train_url, csv_path) The fetch_train_data() function is used to fetch the dataset. fetch_train_data() The dataset is downloaded and saved in the files section of Google Colabs under the folders datasets and players_20. Now all that’s left to do is to load the data into a pandas DataFrame. Luckily, there is a function that we can create to return a pandas DataFrame object. import pandas as pddef load_train_data(train_path=TRAIN_PATH): csv_path = os.path.join(train_path, "players_20.csv") return pd.read_csv(csv_path) I called the load_train_data() function into player_data variable to save the DataFrame into a variable to make things easier. The DataFrame’s head() method is used to look at the top five rows of the data. player_data = load_train_data()player_data.head() I used the shape method to return a tuple representing the dimensionality of the DataFrame. By using the shape method, we can see how many rows and columns there are in the dataset. player_data.shape(18278, 104) As we can see from the tuple, the dataset has 18,278 rows and 104 columns. We don’t need to use all the columns so it’s best if we truncate the DataFrame to only include the target column and the player stats columns. There are 34 player stats columns so we’ll need to select those. #player stat featurescolumns = ['overall','attacking_crossing', 'attacking_finishing', 'attacking_heading_accuracy', 'attacking_short_passing', 'attacking_volleys', 'skill_dribbling', 'skill_curve', 'skill_fk_accuracy', 'skill_long_passing', 'skill_ball_control', 'movement_acceleration', 'movement_sprint_speed', 'movement_agility', 'movement_reactions', 'movement_balance', 'power_shot_power', 'power_jumping', 'power_stamina', 'power_strength', 'power_long_shots', 'mentality_aggression', 'mentality_interceptions', 'mentality_positioning', 'mentality_vision', 'mentality_penalties', 'mentality_composure', 'defending_marking', 'defending_standing_tackle', 'defending_sliding_tackle', 'goalkeeping_diving', 'goalkeeping_handling', 'goalkeeping_kicking', 'goalkeeping_positioning', 'goalkeeping_reflexes']player_df = player_data[columns]player_df.head() I used the info() method on the new DataFrame to get a quick description o the data. player_df.info() We can see from the data that there are 18,278 non-null values in the DataFrame which means we don’t have to worry about missing values. To get a statistical description of the data, we can use the describe() method. player_df.describe() Just for good measure, let’s use the shape method again to see the dimensionality of the new DataFrame. player_df.shape(18278, 35) Another great way to get a feel of the data is to plot a histogram of every numerical attribute. To plot a histogram of every attribute, just call the hist() method on the DataFrame. The hist() method requires the matplotlib library. You can specify the number of bins for each histogram and you can also specify the size of the figure. I chose to go with 40 bins and a figure size of (27,17), but all of that is completely up to you. Histograms are useful because they show the number of instances (y-axis) that have a given value range (x-axis). player_df.hist(bins=40, figsize=(27,17))plt.show() As we can see from the figure, each histogram has a value range of 0 to 100. This is a good indication that every attribute has the same scale which means we don’t have to do any feature scaling transformations. For good practice, I like to be completely sure that there are no missing values in the data, so I use the isna().any() method to return a True or False statement on whether or not the data has missing values. player_df.isna().any() As we can see from the output, the return value is False on every attribute which means that there are no missing values. We are ready to continue!!! After exploring the data, the next thing we need to do is to split the data into training and testing sets. We can do this by splitting the data ourselves, or by creating a function to do it for us. Luckily for us, Scikit-Learn has a cool feature that can split the dataset into training and testing sets. The train_test_split() function can easily split the data into the sets we need. I set test_size=0.2 so that 20% of the data is stored in the test set. The other 80% of the data is stored in the training set. The training set should have more of the data because it is the set which the model learns from. The testing set will be the set that we use to validate the model. from sklearn.model_selection import train_test_splittrain_set, test_set = train_test_split(player_df, test_size=0.2, random_state=42)print("Length of training data:", len(train_set))print("Length of testing data:", len(test_set))print("Length of total data:", len(player_df))Length of training data: 14622 Length of testing data: 3656 Length of total data: 18278 You can compute the standard correlation coefficient between each pair of attributes using the corr() method. Looking at all the correlations between each attribute will take up too much time, so let’s just see how much each attribute correlates with the overall value. fifa_df = train_set.copy()corr_matrix = fifa_df.corr()corr_matrix['overall'].sort_values(ascending=False) The correlation coefficient ranges from -1 to 1. When the correlation coefficient is close to 1, it means that there is a strong positive correlation; for example, overall tends to go up when movement reactions goes up. When the correlation coefficient is close to -1, it means that there is a strong negative correlation (i.e., the opposite of a strong positive correlation). To visualize the correlation between attributes, we can use the pandas scatter_matrix() function. This function plots every numerical attribute against every other numerical attributes. Let’s just look at the top five promising attributes to make things easier since there are 35 numerical attributes. from pandas.plotting import scatter_matrixattributes = [‘overall’, ‘movement_reactions’, ‘mentality_composure’, ‘power_shot_power’, ‘mentality_vision’]scatter_matrix(fifa_df[attributes], figsize=(15,12))plt.show() Strong correlation relationships tend to be linear, so the most promising attribute to predict overall is movement reactions. As we can see from the figure, movement reactions and overall have a very strong linear relationship. Let’s take a closer look at the correlation scatterplot. fifa_df.plot(kind=’scatter’, x=’movement_reactions’, y=’overall’, alpha=0.1, color=’red’)plt.show() The correlation is indeed very strong; you can clearly see an upward trend. Now, it’s time to prepare the data for ML algorithms. I split the training set and testing set into separate sets of features and targets. The DataFrame y_train and y_test contain the target values (the target value is overall) and X_train and X_test contain the feature values (every other attribute that correlates to the target value). y_train = train_set['overall']X_train = train_set.drop('overall', axis=1)y_test = test_set['overall']X_test = test_set.drop('overall', axis=1) Let’s first train a Linear Regression model using Scikit-Learn’s LinearRegression() function: from sklearn.linear_model import LinearRegressionlin_reg = LinearRegression()lin_reg.fit(X_train, y_train) Let’s measure the regression model’s RMSE on the whole training set using Scikit-Learn’s mean_square_error() function: from sklearn.metrics import mean_squared_errory_predictions = lin_reg.predict(X_train)lin_mse = mean_squared_error(y_train, y_predictions)lin_rmse = np.sqrt(lin_mse)lin_rmse2.493574884183225 Not a bad score!!! It seems that a Linear Regression model could do the trick. From what we saw from the scatter matrix is that not every attribute has a linear relationship. For nonlinear relationships, we would need a more powerful model so let’s train a Decision Tree Regression model. This is a powerful model, capable of finding complex nonlinear relationships in the data. Let’s use Scikit-Learn’s DecisionTreeRegressor() function: from sklearn.tree import DecisionTreeRegressortree_reg = DecisionTreeRegressor()atree_reg.fit(X_train, y_train) Again, let’s measure the model’s RMSE: y_predictions = tree_reg.predict(X_train)tree_mse = mean_squared_error(y_train, y_predictions)tree_rmse = np.sqrt(tree_mse)tree_rmse0.0 What?! An RMSE of 0.0!!! Is this a perfect model? Actually, it could be that this model has badly overfit the data. That’s why in every ML project it is important that you perform model validation, but we’ll get to that later. For now, let’s just train our final model which is a Random Forest Regression model. We can train a Random Forest Regression model using Scikit-Learn’s RandomForestRegressor() function: from sklearn.ensemble import RandomForestRegressorforest_reg = RandomForestRegressor()forest_reg.fit(X_train, y_train) Let’s look at the RMSE for this model: y_predictions = forest_reg.predict(X_train)forest_mse = mean_squared_error(y_train, y_predictions)forest_rmse = np.sqrt(forest_mse)forest_rmse0.4774070457668509 It’s a better score than our Linear Regression model, but it’s not as good as our Decision Tree model. Again, it could be that our Decision Tree model has badly overfit the data, which is why we always need to validate each model before selecting the best one. An easy way to validate a model’s accuracy is to use Scikit-Learn’s K-fold cross-validation feature. Cross-validation randomly splits the training set into 10 distinct subsets called folds, then it trains and evaluates the models 10 times, picking a different fold for evaluation every time and training on the 9 folds. The result is an array containing the 10 evaluation scores. We need to take a look at the mean validation score before we can choose the best model. Let’s look at the cross-validation scores of our Linear Regression model: from sklearn.model_selection import cross_val_scorescores = cross_val_score(lin_reg, X_train, y_train,scoring='neg_mean_squared_error', cv=10)lin_reg_scores = np.sqrt(-scores)def display_scores(scores): print("Scores:", scores) print("Mean:", scores.mean()) print("Standard Deviation:", scores.std())display_scores(lin_reg_scores)Scores: [2.48985397 2.509888 2.50910312 2.4642167 2.46189444 2.51445854 2.48370267 2.4734443 2.48382446 2.59475861] Mean: 2.4985144826450054 Standard Deviation: 0.03662607159427437 Now let’s look at the cross-validation scores of our Decision Tree model: scores = cross_val_score(tree_reg, X_train, y_train,scoring='neg_mean_squared_error', cv=10)tree_scores = np.sqrt(-scores)display_scores(tree_scores)Scores: [2.03976196 2.10100389 2.24933491 2.18751588 2.13289653 2.1158318 2.10529916 2.08391009 2.30935171 2.15395796] Mean: 2.147886387907302 Standard Deviation: 0.07682311253910523 Now that’s a more believable score than the first. It’s still better than our Linear Regression model, but let’s look at the cross-validation score of our Random Forest model: scores = cross_val_score(forest_reg, X_train, y_train,scoring='neg_mean_squared_error', cv=10)forest_scores = np.sqrt(-scores)display_scores(forest_scores)Scores: [1.29156727 1.24883845 1.2625419 1.288613 1.22436926 1.30612055 1.25621857 1.24755531 1.30399247 1.28656714] Mean: 1.2716383911151843 Standard Deviation: 0.026074298378757566 Wow!!! This might just be the best score we’ve seen. Random Forests look very promising. This is the model that we’ll use for our project. Now that we have selected our model, we need to fine tune it. Fine tuning requires that we fiddle with the hyperparameters manually, until we find a great combination of hyperparameter values. Fine tuning is very tedious work and can take a long time if the dataset is large. You may not even have time to explore many combinations. Instead of doing everything manually, there is an easier option that Scikit-Learn provides. Instead of fiddling with the hyperparameters manually, you should use Scikit-Learn’s GridSearchCV to search for you. All you need to do is tell it which hyperparameters you want it to experiment with and what to try out, and it will use cross-validation to evaluate all the possible combinations of hyperparameter values. The code below provides the parameters that I used to experiment with. from sklearn.model_selection import GridSearchCVparam_grid = [{'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},{'bootstrap': [False], 'n_estimators': [3,10], 'max_features': [2,3,4]},]forest_reg = RandomForestRegressor()grid_search = GridSearchCV(forest_reg, param_grid, cv=5,scoring='neg_mean_squared_error',return_train_score=True)grid_search.fit(X_train, y_train) When it’s done training, you can get the best combination of parameters like this: grid_search.best_params_{'max_features': 8, 'n_estimators': 30} You can also get the best estimator directly: grid_search.best_estimator_RandomForestRegressor(bootstrap=True, ccp_alpha=0.0, criterion='mse', max_depth=None, max_features=8, max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=30, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False) Of course, you can experiment with any hyperparameter values, but I think this will work for now. After tweaking the model on the training set, it’s finally time to evaluate the final model on the test set. The process is pretty similar, but this time we need to specify the best estimator to the final model. Again, we’ll need to measure the performance of the final model. The code to do that is below: final_model = grid_search.best_estimator_final_predictions = final_model.predict(X_test)final_mse = mean_squared_error(y_test, final_predictions)final_rmse = np.sqrt(final_mse)final_rmse1.135337798136083 The score is the best we have seen so far, not to mention it was also used on data that the model has not previously seen. If I’m being honest, I didn’t expect the model to do this well, but we can’t just assume that the RMSE will always be a certain value. We want to have an idea of how percise this estimate is. For this, you can compute a 95% confidence interval for the generalization error using scipy.stats.t.interval(): confidence = 0.95squared_errors = (final_predictions - y_test)**2np.sqrt(stats.t.interval(confidence, len(squared_errors)-1,loc=squared_errors.mean(),scale=stats.sem(squared_errors)))array([1.10181563, 1.16789818]) We can see that the RMSE will be between 1.10 and 1.17 95% of the time. We are pretty much done with the model, but just out of curiosity, we would want to see how the predictions differed from the actual target. To do this, just selected five instances from the test set and use the predict() method on the final model: some_data = X_test.iloc[:5]some_label = y_test.iloc[:5]print("Predictions:", final_model.predict(some_data))print("Labels:", list(some_label))Predictions: [64.2 73.8 68.76666667 68.13333333 63.4 ] Labels: [64, 74, 69, 68, 63] The predictions are pretty accurate. I’m surprised that the model performed this well. I’m very satisfied with the results. This project showed us that we can build an ML Model to predict a player’s overall FUT rating. This project was a lot of fun to make and I learned a lot from it. I’m passionate about ML and all the possibilities that it has to offer. I am very excited to explore more of this field and learn everything that I can along the way. I hope you enjoyed this article and maybe you can start your own ML project someday!!!
[ { "code": null, "e": 303, "s": 172, "text": "This project follows the principles/steps outlined in the Machine Learning End-To-End guideline by ML consultant Aurélien Géron." }, { "code": null, "e": 637, "s": 303, "text": "Machine Learning (ML) is a subset of Artificial Intelligence (AI) that uses computer algorithms to find patterns in large datasets without being explicitly programmed. ML gives the computer the ability to learn and improve on its own so that it can produce the best model from the data. A lot of applications nowadays use ML such as:" }, { "code": null, "e": 661, "s": 637, "text": "Product Recommendations" }, { "code": null, "e": 681, "s": 661, "text": "Email Spam Detector" }, { "code": null, "e": 699, "s": 681, "text": "Malware Detection" }, { "code": null, "e": 716, "s": 699, "text": "Face Recognition" }, { "code": null, "e": 1426, "s": 716, "text": "I’ve been playing the FIFA games since I can remember. I love being able to play as my favorite football players and teams. Although the games nowadays get a bad rap for being mostly pay-to-win, I still find myself enjoying the spoils of FIFA Ultimate Team (FUT) and the competitive multiplayer. With that being said, I’ve always wondered how the developers decide on player ratings, and then I asked myself, “Could a machine do it too?”. It could very well be that the developing team at Electronic Arts (EA) use an ML model to decide the player ratings, but that didn’t stop me from building my very own. This project was my attempt at creating an ML model that can predict the overall rating of any player." }, { "code": null, "e": 1473, "s": 1426, "text": "I used Google Colabs to complete this project." }, { "code": null, "e": 2018, "s": 1473, "text": "I found a large dataset of the FIFA games on Kaggle. The dataset consists of data from FIFA 15 to FIFA 20. We will be using the latest FIFA game in the dataset which is FIFA 20. The dataset can be downloaded from Kaggle. The dataset consists of 18,278 rows and 104 columns. The columns contain features such as Player Name, Age, Height, Weight, Nationality, and many more. Since we are trying to predict the overall rating, we would only need to focus on the features that have correlations with the overall rating, but we’ll get to that later." }, { "code": null, "e": 2846, "s": 2018, "text": "The first thing that any ML Engineer should do is to define the problem. For this project, the problem we are facing is accurately predicting the player ratings without having to hard code an algorithm, so building a workable ML model should be our end goal. In FIFA 20, a player’s overall score is defined by the score of each player attribute such as Pace, Shooting, Passing, Dribbling, and many others. We are trying to predict the overall score based on the player’s offensive and defensive attributes. The data already comes with labeled training examples which means we are dealing with a supervised learning problem. It is also a typical regression task since we are tasked with predicting a value. More specifically, this is a multiple regression problem since the model will use multiple features to make a prediction." }, { "code": null, "e": 3297, "s": 2846, "text": "Now that we have defined the problem, we need to select a performance measure. I like to use the Root Mean Square Error (RMSE). This is the preferred performance measure for regression problems. The RMSE is a measure of how well the model performed. It gives an idea of how much error the system makes in its prediction. RMSE is the calculation of the residuals (prediction errors) with respect to the line of best fit. The formula can be seen below:" }, { "code": null, "e": 3374, "s": 3297, "text": "To learn more about RMSE and how it works, I recommend reading this article." }, { "code": null, "e": 3410, "s": 3374, "text": "Now we are ready to start coding!!!" }, { "code": null, "e": 3635, "s": 3410, "text": "The first thing that we need to do is to import the most common data science libraries such as numpy, scipy, and pandas. We also need to import matplotlib and seaborn so that we can plot graphs to help us visualize the data." }, { "code": null, "e": 4180, "s": 3635, "text": "# Common importsimport numpy as npimport pandas as pdimport osimport seaborn as snsfrom scipy import statsimport missingno as msno# To plot pretty figures%matplotlib inlineimport matplotlib as mplimport matplotlib.pyplot as pltfrom matplotlib import stylesns.set(style='ticks', color_codes=True)sns.set(style='darkgrid')import plotly.express as px# Ignore useless warnings (see SciPy issue #5998)import warningswarnings.filterwarnings(action=\"ignore\", message=\"^internal gelsd\")warnings.filterwarnings('always')warnings.filterwarnings('ignore')" }, { "code": null, "e": 4504, "s": 4180, "text": "I saved the dataset to my GitHub repository which makes it easier for me to download the dataset without having to search for it on my machine. Having a function to download the data online is really useful if the data is constantly changing. It also saves the trouble of having to install the dataset on multiple machines." }, { "code": null, "e": 4925, "s": 4504, "text": "import urllib.requestDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/jpzambranoleon/ML_Projects/master/\"TRAIN_PATH = os.path.join(\"datasets\", \"players_20\")TRAIN_URL = DOWNLOAD_ROOT + \"datasets/players_20.csv\"def fetch_train_data(train_url=TRAIN_URL, train_path=TRAIN_PATH): os.makedirs(train_path, exist_ok=True) csv_path = os.path.join(train_path, \"players_20.csv\") urllib.request.urlretrieve(train_url, csv_path)" }, { "code": null, "e": 4987, "s": 4925, "text": "The fetch_train_data() function is used to fetch the dataset." }, { "code": null, "e": 5006, "s": 4987, "text": "fetch_train_data()" }, { "code": null, "e": 5279, "s": 5006, "text": "The dataset is downloaded and saved in the files section of Google Colabs under the folders datasets and players_20. Now all that’s left to do is to load the data into a pandas DataFrame. Luckily, there is a function that we can create to return a pandas DataFrame object." }, { "code": null, "e": 5427, "s": 5279, "text": "import pandas as pddef load_train_data(train_path=TRAIN_PATH): csv_path = os.path.join(train_path, \"players_20.csv\") return pd.read_csv(csv_path)" }, { "code": null, "e": 5634, "s": 5427, "text": "I called the load_train_data() function into player_data variable to save the DataFrame into a variable to make things easier. The DataFrame’s head() method is used to look at the top five rows of the data." }, { "code": null, "e": 5684, "s": 5634, "text": "player_data = load_train_data()player_data.head()" }, { "code": null, "e": 5866, "s": 5684, "text": "I used the shape method to return a tuple representing the dimensionality of the DataFrame. By using the shape method, we can see how many rows and columns there are in the dataset." }, { "code": null, "e": 5896, "s": 5866, "text": "player_data.shape(18278, 104)" }, { "code": null, "e": 6179, "s": 5896, "text": "As we can see from the tuple, the dataset has 18,278 rows and 104 columns. We don’t need to use all the columns so it’s best if we truncate the DataFrame to only include the target column and the player stats columns. There are 34 player stats columns so we’ll need to select those." }, { "code": null, "e": 7035, "s": 6179, "text": "#player stat featurescolumns = ['overall','attacking_crossing', 'attacking_finishing', 'attacking_heading_accuracy', 'attacking_short_passing', 'attacking_volleys', 'skill_dribbling', 'skill_curve', 'skill_fk_accuracy', 'skill_long_passing', 'skill_ball_control', 'movement_acceleration', 'movement_sprint_speed', 'movement_agility', 'movement_reactions', 'movement_balance', 'power_shot_power', 'power_jumping', 'power_stamina', 'power_strength', 'power_long_shots', 'mentality_aggression', 'mentality_interceptions', 'mentality_positioning', 'mentality_vision', 'mentality_penalties', 'mentality_composure', 'defending_marking', 'defending_standing_tackle', 'defending_sliding_tackle', 'goalkeeping_diving', 'goalkeeping_handling', 'goalkeeping_kicking', 'goalkeeping_positioning', 'goalkeeping_reflexes']player_df = player_data[columns]player_df.head()" }, { "code": null, "e": 7120, "s": 7035, "text": "I used the info() method on the new DataFrame to get a quick description o the data." }, { "code": null, "e": 7137, "s": 7120, "text": "player_df.info()" }, { "code": null, "e": 7274, "s": 7137, "text": "We can see from the data that there are 18,278 non-null values in the DataFrame which means we don’t have to worry about missing values." }, { "code": null, "e": 7354, "s": 7274, "text": "To get a statistical description of the data, we can use the describe() method." }, { "code": null, "e": 7375, "s": 7354, "text": "player_df.describe()" }, { "code": null, "e": 7479, "s": 7375, "text": "Just for good measure, let’s use the shape method again to see the dimensionality of the new DataFrame." }, { "code": null, "e": 7506, "s": 7479, "text": "player_df.shape(18278, 35)" }, { "code": null, "e": 8054, "s": 7506, "text": "Another great way to get a feel of the data is to plot a histogram of every numerical attribute. To plot a histogram of every attribute, just call the hist() method on the DataFrame. The hist() method requires the matplotlib library. You can specify the number of bins for each histogram and you can also specify the size of the figure. I chose to go with 40 bins and a figure size of (27,17), but all of that is completely up to you. Histograms are useful because they show the number of instances (y-axis) that have a given value range (x-axis)." }, { "code": null, "e": 8105, "s": 8054, "text": "player_df.hist(bins=40, figsize=(27,17))plt.show()" }, { "code": null, "e": 8317, "s": 8105, "text": "As we can see from the figure, each histogram has a value range of 0 to 100. This is a good indication that every attribute has the same scale which means we don’t have to do any feature scaling transformations." }, { "code": null, "e": 8527, "s": 8317, "text": "For good practice, I like to be completely sure that there are no missing values in the data, so I use the isna().any() method to return a True or False statement on whether or not the data has missing values." }, { "code": null, "e": 8550, "s": 8527, "text": "player_df.isna().any()" }, { "code": null, "e": 8700, "s": 8550, "text": "As we can see from the output, the return value is False on every attribute which means that there are no missing values. We are ready to continue!!!" }, { "code": null, "e": 9379, "s": 8700, "text": "After exploring the data, the next thing we need to do is to split the data into training and testing sets. We can do this by splitting the data ourselves, or by creating a function to do it for us. Luckily for us, Scikit-Learn has a cool feature that can split the dataset into training and testing sets. The train_test_split() function can easily split the data into the sets we need. I set test_size=0.2 so that 20% of the data is stored in the test set. The other 80% of the data is stored in the training set. The training set should have more of the data because it is the set which the model learns from. The testing set will be the set that we use to validate the model." }, { "code": null, "e": 9742, "s": 9379, "text": "from sklearn.model_selection import train_test_splittrain_set, test_set = train_test_split(player_df, test_size=0.2, random_state=42)print(\"Length of training data:\", len(train_set))print(\"Length of testing data:\", len(test_set))print(\"Length of total data:\", len(player_df))Length of training data: 14622 Length of testing data: 3656 Length of total data: 18278" }, { "code": null, "e": 10012, "s": 9742, "text": "You can compute the standard correlation coefficient between each pair of attributes using the corr() method. Looking at all the correlations between each attribute will take up too much time, so let’s just see how much each attribute correlates with the overall value." }, { "code": null, "e": 10118, "s": 10012, "text": "fifa_df = train_set.copy()corr_matrix = fifa_df.corr()corr_matrix['overall'].sort_values(ascending=False)" }, { "code": null, "e": 10495, "s": 10118, "text": "The correlation coefficient ranges from -1 to 1. When the correlation coefficient is close to 1, it means that there is a strong positive correlation; for example, overall tends to go up when movement reactions goes up. When the correlation coefficient is close to -1, it means that there is a strong negative correlation (i.e., the opposite of a strong positive correlation)." }, { "code": null, "e": 10797, "s": 10495, "text": "To visualize the correlation between attributes, we can use the pandas scatter_matrix() function. This function plots every numerical attribute against every other numerical attributes. Let’s just look at the top five promising attributes to make things easier since there are 35 numerical attributes." }, { "code": null, "e": 11011, "s": 10797, "text": "from pandas.plotting import scatter_matrixattributes = [‘overall’, ‘movement_reactions’, ‘mentality_composure’, ‘power_shot_power’, ‘mentality_vision’]scatter_matrix(fifa_df[attributes], figsize=(15,12))plt.show()" }, { "code": null, "e": 11239, "s": 11011, "text": "Strong correlation relationships tend to be linear, so the most promising attribute to predict overall is movement reactions. As we can see from the figure, movement reactions and overall have a very strong linear relationship." }, { "code": null, "e": 11296, "s": 11239, "text": "Let’s take a closer look at the correlation scatterplot." }, { "code": null, "e": 11396, "s": 11296, "text": "fifa_df.plot(kind=’scatter’, x=’movement_reactions’, y=’overall’, alpha=0.1, color=’red’)plt.show()" }, { "code": null, "e": 11472, "s": 11396, "text": "The correlation is indeed very strong; you can clearly see an upward trend." }, { "code": null, "e": 11526, "s": 11472, "text": "Now, it’s time to prepare the data for ML algorithms." }, { "code": null, "e": 11811, "s": 11526, "text": "I split the training set and testing set into separate sets of features and targets. The DataFrame y_train and y_test contain the target values (the target value is overall) and X_train and X_test contain the feature values (every other attribute that correlates to the target value)." }, { "code": null, "e": 11954, "s": 11811, "text": "y_train = train_set['overall']X_train = train_set.drop('overall', axis=1)y_test = test_set['overall']X_test = test_set.drop('overall', axis=1)" }, { "code": null, "e": 12048, "s": 11954, "text": "Let’s first train a Linear Regression model using Scikit-Learn’s LinearRegression() function:" }, { "code": null, "e": 12155, "s": 12048, "text": "from sklearn.linear_model import LinearRegressionlin_reg = LinearRegression()lin_reg.fit(X_train, y_train)" }, { "code": null, "e": 12274, "s": 12155, "text": "Let’s measure the regression model’s RMSE on the whole training set using Scikit-Learn’s mean_square_error() function:" }, { "code": null, "e": 12465, "s": 12274, "text": "from sklearn.metrics import mean_squared_errory_predictions = lin_reg.predict(X_train)lin_mse = mean_squared_error(y_train, y_predictions)lin_rmse = np.sqrt(lin_mse)lin_rmse2.493574884183225" }, { "code": null, "e": 12903, "s": 12465, "text": "Not a bad score!!! It seems that a Linear Regression model could do the trick. From what we saw from the scatter matrix is that not every attribute has a linear relationship. For nonlinear relationships, we would need a more powerful model so let’s train a Decision Tree Regression model. This is a powerful model, capable of finding complex nonlinear relationships in the data. Let’s use Scikit-Learn’s DecisionTreeRegressor() function:" }, { "code": null, "e": 13015, "s": 12903, "text": "from sklearn.tree import DecisionTreeRegressortree_reg = DecisionTreeRegressor()atree_reg.fit(X_train, y_train)" }, { "code": null, "e": 13054, "s": 13015, "text": "Again, let’s measure the model’s RMSE:" }, { "code": null, "e": 13190, "s": 13054, "text": "y_predictions = tree_reg.predict(X_train)tree_mse = mean_squared_error(y_train, y_predictions)tree_rmse = np.sqrt(tree_mse)tree_rmse0.0" }, { "code": null, "e": 13240, "s": 13190, "text": "What?! An RMSE of 0.0!!! Is this a perfect model?" }, { "code": null, "e": 13417, "s": 13240, "text": "Actually, it could be that this model has badly overfit the data. That’s why in every ML project it is important that you perform model validation, but we’ll get to that later." }, { "code": null, "e": 13502, "s": 13417, "text": "For now, let’s just train our final model which is a Random Forest Regression model." }, { "code": null, "e": 13603, "s": 13502, "text": "We can train a Random Forest Regression model using Scikit-Learn’s RandomForestRegressor() function:" }, { "code": null, "e": 13722, "s": 13603, "text": "from sklearn.ensemble import RandomForestRegressorforest_reg = RandomForestRegressor()forest_reg.fit(X_train, y_train)" }, { "code": null, "e": 13761, "s": 13722, "text": "Let’s look at the RMSE for this model:" }, { "code": null, "e": 13922, "s": 13761, "text": "y_predictions = forest_reg.predict(X_train)forest_mse = mean_squared_error(y_train, y_predictions)forest_rmse = np.sqrt(forest_mse)forest_rmse0.4774070457668509" }, { "code": null, "e": 14652, "s": 13922, "text": "It’s a better score than our Linear Regression model, but it’s not as good as our Decision Tree model. Again, it could be that our Decision Tree model has badly overfit the data, which is why we always need to validate each model before selecting the best one. An easy way to validate a model’s accuracy is to use Scikit-Learn’s K-fold cross-validation feature. Cross-validation randomly splits the training set into 10 distinct subsets called folds, then it trains and evaluates the models 10 times, picking a different fold for evaluation every time and training on the 9 folds. The result is an array containing the 10 evaluation scores. We need to take a look at the mean validation score before we can choose the best model." }, { "code": null, "e": 14726, "s": 14652, "text": "Let’s look at the cross-validation scores of our Linear Regression model:" }, { "code": null, "e": 15245, "s": 14726, "text": "from sklearn.model_selection import cross_val_scorescores = cross_val_score(lin_reg, X_train, y_train,scoring='neg_mean_squared_error', cv=10)lin_reg_scores = np.sqrt(-scores)def display_scores(scores): print(\"Scores:\", scores) print(\"Mean:\", scores.mean()) print(\"Standard Deviation:\", scores.std())display_scores(lin_reg_scores)Scores: [2.48985397 2.509888 2.50910312 2.4642167 2.46189444 2.51445854 2.48370267 2.4734443 2.48382446 2.59475861] Mean: 2.4985144826450054 Standard Deviation: 0.03662607159427437" }, { "code": null, "e": 15319, "s": 15245, "text": "Now let’s look at the cross-validation scores of our Decision Tree model:" }, { "code": null, "e": 15652, "s": 15319, "text": "scores = cross_val_score(tree_reg, X_train, y_train,scoring='neg_mean_squared_error', cv=10)tree_scores = np.sqrt(-scores)display_scores(tree_scores)Scores: [2.03976196 2.10100389 2.24933491 2.18751588 2.13289653 2.1158318 2.10529916 2.08391009 2.30935171 2.15395796] Mean: 2.147886387907302 Standard Deviation: 0.07682311253910523" }, { "code": null, "e": 15828, "s": 15652, "text": "Now that’s a more believable score than the first. It’s still better than our Linear Regression model, but let’s look at the cross-validation score of our Random Forest model:" }, { "code": null, "e": 16170, "s": 15828, "text": "scores = cross_val_score(forest_reg, X_train, y_train,scoring='neg_mean_squared_error', cv=10)forest_scores = np.sqrt(-scores)display_scores(forest_scores)Scores: [1.29156727 1.24883845 1.2625419 1.288613 1.22436926 1.30612055 1.25621857 1.24755531 1.30399247 1.28656714] Mean: 1.2716383911151843 Standard Deviation: 0.026074298378757566" }, { "code": null, "e": 16309, "s": 16170, "text": "Wow!!! This might just be the best score we’ve seen. Random Forests look very promising. This is the model that we’ll use for our project." }, { "code": null, "e": 16734, "s": 16309, "text": "Now that we have selected our model, we need to fine tune it. Fine tuning requires that we fiddle with the hyperparameters manually, until we find a great combination of hyperparameter values. Fine tuning is very tedious work and can take a long time if the dataset is large. You may not even have time to explore many combinations. Instead of doing everything manually, there is an easier option that Scikit-Learn provides." }, { "code": null, "e": 17127, "s": 16734, "text": "Instead of fiddling with the hyperparameters manually, you should use Scikit-Learn’s GridSearchCV to search for you. All you need to do is tell it which hyperparameters you want it to experiment with and what to try out, and it will use cross-validation to evaluate all the possible combinations of hyperparameter values. The code below provides the parameters that I used to experiment with." }, { "code": null, "e": 17505, "s": 17127, "text": "from sklearn.model_selection import GridSearchCVparam_grid = [{'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8]},{'bootstrap': [False], 'n_estimators': [3,10], 'max_features': [2,3,4]},]forest_reg = RandomForestRegressor()grid_search = GridSearchCV(forest_reg, param_grid, cv=5,scoring='neg_mean_squared_error',return_train_score=True)grid_search.fit(X_train, y_train)" }, { "code": null, "e": 17588, "s": 17505, "text": "When it’s done training, you can get the best combination of parameters like this:" }, { "code": null, "e": 17652, "s": 17588, "text": "grid_search.best_params_{'max_features': 8, 'n_estimators': 30}" }, { "code": null, "e": 17698, "s": 17652, "text": "You can also get the best estimator directly:" }, { "code": null, "e": 18164, "s": 17698, "text": "grid_search.best_estimator_RandomForestRegressor(bootstrap=True, ccp_alpha=0.0, criterion='mse', max_depth=None, max_features=8, max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=30, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False)" }, { "code": null, "e": 18262, "s": 18164, "text": "Of course, you can experiment with any hyperparameter values, but I think this will work for now." }, { "code": null, "e": 18569, "s": 18262, "text": "After tweaking the model on the training set, it’s finally time to evaluate the final model on the test set. The process is pretty similar, but this time we need to specify the best estimator to the final model. Again, we’ll need to measure the performance of the final model. The code to do that is below:" }, { "code": null, "e": 18773, "s": 18569, "text": "final_model = grid_search.best_estimator_final_predictions = final_model.predict(X_test)final_mse = mean_squared_error(y_test, final_predictions)final_rmse = np.sqrt(final_mse)final_rmse1.135337798136083" }, { "code": null, "e": 19201, "s": 18773, "text": "The score is the best we have seen so far, not to mention it was also used on data that the model has not previously seen. If I’m being honest, I didn’t expect the model to do this well, but we can’t just assume that the RMSE will always be a certain value. We want to have an idea of how percise this estimate is. For this, you can compute a 95% confidence interval for the generalization error using scipy.stats.t.interval():" }, { "code": null, "e": 19416, "s": 19201, "text": "confidence = 0.95squared_errors = (final_predictions - y_test)**2np.sqrt(stats.t.interval(confidence, len(squared_errors)-1,loc=squared_errors.mean(),scale=stats.sem(squared_errors)))array([1.10181563, 1.16789818])" }, { "code": null, "e": 19471, "s": 19416, "text": "We can see that the RMSE will be between 1.10 and 1.17" }, { "code": null, "e": 19488, "s": 19471, "text": "95% of the time." }, { "code": null, "e": 19737, "s": 19488, "text": "We are pretty much done with the model, but just out of curiosity, we would want to see how the predictions differed from the actual target. To do this, just selected five instances from the test set and use the predict() method on the final model:" }, { "code": null, "e": 19974, "s": 19737, "text": "some_data = X_test.iloc[:5]some_label = y_test.iloc[:5]print(\"Predictions:\", final_model.predict(some_data))print(\"Labels:\", list(some_label))Predictions: [64.2 73.8 68.76666667 68.13333333 63.4 ] Labels: [64, 74, 69, 68, 63]" }, { "code": null, "e": 20098, "s": 19974, "text": "The predictions are pretty accurate. I’m surprised that the model performed this well. I’m very satisfied with the results." } ]
How to Colab with TPU. Training a Huggingface BERT on Google... | by Rohan Jagtap | Towards Data Science
TPUs (Tensor Processing Units) are application-specific integrated circuits (ASICs) that are optimized specifically for processing matrices. Cloud TPU resources accelerate the performance of linear algebra computation, which is used heavily in machine learning applications — Cloud TPU Documentation Google Colab provides experimental support for TPUs for free! In this article, we’ll be discussing how to train a model using TPU on Colab. Specifically, we’ll be training BERT for text classification using the transformers package by huggingface on a TPU. First things first. Since the TPU is optimized for some specific operations, we need to check if our model actually uses them; i.e. we need to check if the TPU actually helps our model to train faster. Following are some use cases where we might want to use a TPU as mentioned in the Cloud TPU Documentation: Models dominated by matrix computations Models with no custom TensorFlow operations inside the main training loop Models that train for weeks or months Larger and very large models with very large effective batch sizes If your model uses a custom TensorFlow operation that is not present in Cloud TPU supported TensorFlow ops, you may rather use a GPU accelerator instead. TPUs work on the cloud, unlike GPUs or CPUs that work locally. Hence we need some initialization before we start: If you observe the output from the snippet above, our TPU cluster has 8 logical TPU devices (0–7) that are capable of parallel processing. Hence, we define a distribution strategy for distributed training over these 8 devices: strategy = tf.distribute.TPUStrategy(resolver) For more on distributed training refer: https://www.tensorflow.org/guide/distributed_training In this section, we’ll be actually seeing how to train a BERT on TPU. We will do this in 2 ways: Using model.fit()Using Custom Training Loop. Using model.fit() Using Custom Training Loop. Since we are using a distribution strategy, the model must be created on each device for parameter sharing. Hence, the model needs to be created and built within the strategy’s scope: Then, we simply fit the model on the data as one would do in a regular training setting: To save the model weights: model.save_weights("checkpoint/tpu-model.h5") In the next subsection, we will discuss how to do the same thing using a custom training loop. Here, we just need to tweak a few things manually that TensorFlow did for us in the backend in the previous method. First, we create a data pipeline using tf.data API: Now, the reason we didn’t have to worry about this in the previous part is that TensorFlow took care of these things itself; i.e. when we called model.fit(). Also this time, we need to manually distribute the dataset among the TPU devices: Next, we create and build the model in the exact same way as in the previous method. Optionally, we can add some metrics in the strategy scope for manual loss and accuracy monitoring: Now comes the most important part, i.e. the training step function. But first, let’s create an iterator for the distributed dataset: train_iterator = iter(train_dataset) Then we write the train_step function and decorate it using @tf.function as one would normally do. We use strategy.run() to execute the training step: Finally, we run this train_step function for a few epochs in the training loop: This time, let’s try saving the model using Checkpoints. Now there’s a issue here. Well, we can’t save the model just like that. The error is pretty clear, it says you cannot access the local file system while executing eagerly, as the execution is taken to the cloud for the TPU to perform its ops. So, to overcome this, we need to save the checkpoint in a GCS bucket. You can create a free tier GCP account here. First, we need to create a cloud storage bucket. Here is a tutorial from the official docs for creating a GCS bucket. Next, we need to sign in using our GCP credentials and set the GCP project to the active configuration: from google.colab import authauth.authenticate_user()!gcloud config set project <project-id> gcloud config set sets the specified property in your active configuration only. — Google Cloud Docs Once this is done, we can access our bucket by simply using: gs://<bucket-name>/<file-path> Now the checkpoint looks something like this: And this time, it will successfully save the model checkpoint to your bucket! In this article, we saw why and how to tweak the original code that one would write to train a model, to make it TPU compatible. We also discussed when to and when not to use a TPU for training.
[ { "code": null, "e": 313, "s": 172, "text": "TPUs (Tensor Processing Units) are application-specific integrated circuits (ASICs) that are optimized specifically for processing matrices." }, { "code": null, "e": 446, "s": 313, "text": "Cloud TPU resources accelerate the performance of linear algebra computation, which is used heavily in machine learning applications" }, { "code": null, "e": 472, "s": 446, "text": "— Cloud TPU Documentation" }, { "code": null, "e": 729, "s": 472, "text": "Google Colab provides experimental support for TPUs for free! In this article, we’ll be discussing how to train a model using TPU on Colab. Specifically, we’ll be training BERT for text classification using the transformers package by huggingface on a TPU." }, { "code": null, "e": 1038, "s": 729, "text": "First things first. Since the TPU is optimized for some specific operations, we need to check if our model actually uses them; i.e. we need to check if the TPU actually helps our model to train faster. Following are some use cases where we might want to use a TPU as mentioned in the Cloud TPU Documentation:" }, { "code": null, "e": 1078, "s": 1038, "text": "Models dominated by matrix computations" }, { "code": null, "e": 1152, "s": 1078, "text": "Models with no custom TensorFlow operations inside the main training loop" }, { "code": null, "e": 1190, "s": 1152, "text": "Models that train for weeks or months" }, { "code": null, "e": 1257, "s": 1190, "text": "Larger and very large models with very large effective batch sizes" }, { "code": null, "e": 1411, "s": 1257, "text": "If your model uses a custom TensorFlow operation that is not present in Cloud TPU supported TensorFlow ops, you may rather use a GPU accelerator instead." }, { "code": null, "e": 1525, "s": 1411, "text": "TPUs work on the cloud, unlike GPUs or CPUs that work locally. Hence we need some initialization before we start:" }, { "code": null, "e": 1752, "s": 1525, "text": "If you observe the output from the snippet above, our TPU cluster has 8 logical TPU devices (0–7) that are capable of parallel processing. Hence, we define a distribution strategy for distributed training over these 8 devices:" }, { "code": null, "e": 1799, "s": 1752, "text": "strategy = tf.distribute.TPUStrategy(resolver)" }, { "code": null, "e": 1893, "s": 1799, "text": "For more on distributed training refer: https://www.tensorflow.org/guide/distributed_training" }, { "code": null, "e": 1990, "s": 1893, "text": "In this section, we’ll be actually seeing how to train a BERT on TPU. We will do this in 2 ways:" }, { "code": null, "e": 2035, "s": 1990, "text": "Using model.fit()Using Custom Training Loop." }, { "code": null, "e": 2053, "s": 2035, "text": "Using model.fit()" }, { "code": null, "e": 2081, "s": 2053, "text": "Using Custom Training Loop." }, { "code": null, "e": 2265, "s": 2081, "text": "Since we are using a distribution strategy, the model must be created on each device for parameter sharing. Hence, the model needs to be created and built within the strategy’s scope:" }, { "code": null, "e": 2354, "s": 2265, "text": "Then, we simply fit the model on the data as one would do in a regular training setting:" }, { "code": null, "e": 2381, "s": 2354, "text": "To save the model weights:" }, { "code": null, "e": 2427, "s": 2381, "text": "model.save_weights(\"checkpoint/tpu-model.h5\")" }, { "code": null, "e": 2522, "s": 2427, "text": "In the next subsection, we will discuss how to do the same thing using a custom training loop." }, { "code": null, "e": 2638, "s": 2522, "text": "Here, we just need to tweak a few things manually that TensorFlow did for us in the backend in the previous method." }, { "code": null, "e": 2690, "s": 2638, "text": "First, we create a data pipeline using tf.data API:" }, { "code": null, "e": 2930, "s": 2690, "text": "Now, the reason we didn’t have to worry about this in the previous part is that TensorFlow took care of these things itself; i.e. when we called model.fit(). Also this time, we need to manually distribute the dataset among the TPU devices:" }, { "code": null, "e": 3114, "s": 2930, "text": "Next, we create and build the model in the exact same way as in the previous method. Optionally, we can add some metrics in the strategy scope for manual loss and accuracy monitoring:" }, { "code": null, "e": 3247, "s": 3114, "text": "Now comes the most important part, i.e. the training step function. But first, let’s create an iterator for the distributed dataset:" }, { "code": null, "e": 3284, "s": 3247, "text": "train_iterator = iter(train_dataset)" }, { "code": null, "e": 3435, "s": 3284, "text": "Then we write the train_step function and decorate it using @tf.function as one would normally do. We use strategy.run() to execute the training step:" }, { "code": null, "e": 3515, "s": 3435, "text": "Finally, we run this train_step function for a few epochs in the training loop:" }, { "code": null, "e": 3644, "s": 3515, "text": "This time, let’s try saving the model using Checkpoints. Now there’s a issue here. Well, we can’t save the model just like that." }, { "code": null, "e": 3815, "s": 3644, "text": "The error is pretty clear, it says you cannot access the local file system while executing eagerly, as the execution is taken to the cloud for the TPU to perform its ops." }, { "code": null, "e": 4048, "s": 3815, "text": "So, to overcome this, we need to save the checkpoint in a GCS bucket. You can create a free tier GCP account here. First, we need to create a cloud storage bucket. Here is a tutorial from the official docs for creating a GCS bucket." }, { "code": null, "e": 4152, "s": 4048, "text": "Next, we need to sign in using our GCP credentials and set the GCP project to the active configuration:" }, { "code": null, "e": 4245, "s": 4152, "text": "from google.colab import authauth.authenticate_user()!gcloud config set project <project-id>" }, { "code": null, "e": 4326, "s": 4245, "text": "gcloud config set sets the specified property in your active configuration only." }, { "code": null, "e": 4346, "s": 4326, "text": "— Google Cloud Docs" }, { "code": null, "e": 4407, "s": 4346, "text": "Once this is done, we can access our bucket by simply using:" }, { "code": null, "e": 4438, "s": 4407, "text": "gs://<bucket-name>/<file-path>" }, { "code": null, "e": 4484, "s": 4438, "text": "Now the checkpoint looks something like this:" }, { "code": null, "e": 4562, "s": 4484, "text": "And this time, it will successfully save the model checkpoint to your bucket!" } ]
MATLAB - Variables
In MATLAB environment, every variable is an array or matrix. You can assign variables in a simple way. For example, x = 3 % defining x and initializing it with a value MATLAB will execute the above statement and return the following result − x = 3 It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another example, x = sqrt(16) % defining x and initializing it with an expression MATLAB will execute the above statement and return the following result − x = 4 Please note that − Once a variable is entered into the system, you can refer to it later. Once a variable is entered into the system, you can refer to it later. Variables must have values before they are used. Variables must have values before they are used. When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later. When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later. For example, sqrt(78) MATLAB will execute the above statement and return the following result − ans = 8.8318 You can use this variable ans − sqrt(78); 9876/ans MATLAB will execute the above statement and return the following result − ans = 1118.2 Let's look at another example − x = 7 * 8; y = x * 7.89 MATLAB will execute the above statement and return the following result − y = 441.84 You can have multiple assignments on the same line. For example, a = 2; b = 7; c = a * b MATLAB will execute the above statement and return the following result − c = 14 The who command displays all the variable names you have used. who MATLAB will execute the above statement and return the following result − Your variables are: a ans b c The whos command displays little more about the variables − Variables currently in memory Type of each variables Memory allocated to each variable Whether they are complex variables or not whos MATLAB will execute the above statement and return the following result − Attr Name Size Bytes Class ==== ==== ==== ==== ===== a 1x1 8 double ans 1x70 757 cell b 1x1 8 double c 1x1 8 double Total is 73 elements using 781 bytes The clear command deletes all (or the specified) variable(s) from the memory. clear x % it will delete x, won't display anything clear % it will delete all variables in the workspace % peacefully and unobtrusively Long assignments can be extended to another line by using an ellipses (...). For example, initial_velocity = 0; acceleration = 9.8; time = 20; final_velocity = initial_velocity + acceleration * time MATLAB will execute the above statement and return the following result − final_velocity = 196 By default, MATLAB displays numbers with four decimal place values. This is known as short format. However, if you want more precision, you need to use the format command. The format long command displays 16 digits after decimal. For example − format long x = 7 + 10/3 + 5 ^ 1.2 MATLAB will execute the above statement and return the following result− x = 17.2319816406394 Another example, format short x = 7 + 10/3 + 5 ^ 1.2 MATLAB will execute the above statement and return the following result − x = 17.232 The format bank command rounds numbers to two decimal places. For example, format bank daily_wage = 177.45; weekly_wage = daily_wage * 6 MATLAB will execute the above statement and return the following result − weekly_wage = 1064.70 MATLAB displays large numbers using exponential notation. The format short e command allows displaying in exponential form with four decimal places plus the exponent. For example, format short e 4.678 * 4.9 MATLAB will execute the above statement and return the following result − ans = 2.2922e+01 The format long e command allows displaying in exponential form with four decimal places plus the exponent. For example, format long e x = pi MATLAB will execute the above statement and return the following result − x = 3.141592653589793e+00 The format rat command gives the closest rational expression resulting from a calculation. For example, format rat 4.678 * 4.9 MATLAB will execute the above statement and return the following result − ans = 34177/1491 A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors − Row vectors Column vectors Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements. For example, r = [7 8 9 10 11] MATLAB will execute the above statement and return the following result − r = 7 8 9 10 11 Another example, r = [7 8 9 10 11]; t = [2, 3, 4, 5, 6]; res = r + t MATLAB will execute the above statement and return the following result − res = 9 11 13 15 17 Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;) to delimit the elements. c = [7; 8; 9; 10; 11] MATLAB will execute the above statement and return the following result − c = 7 8 9 10 11 A matrix is a two-dimensional array of numbers. In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated elements, and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix as − m = [1 2 3; 4 5 6; 7 8 9] MATLAB will execute the above statement and return the following result − m = 1 2 3 4 5 6 7 8 9 30 Lectures 4 hours Nouman Azam 127 Lectures 12 hours Nouman Azam 17 Lectures 3 hours Sanjeev 37 Lectures 5 hours TELCOMA Global 22 Lectures 4 hours TELCOMA Global 18 Lectures 3 hours Phinite Academy Print Add Notes Bookmark this page
[ { "code": null, "e": 2202, "s": 2141, "text": "In MATLAB environment, every variable is an array or matrix." }, { "code": null, "e": 2257, "s": 2202, "text": "You can assign variables in a simple way. For example," }, { "code": null, "e": 2316, "s": 2257, "text": "x = 3\t % defining x and initializing it with a value" }, { "code": null, "e": 2390, "s": 2316, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 2397, "s": 2390, "text": "x = 3\n" }, { "code": null, "e": 2501, "s": 2397, "text": "It creates a 1-by-1 matrix named x and stores the value 3 in its element. Let us check another example," }, { "code": null, "e": 2567, "s": 2501, "text": "x = sqrt(16) \t% defining x and initializing it with an expression" }, { "code": null, "e": 2641, "s": 2567, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 2648, "s": 2641, "text": "x = 4\n" }, { "code": null, "e": 2667, "s": 2648, "text": "Please note that −" }, { "code": null, "e": 2738, "s": 2667, "text": "Once a variable is entered into the system, you can refer to it later." }, { "code": null, "e": 2809, "s": 2738, "text": "Once a variable is entered into the system, you can refer to it later." }, { "code": null, "e": 2858, "s": 2809, "text": "Variables must have values before they are used." }, { "code": null, "e": 2907, "s": 2858, "text": "Variables must have values before they are used." }, { "code": null, "e": 3053, "s": 2907, "text": "When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later." }, { "code": null, "e": 3199, "s": 3053, "text": "When an expression returns a result that is not assigned to any variable, the system assigns it to a variable named ans, which can be used later." }, { "code": null, "e": 3212, "s": 3199, "text": "For example," }, { "code": null, "e": 3221, "s": 3212, "text": "sqrt(78)" }, { "code": null, "e": 3295, "s": 3221, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3310, "s": 3295, "text": "ans = 8.8318\n" }, { "code": null, "e": 3342, "s": 3310, "text": "You can use this variable ans −" }, { "code": null, "e": 3361, "s": 3342, "text": "sqrt(78);\n9876/ans" }, { "code": null, "e": 3435, "s": 3361, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3450, "s": 3435, "text": "ans = 1118.2\n" }, { "code": null, "e": 3482, "s": 3450, "text": "Let's look at another example −" }, { "code": null, "e": 3506, "s": 3482, "text": "x = 7 * 8;\ny = x * 7.89" }, { "code": null, "e": 3580, "s": 3506, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3593, "s": 3580, "text": "y = 441.84\n" }, { "code": null, "e": 3658, "s": 3593, "text": "You can have multiple assignments on the same line. For example," }, { "code": null, "e": 3682, "s": 3658, "text": "a = 2; b = 7; c = a * b" }, { "code": null, "e": 3756, "s": 3682, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3764, "s": 3756, "text": "c = 14\n" }, { "code": null, "e": 3827, "s": 3764, "text": "The who command displays all the variable names you have used." }, { "code": null, "e": 3832, "s": 3827, "text": "who\n" }, { "code": null, "e": 3906, "s": 3832, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 3947, "s": 3906, "text": "Your variables are:\na ans b c \n" }, { "code": null, "e": 4007, "s": 3947, "text": "The whos command displays little more about the variables −" }, { "code": null, "e": 4037, "s": 4007, "text": "Variables currently in memory" }, { "code": null, "e": 4060, "s": 4037, "text": "Type of each variables" }, { "code": null, "e": 4094, "s": 4060, "text": "Memory allocated to each variable" }, { "code": null, "e": 4136, "s": 4094, "text": "Whether they are complex variables or not" }, { "code": null, "e": 4142, "s": 4136, "text": "whos\n" }, { "code": null, "e": 4216, "s": 4142, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 4540, "s": 4216, "text": "Attr Name Size Bytes Class\n==== ==== ==== ==== ===== \n a 1x1 8 double\n ans 1x70 757 cell\n b 1x1 8 double\n c 1x1 8 double\n\nTotal is 73 elements using 781 bytes \n" }, { "code": null, "e": 4618, "s": 4540, "text": "The clear command deletes all (or the specified) variable(s) from the memory." }, { "code": null, "e": 4779, "s": 4618, "text": "clear x % it will delete x, won't display anything\nclear % it will delete all variables in the workspace\n % peacefully and unobtrusively \n" }, { "code": null, "e": 4869, "s": 4779, "text": "Long assignments can be extended to another line by using an ellipses (...). For example," }, { "code": null, "e": 4978, "s": 4869, "text": "initial_velocity = 0;\nacceleration = 9.8;\ntime = 20;\nfinal_velocity = initial_velocity + acceleration * time" }, { "code": null, "e": 5052, "s": 4978, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 5074, "s": 5052, "text": "final_velocity = 196\n" }, { "code": null, "e": 5173, "s": 5074, "text": "By default, MATLAB displays numbers with four decimal place values. This is known as short format." }, { "code": null, "e": 5246, "s": 5173, "text": "However, if you want more precision, you need to use the format command." }, { "code": null, "e": 5304, "s": 5246, "text": "The format long command displays 16 digits after decimal." }, { "code": null, "e": 5318, "s": 5304, "text": "For example −" }, { "code": null, "e": 5353, "s": 5318, "text": "format long\nx = 7 + 10/3 + 5 ^ 1.2" }, { "code": null, "e": 5426, "s": 5353, "text": "MATLAB will execute the above statement and return the following result−" }, { "code": null, "e": 5448, "s": 5426, "text": "x = 17.2319816406394\n" }, { "code": null, "e": 5465, "s": 5448, "text": "Another example," }, { "code": null, "e": 5501, "s": 5465, "text": "format short\nx = 7 + 10/3 + 5 ^ 1.2" }, { "code": null, "e": 5575, "s": 5501, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 5587, "s": 5575, "text": "x = 17.232\n" }, { "code": null, "e": 5662, "s": 5587, "text": "The format bank command rounds numbers to two decimal places. For example," }, { "code": null, "e": 5724, "s": 5662, "text": "format bank\ndaily_wage = 177.45;\nweekly_wage = daily_wage * 6" }, { "code": null, "e": 5798, "s": 5724, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 5821, "s": 5798, "text": "weekly_wage = 1064.70\n" }, { "code": null, "e": 5879, "s": 5821, "text": "MATLAB displays large numbers using exponential notation." }, { "code": null, "e": 5988, "s": 5879, "text": "The format short e command allows displaying in exponential form with four decimal places plus the exponent." }, { "code": null, "e": 6001, "s": 5988, "text": "For example," }, { "code": null, "e": 6028, "s": 6001, "text": "format short e\n4.678 * 4.9" }, { "code": null, "e": 6102, "s": 6028, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 6120, "s": 6102, "text": "ans = 2.2922e+01\n" }, { "code": null, "e": 6241, "s": 6120, "text": "The format long e command allows displaying in exponential form with four decimal places plus the exponent. For example," }, { "code": null, "e": 6262, "s": 6241, "text": "format long e\nx = pi" }, { "code": null, "e": 6336, "s": 6262, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 6363, "s": 6336, "text": "x = 3.141592653589793e+00\n" }, { "code": null, "e": 6467, "s": 6363, "text": "The format rat command gives the closest rational expression resulting from a calculation. For example," }, { "code": null, "e": 6490, "s": 6467, "text": "format rat\n4.678 * 4.9" }, { "code": null, "e": 6564, "s": 6490, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 6583, "s": 6564, "text": "ans = 34177/1491 \n" }, { "code": null, "e": 6677, "s": 6583, "text": "A vector is a one-dimensional array of numbers. MATLAB allows creating two types of vectors −" }, { "code": null, "e": 6689, "s": 6677, "text": "Row vectors" }, { "code": null, "e": 6704, "s": 6689, "text": "Column vectors" }, { "code": null, "e": 6827, "s": 6704, "text": "Row vectors are created by enclosing the set of elements in square brackets, using space or comma to delimit the elements." }, { "code": null, "e": 6840, "s": 6827, "text": "For example," }, { "code": null, "e": 6858, "s": 6840, "text": "r = [7 8 9 10 11]" }, { "code": null, "e": 6932, "s": 6858, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 6964, "s": 6932, "text": "r =\n\n 7 8 9 10 11 \n" }, { "code": null, "e": 6981, "s": 6964, "text": "Another example," }, { "code": null, "e": 7033, "s": 6981, "text": "r = [7 8 9 10 11];\nt = [2, 3, 4, 5, 6];\nres = r + t" }, { "code": null, "e": 7107, "s": 7033, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 7170, "s": 7107, "text": "res =\n\n 9 11 13 15 17\n" }, { "code": null, "e": 7294, "s": 7170, "text": "Column vectors are created by enclosing the set of elements in square brackets, using semicolon(;) to delimit the elements." }, { "code": null, "e": 7319, "s": 7294, "text": "c = [7; 8; 9; 10; 11]" }, { "code": null, "e": 7393, "s": 7319, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 7473, "s": 7393, "text": "c =\n 7 \n 8 \n 9 \n 10 \n 11 \n" }, { "code": null, "e": 7521, "s": 7473, "text": "A matrix is a two-dimensional array of numbers." }, { "code": null, "e": 7720, "s": 7521, "text": "In MATLAB, a matrix is created by entering each row as a sequence of space or comma separated elements, and end of a row is demarcated by a semicolon. For example, let us create a 3-by-3 matrix as −" }, { "code": null, "e": 7746, "s": 7720, "text": "m = [1 2 3; 4 5 6; 7 8 9]" }, { "code": null, "e": 7820, "s": 7746, "text": "MATLAB will execute the above statement and return the following result −" }, { "code": null, "e": 7963, "s": 7820, "text": "m =\n 1 2 3 \n 4 5 6 \n 7 8 9 \n" }, { "code": null, "e": 7996, "s": 7963, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 8009, "s": 7996, "text": " Nouman Azam" }, { "code": null, "e": 8044, "s": 8009, "text": "\n 127 Lectures \n 12 hours \n" }, { "code": null, "e": 8057, "s": 8044, "text": " Nouman Azam" }, { "code": null, "e": 8090, "s": 8057, "text": "\n 17 Lectures \n 3 hours \n" }, { "code": null, "e": 8099, "s": 8090, "text": " Sanjeev" }, { "code": null, "e": 8132, "s": 8099, "text": "\n 37 Lectures \n 5 hours \n" }, { "code": null, "e": 8148, "s": 8132, "text": " TELCOMA Global" }, { "code": null, "e": 8181, "s": 8148, "text": "\n 22 Lectures \n 4 hours \n" }, { "code": null, "e": 8197, "s": 8181, "text": " TELCOMA Global" }, { "code": null, "e": 8230, "s": 8197, "text": "\n 18 Lectures \n 3 hours \n" }, { "code": null, "e": 8247, "s": 8230, "text": " Phinite Academy" }, { "code": null, "e": 8254, "s": 8247, "text": " Print" }, { "code": null, "e": 8265, "s": 8254, "text": " Add Notes" } ]
PySpark Window Functions - GeeksforGeeks
20 Sep, 2021 PySpark Window function performs statistical operations such as rank, row number, etc. on a group, frame, or collection of rows and returns results for each row individually. It is also popularly growing to perform data transformations. We will understand the concept of window functions, syntax, and finally how to use them with PySpark SQL and PySpark DataFrame API. There are mainly three types of Window function: Analytical Function Ranking Function Aggregate Function To perform window function operation on a group of rows first, we need to partition i.e. define the group of data rows using window.partition() function, and for row number and rank function we need to additionally order by on partition data using ORDER BY clause. Syntax for Window.partition: Window.partitionBy(“column_name”).orderBy(“column_name”) Syntax for Window function: DataFrame.withColumn(“new_col_name”, Window_function().over(Window_partition)) Let’s understand and implement all these functions one by one with examples. An analytic function is a function that returns a result after operating on data or a finite set of rows partitioned by a SELECT clause or in the ORDER BY clause. It returns a result in the same number of rows as the number of input rows. E.g. lead(), lag(), cume_dist(). Creating dataframe for demonstration: Before we start with these functions, first we need to create a DataFrame. We will create a DataFrame that contains employee details like Employee_Name, Age, Department, Salary. After creating the DataFrame we will apply each analytical function on this DataFrame df. Python3 # importing pysparkfrom pyspark.sql.window import Windowimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # creating a sparksession object# and providing appNamespark = SparkSession.builder.appName("pyspark_window").getOrCreate() # sample data for dataframesampleData = (("Ram", 28, "Sales", 3000), ("Meena", 33, "Sales", 4600), ("Robin", 40, "Sales", 4100), ("Kunal", 25, "Finance", 3000), ("Ram", 28, "Sales", 3000), ("Srishti", 46, "Management", 3300), ("Jeny", 26, "Finance", 3900), ("Hitesh", 30, "Marketing", 3000), ("Kailash", 29, "Marketing", 2000), ("Sharad", 39, "Sales", 4100) ) # column names for dataframecolumns = ["Employee_Name", "Age", "Department", "Salary"] # creating the dataframe dfdf = spark.createDataFrame(data=sampleData, schema=columns) # importing Window from pyspark.sql.window # creating a window# partition of dataframewindowPartition = Window.partitionBy("Department").orderBy("Age") # print schemadf.printSchema() # show dfdf.show() Output: This is the DataFrame on which we will apply all the analytical functions. cume_dist() window function is used to get the cumulative distribution within a window partition. It is similar to CUME_DIST in SQL. Let’s see an example: Python3 # importing cume_dist()# from pyspark.sql.functionsfrom pyspark.sql.functions import cume_dist # applying window function with# the help of DataFrame.withColumndf.withColumn("cume_dist", cume_dist().over(windowPartition)).show() Output: In the output, we can see that a new column is added to the df named “cume_dist” that contains the cumulative distribution of the Department column which is ordered by the Age column. A lag() function is used to access previous rows’ data as per the defined offset value in the function. This function is similar to the LAG in SQL. Python3 # importing lag() from pyspark.sql.functionsfrom pyspark.sql.functions import lag df.withColumn("Lag", lag("Salary", 2).over(windowPartition)) \ .show() Output: In the output, we can see that lag column is added to the df that contains lag values. In the first 2 rows there is a null value as we have defined offset 2 followed by column Salary in the lag() function. The next rows contain the values of previous rows. A lead() function is used to access next rows data as per the defined offset value in the function. This function is similar to the LEAD in SQL and just opposite to lag() function or LAG in SQL. Python3 # importing lead() from pyspark.sql.functionsfrom pyspark.sql.functions import lead df.withColumn("Lead", lead("salary", 2).over(windowPartition)) \ .show() Output: The function returns the statistical rank of a given value for each row in a partition or group. The goal of this function is to provide consecutive numbering of the rows in the resultant column, set by the order selected in the Window.partition for each partition specified in the OVER clause. E.g. row_number(), rank(), dense_rank(), etc. Creating Dataframe for demonstration: Before we start with these functions, first we need to create a DataFrame. We will create a DataFrame that contains student details like Roll_No, Student_Name, Subject, Marks. After creating the DataFrame we will apply each Ranking function on this DataFrame df2. Python3 # importing pysparkfrom pyspark.sql.window import Windowimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # creating a sparksession object and providing appNamespark = SparkSession.builder.appName("pyspark_window").getOrCreate() # sample data for dataframesampleData = ((101, "Ram", "Biology", 80), (103, "Meena", "Social Science", 78), (104, "Robin", "Sanskrit", 58), (102, "Kunal", "Phisycs", 89), (101, "Ram", "Biology", 80), (106, "Srishti", "Maths", 70), (108, "Jeny", "Physics", 75), (107, "Hitesh", "Maths", 88), (109, "Kailash", "Maths", 90), (105, "Sharad", "Social Science", 84) ) # column names for dataframecolumns = ["Roll_No", "Student_Name", "Subject", "Marks"] # creating the dataframe dfdf2 = spark.createDataFrame(data=sampleData, schema=columns) # importing window from pyspark.sql.window # creating a window partition of dataframewindowPartition = Window.partitionBy("Subject").orderBy("Marks") # print schemadf2.printSchema() # show dfdf2.show() Output: This is the DataFrame df2 on which we will apply all the Window ranking function. row_number() function is used to gives a sequential number to each row present in the table. Let’s see the example: Python3 # importing row_number() from pyspark.sql.functionsfrom pyspark.sql.functions import row_number # applying the row_number() functiondf2.withColumn("row_number", row_number().over(windowPartition)).show() Output: In this output, we can see that we have the row number for each row based on the specified partition i.e. the row numbers are given followed by the Subject and Marks column. The rank function is used to give ranks to rows specified in the window partition. This function leaves gaps in rank if there are ties. Let’s see the example: Python3 # importing rank() from pyspark.sql.functionsfrom pyspark.sql.functions import rank # applying the rank() functiondf2.withColumn("rank", rank().over(windowPartition)) \ .show() Output: In the output, the rank is provided to each row as per the Subject and Marks column as specified in the window partition. This function is similar to rank() function. It also provides rank to rows but in a percentile format. Let’s see the example: Python3 # importing percent_rank() from pyspark.sql.functionsfrom pyspark.sql.functions import percent_rank # applying the percent_rank() functiondf2.withColumn("percent_rank", percent_rank().over(windowPartition)).show() Output: We can see that in the output the rank column contains values in a percentile form i.e. in the decimal format. This function is used to get the rank of each row in the form of row numbers. This is similar to rank() function, there is only one difference the rank function leaves gaps in rank when there are ties. Let’s see the example: Python3 # importing dense_rank() from pyspark.sql.functionsfrom pyspark.sql.functions import dense_rank # applying the dense_rank() functiondf2.withColumn("dense_rank", dense_rank().over(windowPartition)).show() Output: In the output, we can see that the ranks are given in the form of row numbers. An aggregate function or aggregation function is a function where the values of multiple rows are grouped to form a single summary value. The definition of the groups of rows on which they operate is done by using the SQL GROUP BY clause. E.g. AVERAGE, SUM, MIN, MAX, etc. Creating Dataframe for demonstration: Before we start with these functions, we will create a new DataFrame that contains employee details like Employee_Name, Department, and Salary. After creating the DataFrame we will apply each Aggregate function on this DataFrame. Python3 # importing pysparkimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # creating a sparksession# object and providing appNamespark = SparkSession.builder.appName("pyspark_window").getOrCreate() # sample data for dataframesampleData = (("Ram", "Sales", 3000), ("Meena", "Sales", 4600), ("Robin", "Sales", 4100), ("Kunal", "Finance", 3000), ("Ram", "Sales", 3000), ("Srishti", "Management", 3300), ("Jeny", "Finance", 3900), ("Hitesh", "Marketing", 3000), ("Kailash", "Marketing", 2000), ("Sharad", "Sales", 4100) ) # column names for dataframecolumns = ["Employee_Name", "Department", "Salary"] # creating the dataframe dfdf3 = spark.createDataFrame(data=sampleData, schema=columns) # print schemadf3.printSchema() # show dfdf3.show() Output: This is the DataFrame df3 on which we will apply all the aggregate functions. Python3 # importing window from pyspark.sql.windowfrom pyspark.sql.window import Window # importing aggregate functions# from pyspark.sql.functionsfrom pyspark.sql.functions import col,avg,sum,min,max,row_number # creating a window partition of dataframewindowPartitionAgg = Window.partitionBy("Department") # applying window aggregate function# to df3 with the help of withColumn # this is average()df3.withColumn("Avg", avg(col("salary")).over(windowPartitionAgg)) #this is sum() .withColumn("Sum", sum(col("salary")).over(windowPartitionAgg)) #this is min() .withColumn("Min", min(col("salary")).over(windowPartitionAgg)) #this is max() .withColumn("Max", max(col("salary")).over(windowPartitionAgg)).show() Output: In the output df, we can see that there are four new columns added to df. In the code, we have applied all the four aggregate functions one by one. We got four output columns added to the df3 that contains values for each row. These four columns contain the Average, Sum, Minimum, and Maximum values of the Salary column. akshaysingh98088 Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n20 Sep, 2021" }, { "code": null, "e": 24271, "s": 23901, "text": "PySpark Window function performs statistical operations such as rank, row number, etc. on a group, frame, or collection of rows and returns results for each row individually. It is also popularly growing to perform data transformations. We will understand the concept of window functions, syntax, and finally how to use them with PySpark SQL and PySpark DataFrame API. " }, { "code": null, "e": 24320, "s": 24271, "text": "There are mainly three types of Window function:" }, { "code": null, "e": 24340, "s": 24320, "text": "Analytical Function" }, { "code": null, "e": 24357, "s": 24340, "text": "Ranking Function" }, { "code": null, "e": 24376, "s": 24357, "text": "Aggregate Function" }, { "code": null, "e": 24642, "s": 24376, "text": "To perform window function operation on a group of rows first, we need to partition i.e. define the group of data rows using window.partition() function, and for row number and rank function we need to additionally order by on partition data using ORDER BY clause. " }, { "code": null, "e": 24671, "s": 24642, "text": "Syntax for Window.partition:" }, { "code": null, "e": 24728, "s": 24671, "text": "Window.partitionBy(“column_name”).orderBy(“column_name”)" }, { "code": null, "e": 24756, "s": 24728, "text": "Syntax for Window function:" }, { "code": null, "e": 24835, "s": 24756, "text": "DataFrame.withColumn(“new_col_name”, Window_function().over(Window_partition))" }, { "code": null, "e": 24912, "s": 24835, "text": "Let’s understand and implement all these functions one by one with examples." }, { "code": null, "e": 25184, "s": 24912, "text": "An analytic function is a function that returns a result after operating on data or a finite set of rows partitioned by a SELECT clause or in the ORDER BY clause. It returns a result in the same number of rows as the number of input rows. E.g. lead(), lag(), cume_dist()." }, { "code": null, "e": 25222, "s": 25184, "text": "Creating dataframe for demonstration:" }, { "code": null, "e": 25490, "s": 25222, "text": "Before we start with these functions, first we need to create a DataFrame. We will create a DataFrame that contains employee details like Employee_Name, Age, Department, Salary. After creating the DataFrame we will apply each analytical function on this DataFrame df." }, { "code": null, "e": 25498, "s": 25490, "text": "Python3" }, { "code": "# importing pysparkfrom pyspark.sql.window import Windowimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # creating a sparksession object# and providing appNamespark = SparkSession.builder.appName(\"pyspark_window\").getOrCreate() # sample data for dataframesampleData = ((\"Ram\", 28, \"Sales\", 3000), (\"Meena\", 33, \"Sales\", 4600), (\"Robin\", 40, \"Sales\", 4100), (\"Kunal\", 25, \"Finance\", 3000), (\"Ram\", 28, \"Sales\", 3000), (\"Srishti\", 46, \"Management\", 3300), (\"Jeny\", 26, \"Finance\", 3900), (\"Hitesh\", 30, \"Marketing\", 3000), (\"Kailash\", 29, \"Marketing\", 2000), (\"Sharad\", 39, \"Sales\", 4100) ) # column names for dataframecolumns = [\"Employee_Name\", \"Age\", \"Department\", \"Salary\"] # creating the dataframe dfdf = spark.createDataFrame(data=sampleData, schema=columns) # importing Window from pyspark.sql.window # creating a window# partition of dataframewindowPartition = Window.partitionBy(\"Department\").orderBy(\"Age\") # print schemadf.printSchema() # show dfdf.show()", "e": 26655, "s": 25498, "text": null }, { "code": null, "e": 26663, "s": 26655, "text": "Output:" }, { "code": null, "e": 26738, "s": 26663, "text": "This is the DataFrame on which we will apply all the analytical functions." }, { "code": null, "e": 26893, "s": 26738, "text": "cume_dist() window function is used to get the cumulative distribution within a window partition. It is similar to CUME_DIST in SQL. Let’s see an example:" }, { "code": null, "e": 26901, "s": 26893, "text": "Python3" }, { "code": "# importing cume_dist()# from pyspark.sql.functionsfrom pyspark.sql.functions import cume_dist # applying window function with# the help of DataFrame.withColumndf.withColumn(\"cume_dist\", cume_dist().over(windowPartition)).show()", "e": 27143, "s": 26901, "text": null }, { "code": null, "e": 27151, "s": 27143, "text": "Output:" }, { "code": null, "e": 27335, "s": 27151, "text": "In the output, we can see that a new column is added to the df named “cume_dist” that contains the cumulative distribution of the Department column which is ordered by the Age column." }, { "code": null, "e": 27483, "s": 27335, "text": "A lag() function is used to access previous rows’ data as per the defined offset value in the function. This function is similar to the LAG in SQL." }, { "code": null, "e": 27491, "s": 27483, "text": "Python3" }, { "code": "# importing lag() from pyspark.sql.functionsfrom pyspark.sql.functions import lag df.withColumn(\"Lag\", lag(\"Salary\", 2).over(windowPartition)) \\ .show()", "e": 27647, "s": 27491, "text": null }, { "code": null, "e": 27655, "s": 27647, "text": "Output:" }, { "code": null, "e": 27912, "s": 27655, "text": "In the output, we can see that lag column is added to the df that contains lag values. In the first 2 rows there is a null value as we have defined offset 2 followed by column Salary in the lag() function. The next rows contain the values of previous rows." }, { "code": null, "e": 28107, "s": 27912, "text": "A lead() function is used to access next rows data as per the defined offset value in the function. This function is similar to the LEAD in SQL and just opposite to lag() function or LAG in SQL." }, { "code": null, "e": 28115, "s": 28107, "text": "Python3" }, { "code": "# importing lead() from pyspark.sql.functionsfrom pyspark.sql.functions import lead df.withColumn(\"Lead\", lead(\"salary\", 2).over(windowPartition)) \\ .show()", "e": 28275, "s": 28115, "text": null }, { "code": null, "e": 28283, "s": 28275, "text": "Output:" }, { "code": null, "e": 28624, "s": 28283, "text": "The function returns the statistical rank of a given value for each row in a partition or group. The goal of this function is to provide consecutive numbering of the rows in the resultant column, set by the order selected in the Window.partition for each partition specified in the OVER clause. E.g. row_number(), rank(), dense_rank(), etc." }, { "code": null, "e": 28662, "s": 28624, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 28926, "s": 28662, "text": "Before we start with these functions, first we need to create a DataFrame. We will create a DataFrame that contains student details like Roll_No, Student_Name, Subject, Marks. After creating the DataFrame we will apply each Ranking function on this DataFrame df2." }, { "code": null, "e": 28934, "s": 28926, "text": "Python3" }, { "code": "# importing pysparkfrom pyspark.sql.window import Windowimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # creating a sparksession object and providing appNamespark = SparkSession.builder.appName(\"pyspark_window\").getOrCreate() # sample data for dataframesampleData = ((101, \"Ram\", \"Biology\", 80), (103, \"Meena\", \"Social Science\", 78), (104, \"Robin\", \"Sanskrit\", 58), (102, \"Kunal\", \"Phisycs\", 89), (101, \"Ram\", \"Biology\", 80), (106, \"Srishti\", \"Maths\", 70), (108, \"Jeny\", \"Physics\", 75), (107, \"Hitesh\", \"Maths\", 88), (109, \"Kailash\", \"Maths\", 90), (105, \"Sharad\", \"Social Science\", 84) ) # column names for dataframecolumns = [\"Roll_No\", \"Student_Name\", \"Subject\", \"Marks\"] # creating the dataframe dfdf2 = spark.createDataFrame(data=sampleData, schema=columns) # importing window from pyspark.sql.window # creating a window partition of dataframewindowPartition = Window.partitionBy(\"Subject\").orderBy(\"Marks\") # print schemadf2.printSchema() # show dfdf2.show()", "e": 30083, "s": 28934, "text": null }, { "code": null, "e": 30091, "s": 30083, "text": "Output:" }, { "code": null, "e": 30173, "s": 30091, "text": "This is the DataFrame df2 on which we will apply all the Window ranking function." }, { "code": null, "e": 30289, "s": 30173, "text": "row_number() function is used to gives a sequential number to each row present in the table. Let’s see the example:" }, { "code": null, "e": 30297, "s": 30289, "text": "Python3" }, { "code": "# importing row_number() from pyspark.sql.functionsfrom pyspark.sql.functions import row_number # applying the row_number() functiondf2.withColumn(\"row_number\", row_number().over(windowPartition)).show()", "e": 30515, "s": 30297, "text": null }, { "code": null, "e": 30524, "s": 30515, "text": "Output: " }, { "code": null, "e": 30699, "s": 30524, "text": "In this output, we can see that we have the row number for each row based on the specified partition i.e. the row numbers are given followed by the Subject and Marks column. " }, { "code": null, "e": 30858, "s": 30699, "text": "The rank function is used to give ranks to rows specified in the window partition. This function leaves gaps in rank if there are ties. Let’s see the example:" }, { "code": null, "e": 30866, "s": 30858, "text": "Python3" }, { "code": "# importing rank() from pyspark.sql.functionsfrom pyspark.sql.functions import rank # applying the rank() functiondf2.withColumn(\"rank\", rank().over(windowPartition)) \\ .show()", "e": 31046, "s": 30866, "text": null }, { "code": null, "e": 31054, "s": 31046, "text": "Output:" }, { "code": null, "e": 31176, "s": 31054, "text": "In the output, the rank is provided to each row as per the Subject and Marks column as specified in the window partition." }, { "code": null, "e": 31303, "s": 31176, "text": "This function is similar to rank() function. It also provides rank to rows but in a percentile format. Let’s see the example: " }, { "code": null, "e": 31311, "s": 31303, "text": "Python3" }, { "code": "# importing percent_rank() from pyspark.sql.functionsfrom pyspark.sql.functions import percent_rank # applying the percent_rank() functiondf2.withColumn(\"percent_rank\", percent_rank().over(windowPartition)).show()", "e": 31539, "s": 31311, "text": null }, { "code": null, "e": 31547, "s": 31539, "text": "Output:" }, { "code": null, "e": 31658, "s": 31547, "text": "We can see that in the output the rank column contains values in a percentile form i.e. in the decimal format." }, { "code": null, "e": 31883, "s": 31658, "text": "This function is used to get the rank of each row in the form of row numbers. This is similar to rank() function, there is only one difference the rank function leaves gaps in rank when there are ties. Let’s see the example:" }, { "code": null, "e": 31891, "s": 31883, "text": "Python3" }, { "code": "# importing dense_rank() from pyspark.sql.functionsfrom pyspark.sql.functions import dense_rank # applying the dense_rank() functiondf2.withColumn(\"dense_rank\", dense_rank().over(windowPartition)).show()", "e": 32109, "s": 31891, "text": null }, { "code": null, "e": 32118, "s": 32109, "text": "Output: " }, { "code": null, "e": 32198, "s": 32118, "text": "In the output, we can see that the ranks are given in the form of row numbers. " }, { "code": null, "e": 32472, "s": 32198, "text": "An aggregate function or aggregation function is a function where the values of multiple rows are grouped to form a single summary value. The definition of the groups of rows on which they operate is done by using the SQL GROUP BY clause. E.g. AVERAGE, SUM, MIN, MAX, etc. " }, { "code": null, "e": 32510, "s": 32472, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 32740, "s": 32510, "text": "Before we start with these functions, we will create a new DataFrame that contains employee details like Employee_Name, Department, and Salary. After creating the DataFrame we will apply each Aggregate function on this DataFrame." }, { "code": null, "e": 32748, "s": 32740, "text": "Python3" }, { "code": "# importing pysparkimport pyspark # importing sparksessiofrom pyspark.sql import SparkSession # creating a sparksession# object and providing appNamespark = SparkSession.builder.appName(\"pyspark_window\").getOrCreate() # sample data for dataframesampleData = ((\"Ram\", \"Sales\", 3000), (\"Meena\", \"Sales\", 4600), (\"Robin\", \"Sales\", 4100), (\"Kunal\", \"Finance\", 3000), (\"Ram\", \"Sales\", 3000), (\"Srishti\", \"Management\", 3300), (\"Jeny\", \"Finance\", 3900), (\"Hitesh\", \"Marketing\", 3000), (\"Kailash\", \"Marketing\", 2000), (\"Sharad\", \"Sales\", 4100) ) # column names for dataframecolumns = [\"Employee_Name\", \"Department\", \"Salary\"] # creating the dataframe dfdf3 = spark.createDataFrame(data=sampleData, schema=columns) # print schemadf3.printSchema() # show dfdf3.show()", "e": 33663, "s": 32748, "text": null }, { "code": null, "e": 33671, "s": 33663, "text": "Output:" }, { "code": null, "e": 33749, "s": 33671, "text": "This is the DataFrame df3 on which we will apply all the aggregate functions." }, { "code": null, "e": 33757, "s": 33749, "text": "Python3" }, { "code": "# importing window from pyspark.sql.windowfrom pyspark.sql.window import Window # importing aggregate functions# from pyspark.sql.functionsfrom pyspark.sql.functions import col,avg,sum,min,max,row_number # creating a window partition of dataframewindowPartitionAgg = Window.partitionBy(\"Department\") # applying window aggregate function# to df3 with the help of withColumn # this is average()df3.withColumn(\"Avg\", avg(col(\"salary\")).over(windowPartitionAgg)) #this is sum() .withColumn(\"Sum\", sum(col(\"salary\")).over(windowPartitionAgg)) #this is min() .withColumn(\"Min\", min(col(\"salary\")).over(windowPartitionAgg)) #this is max() .withColumn(\"Max\", max(col(\"salary\")).over(windowPartitionAgg)).show()", "e": 34526, "s": 33757, "text": null }, { "code": null, "e": 34535, "s": 34526, "text": "Output: " }, { "code": null, "e": 34858, "s": 34535, "text": "In the output df, we can see that there are four new columns added to df. In the code, we have applied all the four aggregate functions one by one. We got four output columns added to the df3 that contains values for each row. These four columns contain the Average, Sum, Minimum, and Maximum values of the Salary column." }, { "code": null, "e": 34877, "s": 34860, "text": "akshaysingh98088" }, { "code": null, "e": 34884, "s": 34877, "text": "Picked" }, { "code": null, "e": 34899, "s": 34884, "text": "Python-Pyspark" }, { "code": null, "e": 34906, "s": 34899, "text": "Python" }, { "code": null, "e": 35004, "s": 34906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35013, "s": 35004, "text": "Comments" }, { "code": null, "e": 35026, "s": 35013, "text": "Old Comments" }, { "code": null, "e": 35058, "s": 35026, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 35114, "s": 35058, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 35156, "s": 35114, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 35198, "s": 35156, "text": "Check if element exists in list in Python" }, { "code": null, "e": 35234, "s": 35198, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 35273, "s": 35234, "text": "Python | Get unique values from a list" }, { "code": null, "e": 35295, "s": 35273, "text": "Defaultdict in Python" }, { "code": null, "e": 35326, "s": 35295, "text": "Python | os.path.join() method" }, { "code": null, "e": 35353, "s": 35326, "text": "Python Classes and Objects" } ]
C Program To Check If A Singly Linked List Is Palindrome - GeeksforGeeks
24 Dec, 2021 Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false. METHOD 1 (By reversing the list): This method takes O(n) time and O(1) extra space. 1) Get the middle of the linked list. 2) Reverse the second half of the linked list. 3) Check if the first half and second half are identical. 4) Construct the original linked list by reversing the second half again and attaching it back to the first half To divide the list into two halves, method 2 of this post is used. When a number of nodes are even, the first and second half contain exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don’t want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable ‘midnode’. C // C++ program to check if a linked list// is palindrome#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // Link list nodestruct Node{ char data; struct Node* next;}; void reverse(struct Node**);bool compareLists(struct Node*, struct Node*); // Function to check if given linked// list is palindrome or notbool isPalindrome(struct Node* head){ struct Node *slow_ptr = head, *fast_ptr = head; struct Node *second_half, *prev_of_slow_ptr = head; // To handle odd size list struct Node* midnode = NULL; // Initialize result bool res = true; if (head != NULL && head->next != NULL) { // Get the middle of the list. // Move slow_ptr by 1 and // fast_ptrr by 2, slow_ptr // will have the middle node while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; // We need previous of the slow_ptr for // linked lists with odd elements prev_of_slow_ptr = slow_ptr; slow_ptr = slow_ptr->next; } /* fast_ptr would become NULL when there are even elements in list. And not NULL for odd elements. We need to skip the middle node for odd case and store it somewhere so that we can restore the original list*/ if (fast_ptr != NULL) { midnode = slow_ptr; slow_ptr = slow_ptr->next; } // Now reverse the second half and // compare it with first half second_half = slow_ptr; // NULL terminate first half prev_of_slow_ptr->next = NULL; // Reverse the second half reverse(&second_half); // Compare res = compareLists(head, second_half); // Construct the original list back // Reverse the second half again reverse(&second_half); // If there was a mid node (odd size // case) which was not part of either // first half or second half. if (midnode != NULL) { prev_of_slow_ptr->next = midnode; midnode->next = second_half; } else prev_of_slow_ptr->next = second_half; } return res;} // Function to reverse the linked list// Note that this function may change// the headvoid reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev;} // Function to check if two input// lists have same databool compareLists(struct Node* head1, struct Node* head2){ struct Node* temp1 = head1; struct Node* temp2 = head2; while (temp1 && temp2) { if (temp1->data == temp2->data) { temp1 = temp1->next; temp2 = temp2->next; } else return 0; } // Both are empty return 1 if (temp1 == NULL && temp2 == NULL) return 1; // Will reach here when one is NULL // and other is not return 0;} // Push a node to linked list.// Note that this function// changes the headvoid push(struct Node** head_ref, char new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // A utility function to print a// given linked listvoid printList(struct Node* ptr){ while (ptr != NULL) { printf("%c->", ptr->data); ptr = ptr->next; } printf("NULL");} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; char str[] = "abacaba"; int i; for (i = 0; str[i] != ''; i++) { push(&head, str[i]); printList(head); isPalindrome(head) ? printf("Is Palindrome") : printf("Not Palindrome"); } return 0;} Output: a->NULL Is Palindrome b->a->NULL Not Palindrome a->b->a->NULL Is Palindrome c->a->b->a->NULL Not Palindrome a->c->a->b->a->NULL Not Palindrome b->a->c->a->b->a->NULL Not Palindrome a->b->a->c->a->b->a->NULL Is Palindrome Time Complexity: O(n) Auxiliary Space: O(1) METHOD 2 (Using Recursion): Use two pointers left and right. Move right and left using recursion and check for following in each recursive call. 1) Sub-list is a palindrome. 2) Value at current left and right are matching. If both above conditions are true then return true. The idea is to use function call stack as a container. Recursively traverse till the end of the list. When we return from the last NULL, we will be at the last node. The last node is to be compared with the first node of the list. In order to access the first node of the list, we need the list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need a reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.Thanks to Sharad Chandra for suggesting this approach. C // Recursive program to check if a// given linked list is palindrome#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // Link list nodestruct node{ char data; struct node* next;}; // Initial parameters to this// function are &head and headbool isPalindromeUtil(struct node** left, struct node* right){ // Stop recursion when right // becomes NULL if (right == NULL) return true; // If sub-list is not palindrome then // no need to check for current left // and right, return false bool isp = isPalindromeUtil(left, right->next); if (isp == false) return false; // Check values at current left and right bool isp1 = (right->data == (*left)->data); // Move left to next node *left = (*left)->next; return isp1;} // A wrapper over isPalindromeUtil()bool isPalindrome(struct node* head){ isPalindromeUtil(&head, head);} // Push a node to linked list.// Note that this function changes// the headvoid push(struct node** head_ref, char new_data){ // Allocate node struct node* new_node = (struct node*)malloc(sizeof(struct node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // A utility function to print a// given linked listvoid printList(struct node* ptr){ while (ptr != NULL) { printf("%c->", ptr->data); ptr = ptr->next; } printf("NULL\n");} // Driver codeint main(){ // Start with the empty list struct node* head = NULL; char str[] = "abacaba"; int i; for (i = 0; str[i] != '\0'; i++) { push(&head, str[i]); printList(head); isPalindrome(head) ? printf("Is Palindrome\n\n") : printf("Not Palindrome\n\n"); } return 0;} Output: a->NULL Not Palindrome b->a->NULL Not Palindrome a->b->a->NULL Is Palindrome c->a->b->a->NULL Not Palindrome a->c->a->b->a->NULL Not Palindrome b->a->c->a->b->a->NULL Not Palindrome a->b->a->c->a->b->a->NULL Is Palindrome Time Complexity: O(n) Auxiliary Space: O(n) if Function Call Stack size is considered, otherwise O(1). Please refer complete article on Function to check if a singly linked list is palindrome for more details! saurabh1990aror sagartomar9927 Accolite Adobe Amazon KLA Tencor Kritikal Solutions Linked Lists Microsoft palindrome Snapdeal Yodlee Infotech C Language C Programs Linked List Accolite Amazon Microsoft Snapdeal Adobe Yodlee Infotech KLA Tencor Kritikal Solutions Linked List palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C Arrow operator -> in C/C++ with Examples 'this' pointer in C++ Strings in C Arrow operator -> in C/C++ with Examples C Program to read contents of Whole File UDP Server-Client implementation in C Header files in C/C++ and its uses
[ { "code": null, "e": 23895, "s": 23867, "text": "\n24 Dec, 2021" }, { "code": null, "e": 24019, "s": 23895, "text": "Given a singly linked list of characters, write a function that returns true if the given list is a palindrome, else false." }, { "code": null, "e": 24359, "s": 24019, "text": "METHOD 1 (By reversing the list): This method takes O(n) time and O(1) extra space. 1) Get the middle of the linked list. 2) Reverse the second half of the linked list. 3) Check if the first half and second half are identical. 4) Construct the original linked list by reversing the second half again and attaching it back to the first half" }, { "code": null, "e": 24427, "s": 24359, "text": "To divide the list into two halves, method 2 of this post is used. " }, { "code": null, "e": 24756, "s": 24427, "text": "When a number of nodes are even, the first and second half contain exactly half nodes. The challenging thing in this method is to handle the case when the number of nodes is odd. We don’t want the middle node as part of the lists as we are going to compare them for equality. For odd cases, we use a separate variable ‘midnode’." }, { "code": null, "e": 24758, "s": 24756, "text": "C" }, { "code": "// C++ program to check if a linked list// is palindrome#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // Link list nodestruct Node{ char data; struct Node* next;}; void reverse(struct Node**);bool compareLists(struct Node*, struct Node*); // Function to check if given linked// list is palindrome or notbool isPalindrome(struct Node* head){ struct Node *slow_ptr = head, *fast_ptr = head; struct Node *second_half, *prev_of_slow_ptr = head; // To handle odd size list struct Node* midnode = NULL; // Initialize result bool res = true; if (head != NULL && head->next != NULL) { // Get the middle of the list. // Move slow_ptr by 1 and // fast_ptrr by 2, slow_ptr // will have the middle node while (fast_ptr != NULL && fast_ptr->next != NULL) { fast_ptr = fast_ptr->next->next; // We need previous of the slow_ptr for // linked lists with odd elements prev_of_slow_ptr = slow_ptr; slow_ptr = slow_ptr->next; } /* fast_ptr would become NULL when there are even elements in list. And not NULL for odd elements. We need to skip the middle node for odd case and store it somewhere so that we can restore the original list*/ if (fast_ptr != NULL) { midnode = slow_ptr; slow_ptr = slow_ptr->next; } // Now reverse the second half and // compare it with first half second_half = slow_ptr; // NULL terminate first half prev_of_slow_ptr->next = NULL; // Reverse the second half reverse(&second_half); // Compare res = compareLists(head, second_half); // Construct the original list back // Reverse the second half again reverse(&second_half); // If there was a mid node (odd size // case) which was not part of either // first half or second half. if (midnode != NULL) { prev_of_slow_ptr->next = midnode; midnode->next = second_half; } else prev_of_slow_ptr->next = second_half; } return res;} // Function to reverse the linked list// Note that this function may change// the headvoid reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; while (current != NULL) { next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev;} // Function to check if two input// lists have same databool compareLists(struct Node* head1, struct Node* head2){ struct Node* temp1 = head1; struct Node* temp2 = head2; while (temp1 && temp2) { if (temp1->data == temp2->data) { temp1 = temp1->next; temp2 = temp2->next; } else return 0; } // Both are empty return 1 if (temp1 == NULL && temp2 == NULL) return 1; // Will reach here when one is NULL // and other is not return 0;} // Push a node to linked list.// Note that this function// changes the headvoid push(struct Node** head_ref, char new_data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // A utility function to print a// given linked listvoid printList(struct Node* ptr){ while (ptr != NULL) { printf(\"%c->\", ptr->data); ptr = ptr->next; } printf(\"NULL\");} // Driver codeint main(){ // Start with the empty list struct Node* head = NULL; char str[] = \"abacaba\"; int i; for (i = 0; str[i] != ''; i++) { push(&head, str[i]); printList(head); isPalindrome(head) ? printf(\"Is Palindrome\") : printf(\"Not Palindrome\"); } return 0;}", "e": 28915, "s": 24758, "text": null }, { "code": null, "e": 28924, "s": 28915, "text": "Output: " }, { "code": null, "e": 29151, "s": 28924, "text": "a->NULL\nIs Palindrome\n\nb->a->NULL\nNot Palindrome\n\na->b->a->NULL\nIs Palindrome\n\nc->a->b->a->NULL\nNot Palindrome\n\na->c->a->b->a->NULL\nNot Palindrome\n\nb->a->c->a->b->a->NULL\nNot Palindrome\n\na->b->a->c->a->b->a->NULL\nIs Palindrome" }, { "code": null, "e": 29197, "s": 29151, "text": "Time Complexity: O(n) Auxiliary Space: O(1) " }, { "code": null, "e": 29420, "s": 29197, "text": "METHOD 2 (Using Recursion): Use two pointers left and right. Move right and left using recursion and check for following in each recursive call. 1) Sub-list is a palindrome. 2) Value at current left and right are matching." }, { "code": null, "e": 29472, "s": 29420, "text": "If both above conditions are true then return true." }, { "code": null, "e": 29703, "s": 29472, "text": "The idea is to use function call stack as a container. Recursively traverse till the end of the list. When we return from the last NULL, we will be at the last node. The last node is to be compared with the first node of the list." }, { "code": null, "e": 30424, "s": 29703, "text": "In order to access the first node of the list, we need the list head to be available in the last call of recursion. Hence, we pass head also to the recursive function. If they both match we need to compare (2, n-2) nodes. Again when recursion falls back to (n-2)nd node, we need a reference to 2nd node from the head. We advance the head pointer in the previous call, to refer to the next node in the list.However, the trick is identifying a double-pointer. Passing a single pointer is as good as pass-by-value, and we will pass the same pointer again and again. We need to pass the address of the head pointer for reflecting the changes in parent recursive calls.Thanks to Sharad Chandra for suggesting this approach. " }, { "code": null, "e": 30426, "s": 30424, "text": "C" }, { "code": "// Recursive program to check if a// given linked list is palindrome#include <stdbool.h>#include <stdio.h>#include <stdlib.h> // Link list nodestruct node{ char data; struct node* next;}; // Initial parameters to this// function are &head and headbool isPalindromeUtil(struct node** left, struct node* right){ // Stop recursion when right // becomes NULL if (right == NULL) return true; // If sub-list is not palindrome then // no need to check for current left // and right, return false bool isp = isPalindromeUtil(left, right->next); if (isp == false) return false; // Check values at current left and right bool isp1 = (right->data == (*left)->data); // Move left to next node *left = (*left)->next; return isp1;} // A wrapper over isPalindromeUtil()bool isPalindrome(struct node* head){ isPalindromeUtil(&head, head);} // Push a node to linked list.// Note that this function changes// the headvoid push(struct node** head_ref, char new_data){ // Allocate node struct node* new_node = (struct node*)malloc(sizeof(struct node)); // Put in the data new_node->data = new_data; // Link the old list off the new node new_node->next = (*head_ref); // Move the head to point to the new node (*head_ref) = new_node;} // A utility function to print a// given linked listvoid printList(struct node* ptr){ while (ptr != NULL) { printf(\"%c->\", ptr->data); ptr = ptr->next; } printf(\"NULL\\n\");} // Driver codeint main(){ // Start with the empty list struct node* head = NULL; char str[] = \"abacaba\"; int i; for (i = 0; str[i] != '\\0'; i++) { push(&head, str[i]); printList(head); isPalindrome(head) ? printf(\"Is Palindrome\\n\\n\") : printf(\"Not Palindrome\\n\\n\"); } return 0;}", "e": 32328, "s": 30426, "text": null }, { "code": null, "e": 32337, "s": 32328, "text": "Output: " }, { "code": null, "e": 32565, "s": 32337, "text": "a->NULL\nNot Palindrome\n\nb->a->NULL\nNot Palindrome\n\na->b->a->NULL\nIs Palindrome\n\nc->a->b->a->NULL\nNot Palindrome\n\na->c->a->b->a->NULL\nNot Palindrome\n\nb->a->c->a->b->a->NULL\nNot Palindrome\n\na->b->a->c->a->b->a->NULL\nIs Palindrome" }, { "code": null, "e": 32668, "s": 32565, "text": "Time Complexity: O(n) Auxiliary Space: O(n) if Function Call Stack size is considered, otherwise O(1)." }, { "code": null, "e": 32776, "s": 32668, "text": "Please refer complete article on Function to check if a singly linked list is palindrome for more details! " }, { "code": null, "e": 32792, "s": 32776, "text": "saurabh1990aror" }, { "code": null, "e": 32807, "s": 32792, "text": "sagartomar9927" }, { "code": null, "e": 32816, "s": 32807, "text": "Accolite" }, { "code": null, "e": 32822, "s": 32816, "text": "Adobe" }, { "code": null, "e": 32829, "s": 32822, "text": "Amazon" }, { "code": null, "e": 32840, "s": 32829, "text": "KLA Tencor" }, { "code": null, "e": 32859, "s": 32840, "text": "Kritikal Solutions" }, { "code": null, "e": 32872, "s": 32859, "text": "Linked Lists" }, { "code": null, "e": 32882, "s": 32872, "text": "Microsoft" }, { "code": null, "e": 32893, "s": 32882, "text": "palindrome" }, { "code": null, "e": 32902, "s": 32893, "text": "Snapdeal" }, { "code": null, "e": 32918, "s": 32902, "text": "Yodlee Infotech" }, { "code": null, "e": 32929, "s": 32918, "text": "C Language" }, { "code": null, "e": 32940, "s": 32929, "text": "C Programs" }, { "code": null, "e": 32952, "s": 32940, "text": "Linked List" }, { "code": null, "e": 32961, "s": 32952, "text": "Accolite" }, { "code": null, "e": 32968, "s": 32961, "text": "Amazon" }, { "code": null, "e": 32978, "s": 32968, "text": "Microsoft" }, { "code": null, "e": 32987, "s": 32978, "text": "Snapdeal" }, { "code": null, "e": 32993, "s": 32987, "text": "Adobe" }, { "code": null, "e": 33009, "s": 32993, "text": "Yodlee Infotech" }, { "code": null, "e": 33020, "s": 33009, "text": "KLA Tencor" }, { "code": null, "e": 33039, "s": 33020, "text": "Kritikal Solutions" }, { "code": null, "e": 33051, "s": 33039, "text": "Linked List" }, { "code": null, "e": 33062, "s": 33051, "text": "palindrome" }, { "code": null, "e": 33160, "s": 33062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33169, "s": 33160, "text": "Comments" }, { "code": null, "e": 33182, "s": 33169, "text": "Old Comments" }, { "code": null, "e": 33220, "s": 33182, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 33246, "s": 33220, "text": "Exception Handling in C++" }, { "code": null, "e": 33266, "s": 33246, "text": "Multithreading in C" }, { "code": null, "e": 33307, "s": 33266, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33329, "s": 33307, "text": "'this' pointer in C++" }, { "code": null, "e": 33342, "s": 33329, "text": "Strings in C" }, { "code": null, "e": 33383, "s": 33342, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33424, "s": 33383, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 33462, "s": 33424, "text": "UDP Server-Client implementation in C" } ]
Interactive Visualization of Decision Trees with Jupyter Widgets | by Dafni Sidiropoulou Velidou | Towards Data Science
Decision Trees are broadly used supervised models for classification and regression tasks. In this article, we will talk about decision tree classifiers and how we can dynamically visualize them. These classifiers build a sequence of simple if/else rules on the training data through which they predict the target value. Decision trees are simple to interpret due to their structure and the ability we have to visualize the modeled tree. Using sklearn export_graphviz function we can display the tree within a Jupyter notebook. For this demonstration, we will use the sklearn wine data set. from sklearn.tree import DecisionTreeClassifier, export_graphvizfrom sklearn import treefrom sklearn.datasets import load_winefrom IPython.display import SVGfrom graphviz import Sourcefrom IPython.display import display# load datasetdata = load_wine()# feature matrixX = data.data# target vectory = data.target# class labelslabels = data.feature_names# print dataset descriptionprint(data.DESCR)estimator = DecisionTreeClassifier()estimator.fit(X, y)graph = Source(tree.export_graphviz(estimator, out_file=None , feature_names=labels, class_names=['0', '1', '2'] , filled = True))display(SVG(graph.pipe(format='svg'))) In the tree plot, each node contains the condition (if/else rule) that splits the data, along with a series of other metrics of the node. Gini refers to the Gini impurity, a measure of the impurity of the node, i.e. how homogeneous are the samples within the node. We say that a node is pure when all its samples belong to the same class. In that case, there is no need for further split and this node is called a leaf. Samples is the number of instances in the node, while the value array shows the distribution of these instances per class. At the bottom we see the majority class of the node. When filled option of export_graphviz is set to True each node gets colored according to the majority class. While easy to understand, decision trees tend to over-fit the data, by constructing complex models. Over fitted models will most likely not generalize well in “unseen” data. Two main approaches to prevent over-fitting are pre and post-pruning. Pre-pruning means restricting the depth of a tree prior to creation while post-pruning is removing non-informative nodes after the tree has been built. Sklearn learn decision tree classifier implements only pre-pruning. Pre-pruning can be controlled through several parameters such as the maximum depth of the tree, the minimum number of samples required for a node to keep splitting and the minimum number of instances required for a leaf . Below, we plot a decision tree on the same data, this time setting max_depth = 3. This model is less deep and thus less complex than the one we trained and plotted initially. Other than pre-pruning parameters, a decision tree has a series of other parameters that we try to optimize whenever building a classification model. We usually assess the effect of these parameters by looking at accuracy metrics. To get a grasp of how changes in parameters affect the structure of the tree we could again visualize a tree at each stage. Instead of plotting a tree each time we make a change, we can make use of Jupyter Widgets (ipywidgets) to build an interactive plot of our tree. Jupyter widgets are interactive elements that allow us to render controls inside the notebook. There are two options to install ipywidgets, through pip and conda. With pip pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension With conda conda install -c conda-forge ipywidgets For this application, we will use the interactive function. First, we define a function that trains and plots a decision tree. Then, we pass this function along with a set of values for each of the parameters of interest to the interactive function. The latter returns a Widget instance that we show with display. from sklearn.tree import DecisionTreeClassifier, export_graphvizfrom sklearn import treefrom sklearn.datasets import load_winefrom IPython.display import SVGfrom graphviz import Sourcefrom IPython.display import display from ipywidgets import interactive# load datasetdata = load_wine()# feature matrixX = data.data# target vectory = data.target# class labelslabels = data.feature_namesdef plot_tree(crit, split, depth, min_split, min_leaf=0.2):estimator = DecisionTreeClassifier(random_state = 0 , criterion = crit , splitter = split , max_depth = depth , min_samples_split=min_split , min_samples_leaf=min_leaf) estimator.fit(X, y)graph = Source(tree.export_graphviz(estimator , out_file=None , feature_names=labels , class_names=['0', '1', '2'] , filled = True)) display(SVG(graph.pipe(format='svg')))return estimatorinter=interactive(plot_tree , crit = ["gini", "entropy"] , split = ["best", "random"] , depth=[1,2,3,4] , min_split=(0.1,1) , min_leaf=(0.1,0.5))display(inter) In this example, we expose the following parameters: criterion: measure of the quality of split at the nodes splitter: the split strategy at each node max_depth: the maximum depth of the tree min_samples_split: the minimum required number of instances in a node min_samples_leaf: the minimum required number of instances at a leaf node The last two parameters can be set either as integers or floats. Floats are interpreted as percentages of the total number of instances. For more details on the parameters you can read the sklearn class documentation. This interactive widget allows us to modify the tree parameters and see the plot change dynamically. Through this interaction we are able to get a grasp of the effect of each parameter, by revealing the resulting change at each step. Although this is not a tool for model performance assessment or parameter tuning, it has several benefits. It can serve as a means of assessing the complexity of our model, through the inspection of depth, number of nodes and purity of leaves. On the other hand, it can give us useful insights on the data, as we see how many and which features the tree has used. In addition, we might be able to discover conditions that clearly distinguish our samples into the different classes. In conclusion, I find this interactive visualization a fun tool to get a deeper understanding of the abstract process of building a decision tree, detached from a particular data set, that will give us a head start next time we build a decision tree for one of our projects!
[ { "code": null, "e": 610, "s": 172, "text": "Decision Trees are broadly used supervised models for classification and regression tasks. In this article, we will talk about decision tree classifiers and how we can dynamically visualize them. These classifiers build a sequence of simple if/else rules on the training data through which they predict the target value. Decision trees are simple to interpret due to their structure and the ability we have to visualize the modeled tree." }, { "code": null, "e": 763, "s": 610, "text": "Using sklearn export_graphviz function we can display the tree within a Jupyter notebook. For this demonstration, we will use the sklearn wine data set." }, { "code": null, "e": 1387, "s": 763, "text": "from sklearn.tree import DecisionTreeClassifier, export_graphvizfrom sklearn import treefrom sklearn.datasets import load_winefrom IPython.display import SVGfrom graphviz import Sourcefrom IPython.display import display# load datasetdata = load_wine()# feature matrixX = data.data# target vectory = data.target# class labelslabels = data.feature_names# print dataset descriptionprint(data.DESCR)estimator = DecisionTreeClassifier()estimator.fit(X, y)graph = Source(tree.export_graphviz(estimator, out_file=None , feature_names=labels, class_names=['0', '1', '2'] , filled = True))display(SVG(graph.pipe(format='svg')))" }, { "code": null, "e": 2092, "s": 1387, "text": "In the tree plot, each node contains the condition (if/else rule) that splits the data, along with a series of other metrics of the node. Gini refers to the Gini impurity, a measure of the impurity of the node, i.e. how homogeneous are the samples within the node. We say that a node is pure when all its samples belong to the same class. In that case, there is no need for further split and this node is called a leaf. Samples is the number of instances in the node, while the value array shows the distribution of these instances per class. At the bottom we see the majority class of the node. When filled option of export_graphviz is set to True each node gets colored according to the majority class." }, { "code": null, "e": 2488, "s": 2092, "text": "While easy to understand, decision trees tend to over-fit the data, by constructing complex models. Over fitted models will most likely not generalize well in “unseen” data. Two main approaches to prevent over-fitting are pre and post-pruning. Pre-pruning means restricting the depth of a tree prior to creation while post-pruning is removing non-informative nodes after the tree has been built." }, { "code": null, "e": 2860, "s": 2488, "text": "Sklearn learn decision tree classifier implements only pre-pruning. Pre-pruning can be controlled through several parameters such as the maximum depth of the tree, the minimum number of samples required for a node to keep splitting and the minimum number of instances required for a leaf . Below, we plot a decision tree on the same data, this time setting max_depth = 3." }, { "code": null, "e": 2953, "s": 2860, "text": "This model is less deep and thus less complex than the one we trained and plotted initially." }, { "code": null, "e": 3453, "s": 2953, "text": "Other than pre-pruning parameters, a decision tree has a series of other parameters that we try to optimize whenever building a classification model. We usually assess the effect of these parameters by looking at accuracy metrics. To get a grasp of how changes in parameters affect the structure of the tree we could again visualize a tree at each stage. Instead of plotting a tree each time we make a change, we can make use of Jupyter Widgets (ipywidgets) to build an interactive plot of our tree." }, { "code": null, "e": 3616, "s": 3453, "text": "Jupyter widgets are interactive elements that allow us to render controls inside the notebook. There are two options to install ipywidgets, through pip and conda." }, { "code": null, "e": 3625, "s": 3616, "text": "With pip" }, { "code": null, "e": 3698, "s": 3625, "text": "pip install ipywidgetsjupyter nbextension enable --py widgetsnbextension" }, { "code": null, "e": 3709, "s": 3698, "text": "With conda" }, { "code": null, "e": 3749, "s": 3709, "text": "conda install -c conda-forge ipywidgets" }, { "code": null, "e": 4063, "s": 3749, "text": "For this application, we will use the interactive function. First, we define a function that trains and plots a decision tree. Then, we pass this function along with a set of values for each of the parameters of interest to the interactive function. The latter returns a Widget instance that we show with display." }, { "code": null, "e": 5139, "s": 4063, "text": "from sklearn.tree import DecisionTreeClassifier, export_graphvizfrom sklearn import treefrom sklearn.datasets import load_winefrom IPython.display import SVGfrom graphviz import Sourcefrom IPython.display import display from ipywidgets import interactive# load datasetdata = load_wine()# feature matrixX = data.data# target vectory = data.target# class labelslabels = data.feature_namesdef plot_tree(crit, split, depth, min_split, min_leaf=0.2):estimator = DecisionTreeClassifier(random_state = 0 , criterion = crit , splitter = split , max_depth = depth , min_samples_split=min_split , min_samples_leaf=min_leaf) estimator.fit(X, y)graph = Source(tree.export_graphviz(estimator , out_file=None , feature_names=labels , class_names=['0', '1', '2'] , filled = True)) display(SVG(graph.pipe(format='svg')))return estimatorinter=interactive(plot_tree , crit = [\"gini\", \"entropy\"] , split = [\"best\", \"random\"] , depth=[1,2,3,4] , min_split=(0.1,1) , min_leaf=(0.1,0.5))display(inter)" }, { "code": null, "e": 5192, "s": 5139, "text": "In this example, we expose the following parameters:" }, { "code": null, "e": 5248, "s": 5192, "text": "criterion: measure of the quality of split at the nodes" }, { "code": null, "e": 5290, "s": 5248, "text": "splitter: the split strategy at each node" }, { "code": null, "e": 5331, "s": 5290, "text": "max_depth: the maximum depth of the tree" }, { "code": null, "e": 5401, "s": 5331, "text": "min_samples_split: the minimum required number of instances in a node" }, { "code": null, "e": 5475, "s": 5401, "text": "min_samples_leaf: the minimum required number of instances at a leaf node" }, { "code": null, "e": 5693, "s": 5475, "text": "The last two parameters can be set either as integers or floats. Floats are interpreted as percentages of the total number of instances. For more details on the parameters you can read the sklearn class documentation." }, { "code": null, "e": 5927, "s": 5693, "text": "This interactive widget allows us to modify the tree parameters and see the plot change dynamically. Through this interaction we are able to get a grasp of the effect of each parameter, by revealing the resulting change at each step." }, { "code": null, "e": 6409, "s": 5927, "text": "Although this is not a tool for model performance assessment or parameter tuning, it has several benefits. It can serve as a means of assessing the complexity of our model, through the inspection of depth, number of nodes and purity of leaves. On the other hand, it can give us useful insights on the data, as we see how many and which features the tree has used. In addition, we might be able to discover conditions that clearly distinguish our samples into the different classes." } ]
How to extract first value from a list in R?
To extract first value from a list, we first need to access the element using double square brackets then the sub-element of each element will be accessed using single square brackets. For example, if we have a list called LIST containing five elements each having 10 elements then the first sub-element of the LIST will be selected by using LIST[[1]][1]. Live Demo List1<-list(x1=rnorm(50),x2=rnorm(50)) List1 $x1 [1] 0.11130222 0.16419755 -0.52346744 2.06291702 1.75401221 1.76745535 [7] 2.07647670 0.20604988 0.88090037 0.45002361 -0.41997558 0.13069306 [13] 1.03792793 0.60365638 -0.86619055 -0.94122172 0.64561932 0.50256648 [19] -0.61076372 0.90286990 -0.03448342 1.52897744 -0.12000996 0.07482846 [25] -1.12145357 0.76479988 0.59701522 1.46033578 -0.57620173 -1.17224749 [31] -0.73289297 -1.03691038 -1.28427938 -0.33767539 -1.01044720 0.22021704 [37] 0.67931259 1.79052238 -0.80291917 -0.21613130 0.58112656 0.74238488 [43] -0.37718519 1.31974664 2.33329258 0.33576900 -1.05233449 0.90282079 [49] -0.23821323 -2.18185932 $x2 [1] 0.34801958 -0.24730876 -0.64642026 -0.20068985 0.94328680 -0.35876719 [7] -0.65250327 -0.26434726 0.80161224 -1.98861577 -0.55784172 2.72095292 [13] -0.34377048 -1.41075225 -0.58016709 0.30349424 -0.10171845 -1.63588095 [19] 0.69116860 1.45962094 1.68120904 0.35287888 2.16297295 1.96956313 [25] 0.20567607 0.39924676 0.18837752 -2.34209766 -0.49420627 -0.19967231 [31] -0.06452823 -0.31314817 0.34765525 -0.31236504 -2.01858040 0.09302232 [37] -0.07158963 0.91019112 -0.74267435 -0.40049302 0.18465365 0.65059368 [43] 0.61031556 -0.23870247 -1.63562822 0.37430717 0.98758801 -0.09859013 [49] 0.29618676 0.66022211 List1[[1]][1] [1] 0.1113022 List1[[2]][1] [1] 0.3480196 Live Demo List2<-list(y1=rpois(100,5),y2=rpois(100,5),y3=rpois(100,5),y4=rpois(100,5)) List2 $y1 [1] 0 6 10 5 7 1 8 8 4 4 1 5 7 5 5 10 2 4 4 2 3 5 3 2 2 [26] 5 4 12 4 4 5 4 4 6 6 5 7 10 1 3 9 4 6 3 7 6 4 3 6 5 [51] 8 5 8 5 7 3 4 5 7 6 6 3 5 5 5 1 0 4 7 3 4 7 6 6 3 [76] 3 3 4 3 5 6 4 6 3 4 4 6 7 8 4 3 10 11 6 8 8 6 6 7 4 $y2 [1] 7 7 11 4 4 1 4 7 2 6 2 2 6 2 2 6 3 3 6 2 5 6 6 5 6 [26] 6 1 9 1 1 8 3 5 3 5 6 6 4 4 6 3 9 3 4 5 4 8 6 2 6 [51] 6 2 8 8 8 5 4 1 3 7 8 6 6 10 6 8 5 2 4 7 4 8 4 3 8 [76] 3 3 7 7 7 2 9 3 5 8 3 5 5 7 2 9 8 7 5 2 3 5 7 7 8 $y3 [1] 5 5 3 5 2 6 7 3 3 5 3 6 5 7 3 7 4 5 5 4 5 9 4 1 2 [26] 4 5 5 5 5 4 3 2 6 8 4 13 6 4 6 7 5 5 6 2 3 6 4 4 6 [51] 3 3 6 11 5 7 8 3 3 5 7 3 1 5 4 9 6 7 5 3 6 6 5 6 6 [76] 6 6 2 12 2 1 7 3 6 4 5 4 3 4 3 5 6 4 3 8 6 7 7 7 5 $y4 [1] 6 7 4 6 6 1 7 6 2 6 10 7 5 9 9 3 6 6 10 4 7 4 2 4 10 [26] 6 9 3 3 2 6 5 4 4 3 6 5 3 6 3 7 7 1 4 3 5 10 6 7 4 [51] 5 3 6 8 3 5 4 5 5 5 6 3 4 10 5 3 7 5 5 7 4 4 3 5 6 [76] 4 4 6 9 3 10 12 7 4 9 7 14 10 1 4 4 3 3 6 1 5 2 8 4 7 List2[[1]][1] [1] 0 List2[[2]][1] [1] 7 List2[[3]][1] [1] 5 List2[[4]][1] List2[[4]][1] Live Demo List3<-list(z1=rexp(50),z2=rexp(50),z3=rexp(50),z4=rexp(50)) List3 $z1 [1] 1.718907646 0.790585280 0.204750764 1.203047129 0.189730356 0.265698841 [7] 0.471851353 1.178283257 0.278361849 1.725710894 0.004180386 1.500419515 [13] 0.253964796 1.118053750 0.350007993 0.068681637 0.069928887 0.271137326 [19] 0.316337873 1.513536640 0.608107488 0.100705733 0.091038117 1.680959338 [25] 3.098310359 0.024069859 0.079393005 0.676481508 1.677929247 0.528531744 [31] 0.952730628 0.605817827 0.552035683 0.179703399 0.029881320 1.763623732 [37] 0.251440660 0.489608381 0.343958400 0.680817402 2.488113521 0.182692466 [43] 1.838525970 0.026139385 1.336605331 0.187837140 1.001021679 1.068164745 [49] 0.586717864 0.188288941 $z2 [1] 0.96681400 0.93182169 1.06428806 0.14140707 0.39303890 1.00227481 [7] 0.02706789 2.80852463 1.71280020 1.03406754 1.00638814 0.70394098 [13] 2.02029292 1.21125497 0.82803622 1.84601814 1.67267708 1.62547079 [19] 1.43411676 1.07888560 0.26773645 1.22885541 1.12461358 0.97696734 [25] 0.04547523 0.19367367 0.29813403 1.17887043 0.22968845 0.69612129 [31] 0.60235370 3.02393213 2.27831540 2.85495798 0.57111993 3.15022562 [37] 1.40904829 3.62419435 4.06618871 1.93677916 0.50544569 1.53942186 [43] 4.00923268 0.06415687 0.16847399 0.95837914 2.17440413 0.69603180 [49] 0.32872915 0.87998219 $z3 [1] 0.03984708 0.37911072 0.39527617 1.11247389 0.45724934 1.47759184 [7] 0.90512793 0.35675484 0.88244845 0.12769840 0.00452113 0.53191616 [13] 0.33870747 1.47954421 1.21998604 0.76498694 1.25436621 3.86274192 [19] 0.86903165 1.02575073 3.26314757 0.96884011 2.99768499 0.73019254 [25] 0.81639460 0.69500919 1.32349089 2.55732287 0.86032776 0.21881670 [31] 0.23084453 0.01074831 0.48422758 0.48439722 1.38000094 0.30889465 [37] 1.19599421 0.60671956 1.16873709 0.99445705 0.74635728 0.40339360 [43] 1.32840395 2.92880480 1.04132163 1.68629929 0.25703192 0.68822688 [49] 0.92138168 0.43555544 $z4 [1] 0.019785280 0.332113114 0.603268548 1.475968243 0.404461872 0.084103244 [7] 0.802729027 1.684216058 2.004364217 1.100479145 0.268109553 2.453706887 [13] 0.716849180 0.045104141 0.386609886 0.149478953 1.209757102 0.941370074 [19] 1.726784369 0.681956061 0.427254268 0.830936060 0.692974098 0.716479172 [25] 1.624493349 0.216954219 0.384070517 0.516003236 2.268504498 0.750347184 [31] 2.898988536 0.022540033 0.069682582 0.324829354 0.005932369 1.836073771 [37] 0.608267033 1.554355547 0.664473031 0.228425454 1.815967761 0.046082996 [43] 0.865417744 0.063441784 0.015283203 0.517283282 4.257718179 0.228973207 [49] 0.870923003 1.105269648 List3[[1]][1] [1] 1.718908 List3[[2]][1] [1] 0.966814 List3[[3]][1] [1] 0.03984708 List3[[4]][1] [1] 0.01978528
[ { "code": null, "e": 1418, "s": 1062, "text": "To extract first value from a list, we first need to access the element using double square brackets then the sub-element of each element will be accessed using single square brackets. For example, if we have a list called LIST containing five elements each having 10 elements then the first sub-element of the LIST will be selected by using LIST[[1]][1]." }, { "code": null, "e": 1429, "s": 1418, "text": " Live Demo" }, { "code": null, "e": 1474, "s": 1429, "text": "List1<-list(x1=rnorm(50),x2=rnorm(50))\nList1" }, { "code": null, "e": 2715, "s": 1474, "text": "$x1\n[1] 0.11130222 0.16419755 -0.52346744 2.06291702 1.75401221 1.76745535\n[7] 2.07647670 0.20604988 0.88090037 0.45002361 -0.41997558 0.13069306\n[13] 1.03792793 0.60365638 -0.86619055 -0.94122172 0.64561932 0.50256648\n[19] -0.61076372 0.90286990 -0.03448342 1.52897744 -0.12000996 0.07482846\n[25] -1.12145357 0.76479988 0.59701522 1.46033578 -0.57620173 -1.17224749\n[31] -0.73289297 -1.03691038 -1.28427938 -0.33767539 -1.01044720 0.22021704\n[37] 0.67931259 1.79052238 -0.80291917 -0.21613130 0.58112656 0.74238488\n[43] -0.37718519 1.31974664 2.33329258 0.33576900 -1.05233449 0.90282079\n[49] -0.23821323 -2.18185932\n$x2\n[1] 0.34801958 -0.24730876 -0.64642026 -0.20068985 0.94328680 -0.35876719\n[7] -0.65250327 -0.26434726 0.80161224 -1.98861577 -0.55784172 2.72095292\n[13] -0.34377048 -1.41075225 -0.58016709 0.30349424 -0.10171845 -1.63588095\n[19] 0.69116860 1.45962094 1.68120904 0.35287888 2.16297295 1.96956313\n[25] 0.20567607 0.39924676 0.18837752 -2.34209766 -0.49420627 -0.19967231\n[31] -0.06452823 -0.31314817 0.34765525 -0.31236504 -2.01858040 0.09302232\n[37] -0.07158963 0.91019112 -0.74267435 -0.40049302 0.18465365 0.65059368\n[43] 0.61031556 -0.23870247 -1.63562822 0.37430717 0.98758801 -0.09859013\n[49] 0.29618676 0.66022211" }, { "code": null, "e": 2729, "s": 2715, "text": "List1[[1]][1]" }, { "code": null, "e": 2743, "s": 2729, "text": "[1] 0.1113022" }, { "code": null, "e": 2757, "s": 2743, "text": "List1[[2]][1]" }, { "code": null, "e": 2771, "s": 2757, "text": "[1] 0.3480196" }, { "code": null, "e": 2782, "s": 2771, "text": " Live Demo" }, { "code": null, "e": 2865, "s": 2782, "text": "List2<-list(y1=rpois(100,5),y2=rpois(100,5),y3=rpois(100,5),y4=rpois(100,5))\nList2" }, { "code": null, "e": 3777, "s": 2865, "text": "$y1\n[1] 0 6 10 5 7 1 8 8 4 4 1 5 7 5 5 10 2 4 4 2 3 5 3 2 2\n[26] 5 4 12 4 4 5 4 4 6 6 5 7 10 1 3 9 4 6 3 7 6 4 3 6 5\n[51] 8 5 8 5 7 3 4 5 7 6 6 3 5 5 5 1 0 4 7 3 4 7 6 6 3\n[76] 3 3 4 3 5 6 4 6 3 4 4 6 7 8 4 3 10 11 6 8 8 6 6 7 4\n$y2\n[1] 7 7 11 4 4 1 4 7 2 6 2 2 6 2 2 6 3 3 6 2 5 6 6 5 6\n[26] 6 1 9 1 1 8 3 5 3 5 6 6 4 4 6 3 9 3 4 5 4 8 6 2 6\n[51] 6 2 8 8 8 5 4 1 3 7 8 6 6 10 6 8 5 2 4 7 4 8 4 3 8\n[76] 3 3 7 7 7 2 9 3 5 8 3 5 5 7 2 9 8 7 5 2 3 5 7 7 8\n$y3\n[1] 5 5 3 5 2 6 7 3 3 5 3 6 5 7 3 7 4 5 5 4 5 9 4 1 2\n[26] 4 5 5 5 5 4 3 2 6 8 4 13 6 4 6 7 5 5 6 2 3 6 4 4 6\n[51] 3 3 6 11 5 7 8 3 3 5 7 3 1 5 4 9 6 7 5 3 6 6 5 6 6\n[76] 6 6 2 12 2 1 7 3 6 4 5 4 3 4 3 5 6 4 3 8 6 7 7 7 5\n$y4\n[1] 6 7 4 6 6 1 7 6 2 6 10 7 5 9 9 3 6 6 10 4 7 4 2 4 10\n[26] 6 9 3 3 2 6 5 4 4 3 6 5 3 6 3 7 7 1 4 3 5 10 6 7 4\n[51] 5 3 6 8 3 5 4 5 5 5 6 3 4 10 5 3 7 5 5 7 4 4 3 5 6\n[76] 4 4 6 9 3 10 12 7 4 9 7 14 10 1 4 4 3 3 6 1 5 2 8 4 7" }, { "code": null, "e": 3791, "s": 3777, "text": "List2[[1]][1]" }, { "code": null, "e": 3797, "s": 3791, "text": "[1] 0" }, { "code": null, "e": 3811, "s": 3797, "text": "List2[[2]][1]" }, { "code": null, "e": 3817, "s": 3811, "text": "[1] 7" }, { "code": null, "e": 3831, "s": 3817, "text": "List2[[3]][1]" }, { "code": null, "e": 3838, "s": 3831, "text": "[1] 5\n" }, { "code": null, "e": 3852, "s": 3838, "text": "List2[[4]][1]" }, { "code": null, "e": 3866, "s": 3852, "text": "List2[[4]][1]" }, { "code": null, "e": 3877, "s": 3866, "text": " Live Demo" }, { "code": null, "e": 3944, "s": 3877, "text": "List3<-list(z1=rexp(50),z2=rexp(50),z3=rexp(50),z4=rexp(50))\nList3" }, { "code": null, "e": 6432, "s": 3944, "text": "$z1\n[1] 1.718907646 0.790585280 0.204750764 1.203047129 0.189730356 0.265698841\n[7] 0.471851353 1.178283257 0.278361849 1.725710894 0.004180386 1.500419515\n[13] 0.253964796 1.118053750 0.350007993 0.068681637 0.069928887 0.271137326\n[19] 0.316337873 1.513536640 0.608107488 0.100705733 0.091038117 1.680959338\n[25] 3.098310359 0.024069859 0.079393005 0.676481508 1.677929247 0.528531744\n[31] 0.952730628 0.605817827 0.552035683 0.179703399 0.029881320 1.763623732\n[37] 0.251440660 0.489608381 0.343958400 0.680817402 2.488113521 0.182692466\n[43] 1.838525970 0.026139385 1.336605331 0.187837140 1.001021679 1.068164745\n[49] 0.586717864 0.188288941\n$z2\n[1] 0.96681400 0.93182169 1.06428806 0.14140707 0.39303890 1.00227481\n[7] 0.02706789 2.80852463 1.71280020 1.03406754 1.00638814 0.70394098\n[13] 2.02029292 1.21125497 0.82803622 1.84601814 1.67267708 1.62547079\n[19] 1.43411676 1.07888560 0.26773645 1.22885541 1.12461358 0.97696734\n[25] 0.04547523 0.19367367 0.29813403 1.17887043 0.22968845 0.69612129\n[31] 0.60235370 3.02393213 2.27831540 2.85495798 0.57111993 3.15022562\n[37] 1.40904829 3.62419435 4.06618871 1.93677916 0.50544569 1.53942186\n[43] 4.00923268 0.06415687 0.16847399 0.95837914 2.17440413 0.69603180\n[49] 0.32872915 0.87998219\n$z3\n[1] 0.03984708 0.37911072 0.39527617 1.11247389 0.45724934 1.47759184\n[7] 0.90512793 0.35675484 0.88244845 0.12769840 0.00452113 0.53191616\n[13] 0.33870747 1.47954421 1.21998604 0.76498694 1.25436621 3.86274192\n[19] 0.86903165 1.02575073 3.26314757 0.96884011 2.99768499 0.73019254\n[25] 0.81639460 0.69500919 1.32349089 2.55732287 0.86032776 0.21881670\n[31] 0.23084453 0.01074831 0.48422758 0.48439722 1.38000094 0.30889465\n[37] 1.19599421 0.60671956 1.16873709 0.99445705 0.74635728 0.40339360\n[43] 1.32840395 2.92880480 1.04132163 1.68629929 0.25703192 0.68822688\n[49] 0.92138168 0.43555544\n$z4\n[1] 0.019785280 0.332113114 0.603268548 1.475968243 0.404461872 0.084103244\n[7] 0.802729027 1.684216058 2.004364217 1.100479145 0.268109553 2.453706887\n[13] 0.716849180 0.045104141 0.386609886 0.149478953 1.209757102 0.941370074\n[19] 1.726784369 0.681956061 0.427254268 0.830936060 0.692974098 0.716479172\n[25] 1.624493349 0.216954219 0.384070517 0.516003236 2.268504498 0.750347184\n[31] 2.898988536 0.022540033 0.069682582 0.324829354 0.005932369 1.836073771\n[37] 0.608267033 1.554355547 0.664473031 0.228425454 1.815967761 0.046082996\n[43] 0.865417744 0.063441784 0.015283203 0.517283282 4.257718179 0.228973207\n[49] 0.870923003 1.105269648" }, { "code": null, "e": 6446, "s": 6432, "text": "List3[[1]][1]" }, { "code": null, "e": 6459, "s": 6446, "text": "[1] 1.718908" }, { "code": null, "e": 6473, "s": 6459, "text": "List3[[2]][1]" }, { "code": null, "e": 6486, "s": 6473, "text": "[1] 0.966814" }, { "code": null, "e": 6500, "s": 6486, "text": "List3[[3]][1]" }, { "code": null, "e": 6516, "s": 6500, "text": "[1] 0.03984708\n" }, { "code": null, "e": 6530, "s": 6516, "text": "List3[[4]][1]" }, { "code": null, "e": 6545, "s": 6530, "text": "[1] 0.01978528" } ]
Linux Admin - Using the vi / vim Text Editor
vim represents a newer, improved version of the vi text editor for Linux. vim is installed by default on CentOS 7, the most recent version of CentOS. However, some older and minimal base installs will only include the original vi by default. The biggest difference between vi and vim are advanced ease-of-use features such as moving the cursor with the arrow keys. Where vim will allow the user to navigate a text file with the arrow keys, vi is restricted to using the "h", "j", "k", "l" keys, listed as follows. vi text document navigation − Using vim the same actions can be accomplished with the arrow keys on a standard English (and other common language) based qwerty, keyboard layout. Similarly, vi will often not interpret the numeric keypad on as well. Mostly, these days, vi will be symlinked to vim. If you ever find it frustrating your arrow keys are doing things unexpected when pressed, try using your package manager to install vim. vim uses the concept of modes when manipulating and opening files. The two modes we will focus on are − normal − This is the mode vim uses when a file is first opened, and allows for entering commands normal − This is the mode vim uses when a file is first opened, and allows for entering commands insert − The insert mode is used to actually edit text in a file. insert − The insert mode is used to actually edit text in a file. Let's open a file in vim. We will use the CentOS default dictionary located at /usr/share/dict − [root@localhost rdc]# cp /usr/share/dict/words What you see is the text file opened in normalmode. Now practice navigating the document using the arrow keys. Also, try using the h,j,k and lkeys to navigate the document. Vim expects us to send commands for file operations. To enable line number, use the colon key: shift+:. Your cursor will now appear at the bottom of the document. Type "set nu" and then hit enter. :set nu Now, we will always know where in the file we are. This is also a necessity when programming in vim. Yes! vim has the best syntax highlighting and can be used for making Ruby, Perl, Python, Bash, PHP, and other scripts. Following table lists the most common commands in normal mode. Please try the following tasks in vim, to become familiar with it. Search for the string "test", then first 5 occurrences Search for the string "test", then first 5 occurrences Move to the beginning of the document after finding the first 5 occurrences of "test" Move to the beginning of the document after finding the first 5 occurrences of "test" Go to line 100 using enter Go to line 100 using enter Delete the entire word using "x" Delete the entire word using "x" Undo the deletions using "u" Undo the deletions using "u" Delete the entire line using "dd" Delete the entire line using "dd" Reconstruct the line using "u" Reconstruct the line using "u" We will pretend that we made edits on a critical file and want to be sure not to save any unintended changes. Hit the shift+: and type: q!. This will exit vim, discarding any changes made. Now, we want to actually edit a file in vim: at the console type: vim myfile.txt We are now looking at a blank text buffer in vim. Let's write something: say - hit "i". vim is now in insert mode, allowing us to make edits to a file just like in Notepad. Type a few paragraphs in your buffer, whatever you want. Later, use the following steps to save the file − Step 1 − Press the escape key Step 1 − Press the escape key Step 2 − Press shift+: Step 2 − Press shift+: Step 3 − type w myfile.txt:w and hit Enter Step 3 − type w myfile.txt:w and hit Enter Step 4 − Press shift+: Step 4 − Press shift+: Step 5 − Type q! and hit Enter Step 5 − Type q! and hit Enter We have just created a text-file named, myfile.txt and saved it − [root@localhost]# cat myfile.txt this is my txt file. [root@localhost]# The pipe character "|", will take an output from the first command, passing it to the next command. This is known as Standard Output or stdout. The other common Linux redirector is Standard Input or stdin. Following are two examples; first using the cat command putting the file contents to stdout. Second using cat to read a file with the standardinput redirector outputting its contents. [root@centosLocal centos]# cat output.txt Hello, I am coming from Standard output or STDOUT. [root@centosLocal centos]# [root@centosLocal centos]# cat < stdin.txt Hello, I am being read form Standard input, STDIN. [root@centosLocal centos]# Now, let's "pipe" the stdout of cat to another command. [root@centosLocal centos]# cat output.txt | wc -l 2 [root@centosLocal centos]# Above, we passed cat'sstdout to wc for processing the pipe character. wc then processed the output from cat printing the line count of output.txt to the terminal. Think of the pipe character as a "pipe" passing output from one command, to be processed by the next command. Following are the key concepts to remember when dealing with command redirection. 57 Lectures 7.5 hours Mamta Tripathi 25 Lectures 3 hours Lets Kode It 14 Lectures 1.5 hours Abhilash Nelson 58 Lectures 2.5 hours Frahaan Hussain 129 Lectures 23 hours Eduonix Learning Solutions 23 Lectures 5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2499, "s": 2257, "text": "vim represents a newer, improved version of the vi text editor for Linux. vim is installed by default on CentOS 7, the most recent version of CentOS. However, some older and minimal base installs will only include the original vi by default." }, { "code": null, "e": 2771, "s": 2499, "text": "The biggest difference between vi and vim are advanced ease-of-use features such as moving the cursor with the arrow keys. Where vim will allow the user to navigate a text file with the arrow keys, vi is restricted to using the \"h\", \"j\", \"k\", \"l\" keys, listed as follows." }, { "code": null, "e": 2801, "s": 2771, "text": "vi text document navigation −" }, { "code": null, "e": 3019, "s": 2801, "text": "Using vim the same actions can be accomplished with the arrow keys on a standard English (and other common language) based qwerty, keyboard layout. Similarly, vi will often not interpret the numeric keypad on as well." }, { "code": null, "e": 3205, "s": 3019, "text": "Mostly, these days, vi will be symlinked to vim. If you ever find it frustrating your arrow keys are doing things unexpected when pressed, try using your package manager to install vim." }, { "code": null, "e": 3309, "s": 3205, "text": "vim uses the concept of modes when manipulating and opening files. The two modes we will focus on are −" }, { "code": null, "e": 3406, "s": 3309, "text": "normal − This is the mode vim uses when a file is first opened, and allows for entering commands" }, { "code": null, "e": 3503, "s": 3406, "text": "normal − This is the mode vim uses when a file is first opened, and allows for entering commands" }, { "code": null, "e": 3569, "s": 3503, "text": "insert − The insert mode is used to actually edit text in a file." }, { "code": null, "e": 3635, "s": 3569, "text": "insert − The insert mode is used to actually edit text in a file." }, { "code": null, "e": 3732, "s": 3635, "text": "Let's open a file in vim. We will use the CentOS default dictionary located at /usr/share/dict −" }, { "code": null, "e": 3780, "s": 3732, "text": "[root@localhost rdc]# cp /usr/share/dict/words\n" }, { "code": null, "e": 3953, "s": 3780, "text": "What you see is the text file opened in normalmode. Now practice navigating the document using the arrow keys. Also, try using the h,j,k and lkeys to navigate the document." }, { "code": null, "e": 4150, "s": 3953, "text": "Vim expects us to send commands for file operations. To enable line number, use the colon key: shift+:. Your cursor will now appear at the bottom of the document. Type \"set nu\" and then hit enter." }, { "code": null, "e": 4159, "s": 4150, "text": ":set nu\n" }, { "code": null, "e": 4379, "s": 4159, "text": "Now, we will always know where in the file we are. This is also a necessity when programming in vim. Yes! vim has the best syntax highlighting and can be used for making Ruby, Perl, Python, Bash, PHP, and other scripts." }, { "code": null, "e": 4442, "s": 4379, "text": "Following table lists the most common commands in normal mode." }, { "code": null, "e": 4509, "s": 4442, "text": "Please try the following tasks in vim, to become familiar with it." }, { "code": null, "e": 4564, "s": 4509, "text": "Search for the string \"test\", then first 5 occurrences" }, { "code": null, "e": 4619, "s": 4564, "text": "Search for the string \"test\", then first 5 occurrences" }, { "code": null, "e": 4705, "s": 4619, "text": "Move to the beginning of the document after finding the first 5 occurrences of \"test\"" }, { "code": null, "e": 4791, "s": 4705, "text": "Move to the beginning of the document after finding the first 5 occurrences of \"test\"" }, { "code": null, "e": 4818, "s": 4791, "text": "Go to line 100 using enter" }, { "code": null, "e": 4845, "s": 4818, "text": "Go to line 100 using enter" }, { "code": null, "e": 4878, "s": 4845, "text": "Delete the entire word using \"x\"" }, { "code": null, "e": 4911, "s": 4878, "text": "Delete the entire word using \"x\"" }, { "code": null, "e": 4940, "s": 4911, "text": "Undo the deletions using \"u\"" }, { "code": null, "e": 4969, "s": 4940, "text": "Undo the deletions using \"u\"" }, { "code": null, "e": 5003, "s": 4969, "text": "Delete the entire line using \"dd\"" }, { "code": null, "e": 5037, "s": 5003, "text": "Delete the entire line using \"dd\"" }, { "code": null, "e": 5068, "s": 5037, "text": "Reconstruct the line using \"u\"" }, { "code": null, "e": 5099, "s": 5068, "text": "Reconstruct the line using \"u\"" }, { "code": null, "e": 5288, "s": 5099, "text": "We will pretend that we made edits on a critical file and want to be sure not to save any unintended changes. Hit the shift+: and type: q!. This will exit vim, discarding any changes made." }, { "code": null, "e": 5369, "s": 5288, "text": "Now, we want to actually edit a file in vim: at the console type: vim myfile.txt" }, { "code": null, "e": 5457, "s": 5369, "text": "We are now looking at a blank text buffer in vim. Let's write something: say - hit \"i\"." }, { "code": null, "e": 5649, "s": 5457, "text": "vim is now in insert mode, allowing us to make edits to a file just like in Notepad. Type a few paragraphs in your buffer, whatever you want. Later, use the following steps to save the file −" }, { "code": null, "e": 5679, "s": 5649, "text": "Step 1 − Press the escape key" }, { "code": null, "e": 5709, "s": 5679, "text": "Step 1 − Press the escape key" }, { "code": null, "e": 5732, "s": 5709, "text": "Step 2 − Press shift+:" }, { "code": null, "e": 5755, "s": 5732, "text": "Step 2 − Press shift+:" }, { "code": null, "e": 5798, "s": 5755, "text": "Step 3 − type w myfile.txt:w and hit Enter" }, { "code": null, "e": 5841, "s": 5798, "text": "Step 3 − type w myfile.txt:w and hit Enter" }, { "code": null, "e": 5864, "s": 5841, "text": "Step 4 − Press shift+:" }, { "code": null, "e": 5887, "s": 5864, "text": "Step 4 − Press shift+:" }, { "code": null, "e": 5918, "s": 5887, "text": "Step 5 − Type q! and hit Enter" }, { "code": null, "e": 5949, "s": 5918, "text": "Step 5 − Type q! and hit Enter" }, { "code": null, "e": 6015, "s": 5949, "text": "We have just created a text-file named, myfile.txt and saved it −" }, { "code": null, "e": 6090, "s": 6015, "text": "[root@localhost]# cat myfile.txt \nthis is my txt file.\n[root@localhost]#\n" }, { "code": null, "e": 6296, "s": 6090, "text": "The pipe character \"|\", will take an output from the first command, passing it to the next command. This is known as Standard Output or stdout. The other common Linux redirector is Standard Input or stdin." }, { "code": null, "e": 6480, "s": 6296, "text": "Following are two examples; first using the cat command putting the file contents to stdout. Second using cat to read a file with the standardinput redirector outputting its contents." }, { "code": null, "e": 6605, "s": 6480, "text": "[root@centosLocal centos]# cat output.txt \nHello, \nI am coming from Standard output or STDOUT. \n[root@centosLocal centos]#\n" }, { "code": null, "e": 6731, "s": 6605, "text": "[root@centosLocal centos]# cat < stdin.txt \nHello, \nI am being read form Standard input, STDIN. \n[root@centosLocal centos]#\n" }, { "code": null, "e": 6787, "s": 6731, "text": "Now, let's \"pipe\" the stdout of cat to another command." }, { "code": null, "e": 6869, "s": 6787, "text": "[root@centosLocal centos]# cat output.txt | wc -l \n2 \n[root@centosLocal centos]#\n" }, { "code": null, "e": 7142, "s": 6869, "text": "Above, we passed cat'sstdout to wc for processing the pipe character. wc then processed the output from cat printing the line count of output.txt to the terminal. Think of the pipe character as a \"pipe\" passing output from one command, to be processed by the next command." }, { "code": null, "e": 7224, "s": 7142, "text": "Following are the key concepts to remember when dealing with command redirection." }, { "code": null, "e": 7259, "s": 7224, "text": "\n 57 Lectures \n 7.5 hours \n" }, { "code": null, "e": 7275, "s": 7259, "text": " Mamta Tripathi" }, { "code": null, "e": 7308, "s": 7275, "text": "\n 25 Lectures \n 3 hours \n" }, { "code": null, "e": 7322, "s": 7308, "text": " Lets Kode It" }, { "code": null, "e": 7357, "s": 7322, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7374, "s": 7357, "text": " Abhilash Nelson" }, { "code": null, "e": 7409, "s": 7374, "text": "\n 58 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7426, "s": 7409, "text": " Frahaan Hussain" }, { "code": null, "e": 7461, "s": 7426, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 7489, "s": 7461, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7522, "s": 7489, "text": "\n 23 Lectures \n 5 hours \n" }, { "code": null, "e": 7562, "s": 7522, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 7569, "s": 7562, "text": " Print" }, { "code": null, "e": 7580, "s": 7569, "text": " Add Notes" } ]
Searching in a map using std::map functions in C++ - GeeksforGeeks
25 May, 2018 Usually, main purpose of using map stl container is for efficient search operations and sorted order retrieval. As map stores key-value pair, all the search operations take “O(log(n))” time (n is size of map). Different types of search functions exists in C++ language, each having different functions. In the context of competitive programming, this turns out to be useful when search operations are required and performs better than other containers. Some search operations are discussed below. std::map::find() find() is used to search for the key-value pair and accepts the “key” in its argument to find it. This function returns the pointer to the element if the element is found, else it returns the pointer pointing to the last position of map i.e “map.end()” . // C++ code to demonstrate the working of find() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators map<char, int>::iterator it ; map<char, int>::iterator it1 ; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['d']=20; mp['e']=30; // using find() to search for 'b' // key found // "it" has address of key value pair. it = mp.find('b'); if(it == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair present : " << it->first << "->" << it->second ; cout << endl ; // using find() to search for 'm' // key not found // "it1" has address of end of map. it1 = mp.find('m'); if(it1 == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair present : " << it1->first << "->" << it1->second ; } Output: Key-value pair present : b->10 Key-value pair not present in map std::map::lower_bound() lower_bound() is also used for the search operation but sometimes also returns a valid key-value pair even if it is not present in map . lower_bound() returns address of key value pair, if one is present in map, else returns the address to the smallest key greater than key mentioned in its arguments. If all keys are smaller than the key to be found, it points to “map.end()” . // C++ code to demonstrate the working of lower_bound() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators map<char, int>::iterator it ; map<char, int>::iterator it1 ; map<char, int>::iterator it2 ; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['h']=20; mp['k']=30; // using lower_bound() to search for 'b' // key found // "it" has address of key value pair. it = mp.lower_bound('b'); if(it == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair returned : " << it->first << "->" << it->second ; cout << endl ; // using lower_bound() to search for 'd' // key not found // "it1" has address of next greater key. // key - 'h' it1 = mp.lower_bound('d'); if(it1 == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair returned : " << it1->first << "->" << it1->second ; cout << endl; // using lower_bound() to search for 'p' // key not found // "it2" has address of next greater key. // all keys are smaller, hence returns mp.end() it2 = mp.lower_bound('p'); if(it2 == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair returned : " << it2->first << "->" << it2->second ; } Output: Key-value pair returned : b->10 Key-value pair returned : h->20 Key-value pair not present in map std::map::upper_bound() upper_bound() is also used for the search operation and never returns the key-value pair searched for . upper_bound() returns address of key value pair coming exactly next to the searched key, if one is present in map. If all keys are smaller than the key to be found, it points to “map.end()” // C++ code to demonstrate the working of upper_bound() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators map<char, int>::iterator it ; map<char, int>::iterator it1 ; map<char, int>::iterator it2 ; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['h']=20; mp['k']=30; // using upper_bound() to search for 'b' // key found // "it" has address of key value pair next to 'b' i.e 'c'. it = mp.upper_bound('b'); if(it == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair returned : " << it->first << "->" << it->second ; cout << endl ; // using upper_bound() to search for 'd' // key not found // "it1" has address of next greater key. // key - 'h' it1 = mp.upper_bound('d'); if(it1 == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair returned : " << it1->first << "->" << it1->second ; cout << endl; // using upper_bound() to search for 'p' // key not found // "it2" has address of next greater key. // all keys are smaller, hence returns mp.end() it2 = mp.upper_bound('p'); if(it2 == mp.end()) cout << "Key-value pair not present in map" ; else cout << "Key-value pair returned : " << it2->first << "->" << it2->second ; } Output: Key-value pair returned : c->15 Key-value pair returned : h->20 Key-value pair not present in map std::map::equal-range Yet another function to search in map, it returns the range containing the searched key. As map contains unique elements, range returned contains at most 1 element. This function returns a iterator of pair, whose 1st element points to lower_bound() of the searched key pair, and second element points to the upper_bound() of the searched key. If key is not present, both first element and second element point to the next greater element. // C++ code to demonstrate the working of equal_range() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators pair<map<char, int>::iterator, map<char, int>::iterator> it; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['h']=20; mp['k']=30; // using equal_range() to search for 'b' // key found // 1st element of "it" has the address to lower_bound (b) // 2nd element of "it" has the address to upper_bound (c) it = mp.equal_range('b'); cout << "The lower_bound of key is : " << it.first -> first << "->" << it.first -> second; cout << endl; cout << "The upper_bound of key is : " << it.second -> first << "->" << it.second -> second; cout << endl << endl ; // using equal_range() to search for 'd' // key not found // Both elements of it point to next greater key // key - 'h' it = mp.equal_range('d'); cout << "The lower_bound of key is : " << it.first -> first << "->" << it.first -> second; cout << endl; cout << "The upper_bound of key is : " << it.second -> first << "->" << it.second -> second; } Output: The lower_bound of key is : b->10 The upper_bound of key is : c->15 The lower_bound of key is : h->20 The upper_bound of key is : h->20 This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. cpp-containers-library cpp-map STL C++ Competitive Programming STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Templates in C++ with Examples Socket Programming in C/C++ Polymorphism in C++ Copy Constructor in C++ Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Prefix Sum Array - Implementation and Applications in Competitive Programming Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 25565, "s": 25537, "text": "\n25 May, 2018" }, { "code": null, "e": 26062, "s": 25565, "text": "Usually, main purpose of using map stl container is for efficient search operations and sorted order retrieval. As map stores key-value pair, all the search operations take “O(log(n))” time (n is size of map). Different types of search functions exists in C++ language, each having different functions. In the context of competitive programming, this turns out to be useful when search operations are required and performs better than other containers. Some search operations are discussed below." }, { "code": null, "e": 26079, "s": 26062, "text": "std::map::find()" }, { "code": null, "e": 26334, "s": 26079, "text": "find() is used to search for the key-value pair and accepts the “key” in its argument to find it. This function returns the pointer to the element if the element is found, else it returns the pointer pointing to the last position of map i.e “map.end()” ." }, { "code": "// C++ code to demonstrate the working of find() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators map<char, int>::iterator it ; map<char, int>::iterator it1 ; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['d']=20; mp['e']=30; // using find() to search for 'b' // key found // \"it\" has address of key value pair. it = mp.find('b'); if(it == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair present : \" << it->first << \"->\" << it->second ; cout << endl ; // using find() to search for 'm' // key not found // \"it1\" has address of end of map. it1 = mp.find('m'); if(it1 == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair present : \" << it1->first << \"->\" << it1->second ; }", "e": 27384, "s": 26334, "text": null }, { "code": null, "e": 27392, "s": 27384, "text": "Output:" }, { "code": null, "e": 27458, "s": 27392, "text": "Key-value pair present : b->10\nKey-value pair not present in map\n" }, { "code": null, "e": 27482, "s": 27458, "text": "std::map::lower_bound()" }, { "code": null, "e": 27861, "s": 27482, "text": "lower_bound() is also used for the search operation but sometimes also returns a valid key-value pair even if it is not present in map . lower_bound() returns address of key value pair, if one is present in map, else returns the address to the smallest key greater than key mentioned in its arguments. If all keys are smaller than the key to be found, it points to “map.end()” ." }, { "code": "// C++ code to demonstrate the working of lower_bound() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators map<char, int>::iterator it ; map<char, int>::iterator it1 ; map<char, int>::iterator it2 ; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['h']=20; mp['k']=30; // using lower_bound() to search for 'b' // key found // \"it\" has address of key value pair. it = mp.lower_bound('b'); if(it == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair returned : \" << it->first << \"->\" << it->second ; cout << endl ; // using lower_bound() to search for 'd' // key not found // \"it1\" has address of next greater key. // key - 'h' it1 = mp.lower_bound('d'); if(it1 == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair returned : \" << it1->first << \"->\" << it1->second ; cout << endl; // using lower_bound() to search for 'p' // key not found // \"it2\" has address of next greater key. // all keys are smaller, hence returns mp.end() it2 = mp.lower_bound('p'); if(it2 == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair returned : \" << it2->first << \"->\" << it2->second ; }", "e": 29416, "s": 27861, "text": null }, { "code": null, "e": 29424, "s": 29416, "text": "Output:" }, { "code": null, "e": 29523, "s": 29424, "text": "Key-value pair returned : b->10\nKey-value pair returned : h->20\nKey-value pair not present in map\n" }, { "code": null, "e": 29547, "s": 29523, "text": "std::map::upper_bound()" }, { "code": null, "e": 29841, "s": 29547, "text": "upper_bound() is also used for the search operation and never returns the key-value pair searched for . upper_bound() returns address of key value pair coming exactly next to the searched key, if one is present in map. If all keys are smaller than the key to be found, it points to “map.end()”" }, { "code": "// C++ code to demonstrate the working of upper_bound() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators map<char, int>::iterator it ; map<char, int>::iterator it1 ; map<char, int>::iterator it2 ; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['h']=20; mp['k']=30; // using upper_bound() to search for 'b' // key found // \"it\" has address of key value pair next to 'b' i.e 'c'. it = mp.upper_bound('b'); if(it == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair returned : \" << it->first << \"->\" << it->second ; cout << endl ; // using upper_bound() to search for 'd' // key not found // \"it1\" has address of next greater key. // key - 'h' it1 = mp.upper_bound('d'); if(it1 == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair returned : \" << it1->first << \"->\" << it1->second ; cout << endl; // using upper_bound() to search for 'p' // key not found // \"it2\" has address of next greater key. // all keys are smaller, hence returns mp.end() it2 = mp.upper_bound('p'); if(it2 == mp.end()) cout << \"Key-value pair not present in map\" ; else cout << \"Key-value pair returned : \" << it2->first << \"->\" << it2->second ; }", "e": 31413, "s": 29841, "text": null }, { "code": null, "e": 31421, "s": 31413, "text": "Output:" }, { "code": null, "e": 31520, "s": 31421, "text": "Key-value pair returned : c->15\nKey-value pair returned : h->20\nKey-value pair not present in map\n" }, { "code": null, "e": 31542, "s": 31520, "text": "std::map::equal-range" }, { "code": null, "e": 31981, "s": 31542, "text": "Yet another function to search in map, it returns the range containing the searched key. As map contains unique elements, range returned contains at most 1 element. This function returns a iterator of pair, whose 1st element points to lower_bound() of the searched key pair, and second element points to the upper_bound() of the searched key. If key is not present, both first element and second element point to the next greater element." }, { "code": "// C++ code to demonstrate the working of equal_range() #include<iostream>#include<map> // for map operationsusing namespace std; int main(){ // declaring map // of char and int map< char, int > mp; // declaring iterators pair<map<char, int>::iterator, map<char, int>::iterator> it; // inserting values mp['a']=5; mp['b']=10; mp['c']=15; mp['h']=20; mp['k']=30; // using equal_range() to search for 'b' // key found // 1st element of \"it\" has the address to lower_bound (b) // 2nd element of \"it\" has the address to upper_bound (c) it = mp.equal_range('b'); cout << \"The lower_bound of key is : \" << it.first -> first << \"->\" << it.first -> second; cout << endl; cout << \"The upper_bound of key is : \" << it.second -> first << \"->\" << it.second -> second; cout << endl << endl ; // using equal_range() to search for 'd' // key not found // Both elements of it point to next greater key // key - 'h' it = mp.equal_range('d'); cout << \"The lower_bound of key is : \" << it.first -> first << \"->\" << it.first -> second; cout << endl; cout << \"The upper_bound of key is : \" << it.second -> first << \"->\" << it.second -> second; }", "e": 33299, "s": 31981, "text": null }, { "code": null, "e": 33307, "s": 33299, "text": "Output:" }, { "code": null, "e": 33445, "s": 33307, "text": "The lower_bound of key is : b->10\nThe upper_bound of key is : c->15\n\nThe lower_bound of key is : h->20\nThe upper_bound of key is : h->20\n" }, { "code": null, "e": 33746, "s": 33445, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 33871, "s": 33746, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 33894, "s": 33871, "text": "cpp-containers-library" }, { "code": null, "e": 33902, "s": 33894, "text": "cpp-map" }, { "code": null, "e": 33906, "s": 33902, "text": "STL" }, { "code": null, "e": 33910, "s": 33906, "text": "C++" }, { "code": null, "e": 33934, "s": 33910, "text": "Competitive Programming" }, { "code": null, "e": 33938, "s": 33934, "text": "STL" }, { "code": null, "e": 33942, "s": 33938, "text": "CPP" }, { "code": null, "e": 34040, "s": 33942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34068, "s": 34040, "text": "Operator Overloading in C++" }, { "code": null, "e": 34099, "s": 34068, "text": "Templates in C++ with Examples" }, { "code": null, "e": 34127, "s": 34099, "text": "Socket Programming in C/C++" }, { "code": null, "e": 34147, "s": 34127, "text": "Polymorphism in C++" }, { "code": null, "e": 34171, "s": 34147, "text": "Copy Constructor in C++" }, { "code": null, "e": 34214, "s": 34171, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 34257, "s": 34214, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 34298, "s": 34257, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 34376, "s": 34298, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" } ]
Android, How to crop circular area from bitmap
This example demonstrates how to crop circular area from bitmap in Android . Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:id="@+id/rl" android:padding="16dp" android:background="#edf2ea"> <ImageView android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Circular It" android:layout_alignParentBottom="true" android:layout_alignParentRight="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java package com.medkart.sample; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; public class MainActivity extends AppCompatActivity { private Context mContext; private Resources mResources; private RelativeLayout mRelativeLayout; private Button mBTN; private ImageView mImageView; private Bitmap mBitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get the application context mContext = getApplicationContext(); // Get the Resources mResources = getResources(); // Get the widgets reference from XML layout mRelativeLayout = (RelativeLayout) findViewById(R.id.rl); mImageView = (ImageView) findViewById(R.id.iv); mBTN = (Button) findViewById(R.id.btn); // Get the bitmap resource id final int bitmapResourceID =R.drawable.flower; // Set an image to ImageView mImageView.setImageBitmap(BitmapFactory.decodeResource(mResources, bitmapResourceID)); // Set a click listener for Button widget mBTN.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Get the bitmap from drawable resources mBitmap = BitmapFactory.decodeResource(mResources, bitmapResourceID); // Create a circular bitmap mBitmap = getCircularBitmap(mBitmap); // Add a border around circular bitmap mBitmap = addBorderToCircularBitmap(mBitmap, 15, Color.WHITE); // Add a shadow around circular bitmap mBitmap = addShadowToCircularBitmap(mBitmap, 4, Color.LTGRAY); // Set the ImageView image as drawable object mImageView.setImageBitmap(mBitmap); } }); } protected Bitmap getCircularBitmap(Bitmap srcBitmap) { // Calculate the circular bitmap width with border int squareBitmapWidth = Math.min(srcBitmap.getWidth(), srcBitmap.getHeight()); // Initialize a new instance of Bitmap Bitmap dstBitmap = Bitmap.createBitmap ( squareBitmapWidth, // Width squareBitmapWidth, // Height Bitmap.Config.ARGB_8888 // Config ); Canvas canvas = new Canvas(dstBitmap); // Initialize a new Paint instance Paint paint = new Paint(); paint.setAntiAlias(true); Rect rect = new Rect(0, 0, squareBitmapWidth, squareBitmapWidth); RectF rectF = new RectF(rect); canvas.drawOval(rectF, paint); paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); // Calculate the left and top of copied bitmap float left = (squareBitmapWidth-srcBitmap.getWidth())/2; float top = (squareBitmapWidth-srcBitmap.getHeight())/2; canvas.drawBitmap(srcBitmap, left, top, paint); // Free the native object associated with this bitmap. srcBitmap.recycle(); // Return the circular bitmap return dstBitmap; } // Custom method to add a border around circular bitmap protected Bitmap addBorderToCircularBitmap(Bitmap srcBitmap, int borderWidth, int borderColor) { // Calculate the circular bitmap width with border int dstBitmapWidth = srcBitmap.getWidth()+borderWidth*2; // Initialize a new Bitmap to make it bordered circular bitmap Bitmap dstBitmap = Bitmap.createBitmap(dstBitmapWidth,dstBitmapWidth, Bitmap.Config.ARGB_8888); // Initialize a new Canvas instance Canvas canvas = new Canvas(dstBitmap); // Draw source bitmap to canvas canvas.drawBitmap(srcBitmap, borderWidth, borderWidth, null); // Initialize a new Paint instance to draw border Paint paint = new Paint(); paint.setColor(borderColor); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(borderWidth); paint.setAntiAlias(true); canvas.drawCircle( canvas.getWidth() / 2, // cx canvas.getWidth() / 2, // cy canvas.getWidth()/2 - borderWidth / 2, // Radius paint // Paint ); // Free the native object associated with this bitmap. srcBitmap.recycle(); // Return the bordered circular bitmap return dstBitmap; } // Custom method to add a shadow around circular bitmap protected Bitmap addShadowToCircularBitmap(Bitmap srcBitmap, int shadowWidth, int shadowColor){ // Calculate the circular bitmap width with shadow int dstBitmapWidth = srcBitmap.getWidth()+shadowWidth*2; Bitmap dstBitmap = Bitmap.createBitmap(dstBitmapWidth,dstBitmapWidth, Bitmap.Config.ARGB_8888); // Initialize a new Canvas instance Canvas canvas = new Canvas(dstBitmap); canvas.drawBitmap(srcBitmap, shadowWidth, shadowWidth, null); // Paint to draw circular bitmap shadow Paint paint = new Paint(); paint.setColor(shadowColor); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(shadowWidth); paint.setAntiAlias(true); // Draw the shadow around circular bitmap canvas.drawCircle ( dstBitmapWidth / 2, // cx dstBitmapWidth / 2, // cy dstBitmapWidth / 2 - shadowWidth / 2, // Radius paint // Paint ); srcBitmap.recycle(); return dstBitmap; } } Step 4 − Add the following code to Manifests/AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.medkart.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1139, "s": 1062, "text": "This example demonstrates how to crop circular area from bitmap in Android ." }, { "code": null, "e": 1269, "s": 1139, "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": 1335, "s": 1269, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2188, "s": 1335, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\"\n android:id=\"@+id/rl\"\n android:padding=\"16dp\"\n android:background=\"#edf2ea\">\n <ImageView\n android:id=\"@+id/iv\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n <Button\n android:id=\"@+id/btn\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Circular It\"\n android:layout_alignParentBottom=\"true\"\n android:layout_alignParentRight=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 2246, "s": 2188, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 8070, "s": 2246, "text": "package com.medkart.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.content.Context;\nimport android.content.res.Resources;\nimport android.graphics.Bitmap;\nimport android.graphics.BitmapFactory;\nimport android.graphics.Canvas;\nimport android.graphics.Color;\nimport android.graphics.Paint;\nimport android.graphics.PorterDuff;\nimport android.graphics.PorterDuffXfermode;\nimport android.graphics.Rect;\nimport android.graphics.RectF;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.ImageView;\nimport android.widget.RelativeLayout;\npublic class MainActivity extends AppCompatActivity {\n private Context mContext;\n private Resources mResources;\n private RelativeLayout mRelativeLayout;\n private Button mBTN;\n private ImageView mImageView;\n private Bitmap mBitmap;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n // Get the application context\n mContext = getApplicationContext();\n // Get the Resources\n mResources = getResources();\n // Get the widgets reference from XML layout\n mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);\n mImageView = (ImageView) findViewById(R.id.iv);\n mBTN = (Button) findViewById(R.id.btn);\n // Get the bitmap resource id\n final int bitmapResourceID =R.drawable.flower;\n // Set an image to ImageView\n mImageView.setImageBitmap(BitmapFactory.decodeResource(mResources, bitmapResourceID));\n // Set a click listener for Button widget\n mBTN.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n // Get the bitmap from drawable resources\n mBitmap = BitmapFactory.decodeResource(mResources, bitmapResourceID);\n // Create a circular bitmap\n mBitmap = getCircularBitmap(mBitmap);\n // Add a border around circular bitmap\n mBitmap = addBorderToCircularBitmap(mBitmap, 15, Color.WHITE);\n // Add a shadow around circular bitmap\n mBitmap = addShadowToCircularBitmap(mBitmap, 4, Color.LTGRAY);\n // Set the ImageView image as drawable object\n mImageView.setImageBitmap(mBitmap);\n }\n });\n }\n protected Bitmap getCircularBitmap(Bitmap srcBitmap) {\n // Calculate the circular bitmap width with border\n int squareBitmapWidth = Math.min(srcBitmap.getWidth(), srcBitmap.getHeight());\n // Initialize a new instance of Bitmap\n Bitmap dstBitmap = Bitmap.createBitmap (\n squareBitmapWidth, // Width\n squareBitmapWidth, // Height\n Bitmap.Config.ARGB_8888 // Config\n );\n Canvas canvas = new Canvas(dstBitmap);\n // Initialize a new Paint instance\n Paint paint = new Paint();\n paint.setAntiAlias(true);\n Rect rect = new Rect(0, 0, squareBitmapWidth, squareBitmapWidth);\n RectF rectF = new RectF(rect);\n canvas.drawOval(rectF, paint);\n paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));\n // Calculate the left and top of copied bitmap\n float left = (squareBitmapWidth-srcBitmap.getWidth())/2;\n float top = (squareBitmapWidth-srcBitmap.getHeight())/2;\n canvas.drawBitmap(srcBitmap, left, top, paint);\n // Free the native object associated with this bitmap.\n srcBitmap.recycle();\n // Return the circular bitmap\n return dstBitmap;\n }\n // Custom method to add a border around circular bitmap\n protected Bitmap addBorderToCircularBitmap(Bitmap srcBitmap, int borderWidth, int borderColor) {\n // Calculate the circular bitmap width with border\n int dstBitmapWidth = srcBitmap.getWidth()+borderWidth*2;\n // Initialize a new Bitmap to make it bordered circular bitmap\n Bitmap dstBitmap = Bitmap.createBitmap(dstBitmapWidth,dstBitmapWidth, Bitmap.Config.ARGB_8888);\n // Initialize a new Canvas instance\n Canvas canvas = new Canvas(dstBitmap);\n // Draw source bitmap to canvas\n canvas.drawBitmap(srcBitmap, borderWidth, borderWidth, null);\n // Initialize a new Paint instance to draw border\n Paint paint = new Paint();\n paint.setColor(borderColor);\n paint.setStyle(Paint.Style.STROKE);\n paint.setStrokeWidth(borderWidth);\n paint.setAntiAlias(true);\n canvas.drawCircle(\n canvas.getWidth() / 2, // cx\n canvas.getWidth() / 2, // cy\n canvas.getWidth()/2 - borderWidth / 2, // Radius\n paint // Paint\n );\n // Free the native object associated with this bitmap.\n srcBitmap.recycle();\n // Return the bordered circular bitmap\n return dstBitmap;\n }\n // Custom method to add a shadow around circular bitmap\n protected Bitmap addShadowToCircularBitmap(Bitmap srcBitmap, int shadowWidth, int shadowColor){\n // Calculate the circular bitmap width with shadow\n int dstBitmapWidth = srcBitmap.getWidth()+shadowWidth*2;\n Bitmap dstBitmap = Bitmap.createBitmap(dstBitmapWidth,dstBitmapWidth, Bitmap.Config.ARGB_8888);\n // Initialize a new Canvas instance\n Canvas canvas = new Canvas(dstBitmap);\n canvas.drawBitmap(srcBitmap, shadowWidth, shadowWidth, null);\n // Paint to draw circular bitmap shadow\n Paint paint = new Paint();\n paint.setColor(shadowColor);\n paint.setStyle(Paint.Style.STROKE);\n paint.setStrokeWidth(shadowWidth);\n paint.setAntiAlias(true);\n // Draw the shadow around circular bitmap\n canvas.drawCircle (\n dstBitmapWidth / 2, // cx\n dstBitmapWidth / 2, // cy\n dstBitmapWidth / 2 - shadowWidth / 2, // Radius\n paint // Paint\n );\n srcBitmap.recycle();\n return dstBitmap;\n }\n}" }, { "code": null, "e": 8136, "s": 8070, "text": "Step 4 − Add the following code to Manifests/AndroidManifest.xml" }, { "code": null, "e": 8813, "s": 8136, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.medkart.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 9160, "s": 8813, "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": 9201, "s": 9160, "text": "Click here to download the project code." } ]
C++ Program to Implement Kadane’s Algorithm
Kadane’s algorithm is used to find out the maximum subarray sum from an array of integers. Here we shall discuss a C++ program to implement this algorithm. Begin Function kadanes(int array[], int length): Initialize highestMax = 0 currentElementMax = 0 for i = 0 to length-1 currentElementMax = max(array[i],currentElementMax + array[i]) highestMax = max(highestMax, currentElementMax) return highestMax End #include<iostream> using namespace std; int kadanes(int array[],int length) { int highestMax = 0; int currentElementMax = 0; for(int i = 0; i < length; i++){ currentElementMax =max(array[i],currentElementMax + array[i]) ; highestMax = max(highestMax,currentElementMax); } return highestMax; } int main() { cout << "Enter the array length: "; int l; cin >> l; int arr[l]; cout << "Enter the elements of array: "; for (int i = 0; i < l; i++) { cin >> arr[i]; } cout << "The Maximum Sum is: "<<kadanes(arr,l) << endl; return 0; } Enter the array length: 7 Enter the elements of array: -1 -2 -3 -4 -5 6 7 The Maximum Sum is: 13
[ { "code": null, "e": 1218, "s": 1062, "text": "Kadane’s algorithm is used to find out the maximum subarray sum from an array of integers. Here we shall discuss a C++ program to implement this algorithm." }, { "code": null, "e": 1497, "s": 1218, "text": "Begin\nFunction kadanes(int array[], int length):\n Initialize\n highestMax = 0\n currentElementMax = 0\n for i = 0 to length-1\n currentElementMax = max(array[i],currentElementMax + array[i])\n highestMax = max(highestMax, currentElementMax)\n return highestMax\nEnd" }, { "code": null, "e": 2084, "s": 1497, "text": "#include<iostream>\nusing namespace std;\nint kadanes(int array[],int length) {\n int highestMax = 0;\n int currentElementMax = 0;\n for(int i = 0; i < length; i++){\n currentElementMax =max(array[i],currentElementMax + array[i]) ;\n highestMax = max(highestMax,currentElementMax);\n }\n return highestMax;\n}\nint main() {\n cout << \"Enter the array length: \";\n int l;\n cin >> l;\n int arr[l];\n cout << \"Enter the elements of array: \";\n for (int i = 0; i < l; i++) {\n cin >> arr[i];\n }\n cout << \"The Maximum Sum is: \"<<kadanes(arr,l) << endl;\n return 0;\n}" }, { "code": null, "e": 2181, "s": 2084, "text": "Enter the array length: 7\nEnter the elements of array:\n-1\n-2\n-3\n-4\n-5\n6\n7\nThe Maximum Sum is: 13" } ]
Flutter - Flushbar - GeeksforGeeks
02 Jan, 2022 Flutter is loaded with libraries to make development easier with less code and more functionalities. We are back with another amazing Flutter package today. Showing snackbar in the apps is a common feature of today’s apps. Showing error messages when something goes wrong or sending important notifications to users from time to time is important to stay connected with users and keep them updated about the information. Although there was a simple snackbar package available to show snackbars on the application which was very limited in functionalities now we have an upgraded version of it. The flushbar is not limited to the snackbar functionality but we can customize it to make it as useful and beautiful as possible. To use the flushbar we are going to use the awesome another_flushbar package which supports null safety in Flutter. In this article, we will learn how to create different types of snackbars easily and fastly. Step 1: Add package. To use the package first we need to install it, to do so add dependency in the pubspec.yaml file. Dart dependencies: another_flushbar: ^1.10.28 Then, run pub get in the terminal to install it. Step 2: Import the Library. Import the library to the file in which you have to add the snackbar feature as: Dart import 'package:flushbar/flushbar.dart';import 'package:flushbar/flushbar_helper.dart'; The simple flushbar is just a snackbar with an information message and title. As you can see in the below code of simple flushbar, how simple is its code? We created a simple show_Simple_Snackbar function that shows the widget Flushbar defined inside. Here, we are adding simple messages and text. You can customize the text give it a size, weight, style, etc. Flushbar also contains titleText and message text property which are widgets but in the below code, we used String title and String message giving it the duration of 3 seconds to be on the screen. Dart void show_Simple_Snackbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), title: "This is simple flushbar", message: "Hey, you are a registered user now.", )..show(context); } Output: Sometimes showing only text doesn’t look good. You want to say more. It can be done through icons, which add more meaning to the text and make UI better. Sometimes, we also need to show different kinds of information like warnings, error messages along with their respective icons on the snackbar. This is very easy using Flushbar, you can add any icon and customize it according to your choice with just a few lines of code. Dart void show_Icon_Flushbar(BuildContext context) { Flushbar( icon: Icon( Icons.email_outlined, color: Colors.white, size: 30, ), backgroundColor: Color(0xFF0277BD), duration: Duration(seconds: 4), message: "This email is already registered.", messageSize: 18, titleText: Text("Flushbar with Icon.", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white)), )..show(context); } Output: Well, showing snackbar has gone to a different level now. It’s not just a simple snackbar, it’s a matter of creativity now. You can customize the snackbar using the Flushbar library that might include a floating snackbar, snackbar with different colors, styles, etc. You are not limited to using creativity. You can play with the parameters of Flushbar like giving rounded borders, adding animation to it, and much more. In the below example, I designed the snackbar with gradient colors and gave the box-shadow. Added animation to make it smooth, and gave a dismissable horizontal direction to it. Dart void show_Custom_Flushbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), margin: EdgeInsets.all(8), padding: EdgeInsets.all(10), backgroundGradient: LinearGradient( colors: [ Colors.pink.shade500, Colors.pink.shade300, Colors.pink.shade100 ], stops: [0.4, 0.7, 1], ), boxShadows: [ BoxShadow( color: Colors.black45, offset: Offset(3, 3), blurRadius: 3, ), ], dismissDirection: FlushbarDismissDirection.HORIZONTAL, forwardAnimationCurve: Curves.fastLinearToSlowEaseIn, title: 'This is a floating Flushbar', message: 'Welcome to Flutter community.', messageSize: 17, )..show(context); } Output: However, Flushbar’s creativity doesn’t stop there. You can explore its more properties if you want to go crazier. Previously displaying an error, or success message was a difficult task and time taking process. For this reason, the Flushbar widget includes helpers. It is a simple function that creates a cool snackbar to save you time. Let’s see how much shorter it is to create the snackbar “Information Flushbar” with a helper. Dart void show_FlushbarHelper(BuildContext context) { FlushbarHelper.createInformation( title: "Flushbar Helper", message: "This is illegal action.") ..show(context); } Output: Sometimes, after showing an error message, you want to redirect the user to a different page as per the error. So, there could be any button to click on with the error. What if you can show the button with the snackbar? Is it possible? Yes, you can do this using mainButton property of Flushbar. Like in the below-shown code, I am wrapping the Text “Click me”, inside a GestureDetector which is a child of ButtonBar widget assigned to mainButton property of Flushbar. When this snackbar is shown, the user can click on the text and it will do whatever you give inside the onTap or onPressed whichever property. Dart void show_Button_Flushbar(BuildContext context) { Flushbar( mainButton: ButtonBar( children: [ GestureDetector( onTap: () { print("You clicked me!"); }, child: Text( "Click me", style: TextStyle(color: Colors.white), ), ) ], ), backgroundColor: Colors.black, title: "Flushbar with Button", message: "We require additional information.", messageSize: 17, duration: Duration(seconds: 4), )..show(context); }} Output: Even though Flutter contains its default Snackbar, using Flushbar should be preferred. Flushbar involves less boilerplate code and contains unlimited features to add to. You can style every parameter of the Flushbar widget, and it will surprise you with its ease. Whenever you want to show something more than an error message or success message go for Flushbar library. Complete Flushbar Tutorial Code: Dart import 'package:flutter/material.dart';import 'package:another_flushbar/flushbar.dart';import 'package:another_flushbar/flushbar_helper.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Flushbar Tutorial', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), ); }} class MyHomePage extends StatefulWidget { @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text("GeeksForGeeks"), centerTitle: true), body: Center( child: Column( children: [ SizedBox( height: 40, ), ElevatedButton( onPressed: () { // invoking show_Simple_Snackbar function show_Simple_Snackbar(context); }, child: Text("Simple Snackbar with Flushbar")), ElevatedButton( onPressed: () { // calling function to show flushbar with icon show_Icon_Flushbar(context); }, child: Text("Flushbar with Icon")), ElevatedButton( onPressed: () { //calling show Customized Flushbar show_Custom_Flushbar(context); }, child: Text("Flushbar with gradient colors")), ElevatedButton( onPressed: () { // calling function to FlushbarHelper show_FlushbarHelper(context); }, child: Text("Flushbar Helper")), ElevatedButton( onPressed: () { // calling function to show flushbar with button show_Button_Flushbar(context); }, child: Text("Flushbar with Button")) ], ), ), ); } void show_Simple_Snackbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), title: "This is simple flushbar", message: "Hey, you are a registered user now.", )..show(context); } void show_Icon_Flushbar(BuildContext context) { Flushbar( icon: Icon( Icons.email_outlined, color: Colors.white, size: 30, ), backgroundColor: Color(0xFF0277BD), duration: Duration(seconds: 4), message: "This email is already registered.", messageSize: 18, titleText: Text("Flushbar with Icon.", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white)), )..show(context); } void show_Custom_Flushbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), margin: EdgeInsets.all(8), padding: EdgeInsets.all(10), backgroundGradient: LinearGradient( colors: [ Colors.pink.shade500, Colors.pink.shade300, Colors.pink.shade100 ], stops: [0.4, 0.7, 1], ), boxShadows: [ BoxShadow( color: Colors.black45, offset: Offset(3, 3), blurRadius: 3, ), ], // All of the previous Flushbars could be dismissed // by swiping to any direction dismissDirection: FlushbarDismissDirection.HORIZONTAL, // The default curve is Curves.easeOut forwardAnimationCurve: Curves.fastLinearToSlowEaseIn, title: 'This is a floating Flushbar', message: 'Welcome to Flutter community.', messageSize: 17, )..show(context); } void show_FlushbarHelper(BuildContext context) { FlushbarHelper.createInformation( title: "Flushbar Helper", message: "This is illegal action.") ..show(context); } void show_Button_Flushbar(BuildContext context) { Flushbar( mainButton: ButtonBar( children: [ GestureDetector( onTap: () { print("You clicked me!"); }, child: Text( "Click me", style: TextStyle(color: Colors.white), ), ) ], ), backgroundColor: Colors.black, title: "Flushbar with Button", message: "We require additional information.", messageSize: 17, duration: Duration(seconds: 4), )..show(context); }} Output: Flutter Flutter UI-components Android Dart Flutter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Resource Raw Folder in Android Studio Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? Flexbox-Layout in Android How to Post Data to API using Retrofit in Android? Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Asset Image Splash Screen in Flutter Flutter - Custom Bottom Navigation Bar
[ { "code": null, "e": 26491, "s": 26463, "text": "\n02 Jan, 2022" }, { "code": null, "e": 26649, "s": 26491, "text": "Flutter is loaded with libraries to make development easier with less code and more functionalities. We are back with another amazing Flutter package today. " }, { "code": null, "e": 27088, "s": 26649, "text": "Showing snackbar in the apps is a common feature of today’s apps. Showing error messages when something goes wrong or sending important notifications to users from time to time is important to stay connected with users and keep them updated about the information. Although there was a simple snackbar package available to show snackbars on the application which was very limited in functionalities now we have an upgraded version of it. " }, { "code": null, "e": 27427, "s": 27088, "text": "The flushbar is not limited to the snackbar functionality but we can customize it to make it as useful and beautiful as possible. To use the flushbar we are going to use the awesome another_flushbar package which supports null safety in Flutter. In this article, we will learn how to create different types of snackbars easily and fastly." }, { "code": null, "e": 27448, "s": 27427, "text": "Step 1: Add package." }, { "code": null, "e": 27546, "s": 27448, "text": "To use the package first we need to install it, to do so add dependency in the pubspec.yaml file." }, { "code": null, "e": 27551, "s": 27546, "text": "Dart" }, { "code": "dependencies: another_flushbar: ^1.10.28", "e": 27593, "s": 27551, "text": null }, { "code": null, "e": 27643, "s": 27593, "text": "Then, run pub get in the terminal to install it. " }, { "code": null, "e": 27671, "s": 27643, "text": "Step 2: Import the Library." }, { "code": null, "e": 27752, "s": 27671, "text": "Import the library to the file in which you have to add the snackbar feature as:" }, { "code": null, "e": 27757, "s": 27752, "text": "Dart" }, { "code": "import 'package:flushbar/flushbar.dart';import 'package:flushbar/flushbar_helper.dart';", "e": 27845, "s": 27757, "text": null }, { "code": null, "e": 28403, "s": 27845, "text": "The simple flushbar is just a snackbar with an information message and title. As you can see in the below code of simple flushbar, how simple is its code? We created a simple show_Simple_Snackbar function that shows the widget Flushbar defined inside. Here, we are adding simple messages and text. You can customize the text give it a size, weight, style, etc. Flushbar also contains titleText and message text property which are widgets but in the below code, we used String title and String message giving it the duration of 3 seconds to be on the screen." }, { "code": null, "e": 28408, "s": 28403, "text": "Dart" }, { "code": "void show_Simple_Snackbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), title: \"This is simple flushbar\", message: \"Hey, you are a registered user now.\", )..show(context); }", "e": 28624, "s": 28408, "text": null }, { "code": null, "e": 28632, "s": 28624, "text": "Output:" }, { "code": null, "e": 29058, "s": 28632, "text": "Sometimes showing only text doesn’t look good. You want to say more. It can be done through icons, which add more meaning to the text and make UI better. Sometimes, we also need to show different kinds of information like warnings, error messages along with their respective icons on the snackbar. This is very easy using Flushbar, you can add any icon and customize it according to your choice with just a few lines of code." }, { "code": null, "e": 29063, "s": 29058, "text": "Dart" }, { "code": "void show_Icon_Flushbar(BuildContext context) { Flushbar( icon: Icon( Icons.email_outlined, color: Colors.white, size: 30, ), backgroundColor: Color(0xFF0277BD), duration: Duration(seconds: 4), message: \"This email is already registered.\", messageSize: 18, titleText: Text(\"Flushbar with Icon.\", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white)), )..show(context); }", "e": 29560, "s": 29063, "text": null }, { "code": null, "e": 29568, "s": 29560, "text": "Output:" }, { "code": null, "e": 30168, "s": 29568, "text": "Well, showing snackbar has gone to a different level now. It’s not just a simple snackbar, it’s a matter of creativity now. You can customize the snackbar using the Flushbar library that might include a floating snackbar, snackbar with different colors, styles, etc. You are not limited to using creativity. You can play with the parameters of Flushbar like giving rounded borders, adding animation to it, and much more. In the below example, I designed the snackbar with gradient colors and gave the box-shadow. Added animation to make it smooth, and gave a dismissable horizontal direction to it." }, { "code": null, "e": 30173, "s": 30168, "text": "Dart" }, { "code": "void show_Custom_Flushbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), margin: EdgeInsets.all(8), padding: EdgeInsets.all(10), backgroundGradient: LinearGradient( colors: [ Colors.pink.shade500, Colors.pink.shade300, Colors.pink.shade100 ], stops: [0.4, 0.7, 1], ), boxShadows: [ BoxShadow( color: Colors.black45, offset: Offset(3, 3), blurRadius: 3, ), ], dismissDirection: FlushbarDismissDirection.HORIZONTAL, forwardAnimationCurve: Curves.fastLinearToSlowEaseIn, title: 'This is a floating Flushbar', message: 'Welcome to Flutter community.', messageSize: 17, )..show(context); }", "e": 30935, "s": 30173, "text": null }, { "code": null, "e": 30943, "s": 30935, "text": "Output:" }, { "code": null, "e": 31057, "s": 30943, "text": "However, Flushbar’s creativity doesn’t stop there. You can explore its more properties if you want to go crazier." }, { "code": null, "e": 31374, "s": 31057, "text": "Previously displaying an error, or success message was a difficult task and time taking process. For this reason, the Flushbar widget includes helpers. It is a simple function that creates a cool snackbar to save you time. Let’s see how much shorter it is to create the snackbar “Information Flushbar” with a helper." }, { "code": null, "e": 31379, "s": 31374, "text": "Dart" }, { "code": "void show_FlushbarHelper(BuildContext context) { FlushbarHelper.createInformation( title: \"Flushbar Helper\", message: \"This is illegal action.\") ..show(context); }", "e": 31564, "s": 31379, "text": null }, { "code": null, "e": 31572, "s": 31564, "text": "Output:" }, { "code": null, "e": 32183, "s": 31572, "text": "Sometimes, after showing an error message, you want to redirect the user to a different page as per the error. So, there could be any button to click on with the error. What if you can show the button with the snackbar? Is it possible? Yes, you can do this using mainButton property of Flushbar. Like in the below-shown code, I am wrapping the Text “Click me”, inside a GestureDetector which is a child of ButtonBar widget assigned to mainButton property of Flushbar. When this snackbar is shown, the user can click on the text and it will do whatever you give inside the onTap or onPressed whichever property." }, { "code": null, "e": 32188, "s": 32183, "text": "Dart" }, { "code": "void show_Button_Flushbar(BuildContext context) { Flushbar( mainButton: ButtonBar( children: [ GestureDetector( onTap: () { print(\"You clicked me!\"); }, child: Text( \"Click me\", style: TextStyle(color: Colors.white), ), ) ], ), backgroundColor: Colors.black, title: \"Flushbar with Button\", message: \"We require additional information.\", messageSize: 17, duration: Duration(seconds: 4), )..show(context); }}", "e": 32752, "s": 32188, "text": null }, { "code": null, "e": 32760, "s": 32752, "text": "Output:" }, { "code": null, "e": 33131, "s": 32760, "text": "Even though Flutter contains its default Snackbar, using Flushbar should be preferred. Flushbar involves less boilerplate code and contains unlimited features to add to. You can style every parameter of the Flushbar widget, and it will surprise you with its ease. Whenever you want to show something more than an error message or success message go for Flushbar library." }, { "code": null, "e": 33164, "s": 33131, "text": "Complete Flushbar Tutorial Code:" }, { "code": null, "e": 33169, "s": 33164, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:another_flushbar/flushbar.dart';import 'package:another_flushbar/flushbar_helper.dart'; void main() { runApp(const MyApp());} class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, title: 'Flutter Flushbar Tutorial', theme: ThemeData( primarySwatch: Colors.green, ), home: MyHomePage(), ); }} class MyHomePage extends StatefulWidget { @override State<MyHomePage> createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: Text(\"GeeksForGeeks\"), centerTitle: true), body: Center( child: Column( children: [ SizedBox( height: 40, ), ElevatedButton( onPressed: () { // invoking show_Simple_Snackbar function show_Simple_Snackbar(context); }, child: Text(\"Simple Snackbar with Flushbar\")), ElevatedButton( onPressed: () { // calling function to show flushbar with icon show_Icon_Flushbar(context); }, child: Text(\"Flushbar with Icon\")), ElevatedButton( onPressed: () { //calling show Customized Flushbar show_Custom_Flushbar(context); }, child: Text(\"Flushbar with gradient colors\")), ElevatedButton( onPressed: () { // calling function to FlushbarHelper show_FlushbarHelper(context); }, child: Text(\"Flushbar Helper\")), ElevatedButton( onPressed: () { // calling function to show flushbar with button show_Button_Flushbar(context); }, child: Text(\"Flushbar with Button\")) ], ), ), ); } void show_Simple_Snackbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), title: \"This is simple flushbar\", message: \"Hey, you are a registered user now.\", )..show(context); } void show_Icon_Flushbar(BuildContext context) { Flushbar( icon: Icon( Icons.email_outlined, color: Colors.white, size: 30, ), backgroundColor: Color(0xFF0277BD), duration: Duration(seconds: 4), message: \"This email is already registered.\", messageSize: 18, titleText: Text(\"Flushbar with Icon.\", style: TextStyle( fontSize: 16, fontWeight: FontWeight.bold, color: Colors.white)), )..show(context); } void show_Custom_Flushbar(BuildContext context) { Flushbar( duration: Duration(seconds: 3), margin: EdgeInsets.all(8), padding: EdgeInsets.all(10), backgroundGradient: LinearGradient( colors: [ Colors.pink.shade500, Colors.pink.shade300, Colors.pink.shade100 ], stops: [0.4, 0.7, 1], ), boxShadows: [ BoxShadow( color: Colors.black45, offset: Offset(3, 3), blurRadius: 3, ), ], // All of the previous Flushbars could be dismissed // by swiping to any direction dismissDirection: FlushbarDismissDirection.HORIZONTAL, // The default curve is Curves.easeOut forwardAnimationCurve: Curves.fastLinearToSlowEaseIn, title: 'This is a floating Flushbar', message: 'Welcome to Flutter community.', messageSize: 17, )..show(context); } void show_FlushbarHelper(BuildContext context) { FlushbarHelper.createInformation( title: \"Flushbar Helper\", message: \"This is illegal action.\") ..show(context); } void show_Button_Flushbar(BuildContext context) { Flushbar( mainButton: ButtonBar( children: [ GestureDetector( onTap: () { print(\"You clicked me!\"); }, child: Text( \"Click me\", style: TextStyle(color: Colors.white), ), ) ], ), backgroundColor: Colors.black, title: \"Flushbar with Button\", message: \"We require additional information.\", messageSize: 17, duration: Duration(seconds: 4), )..show(context); }}", "e": 37818, "s": 33169, "text": null }, { "code": null, "e": 37826, "s": 37818, "text": "Output:" }, { "code": null, "e": 37834, "s": 37826, "text": "Flutter" }, { "code": null, "e": 37856, "s": 37834, "text": "Flutter UI-components" }, { "code": null, "e": 37864, "s": 37856, "text": "Android" }, { "code": null, "e": 37869, "s": 37864, "text": "Dart" }, { "code": null, "e": 37877, "s": 37869, "text": "Flutter" }, { "code": null, "e": 37885, "s": 37877, "text": "Android" }, { "code": null, "e": 37983, "s": 37885, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38021, "s": 37983, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 38060, "s": 38021, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 38110, "s": 38060, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 38136, "s": 38110, "text": "Flexbox-Layout in Android" }, { "code": null, "e": 38187, "s": 38136, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 38219, "s": 38187, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 38247, "s": 38219, "text": "Listview.builder in Flutter" }, { "code": null, "e": 38269, "s": 38247, "text": "Flutter - Asset Image" }, { "code": null, "e": 38294, "s": 38269, "text": "Splash Screen in Flutter" } ]
DataTables pageLength Option - GeeksforGeeks
13 Jul, 2021 DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed. The pageLength option is used to specify the number of rows of the table that are to be displayed on one page. This option is relevant when the pagination is used to display many rows. It accepts an integer value that denotes the number of rows to be displayed. Syntax: { pageLength: value } Parameters: This option has a single value as mentioned above and described below. value: This is an integer value that specifies the number of rows to be displayed. The default value is 10. The examples below illustrate the usage of this option. Example 1: This example demonstrates setting the number of rows per page to be 3. HTML <html><head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> <style> th { text-align:left; } </style></head><body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the number of rows to be // displayed per page on the DataTable pageLength: 3 }); }); </script></body></html> Output: Example 2: This example demonstrates setting the number of rows per page to be 6. HTML <!DOCTYPE html><html> <head> <!-- jQuery --> <script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.js"> </script> <!-- DataTables CSS --> <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css"> <!-- DataTables JS --> <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"> </script> <style> th { text-align:left; } </style></head> <body> <h2 style="color:green;"> GeeksForGeeks </h2> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id="tableID" class="display nowrap"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the number of rows to be // displayed per page on the DataTable pageLength: 6 }); }); </script></body> </html> Output: pagelength is 6 Reference link: https://datatables.net/reference/option/pageLength jQuery-DataTables JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show and Hide div elements using radio buttons? How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method jQuery | removeAttr() with Examples How to get the value in an input text box using jQuery ? 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": 25807, "s": 25779, "text": "\n13 Jul, 2021" }, { "code": null, "e": 26145, "s": 25807, "text": "DataTables is jQuery plugin that can be used for adding interactive and advanced controls to HTML tables for the webpage. This also allows the data in the table to be searched, sorted, and filtered according to the needs of the user. The DataTable also exposes a powerful API that can be further used to modify how the data is displayed." }, { "code": null, "e": 26407, "s": 26145, "text": "The pageLength option is used to specify the number of rows of the table that are to be displayed on one page. This option is relevant when the pagination is used to display many rows. It accepts an integer value that denotes the number of rows to be displayed." }, { "code": null, "e": 26415, "s": 26407, "text": "Syntax:" }, { "code": null, "e": 26437, "s": 26415, "text": "{ pageLength: value }" }, { "code": null, "e": 26520, "s": 26437, "text": "Parameters: This option has a single value as mentioned above and described below." }, { "code": null, "e": 26628, "s": 26520, "text": "value: This is an integer value that specifies the number of rows to be displayed. The default value is 10." }, { "code": null, "e": 26686, "s": 26630, "text": "The examples below illustrate the usage of this option." }, { "code": null, "e": 26768, "s": 26686, "text": "Example 1: This example demonstrates setting the number of rows per page to be 3." }, { "code": null, "e": 26773, "s": 26768, "text": "HTML" }, { "code": "<html><head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> <style> th { text-align:left; } </style></head><body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the number of rows to be // displayed per page on the DataTable pageLength: 3 }); }); </script></body></html>", "e": 28605, "s": 26773, "text": null }, { "code": null, "e": 28613, "s": 28605, "text": "Output:" }, { "code": null, "e": 28696, "s": 28613, "text": "Example 2: This example demonstrates setting the number of rows per page to be 6. " }, { "code": null, "e": 28701, "s": 28696, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- jQuery --> <script type=\"text/javascript\" src=\"https://code.jquery.com/jquery-3.5.1.js\"> </script> <!-- DataTables CSS --> <link rel=\"stylesheet\" href=\"https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css\"> <!-- DataTables JS --> <script src=\"https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js\"> </script> <style> th { text-align:left; } </style></head> <body> <h2 style=\"color:green;\"> GeeksForGeeks </h2> <h3>DataTables pageLength Option</h3> <!-- HTML table with random data --> <table id=\"tableID\" class=\"display nowrap\"> <thead> <tr> <th>Day</th> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> <tr> <td>2</td> <td>Patricia</td> <td>22</td> </tr> <tr> <td>2</td> <td>Caleb</td> <td>47</td> </tr> <tr> <td>1</td> <td>Abigail</td> <td>48</td> </tr> <tr> <td>5</td> <td>Rahim</td> <td>44</td> </tr> <tr> <td>5</td> <td>Sheila</td> <td>22</td> </tr> <tr> <td>2</td> <td>Lance</td> <td>48</td> </tr> <tr> <td>5</td> <td>Erin</td> <td>48</td> </tr> <tr> <td>1</td> <td>Christopher</td> <td>28</td> </tr> <tr> <td>2</td> <td>Roary</td> <td>35</td> </tr> <tr> <td>2</td> <td>Astra</td> <td>37</td> </tr> </tbody> </table> <script> // Initialize the DataTable $(document).ready(function () { $('#tableID').DataTable({ // Set the number of rows to be // displayed per page on the DataTable pageLength: 6 }); }); </script></body> </html>", "e": 30546, "s": 28701, "text": null }, { "code": null, "e": 30554, "s": 30546, "text": "Output:" }, { "code": null, "e": 30571, "s": 30554, "text": "pagelength is 6 " }, { "code": null, "e": 30638, "s": 30571, "text": "Reference link: https://datatables.net/reference/option/pageLength" }, { "code": null, "e": 30656, "s": 30638, "text": "jQuery-DataTables" }, { "code": null, "e": 30663, "s": 30656, "text": "JQuery" }, { "code": null, "e": 30680, "s": 30663, "text": "Web Technologies" }, { "code": null, "e": 30778, "s": 30680, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30833, "s": 30778, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 30906, "s": 30833, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 30929, "s": 30906, "text": "jQuery | ajax() Method" }, { "code": null, "e": 30965, "s": 30929, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 31022, "s": 30965, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 31062, "s": 31022, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31095, "s": 31062, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31140, "s": 31095, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31183, "s": 31140, "text": "How to fetch data from an API in ReactJS ?" } ]
Average numbers in array - GeeksforGeeks
13 May, 2022 Given a sequence of positive integers a1, a2, ..., an. Find all such indexes i such that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).Examples : Input : 5 1 2 3 4 5 Output : 1 no. of elements 2 index of element Average of 1, 2, 4 & 5 is 3 so the output is single index i.e. 3. Input : 4 50 50 50 50 Output : 4 no. of elements 0 1 2 3 index of element Average of 50, 50, 50 & 50 is 50 and all the indexes has the same i.e. 50 so the output is indexes 1, 2, 3 & 4. C++ C Java Python3 C# PHP Javascript // CPP program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elements#include <bits/stdc++.h>using namespace std; // function to find number of elements// satisfying condition and their indexesvoid averageNumbers(int arr[], int n, int sum){ int cnt = 0; // calculating average sum /= (double)n; // counting how many elements // satisfies the condition. cout << count(arr, arr + n, sum) << endl; for (int i = 0; i < n; i++) { if ((double)arr[i] == sum) { // output the indices. cout << i << " "; cnt++; } }} // Driver codeint main(){ int n; int arr[] = { 1, 2, 3, 4, 5 }; n = sizeof(arr) / sizeof(arr[0]); double sum = 0; int cnt = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += (double)arr[i]; } averageNumbers(arr, n, sum); return 0;} // C program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elements#include <stdio.h> // function to find number of elements// satisfying condition and their indexesvoid averageNumbers(int arr[], int n, int sum){ int cnt = 0; // calculating average sum /= (double)n; for (int i = 0; i < n; i++) { if ((double)arr[i] == sum) { // counting how many elements // satisfies the condition cnt++; } } printf("%d\n",cnt); for (int i = 0; i < n; i++) { if ((double)arr[i] == sum) { // output the indices. printf("%d ",i); cnt++; } }} // Driver codeint main(){ int n; int arr[] = { 1, 2, 3, 4, 5 }; n = sizeof(arr) / sizeof(arr[0]); double sum = 0; int cnt = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += (double)arr[i]; } averageNumbers(arr, n, sum); return 0;} // This code is contributed by kothvvsaakash. // Java program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elementspublic class GFG { // function to find number of elements// satisfying condition and their indexes static void averageNumbers(int arr[], int n, int sum) { int cnt = 0; // calculating average sum /= (double) n; // counting how many elements // satisfies the condition. System.out.println(count(arr, sum)); for (int i = 0; i < n; i++) { if ((double) arr[i] == sum) { // output the indices. System.out.print(i + " "); cnt++; } } } static int count(int[] array, int sum) { int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] == sum) { count++; } } return count; }// Driver code public static void main(String[] args) { int n; int arr[] = {1, 2, 3, 4, 5}; n = arr.length; int sum = 0; int cnt = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += (double) arr[i]; } averageNumbers(arr, n, sum); } }// This code is contributed by 29AjayKumar # Python 3 program to print all such indices# such that the i-th element equals the# arithmetic mean of all other elements # Function to find number of elements# satisfying condition and their indexesdef averageNumbers(arr, n, sum): cnt = 0 # calculating average sum /= n # counting how many elements # satisfies the condition. print(count(arr, sum)) for i in range(0, n): if (arr[i] == sum): # output the indices. print(i, " ") cnt += 1 def count(array, sum): count = 0 for i in range(0, len(array)): if (array[i] == sum): count += 1 return count # Driver codeif __name__ == '__main__': n = 0 arr = [ 1, 2, 3, 4, 5 ] n = len(arr) sum = 0 cnt = 0 # sum of the elements of the array for i in range(0, n): sum += arr[i] averageNumbers(arr, n, sum) # This code contributed by 29AjayKumar // C# program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elementsusing System;public class GFG { // function to find number of elements// satisfying condition and their indexes static void averageNumbers(int []arr, int n, int sum) { int cnt = 0; // calculating average sum /= n; // counting how many elements // satisfies the condition. Console.WriteLine(count(arr, sum)); for (int i = 0; i < n; i++) { if ((double) arr[i] == sum) { // output the indices. Console.Write(i + " "); cnt++; } } } static int count(int[] array, int sum) { int count = 0; for (int i = 0; i < array.Length; i++) { if (array[i] == sum) { count++; } } return count; }// Driver code public static void Main() { int n; int []arr = {1, 2, 3, 4, 5}; n = arr.Length; int sum = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += arr[i]; } averageNumbers(arr, n, sum); } }// This code is contributed by 29AjayKumar <?php// PHP program to print all such indices// such that the i-th element equals the// arithmetic mean of all other elements // counting how many elements// satisfies the condition.function coun_t($arr, $sum){ $cnt = 0; for ( $i = 0; $i < count($arr); $i++) { if ($arr[$i] == $sum) { $cnt++; } } return $cnt;} // function to find number of elements// satisfying condition and their indexesfunction averageNumbers($arr, $n, $sum){ $cnt = 0; // calculating average $sum /= $n; // counting how many elements // satisfies the condition. echo coun_t($arr, $sum) . "\n"; for ( $i = 0; $i < $n; $i++) { if ($arr[$i] == $sum) { // output the indices. echo $i . " "; $cnt++; } }} // Driver Code$n = 0;$arr = array( 1, 2, 3, 4, 5 );$n = count($arr);$sum = 0;$cnt = 0; // sum of the elements of the arrayfor ($i = 0; $i < $n; $i++){ $sum += $arr[$i];}averageNumbers($arr, $n, $sum); // This code is contributed by// Rajput-Ji?> <script> // Javascript program to print all such indices such // that the i-th element equals the arithmetic // mean of all other elements // function to find number of elements // satisfying condition and their indexes function averageNumbers(arr, n, sum) { let cnt = 0; // calculating average sum /= n; // counting how many elements // satisfies the condition. document.write(count(arr, sum) + "</br>"); for (let i = 0; i < n; i++) { if (arr[i] == sum) { // output the indices. document.write(i + " "); cnt++; } } } function count(array, sum) { let count = 0; for (let i = 0; i < array.length; i++) { if (array[i] == sum) { count++; } } return count; } // Driver code let n; let arr = [1, 2, 3, 4, 5]; n = arr.length; let sum = 0; // sum of the elements of the array for (let i = 0; i < n; i++) { sum += arr[i]; } averageNumbers(arr, n, sum); // This code is contributed by mukesh07.</script> Output: 1 2 Time Complexity: O(n) This article is contributed by Sagar Shukla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 29AjayKumar Rajput-Ji gfg_sal_gfg Akanksha_Rai mukesh07 kothavvsaakash Arrays School Programming Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Reversal algorithm for array rotation Window Sliding Technique Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Python Dictionary Inheritance in C++ Reverse a string in Java Interfaces in Java C++ Classes and Objects
[ { "code": null, "e": 26066, "s": 26038, "text": "\n13 May, 2022" }, { "code": null, "e": 26277, "s": 26066, "text": "Given a sequence of positive integers a1, a2, ..., an. Find all such indexes i such that the i-th element equals the arithmetic mean of all other elements (that is all elements except for this one).Examples : " }, { "code": null, "e": 26632, "s": 26277, "text": "Input : 5\n 1 2 3 4 5\nOutput : 1 no. of elements\n 2 index of element\nAverage of 1, 2, 4 & 5 is 3 so the \noutput is single index i.e. 3.\n\nInput : 4\n 50 50 50 50\nOutput : 4 no. of elements\n 0 1 2 3 index of element\nAverage of 50, 50, 50 & 50 is 50 and \nall the indexes has the same i.e. 50\nso the output is indexes 1, 2, 3 & 4." }, { "code": null, "e": 26640, "s": 26636, "text": "C++" }, { "code": null, "e": 26642, "s": 26640, "text": "C" }, { "code": null, "e": 26647, "s": 26642, "text": "Java" }, { "code": null, "e": 26655, "s": 26647, "text": "Python3" }, { "code": null, "e": 26658, "s": 26655, "text": "C#" }, { "code": null, "e": 26662, "s": 26658, "text": "PHP" }, { "code": null, "e": 26673, "s": 26662, "text": "Javascript" }, { "code": "// CPP program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elements#include <bits/stdc++.h>using namespace std; // function to find number of elements// satisfying condition and their indexesvoid averageNumbers(int arr[], int n, int sum){ int cnt = 0; // calculating average sum /= (double)n; // counting how many elements // satisfies the condition. cout << count(arr, arr + n, sum) << endl; for (int i = 0; i < n; i++) { if ((double)arr[i] == sum) { // output the indices. cout << i << \" \"; cnt++; } }} // Driver codeint main(){ int n; int arr[] = { 1, 2, 3, 4, 5 }; n = sizeof(arr) / sizeof(arr[0]); double sum = 0; int cnt = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += (double)arr[i]; } averageNumbers(arr, n, sum); return 0;}", "e": 27610, "s": 26673, "text": null }, { "code": "// C program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elements#include <stdio.h> // function to find number of elements// satisfying condition and their indexesvoid averageNumbers(int arr[], int n, int sum){ int cnt = 0; // calculating average sum /= (double)n; for (int i = 0; i < n; i++) { if ((double)arr[i] == sum) { // counting how many elements // satisfies the condition cnt++; } } printf(\"%d\\n\",cnt); for (int i = 0; i < n; i++) { if ((double)arr[i] == sum) { // output the indices. printf(\"%d \",i); cnt++; } }} // Driver codeint main(){ int n; int arr[] = { 1, 2, 3, 4, 5 }; n = sizeof(arr) / sizeof(arr[0]); double sum = 0; int cnt = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += (double)arr[i]; } averageNumbers(arr, n, sum); return 0;} // This code is contributed by kothvvsaakash.", "e": 28649, "s": 27610, "text": null }, { "code": "// Java program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elementspublic class GFG { // function to find number of elements// satisfying condition and their indexes static void averageNumbers(int arr[], int n, int sum) { int cnt = 0; // calculating average sum /= (double) n; // counting how many elements // satisfies the condition. System.out.println(count(arr, sum)); for (int i = 0; i < n; i++) { if ((double) arr[i] == sum) { // output the indices. System.out.print(i + \" \"); cnt++; } } } static int count(int[] array, int sum) { int count = 0; for (int i = 0; i < array.length; i++) { if (array[i] == sum) { count++; } } return count; }// Driver code public static void main(String[] args) { int n; int arr[] = {1, 2, 3, 4, 5}; n = arr.length; int sum = 0; int cnt = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += (double) arr[i]; } averageNumbers(arr, n, sum); } }// This code is contributed by 29AjayKumar", "e": 29935, "s": 28649, "text": null }, { "code": "# Python 3 program to print all such indices# such that the i-th element equals the# arithmetic mean of all other elements # Function to find number of elements# satisfying condition and their indexesdef averageNumbers(arr, n, sum): cnt = 0 # calculating average sum /= n # counting how many elements # satisfies the condition. print(count(arr, sum)) for i in range(0, n): if (arr[i] == sum): # output the indices. print(i, \" \") cnt += 1 def count(array, sum): count = 0 for i in range(0, len(array)): if (array[i] == sum): count += 1 return count # Driver codeif __name__ == '__main__': n = 0 arr = [ 1, 2, 3, 4, 5 ] n = len(arr) sum = 0 cnt = 0 # sum of the elements of the array for i in range(0, n): sum += arr[i] averageNumbers(arr, n, sum) # This code contributed by 29AjayKumar", "e": 30875, "s": 29935, "text": null }, { "code": " // C# program to print all such indices such// that the i-th element equals the arithmetic// mean of all other elementsusing System;public class GFG { // function to find number of elements// satisfying condition and their indexes static void averageNumbers(int []arr, int n, int sum) { int cnt = 0; // calculating average sum /= n; // counting how many elements // satisfies the condition. Console.WriteLine(count(arr, sum)); for (int i = 0; i < n; i++) { if ((double) arr[i] == sum) { // output the indices. Console.Write(i + \" \"); cnt++; } } } static int count(int[] array, int sum) { int count = 0; for (int i = 0; i < array.Length; i++) { if (array[i] == sum) { count++; } } return count; }// Driver code public static void Main() { int n; int []arr = {1, 2, 3, 4, 5}; n = arr.Length; int sum = 0; // sum of the elements of the array for (int i = 0; i < n; i++) { sum += arr[i]; } averageNumbers(arr, n, sum); } }// This code is contributed by 29AjayKumar", "e": 32133, "s": 30875, "text": null }, { "code": "<?php// PHP program to print all such indices// such that the i-th element equals the// arithmetic mean of all other elements // counting how many elements// satisfies the condition.function coun_t($arr, $sum){ $cnt = 0; for ( $i = 0; $i < count($arr); $i++) { if ($arr[$i] == $sum) { $cnt++; } } return $cnt;} // function to find number of elements// satisfying condition and their indexesfunction averageNumbers($arr, $n, $sum){ $cnt = 0; // calculating average $sum /= $n; // counting how many elements // satisfies the condition. echo coun_t($arr, $sum) . \"\\n\"; for ( $i = 0; $i < $n; $i++) { if ($arr[$i] == $sum) { // output the indices. echo $i . \" \"; $cnt++; } }} // Driver Code$n = 0;$arr = array( 1, 2, 3, 4, 5 );$n = count($arr);$sum = 0;$cnt = 0; // sum of the elements of the arrayfor ($i = 0; $i < $n; $i++){ $sum += $arr[$i];}averageNumbers($arr, $n, $sum); // This code is contributed by// Rajput-Ji?>", "e": 33195, "s": 32133, "text": null }, { "code": "<script> // Javascript program to print all such indices such // that the i-th element equals the arithmetic // mean of all other elements // function to find number of elements // satisfying condition and their indexes function averageNumbers(arr, n, sum) { let cnt = 0; // calculating average sum /= n; // counting how many elements // satisfies the condition. document.write(count(arr, sum) + \"</br>\"); for (let i = 0; i < n; i++) { if (arr[i] == sum) { // output the indices. document.write(i + \" \"); cnt++; } } } function count(array, sum) { let count = 0; for (let i = 0; i < array.length; i++) { if (array[i] == sum) { count++; } } return count; } // Driver code let n; let arr = [1, 2, 3, 4, 5]; n = arr.length; let sum = 0; // sum of the elements of the array for (let i = 0; i < n; i++) { sum += arr[i]; } averageNumbers(arr, n, sum); // This code is contributed by mukesh07.</script>", "e": 34377, "s": 33195, "text": null }, { "code": null, "e": 34385, "s": 34377, "text": "Output:" }, { "code": null, "e": 34390, "s": 34385, "text": "1\n2 " }, { "code": null, "e": 34833, "s": 34390, "text": "Time Complexity: O(n) This article is contributed by Sagar Shukla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34845, "s": 34833, "text": "29AjayKumar" }, { "code": null, "e": 34855, "s": 34845, "text": "Rajput-Ji" }, { "code": null, "e": 34867, "s": 34855, "text": "gfg_sal_gfg" }, { "code": null, "e": 34880, "s": 34867, "text": "Akanksha_Rai" }, { "code": null, "e": 34889, "s": 34880, "text": "mukesh07" }, { "code": null, "e": 34904, "s": 34889, "text": "kothavvsaakash" }, { "code": null, "e": 34911, "s": 34904, "text": "Arrays" }, { "code": null, "e": 34930, "s": 34911, "text": "School Programming" }, { "code": null, "e": 34937, "s": 34930, "text": "Arrays" }, { "code": null, "e": 35035, "s": 34937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35066, "s": 35035, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35104, "s": 35066, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35129, "s": 35104, "text": "Window Sliding Technique" }, { "code": null, "e": 35150, "s": 35129, "text": "Next Greater Element" }, { "code": null, "e": 35208, "s": 35150, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 35226, "s": 35208, "text": "Python Dictionary" }, { "code": null, "e": 35245, "s": 35226, "text": "Inheritance in C++" }, { "code": null, "e": 35270, "s": 35245, "text": "Reverse a string in Java" }, { "code": null, "e": 35289, "s": 35270, "text": "Interfaces in Java" } ]
Hash data structure - GeeksQuiz
05 Jan, 2020 - - - - - - - 0 1 2 3 4 5 6 1 - - - - - - 0 1 2 3 4 5 6 1 - - - - - 3 0 1 2 3 4 5 6 1 8 - - - - 3 0 1 2 3 4 5 6 1 8 10 - - - 3 0 1 2 3 4 5 6 - - - - - - - 0 1 2 3 4 5 6 1 - - - - - - 0 1 2 3 4 5 6 1 - - - - - 3 0 1 2 3 4 5 6 1 8 - - - - 3 0 1 2 3 4 5 6 1 8 10 - - - 3 0 1 2 3 4 5 6 Hash function given is mod(10). 9679, 1989 and 4199 all these give same hash value i.e 9 1471 and 6171 give hash value 1 Probability that the first 3 slots are unfilled after the first 3 insertions = (probability that first item doesn't go in any of the first 3 slots)* (probability that second item doesn't go in any of the first 3 slots)* (probability that third item doesn't go in any of the first 3 slots) = (97/100) * (97/100) * (97/100) Which one of the following hash functions on integers will distribute keys most uniformly over 10 buckets numbered 0 to 9 for i ranging from 0 to 2020? h(i) = (12 ∗ i) mod 10 h(i) = (11 ∗ i2) mod 10 h(i) =i3 mod 10 h(i) =i2 mod 10 Since mod 10 is used, the last digit matters. If you do cube all numbers from 0 to 9, you get following Number Cube Last Digit in Cube 0 0 0 1 1 1 2 8 8 3 27 7 4 64 4 5 125 5 6 216 6 7 343 3 8 512 2 9 729 9 Therefore all numbers from 0 to 2020 are equally divided in 10 buckets. If we make a table for square, we don't get equal distribution. In the following table. 1, 4, 6 and 9 are repeated, so these buckets would have more entries and buckets 2, 3, 7 and 8 would be empty. Number Square Last Digit in Square 0 0 0 1 1 1 2 4 4 3 9 9 4 16 6 5 25 5 6 36 6 7 49 9 8 64 4 9 81 1 Alternative approach - Using concept of power of cycle: (a) (0,1,4,9,6,5,6,9,4,1,0) repeated (b) (0,1,8,7,4,5,6,3,2,9) repeated (c) (0,1,4,9,6,5,6,9,4,1,0) repeated (d) (0,2,4,6,8) repeated So, only h(i) =i3 mod 10 covers all the digits from 0 to 9. Option (B) is correct. A hash function takes a message of arbitrary length and generates a fixed length code.A hash function takes a message of fixed length and generates a code of variable length.A hash function may give the same hash value for distinct messages. A hash function takes a message of arbitrary length and generates a fixed length code. A hash function takes a message of fixed length and generates a code of variable length. A hash function may give the same hash value for distinct messages. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Must Do Coding Questions for Product Based Companies SQL Query to Convert VARCHAR to INT How to Update Multiple Columns in Single Update Statement in SQL? Difference between var, let and const keywords in JavaScript Array of Objects in C++ with Examples How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File Insert Image in a Jupyter Notebook How to Replace Values in a List in Python?
[ { "code": null, "e": 27530, "s": 27502, "text": "\n05 Jan, 2020" }, { "code": null, "e": 27593, "s": 27530, "text": " - - - - - - -\n 0 1 2 3 4 5 6" }, { "code": null, "e": 27656, "s": 27593, "text": " 1 - - - - - -\n 0 1 2 3 4 5 6" }, { "code": null, "e": 27719, "s": 27656, "text": " 1 - - - - - 3\n 0 1 2 3 4 5 6" }, { "code": null, "e": 27782, "s": 27719, "text": " 1 8 - - - - 3\n 0 1 2 3 4 5 6" }, { "code": null, "e": 27846, "s": 27782, "text": " 1 8 10 - - - 3\n 0 1 2 3 4 5 6" }, { "code": null, "e": 27909, "s": 27846, "text": " - - - - - - -\n 0 1 2 3 4 5 6" }, { "code": null, "e": 27972, "s": 27909, "text": " 1 - - - - - -\n 0 1 2 3 4 5 6" }, { "code": null, "e": 28035, "s": 27972, "text": " 1 - - - - - 3\n 0 1 2 3 4 5 6" }, { "code": null, "e": 28098, "s": 28035, "text": " 1 8 - - - - 3\n 0 1 2 3 4 5 6" }, { "code": null, "e": 28162, "s": 28098, "text": " 1 8 10 - - - 3\n 0 1 2 3 4 5 6" }, { "code": null, "e": 28284, "s": 28162, "text": "Hash function given is mod(10).\n9679, 1989 and 4199 all these give same hash value i.e 9\n1471 and 6171 give hash value 1 " }, { "code": null, "e": 28674, "s": 28284, "text": "Probability that the first 3 slots are unfilled after the first 3 insertions = \n (probability that first item doesn't go in any of the first 3 slots)*\n (probability that second item doesn't go in any of the first 3 slots)*\n (probability that third item doesn't go in any of the first 3 slots)\n\n = (97/100) * (97/100) * (97/100) " }, { "code": null, "e": 28827, "s": 28674, "text": "Which one of the following hash functions on integers will distribute keys most uniformly over 10 buckets numbered 0 to 9 for i ranging from 0 to 2020? " }, { "code": null, "e": 28851, "s": 28827, "text": "h(i) = (12 ∗ i) mod 10 " }, { "code": null, "e": 28876, "s": 28851, "text": "h(i) = (11 ∗ i2) mod 10 " }, { "code": null, "e": 28893, "s": 28876, "text": "h(i) =i3 mod 10 " }, { "code": null, "e": 28911, "s": 28893, "text": "h(i) =i2 mod 10 " }, { "code": null, "e": 29017, "s": 28911, "text": "Since mod 10 is used, the last digit matters. If you do cube all numbers from 0 to 9, you get following " }, { "code": null, "e": 29342, "s": 29017, "text": "Number Cube Last Digit in Cube\n 0 0 0 \n 1 1 1 \n 2 8 8 \n 3 27 7 \n 4 64 4 \n 5 125 5 \n 6 216 6\n 7 343 3\n 8 512 2\n 9 729 9 " }, { "code": null, "e": 29615, "s": 29342, "text": "Therefore all numbers from 0 to 2020 are equally divided in 10 buckets. If we make a table for square, we don't get equal distribution. In the following table. 1, 4, 6 and 9 are repeated, so these buckets would have more entries and buckets 2, 3, 7 and 8 would be empty. " }, { "code": null, "e": 29943, "s": 29615, "text": "Number Square Last Digit in Square\n 0 0 0 \n 1 1 1 \n 2 4 4 \n 3 9 9 \n 4 16 6\n 5 25 5 \n 6 36 6\n 7 49 9\n 8 64 4\n 9 81 1 " }, { "code": null, "e": 30218, "s": 29943, "text": "Alternative approach - Using concept of power of cycle: (a) (0,1,4,9,6,5,6,9,4,1,0) repeated (b) (0,1,8,7,4,5,6,3,2,9) repeated (c) (0,1,4,9,6,5,6,9,4,1,0) repeated (d) (0,2,4,6,8) repeated So, only h(i) =i3 mod 10 covers all the digits from 0 to 9. Option (B) is correct. " }, { "code": null, "e": 30460, "s": 30218, "text": "A hash function takes a message of arbitrary length and generates a fixed length code.A hash function takes a message of fixed length and generates a code of variable length.A hash function may give the same hash value for distinct messages." }, { "code": null, "e": 30547, "s": 30460, "text": "A hash function takes a message of arbitrary length and generates a fixed length code." }, { "code": null, "e": 30636, "s": 30547, "text": "A hash function takes a message of fixed length and generates a code of variable length." }, { "code": null, "e": 30704, "s": 30636, "text": "A hash function may give the same hash value for distinct messages." }, { "code": null, "e": 30802, "s": 30704, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 30811, "s": 30802, "text": "Comments" }, { "code": null, "e": 30824, "s": 30811, "text": "Old Comments" }, { "code": null, "e": 30877, "s": 30824, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 30913, "s": 30877, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 30979, "s": 30913, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 31040, "s": 30979, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31078, "s": 31040, "text": "Array of Objects in C++ with Examples" }, { "code": null, "e": 31140, "s": 31078, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 31220, "s": 31140, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 31261, "s": 31220, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 31296, "s": 31261, "text": "Insert Image in a Jupyter Notebook" } ]
Programs for printing pyramid patterns in Python - GeeksforGeeks
18 Dec, 2021 Patterns can be printed in python using simple for loops. First outer loop is used to handle number of rows and Inner nested loop is used to handle the number of columns. Manipulating the print statements, different number patterns, alphabet patterns or star patterns can be printed. Some of the Patterns are shown in this article. Simple pyramid pattern Python3 # Python 3.x code to demonstrate star pattern # Function to demonstrate printing patterndef pypart(n): # outer loop to handle number of rows # n in this case for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ",end="") # ending line after each row print("\r") # Driver Coden = 5pypart(n) * * * * * * * * * * * * * * * Another Approach: Using List in Python 3, this could be done in a simpler way Python # Python 3.x code to demonstrate star pattern # Function to demonstrate printing patterndef pypart(n): myList = [] for i in range(1,n+1): myList.append("*"*i) print("\n".join(myList)) # Driver Coden = 5pypart(n) * ** *** **** ***** After 180 degree rotation Python3 # Python 3.x code to demonstrate star pattern # Function to demonstrate printing patterndef pypart2(n): # number of spaces k = 2*n - 2 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=" ") # decrementing k after each loop k = k - 2 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ", end="") # ending line after each row print("\r") # Driver Coden = 5pypart2(n) * * * * * * * * * * * * * * * Printing Triangle Python3 # Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern triangledef triangle(n): # number of spaces k = n - 1 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=" ") # decrementing k after each loop k = k - 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print("* ", end="") # ending line after each row print("\r") # Driver Coden = 5triangle(n) * * * * * * * * * * * * * * * Number Pattern Python3 # Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern of numbersdef numpat(n): # initialising starting number num = 1 # outer loop to handle number of rows for i in range(0, n): # re assigning num num = 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing number print(num, end=" ") # incrementing number at each column num = num + 1 # ending line after each row print("\r") # Driver coden = 5numpat(n) 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Numbers without reassigning Python3 # Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern of numbersdef contnum(n): # initializing starting number num = 1 # outer loop to handle number of rows for i in range(0, n): # not re assigning num # num = 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing number print(num, end=" ") # incrementing number at each column num = num + 1 # ending line after each row print("\r") n = 5 # sending 5 as argument# calling Functioncontnum(n) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Character Pattern Python3 # Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern of alphabetsdef alphapat(n): # initializing value corresponding to 'A' # ASCII value num = 65 # outer loop to handle number of rows # 5 in this case for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # explicitly converting to char ch = chr(num) # printing char value print(ch, end=" ") # incrementing number num = num + 1 # ending line after each row print("\r") # Driver Coden = 5alphapat(n) A B B C C C D D D D E E E E E Continuous Character pattern Python3 # Python code 3.x to demonstrate star pattern # Function to demonstrate printing pattern of alphabetsdef contalpha(n): # initializing value corresponding to 'A' # ASCII value num = 65 # outer loop to handle number of rows- for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # explicitly converting to char ch = chr(num) # printing char value print(ch, end=" ") # incrementing at each column num = num +1 # ending line after each row print("\r") # Driver coden = 5contalpha(n) Output: A B C D E F G H I J K L M N O This article is contributed by Manjeet Singh(S.Nupur) . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. aneeshgarray2000 kskaman simranarora5sos pattern-printing Python Pattern-printing Python School Programming pattern-printing 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 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24256, "s": 24228, "text": "\n18 Dec, 2021" }, { "code": null, "e": 24589, "s": 24256, "text": "Patterns can be printed in python using simple for loops. First outer loop is used to handle number of rows and Inner nested loop is used to handle the number of columns. Manipulating the print statements, different number patterns, alphabet patterns or star patterns can be printed. Some of the Patterns are shown in this article. " }, { "code": null, "e": 24612, "s": 24589, "text": "Simple pyramid pattern" }, { "code": null, "e": 24620, "s": 24612, "text": "Python3" }, { "code": "# Python 3.x code to demonstrate star pattern # Function to demonstrate printing patterndef pypart(n): # outer loop to handle number of rows # n in this case for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print(\"* \",end=\"\") # ending line after each row print(\"\\r\") # Driver Coden = 5pypart(n)", "e": 25098, "s": 24620, "text": null }, { "code": null, "e": 25133, "s": 25098, "text": "* \n* * \n* * * \n* * * * \n* * * * * " }, { "code": null, "e": 25211, "s": 25133, "text": "Another Approach: Using List in Python 3, this could be done in a simpler way" }, { "code": null, "e": 25218, "s": 25211, "text": "Python" }, { "code": "# Python 3.x code to demonstrate star pattern # Function to demonstrate printing patterndef pypart(n): myList = [] for i in range(1,n+1): myList.append(\"*\"*i) print(\"\\n\".join(myList)) # Driver Coden = 5pypart(n)", "e": 25446, "s": 25218, "text": null }, { "code": null, "e": 25466, "s": 25446, "text": "*\n**\n***\n****\n*****" }, { "code": null, "e": 25492, "s": 25466, "text": "After 180 degree rotation" }, { "code": null, "e": 25500, "s": 25492, "text": "Python3" }, { "code": "# Python 3.x code to demonstrate star pattern # Function to demonstrate printing patterndef pypart2(n): # number of spaces k = 2*n - 2 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=\" \") # decrementing k after each loop k = k - 2 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print(\"* \", end=\"\") # ending line after each row print(\"\\r\") # Driver Coden = 5pypart2(n)", "e": 26209, "s": 25500, "text": null }, { "code": null, "e": 26264, "s": 26209, "text": " * \n * * \n * * * \n * * * * \n* * * * * " }, { "code": null, "e": 26282, "s": 26264, "text": "Printing Triangle" }, { "code": null, "e": 26290, "s": 26282, "text": "Python3" }, { "code": "# Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern triangledef triangle(n): # number of spaces k = n - 1 # outer loop to handle number of rows for i in range(0, n): # inner loop to handle number spaces # values changing acc. to requirement for j in range(0, k): print(end=\" \") # decrementing k after each loop k = k - 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing stars print(\"* \", end=\"\") # ending line after each row print(\"\\r\") # Driver Coden = 5triangle(n)", "e": 27008, "s": 26290, "text": null }, { "code": null, "e": 27053, "s": 27008, "text": " * \n * * \n * * * \n * * * * \n* * * * * " }, { "code": null, "e": 27068, "s": 27053, "text": "Number Pattern" }, { "code": null, "e": 27076, "s": 27068, "text": "Python3" }, { "code": "# Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern of numbersdef numpat(n): # initialising starting number num = 1 # outer loop to handle number of rows for i in range(0, n): # re assigning num num = 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing number print(num, end=\" \") # incrementing number at each column num = num + 1 # ending line after each row print(\"\\r\") # Driver coden = 5numpat(n)", "e": 27728, "s": 27076, "text": null }, { "code": null, "e": 27763, "s": 27728, "text": "1 \n1 2 \n1 2 3 \n1 2 3 4 \n1 2 3 4 5 " }, { "code": null, "e": 27791, "s": 27763, "text": "Numbers without reassigning" }, { "code": null, "e": 27799, "s": 27791, "text": "Python3" }, { "code": "# Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern of numbersdef contnum(n): # initializing starting number num = 1 # outer loop to handle number of rows for i in range(0, n): # not re assigning num # num = 1 # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # printing number print(num, end=\" \") # incrementing number at each column num = num + 1 # ending line after each row print(\"\\r\") n = 5 # sending 5 as argument# calling Functioncontnum(n)", "e": 28480, "s": 27799, "text": null }, { "code": null, "e": 28521, "s": 28480, "text": "1 \n2 3 \n4 5 6 \n7 8 9 10 \n11 12 13 14 15 " }, { "code": null, "e": 28539, "s": 28521, "text": "Character Pattern" }, { "code": null, "e": 28547, "s": 28539, "text": "Python3" }, { "code": "# Python 3.x code to demonstrate star pattern # Function to demonstrate printing pattern of alphabetsdef alphapat(n): # initializing value corresponding to 'A' # ASCII value num = 65 # outer loop to handle number of rows # 5 in this case for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # explicitly converting to char ch = chr(num) # printing char value print(ch, end=\" \") # incrementing number num = num + 1 # ending line after each row print(\"\\r\") # Driver Coden = 5alphapat(n)", "e": 29253, "s": 28547, "text": null }, { "code": null, "e": 29288, "s": 29253, "text": "A \nB B \nC C C \nD D D D \nE E E E E " }, { "code": null, "e": 29317, "s": 29288, "text": "Continuous Character pattern" }, { "code": null, "e": 29325, "s": 29317, "text": "Python3" }, { "code": "# Python code 3.x to demonstrate star pattern # Function to demonstrate printing pattern of alphabetsdef contalpha(n): # initializing value corresponding to 'A' # ASCII value num = 65 # outer loop to handle number of rows- for i in range(0, n): # inner loop to handle number of columns # values changing acc. to outer loop for j in range(0, i+1): # explicitly converting to char ch = chr(num) # printing char value print(ch, end=\" \") # incrementing at each column num = num +1 # ending line after each row print(\"\\r\") # Driver coden = 5contalpha(n)", "e": 30038, "s": 29325, "text": null }, { "code": null, "e": 30046, "s": 30038, "text": "Output:" }, { "code": null, "e": 30080, "s": 30046, "text": "A \nB C \nD E F \nG H I J \nK L M N O" }, { "code": null, "e": 30511, "s": 30080, "text": "This article is contributed by Manjeet Singh(S.Nupur) . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 30531, "s": 30514, "text": "aneeshgarray2000" }, { "code": null, "e": 30539, "s": 30531, "text": "kskaman" }, { "code": null, "e": 30555, "s": 30539, "text": "simranarora5sos" }, { "code": null, "e": 30572, "s": 30555, "text": "pattern-printing" }, { "code": null, "e": 30596, "s": 30572, "text": "Python Pattern-printing" }, { "code": null, "e": 30603, "s": 30596, "text": "Python" }, { "code": null, "e": 30622, "s": 30603, "text": "School Programming" }, { "code": null, "e": 30639, "s": 30622, "text": "pattern-printing" }, { "code": null, "e": 30737, "s": 30639, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30755, "s": 30737, "text": "Python Dictionary" }, { "code": null, "e": 30790, "s": 30755, "text": "Read a file line by line in Python" }, { "code": null, "e": 30812, "s": 30790, "text": "Enumerate() in Python" }, { "code": null, "e": 30844, "s": 30812, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30874, "s": 30844, "text": "Iterate over a list in Python" }, { "code": null, "e": 30892, "s": 30874, "text": "Python Dictionary" }, { "code": null, "e": 30908, "s": 30892, "text": "Arrays in C/C++" }, { "code": null, "e": 30927, "s": 30908, "text": "Inheritance in C++" }, { "code": null, "e": 30952, "s": 30927, "text": "Reverse a string in Java" } ]
D3.js - Collections API
A collection is simply an object that groups multiple elements into a single unit. It is also called as a container. This chapter explains about collections API in detail. You can configure the API using the following script. <script src = "https://d3js.org/d3-collection.v1.min.js"></script> <script> </script> Collections API contains objects, maps, sets and nests. Following are the most commonly used collections API methods. Objects API Maps API Sets API Nests API Let us go through each of these API in detail. Object API is one of the important data type. It supports the following methods − d3.keys(object) − This method contains the object property keys and returns an array of the property names. d3.keys(object) − This method contains the object property keys and returns an array of the property names. d3.values(object) − This method contains the object values and returns an array of property values. d3.values(object) − This method contains the object values and returns an array of property values. d3.entries(object) − This method is used to return an array containing both keys and values of the specified object. Each entry is an object with a key and value. d3.entries(object) − This method is used to return an array containing both keys and values of the specified object. Each entry is an object with a key and value. Example − Let us consider the following code. d3.entries({one: 1}) Here, key is one and value is 1. Example − Create a webpage objects.html and add the following changes to it. <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3>D3 collection API</h3> <script> var month = {"jan": 1, "Feb": 2, "mar": 3, "apr": 4}; console.log(d3.keys(month)); console.log(d3.values(month)); console.log(d3.entries(month)); </script> </body> </html> Now, request the browser and you will see the following response. A map contains values based on key and value pairs. Each key and value pair is known as an entry. A Map contains only unique keys. It is useful to search, update or delete elements based on the key. Let us go through the various Maps API methods in detail. d3.map([object[, key]]) − This method is used to create a new map. Object is used to copy all enumerable properties. d3.map([object[, key]]) − This method is used to create a new map. Object is used to copy all enumerable properties. map.has(key) − This method is used to check whether map has an entry for the specified key string. map.has(key) − This method is used to check whether map has an entry for the specified key string. map.get(key) − This method is used to return the value for the specified key string. map.get(key) − This method is used to return the value for the specified key string. map.set(key, value) − This method is used to set the value for the specified key string. If the map previously had an entry for the same key string, the old entry is replaced with the new value. map.set(key, value) − This method is used to set the value for the specified key string. If the map previously had an entry for the same key string, the old entry is replaced with the new value. map.remove(key) − It is used to remove the map entry. If the key is not specified, it returns false. map.remove(key) − It is used to remove the map entry. If the key is not specified, it returns false. map.clear() − Removes all entries from this map. map.clear() − Removes all entries from this map. map.keys() − Returns an array of string keys for every entry in this map. map.keys() − Returns an array of string keys for every entry in this map. map.values() − Returns an array of values for every entry in this map. map.values() − Returns an array of values for every entry in this map. map.entries() − Returns an array of key-value objects for each entry in this map. map.entries() − Returns an array of key-value objects for each entry in this map. (x) map.each(function) − This method is used to call the specified function for each entry in the map. (x) map.each(function) − This method is used to call the specified function for each entry in the map. (xi) map.empty() − Returns true if and only if this map has zero entries. (xi) map.empty() − Returns true if and only if this map has zero entries. (xii) map.size() − Returns the number of entries in this map. (xii) map.size() − Returns the number of entries in this map. Example − Create a webpage maps.html and add the following changes to it. <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3>D3 collection API</h3> <script> var month = d3.map([{name: "jan"}, {name: "feb"}], function(d) { return d.name; }); console.log(month.get("jan")); // {"name": "jan"} console.log(month.get("apr")); // undefined console.log(month.has("feb")); // true var map = d3.map().set("fruit", "mango"); console.log(map.get("fruit")); // mango console.log(map.remove("fruit")); // remove key and return true. console.log(map.size()); // size is 0 because key removed. console.log(map.empty()); // true </script> </body> </html> Now, request the browser and we will see the following response. Similarly, you can perform other operations as well. A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. Let us go through the various Sets API methods in detail. d3.set([array[, accessor]]) − This method is used to create a new set. Array is used to add string values. An accessor is optional. d3.set([array[, accessor]]) − This method is used to create a new set. Array is used to add string values. An accessor is optional. set.has(value) − This method is used to check whether the set has an entry for the specified value string. set.has(value) − This method is used to check whether the set has an entry for the specified value string. set.add(value) − It is used to add the specified value string to the set. set.add(value) − It is used to add the specified value string to the set. set.remove(value) − It is used to remove the set that contains the specified value string. set.remove(value) − It is used to remove the set that contains the specified value string. set.clear() − Removes all the values from this set. set.clear() − Removes all the values from this set. set.values() − This method is used to return an array of values to the set. set.values() − This method is used to return an array of values to the set. set.empty() − Returns true if and only if this set has zero values. set.empty() − Returns true if and only if this set has zero values. set.size() − Returns the number of values in this set. set.size() − Returns the number of values in this set. Example − Create a webpage sets.html and add the following changes to it. <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3>D3 collection API</h3> <script> var fruits = d3.set().add("mango") .add("apple").add("orange"); console.log(fruits.has("grapes")); // return false. console.log(fruits.remove("apple")); //true console.log(fruits.size()); // size is 2 console.log(fruits.empty()); // true </script> </body> </html> Now, request the browser and we will see the following response on our screen. Similarly, we can perform other operations as well. Nesting API contains elements in array and performs in a hierarchical tree structure. Let us go through the various Nests API methods in detail. d3.nest() − This method is used to create a new nest. d3.nest() − This method is used to create a new nest. nest.key(key) − This method is used to initialize a new key function. This function is used to invoke each element in an input array and return elements in the group. nest.key(key) − This method is used to initialize a new key function. This function is used to invoke each element in an input array and return elements in the group. nest.sortKeys(comparator) − This method is used to sort keys in a specified comparator. Function is defined as d3.ascending or d3.descending. nest.sortKeys(comparator) − This method is used to sort keys in a specified comparator. Function is defined as d3.ascending or d3.descending. nest.sortValues(comparator) − This method is used to sort values in a specified comparator. Comparator function sorts leaf elements. nest.sortValues(comparator) − This method is used to sort values in a specified comparator. Comparator function sorts leaf elements. nest.map(array) − This method is used to apply the specified array and in returning a nested map. Each entry in the returned map corresponds to a distinct key value returned by the first key function. The entry value depends on the number of registered key functions. nest.map(array) − This method is used to apply the specified array and in returning a nested map. Each entry in the returned map corresponds to a distinct key value returned by the first key function. The entry value depends on the number of registered key functions. nest.object(array) − This method is used to apply the nest operator to the specified array and return a nested object. nest.object(array) − This method is used to apply the nest operator to the specified array and return a nested object. nest.entries(array) − This method is used to apply the nest operator to the specified array and return an array of key-values entries. nest.entries(array) − This method is used to apply the nest operator to the specified array and return an array of key-values entries. Consider a simple webpage nest.html to perform the above discussed nest methods. Example − Let us consider the following example. <html> <head> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> </head> <body> <h3>D3 Nest API</h3> <script> var data = [ { "color" : "red", "key" : 1 }, { "color" : "green", "key" : 2 }, { "color" : "blue", "key" : 75 } ] var nest = d3.nest() .key(function (d) { return d.color; }) .entries(data)console.log(nest); var filter = nest.filter(function (d) { return d.key = = = 'red' }) console.log(filter); </script> </body> </html> Now, check the result in a browser and we will see the following result. Array[3] 0: Object 1: Object 2: Object length: 3 __proto__: Array[0] Array[1] 0: Object length: 1 __proto__: Array[0] Print Add Notes Bookmark this page
[ { "code": null, "e": 2302, "s": 2130, "text": "A collection is simply an object that groups multiple elements into a single unit. It is also called as a container. This chapter explains about collections API in detail." }, { "code": null, "e": 2356, "s": 2302, "text": "You can configure the API using the following script." }, { "code": null, "e": 2443, "s": 2356, "text": "<script src = \"https://d3js.org/d3-collection.v1.min.js\"></script>\n<script>\n\n</script>" }, { "code": null, "e": 2561, "s": 2443, "text": "Collections API contains objects, maps, sets and nests. Following are the most commonly used collections API methods." }, { "code": null, "e": 2573, "s": 2561, "text": "Objects API" }, { "code": null, "e": 2582, "s": 2573, "text": "Maps API" }, { "code": null, "e": 2591, "s": 2582, "text": "Sets API" }, { "code": null, "e": 2601, "s": 2591, "text": "Nests API" }, { "code": null, "e": 2648, "s": 2601, "text": "Let us go through each of these API in detail." }, { "code": null, "e": 2730, "s": 2648, "text": "Object API is one of the important data type. It supports the following methods −" }, { "code": null, "e": 2838, "s": 2730, "text": "d3.keys(object) − This method contains the object property keys and returns an array of the property names." }, { "code": null, "e": 2946, "s": 2838, "text": "d3.keys(object) − This method contains the object property keys and returns an array of the property names." }, { "code": null, "e": 3046, "s": 2946, "text": "d3.values(object) − This method contains the object values and returns an array of property values." }, { "code": null, "e": 3146, "s": 3046, "text": "d3.values(object) − This method contains the object values and returns an array of property values." }, { "code": null, "e": 3309, "s": 3146, "text": "d3.entries(object) − This method is used to return an array containing both keys and values of the specified object. Each entry is an object with a key and value." }, { "code": null, "e": 3472, "s": 3309, "text": "d3.entries(object) − This method is used to return an array containing both keys and values of the specified object. Each entry is an object with a key and value." }, { "code": null, "e": 3518, "s": 3472, "text": "Example − Let us consider the following code." }, { "code": null, "e": 3539, "s": 3518, "text": "d3.entries({one: 1})" }, { "code": null, "e": 3572, "s": 3539, "text": "Here, key is one and value is 1." }, { "code": null, "e": 3649, "s": 3572, "text": "Example − Create a webpage objects.html and add the following changes to it." }, { "code": null, "e": 4040, "s": 3649, "text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>D3 collection API</h3>\n <script>\n var month = {\"jan\": 1, \"Feb\": 2, \"mar\": 3, \"apr\": 4};\n console.log(d3.keys(month));\n console.log(d3.values(month));\n console.log(d3.entries(month));\n </script>\n </body>\n</html>" }, { "code": null, "e": 4106, "s": 4040, "text": "Now, request the browser and you will see the following response." }, { "code": null, "e": 4363, "s": 4106, "text": "A map contains values based on key and value pairs. Each key and value pair is known as an entry. A Map contains only unique keys. It is useful to search, update or delete elements based on the key. Let us go through the various Maps API methods in detail." }, { "code": null, "e": 4480, "s": 4363, "text": "d3.map([object[, key]]) − This method is used to create a new map. Object is used to copy all enumerable properties." }, { "code": null, "e": 4597, "s": 4480, "text": "d3.map([object[, key]]) − This method is used to create a new map. Object is used to copy all enumerable properties." }, { "code": null, "e": 4696, "s": 4597, "text": "map.has(key) − This method is used to check whether map has an entry for the specified key string." }, { "code": null, "e": 4795, "s": 4696, "text": "map.has(key) − This method is used to check whether map has an entry for the specified key string." }, { "code": null, "e": 4880, "s": 4795, "text": "map.get(key) − This method is used to return the value for the specified key string." }, { "code": null, "e": 4965, "s": 4880, "text": "map.get(key) − This method is used to return the value for the specified key string." }, { "code": null, "e": 5160, "s": 4965, "text": "map.set(key, value) − This method is used to set the value for the specified key string. If the map previously had an entry for the same key string, the old entry is replaced with the new value." }, { "code": null, "e": 5355, "s": 5160, "text": "map.set(key, value) − This method is used to set the value for the specified key string. If the map previously had an entry for the same key string, the old entry is replaced with the new value." }, { "code": null, "e": 5456, "s": 5355, "text": "map.remove(key) − It is used to remove the map entry. If the key is not specified, it returns false." }, { "code": null, "e": 5557, "s": 5456, "text": "map.remove(key) − It is used to remove the map entry. If the key is not specified, it returns false." }, { "code": null, "e": 5606, "s": 5557, "text": "map.clear() − Removes all entries from this map." }, { "code": null, "e": 5655, "s": 5606, "text": "map.clear() − Removes all entries from this map." }, { "code": null, "e": 5729, "s": 5655, "text": "map.keys() − Returns an array of string keys for every entry in this map." }, { "code": null, "e": 5803, "s": 5729, "text": "map.keys() − Returns an array of string keys for every entry in this map." }, { "code": null, "e": 5874, "s": 5803, "text": "map.values() − Returns an array of values for every entry in this map." }, { "code": null, "e": 5945, "s": 5874, "text": "map.values() − Returns an array of values for every entry in this map." }, { "code": null, "e": 6027, "s": 5945, "text": "map.entries() − Returns an array of key-value objects for each entry in this map." }, { "code": null, "e": 6109, "s": 6027, "text": "map.entries() − Returns an array of key-value objects for each entry in this map." }, { "code": null, "e": 6212, "s": 6109, "text": "(x) map.each(function) − This method is used to call the specified function for each entry in the map." }, { "code": null, "e": 6315, "s": 6212, "text": "(x) map.each(function) − This method is used to call the specified function for each entry in the map." }, { "code": null, "e": 6389, "s": 6315, "text": "(xi) map.empty() − Returns true if and only if this map has zero entries." }, { "code": null, "e": 6463, "s": 6389, "text": "(xi) map.empty() − Returns true if and only if this map has zero entries." }, { "code": null, "e": 6525, "s": 6463, "text": "(xii) map.size() − Returns the number of entries in this map." }, { "code": null, "e": 6587, "s": 6525, "text": "(xii) map.size() − Returns the number of entries in this map." }, { "code": null, "e": 6661, "s": 6587, "text": "Example − Create a webpage maps.html and add the following changes to it." }, { "code": null, "e": 7437, "s": 6661, "text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>D3 collection API</h3>\n <script>\n var month = d3.map([{name: \"jan\"}, {name: \"feb\"}], \n function(d) { return d.name; });\n console.log(month.get(\"jan\")); // {\"name\": \"jan\"}\n console.log(month.get(\"apr\")); // undefined\n console.log(month.has(\"feb\")); // true\n \n var map = d3.map().set(\"fruit\", \"mango\");\n console.log(map.get(\"fruit\")); // mango\n console.log(map.remove(\"fruit\")); // remove key and return true.\n console.log(map.size()); // size is 0 because key removed.\n console.log(map.empty()); // true\n </script>\n </body>\n</html>" }, { "code": null, "e": 7502, "s": 7437, "text": "Now, request the browser and we will see the following response." }, { "code": null, "e": 7555, "s": 7502, "text": "Similarly, you can perform other operations as well." }, { "code": null, "e": 7719, "s": 7555, "text": "A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. Let us go through the various Sets API methods in detail." }, { "code": null, "e": 7851, "s": 7719, "text": "d3.set([array[, accessor]]) − This method is used to create a new set. Array is used to add string values. An accessor is optional." }, { "code": null, "e": 7983, "s": 7851, "text": "d3.set([array[, accessor]]) − This method is used to create a new set. Array is used to add string values. An accessor is optional." }, { "code": null, "e": 8090, "s": 7983, "text": "set.has(value) − This method is used to check whether the set has an entry for the specified value string." }, { "code": null, "e": 8197, "s": 8090, "text": "set.has(value) − This method is used to check whether the set has an entry for the specified value string." }, { "code": null, "e": 8271, "s": 8197, "text": "set.add(value) − It is used to add the specified value string to the set." }, { "code": null, "e": 8345, "s": 8271, "text": "set.add(value) − It is used to add the specified value string to the set." }, { "code": null, "e": 8436, "s": 8345, "text": "set.remove(value) − It is used to remove the set that contains the specified value string." }, { "code": null, "e": 8527, "s": 8436, "text": "set.remove(value) − It is used to remove the set that contains the specified value string." }, { "code": null, "e": 8579, "s": 8527, "text": "set.clear() − Removes all the values from this set." }, { "code": null, "e": 8631, "s": 8579, "text": "set.clear() − Removes all the values from this set." }, { "code": null, "e": 8707, "s": 8631, "text": "set.values() − This method is used to return an array of values to the set." }, { "code": null, "e": 8783, "s": 8707, "text": "set.values() − This method is used to return an array of values to the set." }, { "code": null, "e": 8851, "s": 8783, "text": "set.empty() − Returns true if and only if this set has zero values." }, { "code": null, "e": 8919, "s": 8851, "text": "set.empty() − Returns true if and only if this set has zero values." }, { "code": null, "e": 8974, "s": 8919, "text": "set.size() − Returns the number of values in this set." }, { "code": null, "e": 9029, "s": 8974, "text": "set.size() − Returns the number of values in this set." }, { "code": null, "e": 9103, "s": 9029, "text": "Example − Create a webpage sets.html and add the following changes to it." }, { "code": null, "e": 9611, "s": 9103, "text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>D3 collection API</h3>\n <script>\n var fruits = d3.set().add(\"mango\")\n .add(\"apple\").add(\"orange\");\n console.log(fruits.has(\"grapes\")); // return false.\n console.log(fruits.remove(\"apple\")); //true\n console.log(fruits.size()); // size is 2\n console.log(fruits.empty()); // true\n </script>\n </body>\n</html>" }, { "code": null, "e": 9690, "s": 9611, "text": "Now, request the browser and we will see the following response on our screen." }, { "code": null, "e": 9742, "s": 9690, "text": "Similarly, we can perform other operations as well." }, { "code": null, "e": 9887, "s": 9742, "text": "Nesting API contains elements in array and performs in a hierarchical tree structure. Let us go through the various Nests API methods in detail." }, { "code": null, "e": 9941, "s": 9887, "text": "d3.nest() − This method is used to create a new nest." }, { "code": null, "e": 9995, "s": 9941, "text": "d3.nest() − This method is used to create a new nest." }, { "code": null, "e": 10162, "s": 9995, "text": "nest.key(key) − This method is used to initialize a new key function. This function is used to invoke each element in an input array and return elements in the group." }, { "code": null, "e": 10329, "s": 10162, "text": "nest.key(key) − This method is used to initialize a new key function. This function is used to invoke each element in an input array and return elements in the group." }, { "code": null, "e": 10471, "s": 10329, "text": "nest.sortKeys(comparator) − This method is used to sort keys in a specified comparator. Function is defined as d3.ascending or d3.descending." }, { "code": null, "e": 10613, "s": 10471, "text": "nest.sortKeys(comparator) − This method is used to sort keys in a specified comparator. Function is defined as d3.ascending or d3.descending." }, { "code": null, "e": 10746, "s": 10613, "text": "nest.sortValues(comparator) − This method is used to sort values in a specified comparator. Comparator function sorts leaf elements." }, { "code": null, "e": 10879, "s": 10746, "text": "nest.sortValues(comparator) − This method is used to sort values in a specified comparator. Comparator function sorts leaf elements." }, { "code": null, "e": 11147, "s": 10879, "text": "nest.map(array) − This method is used to apply the specified array and in returning a nested map. Each entry in the returned map corresponds to a distinct key value returned by the first key function. The entry value depends on the number of registered key functions." }, { "code": null, "e": 11415, "s": 11147, "text": "nest.map(array) − This method is used to apply the specified array and in returning a nested map. Each entry in the returned map corresponds to a distinct key value returned by the first key function. The entry value depends on the number of registered key functions." }, { "code": null, "e": 11534, "s": 11415, "text": "nest.object(array) − This method is used to apply the nest operator to the specified array and return a nested object." }, { "code": null, "e": 11653, "s": 11534, "text": "nest.object(array) − This method is used to apply the nest operator to the specified array and return a nested object." }, { "code": null, "e": 11788, "s": 11653, "text": "nest.entries(array) − This method is used to apply the nest operator to the specified array and return an array of key-values entries." }, { "code": null, "e": 11923, "s": 11788, "text": "nest.entries(array) − This method is used to apply the nest operator to the specified array and return an array of key-values entries." }, { "code": null, "e": 12004, "s": 11923, "text": "Consider a simple webpage nest.html to perform the above discussed nest methods." }, { "code": null, "e": 12053, "s": 12004, "text": "Example − Let us consider the following example." }, { "code": null, "e": 12784, "s": 12053, "text": "<html>\n <head>\n <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script>\n </head>\n\n <body>\n <h3>D3 Nest API</h3>\n <script>\n var data = [\n {\n \"color\" : \"red\",\n \"key\" : 1\n },\n {\n \"color\" : \"green\",\n \"key\" : 2\n },\n {\n \"color\" : \"blue\",\n \"key\" : 75\n }\n ]\n var nest = d3.nest()\n .key(function (d) { return d.color; })\n .entries(data)console.log(nest);\n var filter = nest.filter(function (d) { return d.key = = = 'red' })\n console.log(filter);\n </script>\n </body>\n</html>" }, { "code": null, "e": 12857, "s": 12784, "text": "Now, check the result in a browser and we will see the following result." }, { "code": null, "e": 12977, "s": 12857, "text": "Array[3]\n0: Object\n1: Object\n2: Object\nlength: 3\n__proto__: Array[0]\n\nArray[1]\n0: Object\nlength: 1\n__proto__: Array[0]\n" }, { "code": null, "e": 12984, "s": 12977, "text": " Print" }, { "code": null, "e": 12995, "s": 12984, "text": " Add Notes" } ]
How to perform fisher test in R?
The fisher test helps us to understand whether there exists a significant non-random relationship among categorical variables or not. It is applied on contingency tables because these tables are used to represent the frequency for categorical variables and we can apply it on a matrix as well as matrices have the similar form. In R, we can use fisher.test function to perform the fisher test. Live Demo M1<-matrix(1:9,ncol=3) M1 [,1] [,2] [,3] [1,] 1 4 7 [2,] 2 5 8 [3,] 3 6 9 fisher.test(M1) Fisher's Exact Test for Count Data data: M1 p-value = 0.9888 alternative hypothesis: two.sided Live Demo M2<-matrix(1:16,ncol=4) M2 [,1] [,2] [,3] [,4] [1,] 1 5 9 13 [2,] 2 6 10 14 [3,] 3 7 11 15 [4,] 4 8 12 16 fisher.test(M2) Fisher's Exact Test for Count Data data: M2 p-value = 0.9993 alternative hypothesis: two.sided Live Demo M3<-matrix(sample(0:4,9,replace=TRUE),nrow=3) M3 [,1] [,2] [,3] [1,] 0 0 4 [2,] 4 0 4 [3,] 1 2 3 fisher.test(M3) Fisher's Exact Test for Count Data data: M3 p-value = 0.5567 alternative hypothesis: two.sided Live Demo M4<-matrix(c(14,27,15,24,27,17,39,19,24),nrow=3) M4 [,1] [,2] [,3] [1,] 14 24 39 [2,] 27 27 19 [3,] 15 17 24 fisher.test(M4) Fisher's Exact Test for Count Data data: M4 p-value = 0.02126 alternative hypothesis: two.sided fisher.test(M4,alternative="greater") Fisher's Exact Test for Count Data data: M4 p-value = 0.02126 alternative hypothesis: greater fisher.test(M4,alternative="less") Fisher's Exact Test for Count Data data: M4 p-value = 0.02126 alternative hypothesis: less Live Demo M5<-matrix(sample(c(545,501,576),4,replace=TRUE),nrow=2) M5 [,1] [,2] [1,] 545 545 [2,] 545 545 fisher.test(M5) Fisher's Exact Test for Count Data data: M5 p-value = 1 alternative hypothesis: true odds ratio is not equal to 1 95 percent confidence interval: 0.8391933 1.1916205 sample estimates: odds ratio 1 fisher.test(M5,alternative="greater") Fisher's Exact Test for Count Data data: M5 p-value = 0.5175 alternative hypothesis: true odds ratio is greater than 1 95 percent confidence interval: 0.8626582 Inf sample estimates: odds ratio 1 fisher.test(M5,alternative="less") Fisher's Exact Test for Count Data data: M5 p-value = 0.5175 alternative hypothesis: true odds ratio is less than 1 95 percent confidence interval: 0.000000 1.159208 sample estimates: odds ratio 1
[ { "code": null, "e": 1456, "s": 1062, "text": "The fisher test helps us to understand whether there exists a significant non-random relationship among categorical variables or not. It is applied on contingency tables because these tables are used to represent the frequency for categorical variables and we can apply it on a matrix as well as matrices have the similar form. In R, we can use fisher.test function to perform the fisher test." }, { "code": null, "e": 1467, "s": 1456, "text": " Live Demo" }, { "code": null, "e": 1493, "s": 1467, "text": "M1<-matrix(1:9,ncol=3)\nM1" }, { "code": null, "e": 1563, "s": 1493, "text": " [,1] [,2] [,3]\n[1,] 1 4 7 \n[2,] 2 5 8\n[3,] 3 6 9" }, { "code": null, "e": 1579, "s": 1563, "text": "fisher.test(M1)" }, { "code": null, "e": 1674, "s": 1579, "text": "Fisher's Exact Test for Count\nData\ndata: M1\np-value = 0.9888\nalternative hypothesis: two.sided" }, { "code": null, "e": 1685, "s": 1674, "text": " Live Demo" }, { "code": null, "e": 1712, "s": 1685, "text": "M2<-matrix(1:16,ncol=4)\nM2" }, { "code": null, "e": 1837, "s": 1712, "text": " [,1] [,2] [,3] [,4]\n[1,] 1 5 9 13\n[2,] 2 6 10 14\n[3,] 3 7 11 15\n[4,] 4 8 12 16" }, { "code": null, "e": 1853, "s": 1837, "text": "fisher.test(M2)" }, { "code": null, "e": 1948, "s": 1853, "text": "Fisher's Exact Test for Count Data\ndata: M2\np-value = 0.9993\nalternative hypothesis: two.sided" }, { "code": null, "e": 1959, "s": 1948, "text": " Live Demo" }, { "code": null, "e": 2008, "s": 1959, "text": "M3<-matrix(sample(0:4,9,replace=TRUE),nrow=3)\nM3" }, { "code": null, "e": 2077, "s": 2008, "text": " [,1] [,2] [,3]\n[1,] 0 0 4\n[2,] 4 0 4\n[3,] 1 2 3" }, { "code": null, "e": 2093, "s": 2077, "text": "fisher.test(M3)" }, { "code": null, "e": 2188, "s": 2093, "text": "Fisher's Exact Test for Count\nData\ndata: M3\np-value = 0.5567\nalternative hypothesis: two.sided" }, { "code": null, "e": 2199, "s": 2188, "text": " Live Demo" }, { "code": null, "e": 2251, "s": 2199, "text": "M4<-matrix(c(14,27,15,24,27,17,39,19,24),nrow=3)\nM4" }, { "code": null, "e": 2324, "s": 2251, "text": " [,1] [,2] [,3]\n[1,] 14 24 39\n[2,] 27 27 19\n[3,] 15 17 24" }, { "code": null, "e": 2340, "s": 2324, "text": "fisher.test(M4)" }, { "code": null, "e": 2436, "s": 2340, "text": "Fisher's Exact Test for Count Data\ndata: M4\np-value = 0.02126\nalternative hypothesis: two.sided" }, { "code": null, "e": 2474, "s": 2436, "text": "fisher.test(M4,alternative=\"greater\")" }, { "code": null, "e": 2568, "s": 2474, "text": "Fisher's Exact Test for Count Data\ndata: M4\np-value = 0.02126\nalternative hypothesis: greater" }, { "code": null, "e": 2603, "s": 2568, "text": "fisher.test(M4,alternative=\"less\")" }, { "code": null, "e": 2694, "s": 2603, "text": "Fisher's Exact Test for Count Data\ndata: M4\np-value = 0.02126\nalternative hypothesis: less" }, { "code": null, "e": 2705, "s": 2694, "text": " Live Demo" }, { "code": null, "e": 2765, "s": 2705, "text": "M5<-matrix(sample(c(545,501,576),4,replace=TRUE),nrow=2)\nM5" }, { "code": null, "e": 2805, "s": 2765, "text": " [,1] [,2]\n[1,] 545 545\n[2,] 545 545" }, { "code": null, "e": 2821, "s": 2805, "text": "fisher.test(M5)" }, { "code": null, "e": 3018, "s": 2821, "text": "Fisher's Exact Test for Count Data\ndata: M5\np-value = 1\nalternative hypothesis: true odds ratio is not equal to 1\n95 percent confidence interval: 0.8391933 1.1916205\nsample estimates:\nodds ratio\n1" }, { "code": null, "e": 3056, "s": 3018, "text": "fisher.test(M5,alternative=\"greater\")" }, { "code": null, "e": 3252, "s": 3056, "text": "Fisher's Exact Test for Count Data\ndata: M5\np-value = 0.5175\nalternative hypothesis: true odds ratio is greater than 1\n95 percent confidence interval: 0.8626582 Inf\nsample estimates:\nodds ratio\n1" }, { "code": null, "e": 3287, "s": 3252, "text": "fisher.test(M5,alternative=\"less\")" }, { "code": null, "e": 3484, "s": 3287, "text": "Fisher's Exact Test for Count Data\ndata: M5 p-value = 0.5175\nalternative hypothesis: true\nodds ratio is less than 1\n95 percent confidence interval: 0.000000 1.159208\nsample estimates:\nodds ratio\n1" } ]
Java - String replaceFirst() Method
This method replaces the first substring of this string that matches the given regular expression with the given replacement. Here is the syntax of this method − public String replaceFirst(String regex, String replacement) Here is the detail of parameters − regex − the regular expression to which this string is to be matched. regex − the regular expression to which this string is to be matched. replacement − the string which would replace found expression. replacement − the string which would replace found expression. This method returns a resulting String. import java.io.*; public class Test { public static void main(String args[]) { String Str = new String("Welcome to Tutorialspoint.com"); System.out.print("Return Value :" ); System.out.println(Str.replaceFirst("(.*)Tutorials(.*)", "AMROOD")); System.out.print("Return Value :" ); System.out.println(Str.replaceFirst("Tutorials", "AMROOD")); } } This will produce the following result − Return Value :AMROOD Return Value :Welcome to AMROODpoint.com 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2503, "s": 2377, "text": "This method replaces the first substring of this string that matches the given regular expression with the given replacement." }, { "code": null, "e": 2540, "s": 2503, "text": "Here is the syntax of this method −" }, { "code": null, "e": 2602, "s": 2540, "text": "public String replaceFirst(String regex, String replacement)\n" }, { "code": null, "e": 2637, "s": 2602, "text": "Here is the detail of parameters −" }, { "code": null, "e": 2707, "s": 2637, "text": "regex − the regular expression to which this string is to be matched." }, { "code": null, "e": 2777, "s": 2707, "text": "regex − the regular expression to which this string is to be matched." }, { "code": null, "e": 2840, "s": 2777, "text": "replacement − the string which would replace found expression." }, { "code": null, "e": 2903, "s": 2840, "text": "replacement − the string which would replace found expression." }, { "code": null, "e": 2943, "s": 2903, "text": "This method returns a resulting String." }, { "code": null, "e": 3327, "s": 2943, "text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome to Tutorialspoint.com\");\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.replaceFirst(\"(.*)Tutorials(.*)\", \"AMROOD\"));\n\n System.out.print(\"Return Value :\" );\n System.out.println(Str.replaceFirst(\"Tutorials\", \"AMROOD\"));\n }\n}" }, { "code": null, "e": 3368, "s": 3327, "text": "This will produce the following result −" }, { "code": null, "e": 3431, "s": 3368, "text": "Return Value :AMROOD\nReturn Value :Welcome to AMROODpoint.com\n" }, { "code": null, "e": 3464, "s": 3431, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3480, "s": 3464, "text": " Malhar Lathkar" }, { "code": null, "e": 3513, "s": 3480, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3529, "s": 3513, "text": " Malhar Lathkar" }, { "code": null, "e": 3564, "s": 3529, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3578, "s": 3564, "text": " Anadi Sharma" }, { "code": null, "e": 3612, "s": 3578, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3626, "s": 3612, "text": " Tushar Kale" }, { "code": null, "e": 3663, "s": 3626, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3678, "s": 3663, "text": " Monica Mittal" }, { "code": null, "e": 3711, "s": 3678, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3730, "s": 3711, "text": " Arnab Chakraborty" }, { "code": null, "e": 3737, "s": 3730, "text": " Print" }, { "code": null, "e": 3748, "s": 3737, "text": " Add Notes" } ]
Converting an image to ASCII image in Python - GeeksforGeeks
01 Nov, 2021 Introduction to ASCII art ASCII art is a graphic design technique that uses computers for presentation and consists of pictures pieced together from the 95 printable (from a total of 128) characters defined by the ASCII Standard from 1963 and ASCII compliant character sets with proprietary extended characters (beyond the 128 characters of standard 7-bit ASCII). The term is also loosely used to refer to text based visual art in general. ASCII art can be created with any text editor, and is often used with free-form languages. Most examples of ASCII art require a fixed-width font (non-proportional fonts, as on a traditional typewriter) such as Courier for presentation. Among the oldest known examples of ASCII art are the creations by computer-art pioneer Kenneth Knowlton from around 1966, who was working for Bell Labs at the time. “Studies in Perception I” by Ken Knowlton and Leon Harmon from 1966 shows some examples of their early ASCII art. ASCII art was invented, in large part, because early printers often lacked graphics ability and thus characters were used in place of graphic marks. Also, to mark divisions between different print jobs from different users, bulk printers often used ASCII art to print large banners, making the division easier to spot so that the results could be more easily separated by a computer operator or clerk. ASCII art was also used in early e-mail when images could not be embedded. You can find more about them. [Source : Wiki. How it works: here are the steps the program takes to generate the ASCII image: Convert the input image to grayscale. Split the image into M×N tiles. Correct M (the number of rows) to match the image and font aspect ratio. Compute the average brightness for each image tile and then look up a suitable ASCII character for each. Assemble rows of ASCII character strings and print them to a file to form the final image. Requirements You will do this program in python and we will use Pillow which is Python Imaging Library for read in the images, access their underlying data, and create and modify them and also the scientific module Numpy to compute averages. The Code You’ll begin by defining the grayscale levels used to generate the ASCII art. Then you’ll look at how the image is split into tiles and how average brightness is computed for those tiles. Next, you’ll work on replacing the tiles with ASCII characters to generate the final output. Finally, you’ll set up command line parsing for the program to allow a user to specify the output size, output filename, and so on. Defining the Grayscale Levels and Grid As the first step in creating your program, define the two grayscale levels used to convert brightness values to ASCII characters as global values. >>>gscale1 = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~i!lI;:,\"^`". " #70 levels of gray >>>gscale2 = "@%#*+=-:. " #10 levels of gray The value gscale1 at u is the 70-level grayscale ramp, and gscale2 at v is the simpler 10-level grayscale ramp. Both of these values are stored as strings, with a range of characters that progress from darkest to lightest.Now that you have your grayscale ramps, you can set up the image. The following code opens the image and splits it into a grid: # open image and convert to grayscale >>> image = Image.open(fileName).convert('L') # store dimensions >>> W, H = image.size[0], image.size[1] # compute width of tile >>> w = W/cols # compute tile height based on aspect ratio and scale >>> h = w/scale # compute number of rows >>> rows = int(H/h) Computing the average brightness Next, you compute the average brightness for a tile in the grayscale image. The function getAverageL() does the job. #Given PIL Image, return average value of grayscale value >>>def getAverageL(image): # get image as numpy array ... im = np.array(image) # get shape ... w,h = im.shape # get average ... return np.average(im.reshape(w*h)) First, the image tile is passed in as a PIL Image object. Convert image into a numpy array at second step, at which point ‘im’ becomes a two-dimensional array of brightness for each pixel. At third step , you store the dimensions (width and height) of the image. At fourth step, numpy.average() computes the average of the brightness values in the image by using numpy.reshape() to first convert the two-dimensional array of the dimensions width and height (w,h) into a ?at one-dimensional array whose length is a product of the width times the height (w*h). The numpy.average() call then sums these array values and computes the average. Generating the ASCII Content from the Image # ascii image is a list of character strings >>> aimg = [] # generate list of dimensions >>> for j in range(rows): ... y1 = int(j*h) ... y2 = int((j+1)*h) # correct last tile ... if j == rows-1: ... y2 = H # append an empty string ... aimg.append("") ... for i in range(cols): # crop image to tile ... x1 = int(i*w) ... x2 = int((i+1)*w) # correct last tile ... if i == cols-1: ... x2 = W # crop image to extract tile ... img = image.crop((x1, y1, x2, y2)) # get average luminance ... avg = int(getAverageL(img)) # look up ascii char ... if moreLevels: ... gsval = gscale1[int((avg*69)/255)] ... else: ... gsval = gscale2[int((avg*9)/255)] # append ascii char to string ... aimg[j] += gsval In this section of the program, the ASCII image is first stored as a list of strings, which is initialized at first step. Next, you iterate through the calculated number of row image tiles, and at second step and the following line, you calculate the starting and ending y-coordinates of each image tile. Although these are ?oating-point calculations, truncate them to integers before passing them to an image-cropping method. Next, because dividing the image into tiles creates edge tiles of the same size only when the image width is an integer multiple of the number of columns, correct for the y-coordinate of the tiles in the last row by setting the y-coordinate to the image’s actual height. By doing so, you ensure that the top edge of the image isn’t truncated. At third step, you add an empty string into the ASCII as a compact way to represent the current image row. You’ll fill in this string next. (You treat the string as a list of characters.) At fourth step and the next line, you compute the left and right x-coordinates of each tile, and at fifth step, you correct the x-coordinate for the last tile for the same reasons you corrected the y-coordinate. Use image.crop() at sixth step to extract the image tile and then pass that tile to the getAverageL() function defined above, you scale down the average brightness value from [0, 255] to [0, 9] (the range of values for the default 10-level grayscale ramp). You then use gscale2 (the stored ramp string) as a lookup table for ASCII Art 95 the relevant ASCII value. The line at eight step is similar, except that it’s used only when the command line ?ag is set to use the ramp with 70 levels. Finally, you append the looked-up ASCII value, gsval, to the text row at last step, and the code loops until all rows are processed.Adding Command Line interface and Writing the ASCII Art Strings to a text FileTo add command line interface use the python built-in module argparse. And now finally , take the generated list of ASCII character strings and write those strings to a text file. # open a new text file >>> f = open(outFile, 'w') # write each string in the list to the new file >>> for row in aimg: ... f.write(row + '\n') # clean up >>> f.close() Then add these parts to create your program. The complete code is given below. Python # Python code to convert an image to ASCII image.import sys, random, argparseimport numpy as npimport math from PIL import Image # gray scale level values from:# http://paulbourke.net/dataformats/asciiart/ # 70 levels of graygscale1 = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. " # 10 levels of graygscale2 = '@%#*+=-:. ' def getAverageL(image): """ Given PIL Image, return average value of grayscale value """ # get image as numpy array im = np.array(image) # get shape w,h = im.shape # get average return np.average(im.reshape(w*h)) def covertImageToAscii(fileName, cols, scale, moreLevels): """ Given Image and dims (rows, cols) returns an m*n list of Images """ # declare globals global gscale1, gscale2 # open image and convert to grayscale image = Image.open(fileName).convert('L') # store dimensions W, H = image.size[0], image.size[1] print("input image dims: %d x %d" % (W, H)) # compute width of tile w = W/cols # compute tile height based on aspect ratio and scale h = w/scale # compute number of rows rows = int(H/h) print("cols: %d, rows: %d" % (cols, rows)) print("tile dims: %d x %d" % (w, h)) # check if image size is too small if cols > W or rows > H: print("Image too small for specified cols!") exit(0) # ascii image is a list of character strings aimg = [] # generate list of dimensions for j in range(rows): y1 = int(j*h) y2 = int((j+1)*h) # correct last tile if j == rows-1: y2 = H # append an empty string aimg.append("") for i in range(cols): # crop image to tile x1 = int(i*w) x2 = int((i+1)*w) # correct last tile if i == cols-1: x2 = W # crop image to extract tile img = image.crop((x1, y1, x2, y2)) # get average luminance avg = int(getAverageL(img)) # look up ascii char if moreLevels: gsval = gscale1[int((avg*69)/255)] else: gsval = gscale2[int((avg*9)/255)] # append ascii char to string aimg[j] += gsval # return txt image return aimg # main() functiondef main(): # create parser descStr = "This program converts an image into ASCII art." parser = argparse.ArgumentParser(description=descStr) # add expected arguments parser.add_argument('--file', dest='imgFile', required=True) parser.add_argument('--scale', dest='scale', required=False) parser.add_argument('--out', dest='outFile', required=False) parser.add_argument('--cols', dest='cols', required=False) parser.add_argument('--morelevels',dest='moreLevels',action='store_true') # parse args args = parser.parse_args() imgFile = args.imgFile # set output file outFile = 'out.txt' if args.outFile: outFile = args.outFile # set scale default as 0.43 which suits # a Courier font scale = 0.43 if args.scale: scale = float(args.scale) # set cols cols = 80 if args.cols: cols = int(args.cols) print('generating ASCII art...') # convert image to ascii txt aimg = covertImageToAscii(imgFile, cols, scale, args.moreLevels) # open file f = open(outFile, 'w') # write to file for row in aimg: f.write(row + '\n') # cleanup f.close() print("ASCII art written to %s" % outFile) # call mainif __name__ == '__main__': main() Input: $python "ASCII_IMAGE_GENERATOR.py" --file data/11.jpg --cols 120 Resources1. Wikipedia : ASCII_ART 2. Python Playground: Geeky Projects for the Curious Programmer by Mahesh Venkitachalam. 3. Gray Scale Level Values 4. Github Code for this article This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. surinderdawra388 varshagumber28 gulshankumarar231 surindertarika1234 kashishsoda Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 24460, "s": 24432, "text": "\n01 Nov, 2021" }, { "code": null, "e": 24487, "s": 24460, "text": "Introduction to ASCII art " }, { "code": null, "e": 25939, "s": 24487, "text": "ASCII art is a graphic design technique that uses computers for presentation and consists of pictures pieced together from the 95 printable (from a total of 128) characters defined by the ASCII Standard from 1963 and ASCII compliant character sets with proprietary extended characters (beyond the 128 characters of standard 7-bit ASCII). The term is also loosely used to refer to text based visual art in general. ASCII art can be created with any text editor, and is often used with free-form languages. Most examples of ASCII art require a fixed-width font (non-proportional fonts, as on a traditional typewriter) such as Courier for presentation. Among the oldest known examples of ASCII art are the creations by computer-art pioneer Kenneth Knowlton from around 1966, who was working for Bell Labs at the time. “Studies in Perception I” by Ken Knowlton and Leon Harmon from 1966 shows some examples of their early ASCII art. ASCII art was invented, in large part, because early printers often lacked graphics ability and thus characters were used in place of graphic marks. Also, to mark divisions between different print jobs from different users, bulk printers often used ASCII art to print large banners, making the division easier to spot so that the results could be more easily separated by a computer operator or clerk. ASCII art was also used in early e-mail when images could not be embedded. You can find more about them. [Source : Wiki." }, { "code": null, "e": 25954, "s": 25939, "text": "How it works: " }, { "code": null, "e": 26021, "s": 25954, "text": "here are the steps the program takes to generate the ASCII image: " }, { "code": null, "e": 26059, "s": 26021, "text": "Convert the input image to grayscale." }, { "code": null, "e": 26091, "s": 26059, "text": "Split the image into M×N tiles." }, { "code": null, "e": 26164, "s": 26091, "text": "Correct M (the number of rows) to match the image and font aspect ratio." }, { "code": null, "e": 26269, "s": 26164, "text": "Compute the average brightness for each image tile and then look up a suitable ASCII character for each." }, { "code": null, "e": 26360, "s": 26269, "text": "Assemble rows of ASCII character strings and print them to a file to form the final image." }, { "code": null, "e": 26375, "s": 26360, "text": "Requirements " }, { "code": null, "e": 26604, "s": 26375, "text": "You will do this program in python and we will use Pillow which is Python Imaging Library for read in the images, access their underlying data, and create and modify them and also the scientific module Numpy to compute averages." }, { "code": null, "e": 27027, "s": 26604, "text": "The Code You’ll begin by defining the grayscale levels used to generate the ASCII art. Then you’ll look at how the image is split into tiles and how average brightness is computed for those tiles. Next, you’ll work on replacing the tiles with ASCII characters to generate the final output. Finally, you’ll set up command line parsing for the program to allow a user to specify the output size, output filename, and so on. " }, { "code": null, "e": 27068, "s": 27027, "text": "Defining the Grayscale Levels and Grid " }, { "code": null, "e": 27217, "s": 27068, "text": "As the first step in creating your program, define the two grayscale levels used to convert brightness values to ASCII characters as global values. " }, { "code": null, "e": 27377, "s": 27217, "text": ">>>gscale1 = \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~i!lI;:,\\\"^`\". \" #70 levels of gray\n>>>gscale2 = \"@%#*+=-:. \" #10 levels of gray" }, { "code": null, "e": 27728, "s": 27377, "text": "The value gscale1 at u is the 70-level grayscale ramp, and gscale2 at v is the simpler 10-level grayscale ramp. Both of these values are stored as strings, with a range of characters that progress from darkest to lightest.Now that you have your grayscale ramps, you can set up the image. The following code opens the image and splits it into a grid: " }, { "code": null, "e": 28060, "s": 27728, "text": " # open image and convert to grayscale\n>>> image = Image.open(fileName).convert('L')\n # store dimensions\n>>> W, H = image.size[0], image.size[1]\n # compute width of tile\n>>> w = W/cols\n # compute tile height based on aspect ratio and scale\n>>> h = w/scale\n # compute number of rows\n>>> rows = int(H/h)" }, { "code": null, "e": 28211, "s": 28060, "text": "Computing the average brightness Next, you compute the average brightness for a tile in the grayscale image. The function getAverageL() does the job. " }, { "code": null, "e": 28453, "s": 28211, "text": "#Given PIL Image, return average value of grayscale value\n>>>def getAverageL(image):\n # get image as numpy array\n... im = np.array(image)\n # get shape\n... w,h = im.shape\n # get average\n... return np.average(im.reshape(w*h))" }, { "code": null, "e": 29093, "s": 28453, "text": "First, the image tile is passed in as a PIL Image object. Convert image into a numpy array at second step, at which point ‘im’ becomes a two-dimensional array of brightness for each pixel. At third step , you store the dimensions (width and height) of the image. At fourth step, numpy.average() computes the average of the brightness values in the image by using numpy.reshape() to first convert the two-dimensional array of the dimensions width and height (w,h) into a ?at one-dimensional array whose length is a product of the width times the height (w*h). The numpy.average() call then sums these array values and computes the average. " }, { "code": null, "e": 29138, "s": 29093, "text": "Generating the ASCII Content from the Image " }, { "code": null, "e": 30110, "s": 29138, "text": " # ascii image is a list of character strings\n>>> aimg = []\n # generate list of dimensions\n>>> for j in range(rows):\n... y1 = int(j*h)\n... y2 = int((j+1)*h)\n # correct last tile\n... if j == rows-1:\n... y2 = H\n # append an empty string\n... aimg.append(\"\")\n... for i in range(cols):\n # crop image to tile\n... x1 = int(i*w)\n... x2 = int((i+1)*w)\n # correct last tile\n... if i == cols-1:\n... x2 = W\n # crop image to extract tile\n... img = image.crop((x1, y1, x2, y2))\n # get average luminance\n... avg = int(getAverageL(img))\n # look up ascii char\n... if moreLevels:\n... gsval = gscale1[int((avg*69)/255)]\n... else:\n... gsval = gscale2[int((avg*9)/255)]\n # append ascii char to string\n... aimg[j] += gsval" }, { "code": null, "e": 32162, "s": 30110, "text": "In this section of the program, the ASCII image is first stored as a list of strings, which is initialized at first step. Next, you iterate through the calculated number of row image tiles, and at second step and the following line, you calculate the starting and ending y-coordinates of each image tile. Although these are ?oating-point calculations, truncate them to integers before passing them to an image-cropping method. Next, because dividing the image into tiles creates edge tiles of the same size only when the image width is an integer multiple of the number of columns, correct for the y-coordinate of the tiles in the last row by setting the y-coordinate to the image’s actual height. By doing so, you ensure that the top edge of the image isn’t truncated. At third step, you add an empty string into the ASCII as a compact way to represent the current image row. You’ll fill in this string next. (You treat the string as a list of characters.) At fourth step and the next line, you compute the left and right x-coordinates of each tile, and at fifth step, you correct the x-coordinate for the last tile for the same reasons you corrected the y-coordinate. Use image.crop() at sixth step to extract the image tile and then pass that tile to the getAverageL() function defined above, you scale down the average brightness value from [0, 255] to [0, 9] (the range of values for the default 10-level grayscale ramp). You then use gscale2 (the stored ramp string) as a lookup table for ASCII Art 95 the relevant ASCII value. The line at eight step is similar, except that it’s used only when the command line ?ag is set to use the ramp with 70 levels. Finally, you append the looked-up ASCII value, gsval, to the text row at last step, and the code loops until all rows are processed.Adding Command Line interface and Writing the ASCII Art Strings to a text FileTo add command line interface use the python built-in module argparse. And now finally , take the generated list of ASCII character strings and write those strings to a text file. " }, { "code": null, "e": 32333, "s": 32162, "text": "# open a new text file\n>>> f = open(outFile, 'w')\n# write each string in the list to the new file\n>>> for row in aimg:\n... f.write(row + '\\n')\n# clean up\n>>> f.close()" }, { "code": null, "e": 32413, "s": 32333, "text": "Then add these parts to create your program. The complete code is given below. " }, { "code": null, "e": 32420, "s": 32413, "text": "Python" }, { "code": "# Python code to convert an image to ASCII image.import sys, random, argparseimport numpy as npimport math from PIL import Image # gray scale level values from:# http://paulbourke.net/dataformats/asciiart/ # 70 levels of graygscale1 = \"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \" # 10 levels of graygscale2 = '@%#*+=-:. ' def getAverageL(image): \"\"\" Given PIL Image, return average value of grayscale value \"\"\" # get image as numpy array im = np.array(image) # get shape w,h = im.shape # get average return np.average(im.reshape(w*h)) def covertImageToAscii(fileName, cols, scale, moreLevels): \"\"\" Given Image and dims (rows, cols) returns an m*n list of Images \"\"\" # declare globals global gscale1, gscale2 # open image and convert to grayscale image = Image.open(fileName).convert('L') # store dimensions W, H = image.size[0], image.size[1] print(\"input image dims: %d x %d\" % (W, H)) # compute width of tile w = W/cols # compute tile height based on aspect ratio and scale h = w/scale # compute number of rows rows = int(H/h) print(\"cols: %d, rows: %d\" % (cols, rows)) print(\"tile dims: %d x %d\" % (w, h)) # check if image size is too small if cols > W or rows > H: print(\"Image too small for specified cols!\") exit(0) # ascii image is a list of character strings aimg = [] # generate list of dimensions for j in range(rows): y1 = int(j*h) y2 = int((j+1)*h) # correct last tile if j == rows-1: y2 = H # append an empty string aimg.append(\"\") for i in range(cols): # crop image to tile x1 = int(i*w) x2 = int((i+1)*w) # correct last tile if i == cols-1: x2 = W # crop image to extract tile img = image.crop((x1, y1, x2, y2)) # get average luminance avg = int(getAverageL(img)) # look up ascii char if moreLevels: gsval = gscale1[int((avg*69)/255)] else: gsval = gscale2[int((avg*9)/255)] # append ascii char to string aimg[j] += gsval # return txt image return aimg # main() functiondef main(): # create parser descStr = \"This program converts an image into ASCII art.\" parser = argparse.ArgumentParser(description=descStr) # add expected arguments parser.add_argument('--file', dest='imgFile', required=True) parser.add_argument('--scale', dest='scale', required=False) parser.add_argument('--out', dest='outFile', required=False) parser.add_argument('--cols', dest='cols', required=False) parser.add_argument('--morelevels',dest='moreLevels',action='store_true') # parse args args = parser.parse_args() imgFile = args.imgFile # set output file outFile = 'out.txt' if args.outFile: outFile = args.outFile # set scale default as 0.43 which suits # a Courier font scale = 0.43 if args.scale: scale = float(args.scale) # set cols cols = 80 if args.cols: cols = int(args.cols) print('generating ASCII art...') # convert image to ascii txt aimg = covertImageToAscii(imgFile, cols, scale, args.moreLevels) # open file f = open(outFile, 'w') # write to file for row in aimg: f.write(row + '\\n') # cleanup f.close() print(\"ASCII art written to %s\" % outFile) # call mainif __name__ == '__main__': main()", "e": 35993, "s": 32420, "text": null }, { "code": null, "e": 36002, "s": 35993, "text": "Input: " }, { "code": null, "e": 36067, "s": 36002, "text": "$python \"ASCII_IMAGE_GENERATOR.py\" --file data/11.jpg --cols 120" }, { "code": null, "e": 36671, "s": 36067, "text": "Resources1. Wikipedia : ASCII_ART 2. Python Playground: Geeky Projects for the Curious Programmer by Mahesh Venkitachalam. 3. Gray Scale Level Values 4. Github Code for this article This article is contributed by Subhajit Saha. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 36688, "s": 36671, "text": "surinderdawra388" }, { "code": null, "e": 36703, "s": 36688, "text": "varshagumber28" }, { "code": null, "e": 36721, "s": 36703, "text": "gulshankumarar231" }, { "code": null, "e": 36740, "s": 36721, "text": "surindertarika1234" }, { "code": null, "e": 36752, "s": 36740, "text": "kashishsoda" }, { "code": null, "e": 36759, "s": 36752, "text": "Python" }, { "code": null, "e": 36857, "s": 36759, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36866, "s": 36857, "text": "Comments" }, { "code": null, "e": 36879, "s": 36866, "text": "Old Comments" }, { "code": null, "e": 36897, "s": 36879, "text": "Python Dictionary" }, { "code": null, "e": 36932, "s": 36897, "text": "Read a file line by line in Python" }, { "code": null, "e": 36954, "s": 36932, "text": "Enumerate() in Python" }, { "code": null, "e": 36986, "s": 36954, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 37016, "s": 36986, "text": "Iterate over a list in Python" }, { "code": null, "e": 37058, "s": 37016, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 37084, "s": 37058, "text": "Python String | replace()" }, { "code": null, "e": 37127, "s": 37084, "text": "Python program to convert a list to string" }, { "code": null, "e": 37171, "s": 37127, "text": "Reading and Writing to text files in Python" } ]
MySQL - GROUP BY Clause
You can use GROUP BY to group values from a column, and, if you wish, perform calculations on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column. To understand GROUP BY clause, consider an employee_tbl table, which is having the following records − mysql> SELECT * FROM employee_tbl; +------+------+------------+--------------------+ | id | name | work_date | daily_typing_pages | +------+------+------------+--------------------+ | 1 | John | 2007-01-24 | 250 | | 2 | Ram | 2007-05-27 | 220 | | 3 | Jack | 2007-05-06 | 170 | | 3 | Jack | 2007-04-06 | 100 | | 4 | Jill | 2007-04-06 | 220 | | 5 | Zara | 2007-06-06 | 300 | | 5 | Zara | 2007-02-06 | 350 | +------+------+------------+--------------------+ 7 rows in set (0.00 sec) Now, suppose based on the above table we want to count number of days each employee did work. If we will write a SQL query as follows, then we will get the following result − mysql> SELECT COUNT(*) FROM employee_tbl; +---------------------------+ | COUNT(*) | +---------------------------+ | 7 | +---------------------------+ But this is not serving our purpose, we want to display total number of pages typed by each person separately. This is done by using aggregate functions in conjunction with a GROUP BY clause as follows − mysql> SELECT name, COUNT(*) -> FROM employee_tbl -> GROUP BY name; +------+----------+ | name | COUNT(*) | +------+----------+ | Jack | 2 | | Jill | 1 | | John | 1 | | Ram | 1 | | Zara | 2 | +------+----------+ 5 rows in set (0.04 sec) We will see more functionality related to GROUP BY in other functions like SUM, AVG, etc. 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2508, "s": 2333, "text": "You can use GROUP BY to group values from a column, and, if you wish, perform calculations on that column. You can use COUNT, SUM, AVG, etc., functions on the grouped column." }, { "code": null, "e": 2611, "s": 2508, "text": "To understand GROUP BY clause, consider an employee_tbl table, which is having the following records −" }, { "code": null, "e": 3221, "s": 2611, "text": "mysql> SELECT * FROM employee_tbl;\n+------+------+------------+--------------------+\n| id | name | work_date | daily_typing_pages |\n+------+------+------------+--------------------+\n| 1 | John | 2007-01-24 | 250 |\n| 2 | Ram | 2007-05-27 | 220 |\n| 3 | Jack | 2007-05-06 | 170 |\n| 3 | Jack | 2007-04-06 | 100 |\n| 4 | Jill | 2007-04-06 | 220 |\n| 5 | Zara | 2007-06-06 | 300 |\n| 5 | Zara | 2007-02-06 | 350 |\n+------+------+------------+--------------------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 3315, "s": 3221, "text": "Now, suppose based on the above table we want to count number of days each employee did work." }, { "code": null, "e": 3396, "s": 3315, "text": "If we will write a SQL query as follows, then we will get the following result −" }, { "code": null, "e": 3588, "s": 3396, "text": "mysql> SELECT COUNT(*) FROM employee_tbl;\n+---------------------------+\n| COUNT(*) |\n+---------------------------+\n| 7 |\n+---------------------------+" }, { "code": null, "e": 3792, "s": 3588, "text": "But this is not serving our purpose, we want to display total number of pages typed by each person separately. This is done by using aggregate functions in conjunction with a GROUP BY clause as follows −" }, { "code": null, "e": 4074, "s": 3792, "text": "mysql> SELECT name, COUNT(*)\n -> FROM employee_tbl \n -> GROUP BY name;\n+------+----------+\n| name | COUNT(*) |\n+------+----------+\n| Jack | 2 |\n| Jill | 1 |\n| John | 1 |\n| Ram | 1 |\n| Zara | 2 |\n+------+----------+\n5 rows in set (0.04 sec)" }, { "code": null, "e": 4164, "s": 4074, "text": "We will see more functionality related to GROUP BY in other functions like SUM, AVG, etc." }, { "code": null, "e": 4197, "s": 4164, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 4225, "s": 4197, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4260, "s": 4225, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 4277, "s": 4260, "text": " Frahaan Hussain" }, { "code": null, "e": 4311, "s": 4277, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4346, "s": 4311, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4380, "s": 4346, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 4408, "s": 4380, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 4441, "s": 4408, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 4461, "s": 4441, "text": " Harshit Srivastava" }, { "code": null, "e": 4494, "s": 4461, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 4512, "s": 4494, "text": " Trevoir Williams" }, { "code": null, "e": 4519, "s": 4512, "text": " Print" }, { "code": null, "e": 4530, "s": 4519, "text": " Add Notes" } ]
How to read the windows host file using PowerShell?
Windows Host file that maps the hostname and the IP address is the plain text file. So reading the host file is simpler. We just need to use the Get-Content command to retrieve the file content. Generally, the host file is stored at the location c:\windows\System32\drivers\etc\. If the OS is installed at that location. Or you can use $env:Windir to get the windows directory. To get the file content, Get-Content $env:windir\system32\drivers\etc\hosts # Additionally, comments (such as these) may be inserted on individual # lines or following the machine name denoted by a '#' symbol. # # For example: # # 102.54.94.97 rhino.acme.com # source server # 38.25.63.10 x.acme.com # x client host # localhost name resolution is handled within DNS itself. # 127.0.0.1 localhost # ::1 localhost To get the host file from the remote server, Get-Content \\Computer1\c$\windows\system32\drivers\etc\hosts
[ { "code": null, "e": 1257, "s": 1062, "text": "Windows Host file that maps the hostname and the IP address is the plain text file. So reading the host file is simpler. We just need to use the Get-Content command to retrieve the file content." }, { "code": null, "e": 1384, "s": 1257, "text": "Generally, the host file is stored at the location c:\\windows\\System32\\drivers\\etc\\. If the OS is installed at that location." }, { "code": null, "e": 1441, "s": 1384, "text": "Or you can use $env:Windir to get the windows directory." }, { "code": null, "e": 1466, "s": 1441, "text": "To get the file content," }, { "code": null, "e": 1517, "s": 1466, "text": "Get-Content $env:windir\\system32\\drivers\\etc\\hosts" }, { "code": null, "e": 1925, "s": 1517, "text": "# Additionally, comments (such as these) may be inserted on individual\n# lines or following the machine name denoted by a '#' symbol.\n#\n# For example:\n#\n# 102.54.94.97 rhino.acme.com # source server\n# 38.25.63.10 x.acme.com # x client host\n\n# localhost name resolution is handled within DNS itself.\n# 127.0.0.1 localhost\n# ::1 localhost" }, { "code": null, "e": 1970, "s": 1925, "text": "To get the host file from the remote server," }, { "code": null, "e": 2032, "s": 1970, "text": "Get-Content \\\\Computer1\\c$\\windows\\system32\\drivers\\etc\\hosts" } ]
Program to calculate Variance of first N Natural Numbers - GeeksforGeeks
02 Sep, 2021 Given an integer N, the task is to find the variance of the first N natural numbers. Variance is used to determine how far the data is spread from their average value. It is generally represented by symbol σ2 and the equation for finding the variance is generally given by the following equation: ∑Ni = 1 (xi– mean(x))2 / N where N is the total number of data Examples: Input: 5Output: 2Explanation: Mean of the first 5 numbers = (1 + 2 + 3 + 4 + 5) / 5 = 3 Therefore, Variance = ((1 – 3)2 + (2 – 3)2 + (3 – 3)2+(4 – 3)2+(5 – 3)2) / 5 = (4 + 1 + 0 + 1 + 4) / 5 = 10 / 5. Input: 4Output: 1.25Explanation: Mean of first 4 numbers = (1 + 2 + 3 + 4) / 4 = 2.5 Therefore, Variance = ((1 – 2.5)2 + (2 – 2.5)2 + (3 – 2.5)2 + (4 – 2.5)2) / 4 = (2.25 + 0.25 + 0.25 + 2.25) / 4 = 5 / 4. Naive approach: The simple approach to solve this problem is to first calculate the Mean value of the first N natural numbers and then, traverse over the range [1, N] and calculate the variance. Time Complexity: O(N)Auxiliary Space: O(1) Efficient solution: The above solution can be optimized by simplifying the above-mentioned formulas of Mean and Variance and using the properties of sum of the first N natural number and the sum of the squares of the first N natural numbers, as shown below. .Therefore, calculate (N2 – 1) / 12 and print it as the required result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate Variance// of first N natural numberslong double find_Variance(int n){ long long int numerator = n * n - 1; long double ans = (numerator * 1.0) / 12; return ans;} // Driver Codeint main(){ int N = 5; cout << fixed << setprecision(6) << find_Variance(N);} // Java program to implement// the above approachclass GFG{ // Function to calculate Variance// of first N natural numbersstatic double find_Variance(int n){ long numerator = n * n - 1; double ans = (numerator * 1.0) / 12; return ans;} // Driver Codepublic static void main(String[] args){ int N = 5; System.out.println(find_Variance(N));}} // This code is contributed by AnkThon # Python3 program to implement# the above approach # Function to calculate Variance# of first N natural numbersdef find_Variance(n): numerator = n * n - 1 ans = (numerator * 1.0) / 12 return ans # Driver Codeif __name__ == '__main__': N = 5 a = find_Variance(N) print("{0:.6f}".format(a)) # This code is contributed by mohit kumar 29 // C# program to implement// the above approachusing System;class GFG{ // Function to calculate Variance // of first N natural numbers static double find_Variance(int n) { long numerator = n * n - 1; double ans = (numerator * 1.0) / 12; return ans; } // Driver Code public static void Main(string[] args) { int N = 5; Console.WriteLine(find_Variance(N)); }} // This code is contributed by AnkThon <script> // Javascript program to implement// the above approach // Function to calculate Variance// of first N natural numbersfunction find_Variance(n){ var numerator = n * n - 1 var ans = (numerator * 1.0) / 12 return ans} // Driver Codevar N = 5; document.write (find_Variance(N).toFixed(6)); // This code is contributed by bunnyram19 </script> 2.000000 Time Complexity: O(1)Auxiliary Space: O(1) mohit kumar 29 ankthon bunnyram19 sagar0719kumar maths-mean Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Program to print prime numbers from 1 to N. Fizz Buzz Implementation Program to multiply two matrices Modular multiplicative inverse Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24716, "s": 24688, "text": "\n02 Sep, 2021" }, { "code": null, "e": 24801, "s": 24716, "text": "Given an integer N, the task is to find the variance of the first N natural numbers." }, { "code": null, "e": 25015, "s": 24801, "text": "Variance is used to determine how far the data is spread from their average value. It is generally represented by symbol σ2 and the equation for finding the variance is generally given by the following equation: " }, { "code": null, "e": 25042, "s": 25015, "text": "∑Ni = 1 (xi– mean(x))2 / N" }, { "code": null, "e": 25078, "s": 25042, "text": "where N is the total number of data" }, { "code": null, "e": 25088, "s": 25078, "text": "Examples:" }, { "code": null, "e": 25289, "s": 25088, "text": "Input: 5Output: 2Explanation: Mean of the first 5 numbers = (1 + 2 + 3 + 4 + 5) / 5 = 3 Therefore, Variance = ((1 – 3)2 + (2 – 3)2 + (3 – 3)2+(4 – 3)2+(5 – 3)2) / 5 = (4 + 1 + 0 + 1 + 4) / 5 = 10 / 5." }, { "code": null, "e": 25495, "s": 25289, "text": "Input: 4Output: 1.25Explanation: Mean of first 4 numbers = (1 + 2 + 3 + 4) / 4 = 2.5 Therefore, Variance = ((1 – 2.5)2 + (2 – 2.5)2 + (3 – 2.5)2 + (4 – 2.5)2) / 4 = (2.25 + 0.25 + 0.25 + 2.25) / 4 = 5 / 4." }, { "code": null, "e": 25691, "s": 25495, "text": "Naive approach: The simple approach to solve this problem is to first calculate the Mean value of the first N natural numbers and then, traverse over the range [1, N] and calculate the variance. " }, { "code": null, "e": 25734, "s": 25691, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 25993, "s": 25734, "text": "Efficient solution: The above solution can be optimized by simplifying the above-mentioned formulas of Mean and Variance and using the properties of sum of the first N natural number and the sum of the squares of the first N natural numbers, as shown below. " }, { "code": null, "e": 26066, "s": 25993, "text": ".Therefore, calculate (N2 – 1) / 12 and print it as the required result." }, { "code": null, "e": 26117, "s": 26066, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26121, "s": 26117, "text": "C++" }, { "code": null, "e": 26126, "s": 26121, "text": "Java" }, { "code": null, "e": 26134, "s": 26126, "text": "Python3" }, { "code": null, "e": 26137, "s": 26134, "text": "C#" }, { "code": null, "e": 26148, "s": 26137, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate Variance// of first N natural numberslong double find_Variance(int n){ long long int numerator = n * n - 1; long double ans = (numerator * 1.0) / 12; return ans;} // Driver Codeint main(){ int N = 5; cout << fixed << setprecision(6) << find_Variance(N);}", "e": 26546, "s": 26148, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to calculate Variance// of first N natural numbersstatic double find_Variance(int n){ long numerator = n * n - 1; double ans = (numerator * 1.0) / 12; return ans;} // Driver Codepublic static void main(String[] args){ int N = 5; System.out.println(find_Variance(N));}} // This code is contributed by AnkThon", "e": 26947, "s": 26546, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to calculate Variance# of first N natural numbersdef find_Variance(n): numerator = n * n - 1 ans = (numerator * 1.0) / 12 return ans # Driver Codeif __name__ == '__main__': N = 5 a = find_Variance(N) print(\"{0:.6f}\".format(a)) # This code is contributed by mohit kumar 29", "e": 27316, "s": 26947, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to calculate Variance // of first N natural numbers static double find_Variance(int n) { long numerator = n * n - 1; double ans = (numerator * 1.0) / 12; return ans; } // Driver Code public static void Main(string[] args) { int N = 5; Console.WriteLine(find_Variance(N)); }} // This code is contributed by AnkThon", "e": 27782, "s": 27316, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to calculate Variance// of first N natural numbersfunction find_Variance(n){ var numerator = n * n - 1 var ans = (numerator * 1.0) / 12 return ans} // Driver Codevar N = 5; document.write (find_Variance(N).toFixed(6)); // This code is contributed by bunnyram19 </script>", "e": 28148, "s": 27782, "text": null }, { "code": null, "e": 28157, "s": 28148, "text": "2.000000" }, { "code": null, "e": 28202, "s": 28159, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 28219, "s": 28204, "text": "mohit kumar 29" }, { "code": null, "e": 28227, "s": 28219, "text": "ankthon" }, { "code": null, "e": 28238, "s": 28227, "text": "bunnyram19" }, { "code": null, "e": 28253, "s": 28238, "text": "sagar0719kumar" }, { "code": null, "e": 28264, "s": 28253, "text": "maths-mean" }, { "code": null, "e": 28277, "s": 28264, "text": "Mathematical" }, { "code": null, "e": 28296, "s": 28277, "text": "School Programming" }, { "code": null, "e": 28309, "s": 28296, "text": "Mathematical" }, { "code": null, "e": 28407, "s": 28309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28439, "s": 28407, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 28483, "s": 28439, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 28508, "s": 28483, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 28541, "s": 28508, "text": "Program to multiply two matrices" }, { "code": null, "e": 28572, "s": 28541, "text": "Modular multiplicative inverse" }, { "code": null, "e": 28590, "s": 28572, "text": "Python Dictionary" }, { "code": null, "e": 28606, "s": 28590, "text": "Arrays in C/C++" }, { "code": null, "e": 28625, "s": 28606, "text": "Inheritance in C++" }, { "code": null, "e": 28650, "s": 28625, "text": "Reverse a string in Java" } ]
set::key_comp() in C++ STL - GeeksforGeeks
25 Jun, 2018 set::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container. By default, this is a less object, which returns the same as operator ‘<'. This object determines the order of the elements in the container. It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or false otherwise. Two elements of a set are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments). Syntax: key_compare set_name.key_comp() Parameters: This function does not accept any parameter. Return value: The function returns a copy of the comparison object used by the container. Program to demonstrate the above function: // C++ program to illustrate the// set::key_comp() function#include <bits/stdc++.h>using namespace std; int main(){ // creating a set named 'a' set<int> a; set<int>::key_compare comp = a.key_comp(); // Inserting elements into set for (int i = 0; i <= 10; i++) a.insert(i); cout << "Set a has the numbers: "; // stores the last value of the set int l = *a.rbegin(); // initialising the iterator set<int>::iterator it = a.begin(); // printing elements of all set do { cout << *it << " "; } while (comp(*(++it), l)); return 0;} Set a has the numbers: 0 1 2 3 4 5 6 7 8 9 CPP-Functions cpp-set STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Socket Programming in C/C++ C++ Classes and Objects Operator Overloading in C++ Multidimensional Arrays in C / C++ Virtual Function in C++ Bitwise Operators in C/C++ Constructors in C++ Templates in C++ with Examples Copy Constructor in C++
[ { "code": null, "e": 24506, "s": 24478, "text": "\n25 Jun, 2018" }, { "code": null, "e": 25179, "s": 24506, "text": "set::key_comp() is an inbuilt function in C++ STL which returns a copy of the comparison object used by the container. By default, this is a less object, which returns the same as operator ‘<'. This object determines the order of the elements in the container. It is a function pointer or a function object which takes two arguments of the same type as the container elements and returns true if the first argument is considered to go before the second in the strict weak ordering it defines or false otherwise. Two elements of a set are considered equivalent if key_comp returns false reflexively (i.e., no matter the order in which the elements are passed as arguments)." }, { "code": null, "e": 25187, "s": 25179, "text": "Syntax:" }, { "code": null, "e": 25221, "s": 25187, "text": "key_compare set_name.key_comp() \n" }, { "code": null, "e": 25278, "s": 25221, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 25368, "s": 25278, "text": "Return value: The function returns a copy of the comparison object used by the container." }, { "code": null, "e": 25411, "s": 25368, "text": "Program to demonstrate the above function:" }, { "code": "// C++ program to illustrate the// set::key_comp() function#include <bits/stdc++.h>using namespace std; int main(){ // creating a set named 'a' set<int> a; set<int>::key_compare comp = a.key_comp(); // Inserting elements into set for (int i = 0; i <= 10; i++) a.insert(i); cout << \"Set a has the numbers: \"; // stores the last value of the set int l = *a.rbegin(); // initialising the iterator set<int>::iterator it = a.begin(); // printing elements of all set do { cout << *it << \" \"; } while (comp(*(++it), l)); return 0;}", "e": 26007, "s": 25411, "text": null }, { "code": null, "e": 26051, "s": 26007, "text": "Set a has the numbers: 0 1 2 3 4 5 6 7 8 9\n" }, { "code": null, "e": 26065, "s": 26051, "text": "CPP-Functions" }, { "code": null, "e": 26073, "s": 26065, "text": "cpp-set" }, { "code": null, "e": 26077, "s": 26073, "text": "STL" }, { "code": null, "e": 26081, "s": 26077, "text": "C++" }, { "code": null, "e": 26085, "s": 26081, "text": "STL" }, { "code": null, "e": 26089, "s": 26085, "text": "CPP" }, { "code": null, "e": 26187, "s": 26089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26196, "s": 26187, "text": "Comments" }, { "code": null, "e": 26209, "s": 26196, "text": "Old Comments" }, { "code": null, "e": 26228, "s": 26209, "text": "Inheritance in C++" }, { "code": null, "e": 26256, "s": 26228, "text": "Socket Programming in C/C++" }, { "code": null, "e": 26280, "s": 26256, "text": "C++ Classes and Objects" }, { "code": null, "e": 26308, "s": 26280, "text": "Operator Overloading in C++" }, { "code": null, "e": 26343, "s": 26308, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 26367, "s": 26343, "text": "Virtual Function in C++" }, { "code": null, "e": 26394, "s": 26367, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 26414, "s": 26394, "text": "Constructors in C++" }, { "code": null, "e": 26445, "s": 26414, "text": "Templates in C++ with Examples" } ]
Python | Element indices Summation - GeeksforGeeks
19 Feb, 2020 Usually, we require to find the sum of index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list. Lets discuss certain ways to do so. Method #1 : Naive Method + sum()We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. The sum() is used to perform sum of list. # Python code to demonstrate # Element indices Summation# using naive method + sum() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print ("Original list : " + str(test_list)) # using naive method# Element indices Summation# to find indices for 3res_list = []for i in range(0, len(test_list)) : if test_list[i] == 3 : res_list.append(i)res = sum(res_list) # printing resultant list print ("New indices summation : " + str(res)) Original list : [1, 3, 4, 3, 6, 7] New indices summation : 4 Method #2 : Using list comprehension + sum()List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time. The sum() is used to perform sum of list. # Python code to demonstrate # Element indices Summation# using list comprehension + sum() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print ("Original list : " + str(test_list)) # using list comprehension + sum()# Element indices Summation# to find indices for 3res_list = [i for i in range(len(test_list)) if test_list[i] == 3]res = sum(res_list) # printing resultant list print ("New indices summation : " + str(res)) Original list : [1, 3, 4, 3, 6, 7] New indices summation : 4 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25675, "s": 25647, "text": "\n19 Feb, 2020" }, { "code": null, "e": 25970, "s": 25675, "text": "Usually, we require to find the sum of index, in which the particular value is located. There are many method to achieve that, using index() etc. But sometimes require to find all the indices of a particular value in case it has multiple occurrences in list. Lets discuss certain ways to do so." }, { "code": null, "e": 26243, "s": 25970, "text": "Method #1 : Naive Method + sum()We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. The sum() is used to perform sum of list." }, { "code": "# Python code to demonstrate # Element indices Summation# using naive method + sum() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using naive method# Element indices Summation# to find indices for 3res_list = []for i in range(0, len(test_list)) : if test_list[i] == 3 : res_list.append(i)res = sum(res_list) # printing resultant list print (\"New indices summation : \" + str(res))", "e": 26713, "s": 26243, "text": null }, { "code": null, "e": 26775, "s": 26713, "text": "Original list : [1, 3, 4, 3, 6, 7]\nNew indices summation : 4\n" }, { "code": null, "e": 27033, "s": 26777, "text": "Method #2 : Using list comprehension + sum()List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time. The sum() is used to perform sum of list." }, { "code": "# Python code to demonstrate # Element indices Summation# using list comprehension + sum() # initializing list test_list = [1, 3, 4, 3, 6, 7] # printing initial list print (\"Original list : \" + str(test_list)) # using list comprehension + sum()# Element indices Summation# to find indices for 3res_list = [i for i in range(len(test_list)) if test_list[i] == 3]res = sum(res_list) # printing resultant list print (\"New indices summation : \" + str(res))", "e": 27489, "s": 27033, "text": null }, { "code": null, "e": 27551, "s": 27489, "text": "Original list : [1, 3, 4, 3, 6, 7]\nNew indices summation : 4\n" }, { "code": null, "e": 27572, "s": 27551, "text": "Python list-programs" }, { "code": null, "e": 27579, "s": 27572, "text": "Python" }, { "code": null, "e": 27595, "s": 27579, "text": "Python Programs" }, { "code": null, "e": 27693, "s": 27595, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27711, "s": 27693, "text": "Python Dictionary" }, { "code": null, "e": 27743, "s": 27711, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27765, "s": 27743, "text": "Enumerate() in Python" }, { "code": null, "e": 27807, "s": 27765, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27833, "s": 27807, "text": "Python String | replace()" }, { "code": null, "e": 27876, "s": 27833, "text": "Python program to convert a list to string" }, { "code": null, "e": 27898, "s": 27876, "text": "Defaultdict in Python" }, { "code": null, "e": 27937, "s": 27898, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27983, "s": 27937, "text": "Python | Split string into list of characters" } ]
Remove Sub-Directories from a File System - GeeksforGeeks
08 Jun, 2021 Given an array of strings arr[] consisting of N unique directories in the form of strings, the task is to remove all the subdirectories and print the final array. A directory S is a subdirectory if there exists any directory D such that S is the prefix of D. Examples: Input: arr[] = {“/a”, “/a/j”, “/c/d/e”, “/c/d”, “/b”}Output: { “/a”, “/c/d”, “/b”}Explanation: Directory “/a/j” is a subdirectory of directory “/a”, and “/c/d/e” is a subdirectory of directory “/c/d”.Therefore, remove both of them. Input: arr[] = {“/a”, “/a/b”, “/a/b/c”, “/a/b/c/d”}Output: {“/a”}Explanation: All directories are subdirectories of “/a” Naive Approach: The simplest approach is to traverse the array to check for each string, if there exists a string having it as the prefix and remove such strings from the array. Time Complexity: O(len * N2), where len is the length of the longest string in the array.Auxiliary Space: O(N) Efficient Approach: The idea is to sort the given array and compare the current directory at position i with the previous directory at index (i -1). If arr[i – 1] is the prefix of arr[i] then remove arr[i]. After checking the whole array, print the remaining directories. Follow the below steps to solve the problem: Sort all the directories alphabetically and initialize a vector res. Insert the first directory into res. Check each directory with the last valid directory i.e., last directory from res. The directory is invalid(sub-directory) if it equals to some prefix of the previous valid directory. Else it is valid. If the current directory is valid, then add it to res. Print all the directories present in res after done traversing. Below is the implementation of the above approach: C++ Java Python3 C# // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to remove sub-directories// from the given lists dirvoid eraseSubdirectory(vector<string>& dir){ // Store final result vector<string> res; // Sort the given directories sort(dir.begin(), dir.end()); // Insert 1st directory res.push_back(dir[0]); cout << "{" << dir[0] << ", "; // Iterating in directory for (int i = 1; i < dir.size(); i++) { // Current directory string curr = dir[i]; // Our previous valid directory string prev = res.back(); // Find length of previous directory int l = prev.length(); // If subdirectory is found if (curr.length() > l && curr[l] == '/' && prev == curr.substr(0, l)) continue; // Else store it in result // valid directory res.push_back(curr); cout << curr << ", "; } cout << "}\n";} // Driver Codeint main(){ // Given lists of directories dir[] vector<string> dir = { "/a", "/a/j", "/c/d/e", "/c/d", "/b" }; // Function Call eraseSubdirectory(dir); return 0;} // Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to remove sub-directories// from the given lists dirstatic void eraseSubdirectory(ArrayList<String> dir){ // Store final result ArrayList<String> res = new ArrayList<String>(); // Sort the given directories Collections.sort(dir); // Insert 1st directory res.add(dir.get(0)); System.out.print("{" + dir.get(0) + ", "); // Iterating in directory for(int i = 1; i < dir.size(); i++) { // Current directory String curr = dir.get(i); // Our previous valid directory String prev = res.get(res.size() - 1); // Find length of previous directory int l = prev.length(); // If subdirectory is found if (curr.length() > l && curr.charAt(l) == '/' && prev.equals(curr.substring(0, l))) continue; // Else store it in result // valid directory res.add(curr); System.out.print(curr + ", "); } System.out.print("}\n");} // Driver Codepublic static void main(String[] args){ // Given lists of directories dir[] ArrayList<String> dir = new ArrayList<String>(Arrays.asList( "/a", "/a/j", "/c/d/e", "/c/d", "/b")); // Function Call eraseSubdirectory(dir);}} // This code is contributed by akhilsaini # Python3 program for the above approach # Function to remove sub-directories# from the given lists dirdef eraseSubdirectory(dir): # Store final result res = [] # Sort the given directories dir.sort() # Insert 1st directory res.append(dir[0]) print("{", dir[0], end = ", ") # Iterating in directory for i in range(1, len(dir)): # Current directory curr = dir[i] # Our previous valid directory prev = res[len(res) - 1] # Find length of previous directory l = len(prev) # If subdirectory is found if (len(curr) > l and curr[l] == '/' and prev == curr[:l]): continue # Else store it in result # valid directory res.append(curr) print(curr, end = ", ") print("}") # Driver Codeif __name__ == '__main__': # Given lists of directories dir[] dir = [ "/a", "/a/j", "/c/d/e", "/c/d", "/b" ] # Function Call eraseSubdirectory(dir) # This code is contributed by akhilsaini // C# program for the above approachusing System;using System.Collections; class GFG{ // Function to remove sub-directories// from the given lists dirstatic void eraseSubdirectory(ArrayList dir){ // Store final result ArrayList res = new ArrayList(); // Sort the given directories dir.Sort(); // Insert 1st directory res.Add(dir[0]); Console.Write("{" + dir[0] + ", "); // Iterating in directory for(int i = 1; i < dir.Count; i++) { // Current directory string curr = (string)dir[i]; // Our previous valid directory string prev = (string)res[(res.Count - 1)]; // Find length of previous directory int l = prev.Length; // If subdirectory is found if (curr.Length > l && curr[l] == '/' && prev.Equals(curr.Substring(0, l))) continue; // Else store it in result // valid directory res.Add(curr); Console.Write(curr + ", "); } Console.Write("}\n");} // Driver Codepublic static void Main(){ // Given lists of directories dir[] ArrayList dir = new ArrayList(){ "/a", "/a/j", "/c/d/e", "/c/d", "/b" }; // Function Call eraseSubdirectory(dir);}} // This code is contributed by akhilsaini {/a, /b, /c/d, } Time Complexity: O(N*log N)Auxiliary Space: O(N) akhilsaini simmytarika5 prefix Arrays Sorting Strings Arrays Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element
[ { "code": null, "e": 26041, "s": 26013, "text": "\n08 Jun, 2021" }, { "code": null, "e": 26204, "s": 26041, "text": "Given an array of strings arr[] consisting of N unique directories in the form of strings, the task is to remove all the subdirectories and print the final array." }, { "code": null, "e": 26300, "s": 26204, "text": "A directory S is a subdirectory if there exists any directory D such that S is the prefix of D." }, { "code": null, "e": 26310, "s": 26300, "text": "Examples:" }, { "code": null, "e": 26542, "s": 26310, "text": "Input: arr[] = {“/a”, “/a/j”, “/c/d/e”, “/c/d”, “/b”}Output: { “/a”, “/c/d”, “/b”}Explanation: Directory “/a/j” is a subdirectory of directory “/a”, and “/c/d/e” is a subdirectory of directory “/c/d”.Therefore, remove both of them." }, { "code": null, "e": 26663, "s": 26542, "text": "Input: arr[] = {“/a”, “/a/b”, “/a/b/c”, “/a/b/c/d”}Output: {“/a”}Explanation: All directories are subdirectories of “/a”" }, { "code": null, "e": 26842, "s": 26663, "text": "Naive Approach: The simplest approach is to traverse the array to check for each string, if there exists a string having it as the prefix and remove such strings from the array. " }, { "code": null, "e": 26953, "s": 26842, "text": "Time Complexity: O(len * N2), where len is the length of the longest string in the array.Auxiliary Space: O(N)" }, { "code": null, "e": 27270, "s": 26953, "text": "Efficient Approach: The idea is to sort the given array and compare the current directory at position i with the previous directory at index (i -1). If arr[i – 1] is the prefix of arr[i] then remove arr[i]. After checking the whole array, print the remaining directories. Follow the below steps to solve the problem:" }, { "code": null, "e": 27339, "s": 27270, "text": "Sort all the directories alphabetically and initialize a vector res." }, { "code": null, "e": 27376, "s": 27339, "text": "Insert the first directory into res." }, { "code": null, "e": 27458, "s": 27376, "text": "Check each directory with the last valid directory i.e., last directory from res." }, { "code": null, "e": 27577, "s": 27458, "text": "The directory is invalid(sub-directory) if it equals to some prefix of the previous valid directory. Else it is valid." }, { "code": null, "e": 27632, "s": 27577, "text": "If the current directory is valid, then add it to res." }, { "code": null, "e": 27696, "s": 27632, "text": "Print all the directories present in res after done traversing." }, { "code": null, "e": 27747, "s": 27696, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27751, "s": 27747, "text": "C++" }, { "code": null, "e": 27756, "s": 27751, "text": "Java" }, { "code": null, "e": 27764, "s": 27756, "text": "Python3" }, { "code": null, "e": 27767, "s": 27764, "text": "C#" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to remove sub-directories// from the given lists dirvoid eraseSubdirectory(vector<string>& dir){ // Store final result vector<string> res; // Sort the given directories sort(dir.begin(), dir.end()); // Insert 1st directory res.push_back(dir[0]); cout << \"{\" << dir[0] << \", \"; // Iterating in directory for (int i = 1; i < dir.size(); i++) { // Current directory string curr = dir[i]; // Our previous valid directory string prev = res.back(); // Find length of previous directory int l = prev.length(); // If subdirectory is found if (curr.length() > l && curr[l] == '/' && prev == curr.substr(0, l)) continue; // Else store it in result // valid directory res.push_back(curr); cout << curr << \", \"; } cout << \"}\\n\";} // Driver Codeint main(){ // Given lists of directories dir[] vector<string> dir = { \"/a\", \"/a/j\", \"/c/d/e\", \"/c/d\", \"/b\" }; // Function Call eraseSubdirectory(dir); return 0;}", "e": 28942, "s": 27767, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ // Function to remove sub-directories// from the given lists dirstatic void eraseSubdirectory(ArrayList<String> dir){ // Store final result ArrayList<String> res = new ArrayList<String>(); // Sort the given directories Collections.sort(dir); // Insert 1st directory res.add(dir.get(0)); System.out.print(\"{\" + dir.get(0) + \", \"); // Iterating in directory for(int i = 1; i < dir.size(); i++) { // Current directory String curr = dir.get(i); // Our previous valid directory String prev = res.get(res.size() - 1); // Find length of previous directory int l = prev.length(); // If subdirectory is found if (curr.length() > l && curr.charAt(l) == '/' && prev.equals(curr.substring(0, l))) continue; // Else store it in result // valid directory res.add(curr); System.out.print(curr + \", \"); } System.out.print(\"}\\n\");} // Driver Codepublic static void main(String[] args){ // Given lists of directories dir[] ArrayList<String> dir = new ArrayList<String>(Arrays.asList( \"/a\", \"/a/j\", \"/c/d/e\", \"/c/d\", \"/b\")); // Function Call eraseSubdirectory(dir);}} // This code is contributed by akhilsaini", "e": 30322, "s": 28942, "text": null }, { "code": "# Python3 program for the above approach # Function to remove sub-directories# from the given lists dirdef eraseSubdirectory(dir): # Store final result res = [] # Sort the given directories dir.sort() # Insert 1st directory res.append(dir[0]) print(\"{\", dir[0], end = \", \") # Iterating in directory for i in range(1, len(dir)): # Current directory curr = dir[i] # Our previous valid directory prev = res[len(res) - 1] # Find length of previous directory l = len(prev) # If subdirectory is found if (len(curr) > l and curr[l] == '/' and prev == curr[:l]): continue # Else store it in result # valid directory res.append(curr) print(curr, end = \", \") print(\"}\") # Driver Codeif __name__ == '__main__': # Given lists of directories dir[] dir = [ \"/a\", \"/a/j\", \"/c/d/e\", \"/c/d\", \"/b\" ] # Function Call eraseSubdirectory(dir) # This code is contributed by akhilsaini", "e": 31369, "s": 30322, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections; class GFG{ // Function to remove sub-directories// from the given lists dirstatic void eraseSubdirectory(ArrayList dir){ // Store final result ArrayList res = new ArrayList(); // Sort the given directories dir.Sort(); // Insert 1st directory res.Add(dir[0]); Console.Write(\"{\" + dir[0] + \", \"); // Iterating in directory for(int i = 1; i < dir.Count; i++) { // Current directory string curr = (string)dir[i]; // Our previous valid directory string prev = (string)res[(res.Count - 1)]; // Find length of previous directory int l = prev.Length; // If subdirectory is found if (curr.Length > l && curr[l] == '/' && prev.Equals(curr.Substring(0, l))) continue; // Else store it in result // valid directory res.Add(curr); Console.Write(curr + \", \"); } Console.Write(\"}\\n\");} // Driver Codepublic static void Main(){ // Given lists of directories dir[] ArrayList dir = new ArrayList(){ \"/a\", \"/a/j\", \"/c/d/e\", \"/c/d\", \"/b\" }; // Function Call eraseSubdirectory(dir);}} // This code is contributed by akhilsaini", "e": 32705, "s": 31369, "text": null }, { "code": null, "e": 32722, "s": 32705, "text": "{/a, /b, /c/d, }" }, { "code": null, "e": 32773, "s": 32724, "text": "Time Complexity: O(N*log N)Auxiliary Space: O(N)" }, { "code": null, "e": 32784, "s": 32773, "text": "akhilsaini" }, { "code": null, "e": 32797, "s": 32784, "text": "simmytarika5" }, { "code": null, "e": 32804, "s": 32797, "text": "prefix" }, { "code": null, "e": 32811, "s": 32804, "text": "Arrays" }, { "code": null, "e": 32819, "s": 32811, "text": "Sorting" }, { "code": null, "e": 32827, "s": 32819, "text": "Strings" }, { "code": null, "e": 32834, "s": 32827, "text": "Arrays" }, { "code": null, "e": 32842, "s": 32834, "text": "Strings" }, { "code": null, "e": 32850, "s": 32842, "text": "Sorting" }, { "code": null, "e": 32948, "s": 32850, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32975, "s": 32948, "text": "Count pairs with given sum" }, { "code": null, "e": 33006, "s": 32975, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 33031, "s": 33006, "text": "Window Sliding Technique" }, { "code": null, "e": 33069, "s": 33031, "text": "Reversal algorithm for array rotation" } ]
Menu Driven Shell Script to Check Memory and Disk Usages - GeeksforGeeks
07 Sep, 2021 In Linux most of the time, we automate things using the bash scripts. Some script has only one functionality, but some script can do more than one functions. For that, we have to provide the menu to select the option which function should be performed now. This script is called as Menu-Driven Programs. Free Commands: This command displays the total amount of free space available along with the amount of memory used and swap memory in the system, and also the buffers used by the kernel. Syntax: $free [OPTION] Option: refers to the options compatible with free command. Example: df Commands: The df command (short for disk free), is used to display information related to file systems about total space and available space. Syntax : df [OPTION]... [FILE]... Example: Let’s see the basic algorithm of the menu-driven program: First, create all functions in the script that are performed by the bash script Then we need to provide the menu to the user from which the user has to select the option. For that create one function like show menu which contains all options with the function’s name. Now we need to read the option which is entered by the user for that we need to create another function that reads the option and processes the input. After taking input use if statement or switch statement but switch statement is good. The switch statement mention all options with functions same as the show menu function. Then switch statement will call the appropriate function according to the choices. Then use a while to call the show menu and take the input function until the user does not want to exit from the program. Let’s see one example to understand better. We are going to build one script which performs two functionalities one is to check memory usage and another disk usage. Now let’s move according to the above algorithm. Step 1: We are going to create two functions that check memory usage and disk usage. memoryUsage(){ echo "Memory Usage:" free read -p "Press any key to Continue...." } diskUsage(){ echo "Disk Usage:" df read -p "Press any key to Continue...." } Now we have created memoryUsage function which gives memory usage details and diskUsage Function which gives the details about disk usage. Step 2: Now let’s create a Menu to show a user with the required options show_menu() { clear echo "++++++++++++ MENU +++++++++++++" echo "1. Show Memory Usage." echo "2. Show DIsk Usage." echo "3. Exit" echo "+++++++++++++++++++++++++++++++" } show_menu() function shows the menu to the user which contains three options 1st for memory usage 2nd for disk usage and 3rd to exit from the program. Step 3: Now let’s create the function which takes input according to the menu and process the given input: take_input() { local choice read -p "Select the option from above menu: " choice case $choice in 1) memoryUsage ;; 2) diskUsage ;; 3) exit 0;; *) echo "Enter Valid Option!!" read -p "Press any key to Continue...." esac } take_input function takes the input and passes it to the switch statement in the function .which calls the function according to provided option. Step 4: Now let’s use the while loop to call the show_menu function and the take_input function until the user does not want to exit. while true do show_menu take_input done Below is the full implementation: #!/bin/bash # function to show memory usage memoryUsage(){ echo "Memory Usage:" free read -p "Press any key to Continue...." } # function to show disk usage diskUsage(){ echo "Disk Usage:" df read -p "Press any key to Continue...." } # function to show menu show_menu() { clear echo "++++++++++++ MENU +++++++++++++" echo "1. Show Memory Usage." echo "2. Show DIsk Usage." echo "3. Exit" echo "+++++++++++++++++++++++++++++++" } # function to take input take_input() { #take the input and store it in choice variable local choice read -p "Select the option from above menu: " choice #using switch case statement check the choice and call function. case $choice in 1) memoryUsage ;; 2) diskUsage ;; 3) exit 0;; *) echo "Enter Valid Option!!" read -p "Press any key to Continue...." esac } # for loop to call the show_menu and take_input function. while true do show_menu take_input done Output: gabaa406 Picked Shell Script Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples mv command in Linux with examples Docker - COPY Instruction SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n07 Sep, 2021" }, { "code": null, "e": 25955, "s": 25651, "text": "In Linux most of the time, we automate things using the bash scripts. Some script has only one functionality, but some script can do more than one functions. For that, we have to provide the menu to select the option which function should be performed now. This script is called as Menu-Driven Programs." }, { "code": null, "e": 26142, "s": 25955, "text": "Free Commands: This command displays the total amount of free space available along with the amount of memory used and swap memory in the system, and also the buffers used by the kernel." }, { "code": null, "e": 26150, "s": 26142, "text": "Syntax:" }, { "code": null, "e": 26165, "s": 26150, "text": "$free [OPTION]" }, { "code": null, "e": 26225, "s": 26165, "text": "Option: refers to the options compatible with free command." }, { "code": null, "e": 26234, "s": 26225, "text": "Example:" }, { "code": null, "e": 26379, "s": 26234, "text": "df Commands: The df command (short for disk free), is used to display information related to file systems about total space and available space." }, { "code": null, "e": 26388, "s": 26379, "text": "Syntax :" }, { "code": null, "e": 26413, "s": 26388, "text": "df [OPTION]... [FILE]..." }, { "code": null, "e": 26422, "s": 26413, "text": "Example:" }, { "code": null, "e": 26480, "s": 26422, "text": "Let’s see the basic algorithm of the menu-driven program:" }, { "code": null, "e": 26560, "s": 26480, "text": "First, create all functions in the script that are performed by the bash script" }, { "code": null, "e": 26748, "s": 26560, "text": "Then we need to provide the menu to the user from which the user has to select the option. For that create one function like show menu which contains all options with the function’s name." }, { "code": null, "e": 27156, "s": 26748, "text": "Now we need to read the option which is entered by the user for that we need to create another function that reads the option and processes the input. After taking input use if statement or switch statement but switch statement is good. The switch statement mention all options with functions same as the show menu function. Then switch statement will call the appropriate function according to the choices." }, { "code": null, "e": 27278, "s": 27156, "text": "Then use a while to call the show menu and take the input function until the user does not want to exit from the program." }, { "code": null, "e": 27492, "s": 27278, "text": "Let’s see one example to understand better. We are going to build one script which performs two functionalities one is to check memory usage and another disk usage. Now let’s move according to the above algorithm." }, { "code": null, "e": 27577, "s": 27492, "text": "Step 1: We are going to create two functions that check memory usage and disk usage." }, { "code": null, "e": 27786, "s": 27577, "text": "memoryUsage(){\n echo \"Memory Usage:\"\n free\n read -p \"Press any key to Continue....\"\n}\n\ndiskUsage(){\n echo \"Disk Usage:\"\n df\n read -p \"Press any key to Continue....\"\n}" }, { "code": null, "e": 27925, "s": 27786, "text": "Now we have created memoryUsage function which gives memory usage details and diskUsage Function which gives the details about disk usage." }, { "code": null, "e": 27998, "s": 27925, "text": "Step 2: Now let’s create a Menu to show a user with the required options" }, { "code": null, "e": 28211, "s": 27998, "text": "show_menu()\n{\n clear\n echo \"++++++++++++ MENU +++++++++++++\"\n echo \"1. Show Memory Usage.\"\n echo \"2. Show DIsk Usage.\"\n echo \"3. Exit\"\n echo \"+++++++++++++++++++++++++++++++\"\n}" }, { "code": null, "e": 28362, "s": 28211, "text": "show_menu() function shows the menu to the user which contains three options 1st for memory usage 2nd for disk usage and 3rd to exit from the program." }, { "code": null, "e": 28469, "s": 28362, "text": "Step 3: Now let’s create the function which takes input according to the menu and process the given input:" }, { "code": null, "e": 28811, "s": 28469, "text": "take_input()\n{\n local choice\n read -p \"Select the option from above menu: \" choice\n\n case $choice in\n 1) memoryUsage ;;\n 2) diskUsage ;;\n 3) exit 0;;\n *) echo \"Enter Valid Option!!\"\n read -p \"Press any key to Continue....\"\n\n esac\n}" }, { "code": null, "e": 28957, "s": 28811, "text": "take_input function takes the input and passes it to the switch statement in the function .which calls the function according to provided option." }, { "code": null, "e": 29091, "s": 28957, "text": "Step 4: Now let’s use the while loop to call the show_menu function and the take_input function until the user does not want to exit." }, { "code": null, "e": 29145, "s": 29091, "text": "while true\ndo\n show_menu\n take_input\ndone" }, { "code": null, "e": 29179, "s": 29145, "text": "Below is the full implementation:" }, { "code": null, "e": 30320, "s": 29179, "text": "#!/bin/bash\n\n# function to show memory usage\nmemoryUsage(){\n echo \"Memory Usage:\"\n free\n read -p \"Press any key to Continue....\"\n}\n\n# function to show disk usage\ndiskUsage(){\n echo \"Disk Usage:\"\n df\n read -p \"Press any key to Continue....\"\n}\n\n# function to show menu\nshow_menu()\n{\n clear\n echo \"++++++++++++ MENU +++++++++++++\"\n echo \"1. Show Memory Usage.\"\n echo \"2. Show DIsk Usage.\"\n echo \"3. Exit\"\n echo \"+++++++++++++++++++++++++++++++\"\n}\n\n# function to take input\ntake_input()\n{\n #take the input and store it in choice variable\n local choice\n read -p \"Select the option from above menu: \" choice\n \n #using switch case statement check the choice and call function.\n case $choice in\n 1) memoryUsage ;;\n 2) diskUsage ;;\n 3) exit 0;;\n *) echo \"Enter Valid Option!!\"\n read -p \"Press any key to Continue....\"\n\n esac\n }\n\n# for loop to call the show_menu and take_input function.\nwhile true\ndo\n show_menu\n take_input\ndone" }, { "code": null, "e": 30328, "s": 30320, "text": "Output:" }, { "code": null, "e": 30337, "s": 30328, "text": "gabaa406" }, { "code": null, "e": 30344, "s": 30337, "text": "Picked" }, { "code": null, "e": 30357, "s": 30344, "text": "Shell Script" }, { "code": null, "e": 30368, "s": 30357, "text": "Linux-Unix" }, { "code": null, "e": 30466, "s": 30368, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30501, "s": 30466, "text": "scp command in Linux with Examples" }, { "code": null, "e": 30535, "s": 30501, "text": "mv command in Linux with examples" }, { "code": null, "e": 30561, "s": 30535, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30590, "s": 30561, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 30627, "s": 30590, "text": "chown command in Linux with Examples" }, { "code": null, "e": 30664, "s": 30627, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 30706, "s": 30664, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 30732, "s": 30706, "text": "Thread functions in C/C++" }, { "code": null, "e": 30768, "s": 30732, "text": "uniq Command in LINUX with examples" } ]
Print all substring of a number without any conversion - GeeksforGeeks
25 Oct, 2021 Given an integer N, the task is to print all the substring of N without doing any conversion i.e converting it into a string or an array. Examples: Input: N = 12345 Output: Possible Substrings: {1, 12, 123, 1234, 12345, 2, 23, 234, 2345, 3, 34, 345, 4, 45, 5}Input: N = 123 Output: Possible Substrings: {1, 12, 123, 2, 23, 3} Approach: Take the power of 10 according to size.Divide the number till it will become 0 and print.Then change the number to next the position of that number by taking the modulo with k.Update the no. of digits.Repeat the same process till n becomes 0. Take the power of 10 according to size. Divide the number till it will become 0 and print. Then change the number to next the position of that number by taking the modulo with k. Update the no. of digits. Repeat the same process till n becomes 0. Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to print the substrings of a numbervoid printSubstrings(int n){ // Calculate the total number of digits int s = log10(n); // 0.5 has been added because of it will // return double value like 99.556 int d = (int)(pow(10, s) + 0.5); int k = d; while (n) { // Print all the numbers from // starting position while (d) { cout << n / d << endl; d = d / 10; } // Update the no. n = n % k; // Update the no.of digits k = k / 10; d = k; }} // Driver codeint main(){ int n = 123; printSubstrings(n); return 0;} // Java implementation// of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{// Function to print the// substrings of a numberstatic void printSubstrings(int n){ // Calculate the total // number of digits int s = (int)Math.log10(n); // 0.5 has been added because // of it will return double // value like 99.556 int d = (int)(Math.pow(10, s) + 0.5); int k = d; while (n > 0) { // Print all the numbers // from starting position while (d > 0) { System.out.println(n / d); d = d / 10; } // Update the no. n = n % k; // Update the no.of digits k = k / 10; d = k; }} // Driver codepublic static void main(String args[]){ int n = 123; printSubstrings(n);}} // This code is contributed// by Subhadeep # Python3 implementation of above approachimport math # Function to print the substrings of a numberdef printSubstrings(n): # Calculate the total number of digits s = int(math.log10(n)); # 0.5 has been added because of it will # return double value like 99.556 d = (math.pow(10, s)); k = d; while (n > 0): # Print all the numbers from # starting position while (d > 0): print(int(n // d)); d = int(d / 10); # Update the no. n = int(n % k); # Update the no.of digits k = int(k // 10); d = k; # Driver codeif __name__ == '__main__': n = 123; printSubstrings(n); # This code is contributed by Rajput-Ji // C# implementation// of above approachusing System; class GFG{// Function to print the// substrings of a numberstatic void printSubstrings(int n){ // Calculate the total // number of digits int s = (int)Math.Log10(n); // 0.5 has been added because // of it will return double // value like 99.556 int d = (int)(Math.Pow(10, s) + 0.5); int k = d; while (n > 0) { // Print all the numbers // from starting position while (d > 0) { Console.WriteLine(n / d); d = d / 10; } // Update the no. n = n % k; // Update the no.of digits k = k / 10; d = k; }} // Driver codepublic static void Main(){ int n = 123; printSubstrings(n);}} // This code is contributed// by mits <?php// PHP implementation of above approach // Function to print the substrings// of a numberfunction printSubstrings($n){ // Calculate the total number // of digits $s = (int)log10($n); // 0.5 has been added because // of it will return double // value like 99.556 $d = (int)(pow(10, $s) + 0.5); $k = $d; while ($n) { // Print all the numbers from // starting position while ($d) { echo (int)($n / $d) . "\n"; $d = (int)($d / 10); } // Update the no. $n = $n % $k; // Update the no.of digits $k = (int)($k / 10); $d = $k; }} // Driver code$n = 123;printSubstrings($n); // This code is contributed by mits?> <script> // javascript implementation// of above approach// Function to print the// substrings of a numberfunction printSubstrings(n){ // Calculate the total // number of digits var s = parseInt(Math.log10(n)); // 0.5 has been added because // of it will return double // value like 99.556 var d = parseInt((Math.pow(10, s) + 0.5)); var k = d; while (n > 0) { // Print all the numbers // from starting position while (d > 0) { document.write(parseInt(n / d)+"<br>"); d = parseInt(d / 10); } // Update the no. n = n % k; // Update the no.of digits k = parseInt(k / 10); d = k; }} // Driver code var n = 123;printSubstrings(n); // This code contributed by Princi Singh</script> 1 12 123 2 23 3 tufan_gupta2000 Mithun Kumar Rajput-Ji princi singh ankita_saini maths-log Modular Arithmetic substring Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Program for factorial of a number Find minimum number of coins that make a given value
[ { "code": null, "e": 26261, "s": 26233, "text": "\n25 Oct, 2021" }, { "code": null, "e": 26399, "s": 26261, "text": "Given an integer N, the task is to print all the substring of N without doing any conversion i.e converting it into a string or an array." }, { "code": null, "e": 26411, "s": 26399, "text": "Examples: " }, { "code": null, "e": 26591, "s": 26411, "text": "Input: N = 12345 Output: Possible Substrings: {1, 12, 123, 1234, 12345, 2, 23, 234, 2345, 3, 34, 345, 4, 45, 5}Input: N = 123 Output: Possible Substrings: {1, 12, 123, 2, 23, 3} " }, { "code": null, "e": 26603, "s": 26591, "text": "Approach: " }, { "code": null, "e": 26846, "s": 26603, "text": "Take the power of 10 according to size.Divide the number till it will become 0 and print.Then change the number to next the position of that number by taking the modulo with k.Update the no. of digits.Repeat the same process till n becomes 0." }, { "code": null, "e": 26886, "s": 26846, "text": "Take the power of 10 according to size." }, { "code": null, "e": 26937, "s": 26886, "text": "Divide the number till it will become 0 and print." }, { "code": null, "e": 27025, "s": 26937, "text": "Then change the number to next the position of that number by taking the modulo with k." }, { "code": null, "e": 27051, "s": 27025, "text": "Update the no. of digits." }, { "code": null, "e": 27093, "s": 27051, "text": "Repeat the same process till n becomes 0." }, { "code": null, "e": 27142, "s": 27093, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27146, "s": 27142, "text": "C++" }, { "code": null, "e": 27151, "s": 27146, "text": "Java" }, { "code": null, "e": 27159, "s": 27151, "text": "Python3" }, { "code": null, "e": 27162, "s": 27159, "text": "C#" }, { "code": null, "e": 27166, "s": 27162, "text": "PHP" }, { "code": null, "e": 27177, "s": 27166, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; // Function to print the substrings of a numbervoid printSubstrings(int n){ // Calculate the total number of digits int s = log10(n); // 0.5 has been added because of it will // return double value like 99.556 int d = (int)(pow(10, s) + 0.5); int k = d; while (n) { // Print all the numbers from // starting position while (d) { cout << n / d << endl; d = d / 10; } // Update the no. n = n % k; // Update the no.of digits k = k / 10; d = k; }} // Driver codeint main(){ int n = 123; printSubstrings(n); return 0;}", "e": 27899, "s": 27177, "text": null }, { "code": "// Java implementation// of above approachimport java.util.*;import java.lang.*;import java.io.*; class GFG{// Function to print the// substrings of a numberstatic void printSubstrings(int n){ // Calculate the total // number of digits int s = (int)Math.log10(n); // 0.5 has been added because // of it will return double // value like 99.556 int d = (int)(Math.pow(10, s) + 0.5); int k = d; while (n > 0) { // Print all the numbers // from starting position while (d > 0) { System.out.println(n / d); d = d / 10; } // Update the no. n = n % k; // Update the no.of digits k = k / 10; d = k; }} // Driver codepublic static void main(String args[]){ int n = 123; printSubstrings(n);}} // This code is contributed// by Subhadeep", "e": 28761, "s": 27899, "text": null }, { "code": "# Python3 implementation of above approachimport math # Function to print the substrings of a numberdef printSubstrings(n): # Calculate the total number of digits s = int(math.log10(n)); # 0.5 has been added because of it will # return double value like 99.556 d = (math.pow(10, s)); k = d; while (n > 0): # Print all the numbers from # starting position while (d > 0): print(int(n // d)); d = int(d / 10); # Update the no. n = int(n % k); # Update the no.of digits k = int(k // 10); d = k; # Driver codeif __name__ == '__main__': n = 123; printSubstrings(n); # This code is contributed by Rajput-Ji", "e": 29476, "s": 28761, "text": null }, { "code": "// C# implementation// of above approachusing System; class GFG{// Function to print the// substrings of a numberstatic void printSubstrings(int n){ // Calculate the total // number of digits int s = (int)Math.Log10(n); // 0.5 has been added because // of it will return double // value like 99.556 int d = (int)(Math.Pow(10, s) + 0.5); int k = d; while (n > 0) { // Print all the numbers // from starting position while (d > 0) { Console.WriteLine(n / d); d = d / 10; } // Update the no. n = n % k; // Update the no.of digits k = k / 10; d = k; }} // Driver codepublic static void Main(){ int n = 123; printSubstrings(n);}} // This code is contributed// by mits", "e": 30275, "s": 29476, "text": null }, { "code": "<?php// PHP implementation of above approach // Function to print the substrings// of a numberfunction printSubstrings($n){ // Calculate the total number // of digits $s = (int)log10($n); // 0.5 has been added because // of it will return double // value like 99.556 $d = (int)(pow(10, $s) + 0.5); $k = $d; while ($n) { // Print all the numbers from // starting position while ($d) { echo (int)($n / $d) . \"\\n\"; $d = (int)($d / 10); } // Update the no. $n = $n % $k; // Update the no.of digits $k = (int)($k / 10); $d = $k; }} // Driver code$n = 123;printSubstrings($n); // This code is contributed by mits?>", "e": 31014, "s": 30275, "text": null }, { "code": "<script> // javascript implementation// of above approach// Function to print the// substrings of a numberfunction printSubstrings(n){ // Calculate the total // number of digits var s = parseInt(Math.log10(n)); // 0.5 has been added because // of it will return double // value like 99.556 var d = parseInt((Math.pow(10, s) + 0.5)); var k = d; while (n > 0) { // Print all the numbers // from starting position while (d > 0) { document.write(parseInt(n / d)+\"<br>\"); d = parseInt(d / 10); } // Update the no. n = n % k; // Update the no.of digits k = parseInt(k / 10); d = k; }} // Driver code var n = 123;printSubstrings(n); // This code contributed by Princi Singh</script>", "e": 31821, "s": 31014, "text": null }, { "code": null, "e": 31837, "s": 31821, "text": "1\n12\n123\n2\n23\n3" }, { "code": null, "e": 31855, "s": 31839, "text": "tufan_gupta2000" }, { "code": null, "e": 31868, "s": 31855, "text": "Mithun Kumar" }, { "code": null, "e": 31878, "s": 31868, "text": "Rajput-Ji" }, { "code": null, "e": 31891, "s": 31878, "text": "princi singh" }, { "code": null, "e": 31904, "s": 31891, "text": "ankita_saini" }, { "code": null, "e": 31914, "s": 31904, "text": "maths-log" }, { "code": null, "e": 31933, "s": 31914, "text": "Modular Arithmetic" }, { "code": null, "e": 31943, "s": 31933, "text": "substring" }, { "code": null, "e": 31956, "s": 31943, "text": "Mathematical" }, { "code": null, "e": 31969, "s": 31956, "text": "Mathematical" }, { "code": null, "e": 31988, "s": 31969, "text": "Modular Arithmetic" }, { "code": null, "e": 32086, "s": 31988, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32110, "s": 32086, "text": "Merge two sorted arrays" }, { "code": null, "e": 32153, "s": 32110, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32167, "s": 32153, "text": "Prime Numbers" }, { "code": null, "e": 32209, "s": 32167, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 32231, "s": 32209, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 32304, "s": 32231, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32345, "s": 32304, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 32388, "s": 32345, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 32422, "s": 32388, "text": "Program for factorial of a number" } ]
Next smallest prime palindrome - GeeksforGeeks
10 May, 2021 Given a positive integer N where . The task is to find the smallest prime palindrome greater than or equal to N.Examples: Input: 8 Output: 11 Input: 7000000000 Output: 10000500001 Approach: The Naive approach is to loop from N + 1 until we found the next smallest prime palindrome greater than or equal to N.Efficient Approach: Let’s say P = R is a the next smallest prime-palindrome greater than or equal to N. Now since R is a palindrome, the first half of the digits of R can be used to determine R up to two possibilities. Let k be the first half of the digits in R. For eg. if k = 123, then R = 12321 or R = 123321.Thus, we iterate through each k upto 105 and create the associated palindrome R, and check whether R is a prime or not. Also, we will handle the odd and even palindromes separately, and break them when we found our result.Below is the implementation of above approach: C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; #define ll long long int // Function to check whether// a number is primebool isPrime(ll n){ if (n < 2) return false; for (ll i = 2; i <= sqrt(n); i++) { if (n % i == 0) return false; } return true;} // function to generate next// smallest prime palindromell nextPrimePalindrome(ll N){for (ll k = 1; k < 1000000; k++){ // Check for odd-length palindromes string s = to_string(k); string z(s.begin(), s.end()); reverse(z.begin(), z.end()); // eg. s = '1234' to x = int('1234321') ll x = stoll(s + z.substr(1)); if (x >= N and isPrime(x)) return x; // Check for even-length palindromes s = to_string(k); z = string(s.begin(), s.end()); reverse(z.begin(), z.end()); // eg. s = '1234' to x = int('12344321') x = stoll(s + z); if (x >= N and isPrime(x)) return x;}} // Driver Codeint main(){ ll N = 7000000000; // Function call to print answer cout << nextPrimePalindrome(N) << endl; return 0;} // This code is contributed by// sanjeev2552 // Java implementation of above approachclass GFG{ // Function to check whether// a number is primestatic boolean isPrime(long n){ if (n < 2) return false; for (long i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true;} // reverse the Stringstatic String reverse(String s){ String s1 = ""; for(int i = s.length() - 1; i >= 0; i--) s1 += s.charAt(i); return s1;} // function to generate next// smalongest prime palindromestatic long nextPrimePalindrome(long N){ for (long k = 1; k < 1000000l; k++) { // Check for odd-length palindromes String s = ""+k; String z; z = reverse(s); // eg. s = '1234' to x = int('1234321') long x = Long.parseLong(s + z.substring(1, z.length())); if (x >= N && isPrime(x)) return x; // Check for even-length palindromes s = ""+(k); z = s; z = reverse(z); // eg. s = '1234' to x = int('12344321') x = Long.parseLong(s + z); if (x >= N && isPrime(x)) return x; } return -1;} // Driver Codepublic static void main(String args[]){ long N = 7000000000l; // Function calong to print answer System.out.println( nextPrimePalindrome(N) );}} // This code is contributed by Arnab Kundu # Python3 implementation of above approachimport math # Function to check whether a number is primedef is_prime(n): return n > 1 and all(n % d for d in range(2, int(math.sqrt(n)) + 1)) # function to generate next smallest prime palindromedef NextprimePalindrome(N): for k in range(1, 10**6): # Check for odd-length palindromes s = str(k) x = int(s + s[-2::-1]) # eg. s = '1234' to x = int('1234321') if x >= N and is_prime(x): return x # Check for even-length palindromes s = str(k) x = int(s + s[-1::-1]) # eg. s = '1234' to x = int('12344321') if x >= N and is_prime(x): return x # Driver codeN = 7000000000 # Function call to print answerprint(NextprimePalindrome(N)) # This code is written by# Sanjit_Prasad // C# implementation of above approachusing System; class GFG{ // Function to check whether// a number is primestatic bool isPrime(long n){ if (n < 2) return false; for (long i = 2; i <= Math.Sqrt(n); i++) { if (n % i == 0) return false; } return true;} // reverse the Stringstatic String reverse(String s){ String s1 = ""; for(int i = s.Length - 1; i >= 0; i--) s1 += s[i]; return s1;} // function to generate next// smalongest prime palindromestatic long nextPrimePalindrome(long N){ for (long k = 1; k < 1000000; k++) { // Check for odd-length palindromes String s = ""+k; String z; z = reverse(s); // eg. s = '1234' to x = int('1234321') long x = long.Parse(s + z.Substring(1, z.Length - 1)); if (x >= N && isPrime(x)) return x; // Check for even-length palindromes s = ""+(k); z = s; z = reverse(z); // eg. s = '1234' to x = int('12344321') x = long.Parse(s + z); if (x >= N && isPrime(x)) return x; } return -1;} // Driver Codepublic static void Main(String []args){ long N = 7000000000; // Function calong to print answer Console.WriteLine( nextPrimePalindrome(N) );}} // This code is contributed by PrinciRaj1992 <script> // Javascript implementation of above approach // Function to check whether// a number is primefunction isPrime( n){ if (n < 2) return false; for (var i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true;} // function to generate next// smallest prime palindrome function reverse( s){ var s1 = ""; for(var i = s.length - 1; i >= 0; i--) s1 += s[i]; return s1;} function nextPrimePalindrome( N){for (var k = 1; k < 1000000; k++){ // Check for odd-length palindromes var s = ""+k; var z; z=reverse(s); // eg. s = '1234' to x = int('1234321') var x = Number(s + z.substring(1,z.length)); if (x >= N && isPrime(x)) return x; // Check for even-length palindromes s = ""+k; z = s; z=reverse(z); // eg. s = '1234' to x = int('12344321') x = Number(s + z); if (x >= N && isPrime(x)) return x;}} var N = 7000000000;// Function call to find maximum valuedocument.write(nextPrimePalindrome(N) + "<br>"); // This code is contributed by SoumikMondal </script> 10000500001 Time Complexity: O(N*sqrt(N)) where N is upper limit and the sqrt(N) term comes from checking if a candidate is prime. sanjeev2552 andrew1234 princiraj1992 SoumikMondal palindrome Prime Number Mathematical Mathematical Prime Number palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25963, "s": 25935, "text": "\n10 May, 2021" }, { "code": null, "e": 26087, "s": 25963, "text": "Given a positive integer N where . The task is to find the smallest prime palindrome greater than or equal to N.Examples: " }, { "code": null, "e": 26146, "s": 26087, "text": "Input: 8\nOutput: 11\n\nInput: 7000000000\nOutput: 10000500001" }, { "code": null, "e": 26158, "s": 26146, "text": "Approach: " }, { "code": null, "e": 26859, "s": 26158, "text": "The Naive approach is to loop from N + 1 until we found the next smallest prime palindrome greater than or equal to N.Efficient Approach: Let’s say P = R is a the next smallest prime-palindrome greater than or equal to N. Now since R is a palindrome, the first half of the digits of R can be used to determine R up to two possibilities. Let k be the first half of the digits in R. For eg. if k = 123, then R = 12321 or R = 123321.Thus, we iterate through each k upto 105 and create the associated palindrome R, and check whether R is a prime or not. Also, we will handle the odd and even palindromes separately, and break them when we found our result.Below is the implementation of above approach: " }, { "code": null, "e": 26863, "s": 26859, "text": "C++" }, { "code": null, "e": 26868, "s": 26863, "text": "Java" }, { "code": null, "e": 26876, "s": 26868, "text": "Python3" }, { "code": null, "e": 26879, "s": 26876, "text": "C#" }, { "code": null, "e": 26890, "s": 26879, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; #define ll long long int // Function to check whether// a number is primebool isPrime(ll n){ if (n < 2) return false; for (ll i = 2; i <= sqrt(n); i++) { if (n % i == 0) return false; } return true;} // function to generate next// smallest prime palindromell nextPrimePalindrome(ll N){for (ll k = 1; k < 1000000; k++){ // Check for odd-length palindromes string s = to_string(k); string z(s.begin(), s.end()); reverse(z.begin(), z.end()); // eg. s = '1234' to x = int('1234321') ll x = stoll(s + z.substr(1)); if (x >= N and isPrime(x)) return x; // Check for even-length palindromes s = to_string(k); z = string(s.begin(), s.end()); reverse(z.begin(), z.end()); // eg. s = '1234' to x = int('12344321') x = stoll(s + z); if (x >= N and isPrime(x)) return x;}} // Driver Codeint main(){ ll N = 7000000000; // Function call to print answer cout << nextPrimePalindrome(N) << endl; return 0;} // This code is contributed by// sanjeev2552", "e": 28010, "s": 26890, "text": null }, { "code": "// Java implementation of above approachclass GFG{ // Function to check whether// a number is primestatic boolean isPrime(long n){ if (n < 2) return false; for (long i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true;} // reverse the Stringstatic String reverse(String s){ String s1 = \"\"; for(int i = s.length() - 1; i >= 0; i--) s1 += s.charAt(i); return s1;} // function to generate next// smalongest prime palindromestatic long nextPrimePalindrome(long N){ for (long k = 1; k < 1000000l; k++) { // Check for odd-length palindromes String s = \"\"+k; String z; z = reverse(s); // eg. s = '1234' to x = int('1234321') long x = Long.parseLong(s + z.substring(1, z.length())); if (x >= N && isPrime(x)) return x; // Check for even-length palindromes s = \"\"+(k); z = s; z = reverse(z); // eg. s = '1234' to x = int('12344321') x = Long.parseLong(s + z); if (x >= N && isPrime(x)) return x; } return -1;} // Driver Codepublic static void main(String args[]){ long N = 7000000000l; // Function calong to print answer System.out.println( nextPrimePalindrome(N) );}} // This code is contributed by Arnab Kundu", "e": 29355, "s": 28010, "text": null }, { "code": "# Python3 implementation of above approachimport math # Function to check whether a number is primedef is_prime(n): return n > 1 and all(n % d for d in range(2, int(math.sqrt(n)) + 1)) # function to generate next smallest prime palindromedef NextprimePalindrome(N): for k in range(1, 10**6): # Check for odd-length palindromes s = str(k) x = int(s + s[-2::-1]) # eg. s = '1234' to x = int('1234321') if x >= N and is_prime(x): return x # Check for even-length palindromes s = str(k) x = int(s + s[-1::-1]) # eg. s = '1234' to x = int('12344321') if x >= N and is_prime(x): return x # Driver codeN = 7000000000 # Function call to print answerprint(NextprimePalindrome(N)) # This code is written by# Sanjit_Prasad", "e": 30158, "s": 29355, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ // Function to check whether// a number is primestatic bool isPrime(long n){ if (n < 2) return false; for (long i = 2; i <= Math.Sqrt(n); i++) { if (n % i == 0) return false; } return true;} // reverse the Stringstatic String reverse(String s){ String s1 = \"\"; for(int i = s.Length - 1; i >= 0; i--) s1 += s[i]; return s1;} // function to generate next// smalongest prime palindromestatic long nextPrimePalindrome(long N){ for (long k = 1; k < 1000000; k++) { // Check for odd-length palindromes String s = \"\"+k; String z; z = reverse(s); // eg. s = '1234' to x = int('1234321') long x = long.Parse(s + z.Substring(1, z.Length - 1)); if (x >= N && isPrime(x)) return x; // Check for even-length palindromes s = \"\"+(k); z = s; z = reverse(z); // eg. s = '1234' to x = int('12344321') x = long.Parse(s + z); if (x >= N && isPrime(x)) return x; } return -1;} // Driver Codepublic static void Main(String []args){ long N = 7000000000; // Function calong to print answer Console.WriteLine( nextPrimePalindrome(N) );}} // This code is contributed by PrinciRaj1992", "e": 31496, "s": 30158, "text": null }, { "code": "<script> // Javascript implementation of above approach // Function to check whether// a number is primefunction isPrime( n){ if (n < 2) return false; for (var i = 2; i <= Math.sqrt(n); i++) { if (n % i == 0) return false; } return true;} // function to generate next// smallest prime palindrome function reverse( s){ var s1 = \"\"; for(var i = s.length - 1; i >= 0; i--) s1 += s[i]; return s1;} function nextPrimePalindrome( N){for (var k = 1; k < 1000000; k++){ // Check for odd-length palindromes var s = \"\"+k; var z; z=reverse(s); // eg. s = '1234' to x = int('1234321') var x = Number(s + z.substring(1,z.length)); if (x >= N && isPrime(x)) return x; // Check for even-length palindromes s = \"\"+k; z = s; z=reverse(z); // eg. s = '1234' to x = int('12344321') x = Number(s + z); if (x >= N && isPrime(x)) return x;}} var N = 7000000000;// Function call to find maximum valuedocument.write(nextPrimePalindrome(N) + \"<br>\"); // This code is contributed by SoumikMondal </script>", "e": 32579, "s": 31496, "text": null }, { "code": null, "e": 32591, "s": 32579, "text": "10000500001" }, { "code": null, "e": 32713, "s": 32593, "text": "Time Complexity: O(N*sqrt(N)) where N is upper limit and the sqrt(N) term comes from checking if a candidate is prime. " }, { "code": null, "e": 32725, "s": 32713, "text": "sanjeev2552" }, { "code": null, "e": 32736, "s": 32725, "text": "andrew1234" }, { "code": null, "e": 32750, "s": 32736, "text": "princiraj1992" }, { "code": null, "e": 32763, "s": 32750, "text": "SoumikMondal" }, { "code": null, "e": 32774, "s": 32763, "text": "palindrome" }, { "code": null, "e": 32787, "s": 32774, "text": "Prime Number" }, { "code": null, "e": 32800, "s": 32787, "text": "Mathematical" }, { "code": null, "e": 32813, "s": 32800, "text": "Mathematical" }, { "code": null, "e": 32826, "s": 32813, "text": "Prime Number" }, { "code": null, "e": 32837, "s": 32826, "text": "palindrome" }, { "code": null, "e": 32935, "s": 32837, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32979, "s": 32935, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33021, "s": 32979, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 33052, "s": 33021, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33123, "s": 33052, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 33148, "s": 33123, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33180, "s": 33148, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33213, "s": 33180, "text": "Program to multiply two matrices" }, { "code": null, "e": 33259, "s": 33213, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 33303, "s": 33259, "text": "Generate all permutation of a set in Python" } ]
Java Program to Get TreeMap Key, Value, or Entry Greater or Less than the Specified Value - GeeksforGeeks
07 Jan, 2021 TreeMap class is a red-black tree implementation. It helps us in storing key-value pairs in sorted order. Here 3 approaches are discussed as follows where 4 key-value pairs in the TreeMap in all approaches are as follows along with syntax. tree.put100, "=> Welcoming"); tree.put(120, "=> you to "); tree.put(140, "=> computer science portal"); tree.put(200, "=> Geeks for Geeks"); Approaches: Brute force method just to store TreeMap key-value pairs and display only.Using inbuilt functions: higherKey() method and lowerKey() method of TreeMap class.Using higherEntry().getValue() function and lowerEntry().getValue() function of TreeMap class. Brute force method just to store TreeMap key-value pairs and display only. Using inbuilt functions: higherKey() method and lowerKey() method of TreeMap class. Using higherEntry().getValue() function and lowerEntry().getValue() function of TreeMap class. Method 1: Storing key-value pairs in TreeMap and printing the key-value pairs. Example: Java // Java Program to Get TreeMap Key and Value // Importing all classes// of java.util packageimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tree = new TreeMap<Integer, String>(); // Inserting the Elements into TreeMap tree.put(100, "=> Welcoming"); tree.put(120, "=> you to "); tree.put(140, "=> computer science portal"); tree.put(200, "=> Geeks for Geeks"); // Iterating over TreeMap using for-each loop for (Map.Entry<Integer, String> map : tree.entrySet()) // Displaying all entries- keys and values // using getKey() and getValue() method System.out.println(map.getKey() + " " + map.getValue()); }} 100 => Welcoming 120 => you to 140 => computer science portal 200 => Geeks for Geeks Method 2: Printing the key that is greater than or less than the specified value by using inbuilt functions: higherKey() method and lowerKey() method of TreeMap class The higherKey() method of java.util.TreeMap class is used to return the least key strictly greater than the given key, or null if there is no such key. Syntax: public K higherKey(K key) Parameters: This method takes the key k as a parameter. Return Value: This method returns the least key greater than the key, or null if there is no such key. Exception: This method throws the NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys. The lowerKey() method is used to return the greatest key strictly less than to given key, passed as the parameter. In simpler words, this method is used to find the next greatest element after the element passed as the parameter. Syntax: public K TreeMap.lowerKey(K key) Parameters: This method takes a mandatory parameter key which is the key to be matched. Return Value: This method returns the greatest key strictly less than to key, or null if there is no such key. Example: Java // Java Program to Get TreeMap Key, Value, then// Entry Greater or Less than the Specified Value// using lowerKey() and higherKey() of Tree class // Importing all classes of// java.util packageimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> tree = new TreeMap<Integer, String>(); // Inserting the Elements into TreeMap tree.put(100, "=> Welcoming"); tree.put(120, "=> you to "); tree.put(140, "=> computer science portal"); tree.put(200, "=> Geeks for Geeks"); // Returning the smallest key among all the keys // greater than 150 System.out.println("Smallest key among key > 150 : " + tree.higherKey(150)); // Returning the greatest key among all the keys // smaller than 150 System.out.println("Greatest key among key < 150 : " + tree.lowerKey(150)); }} Smallest key among key > 150 : 200 Greatest key among key < 150 : 140 Method 3: Printing the value corresponding to the key that is greater than or less than the specified key via higherEntry().getValue() function and lowerEntry().getValue() function of TreeMap class The higherEntry() method of java.util.TreeMap class is used to return a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key whereas the lowerEntry() method of java.util.TreeMap class is used to return a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key. Example: Java // Java Program to Get TreeMap Key, Value, or// Entry Greater or Less than the Specified Value// using higherEntry().getValue() function and// lowerEntry().getValue() // Importing all classes of// java.util packageimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> tree = new TreeMap<Integer, String>(); // Inserting the Elements into TreeMap tree.put(100, "=> Welcoming"); tree.put(120, "=> you to "); tree.put(140, "=> computer science portal"); tree.put(200, "=> Geeks for Geeks"); // Returning the value corresponding to the key // which is smallest among the keys greater than 150 System.out.println( tree.higherEntry(150).getValue()); // Returning the value corresponding to the key // which is greatest among the keys smaller than 150 System.out.println(tree.lowerEntry(150).getValue()); }} => Geeks for Geeks => computer science portal java-TreeMap Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 26205, "s": 26177, "text": "\n07 Jan, 2021" }, { "code": null, "e": 26445, "s": 26205, "text": "TreeMap class is a red-black tree implementation. It helps us in storing key-value pairs in sorted order. Here 3 approaches are discussed as follows where 4 key-value pairs in the TreeMap in all approaches are as follows along with syntax." }, { "code": null, "e": 26586, "s": 26445, "text": "tree.put100, \"=> Welcoming\");\ntree.put(120, \"=> you to \");\ntree.put(140, \"=> computer science portal\");\ntree.put(200, \"=> Geeks for Geeks\");" }, { "code": null, "e": 26598, "s": 26586, "text": "Approaches:" }, { "code": null, "e": 26850, "s": 26598, "text": "Brute force method just to store TreeMap key-value pairs and display only.Using inbuilt functions: higherKey() method and lowerKey() method of TreeMap class.Using higherEntry().getValue() function and lowerEntry().getValue() function of TreeMap class." }, { "code": null, "e": 26925, "s": 26850, "text": "Brute force method just to store TreeMap key-value pairs and display only." }, { "code": null, "e": 27009, "s": 26925, "text": "Using inbuilt functions: higherKey() method and lowerKey() method of TreeMap class." }, { "code": null, "e": 27104, "s": 27009, "text": "Using higherEntry().getValue() function and lowerEntry().getValue() function of TreeMap class." }, { "code": null, "e": 27183, "s": 27104, "text": "Method 1: Storing key-value pairs in TreeMap and printing the key-value pairs." }, { "code": null, "e": 27192, "s": 27183, "text": "Example:" }, { "code": null, "e": 27197, "s": 27192, "text": "Java" }, { "code": "// Java Program to Get TreeMap Key and Value // Importing all classes// of java.util packageimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // Initialization of a TreeMap // using Generics TreeMap<Integer, String> tree = new TreeMap<Integer, String>(); // Inserting the Elements into TreeMap tree.put(100, \"=> Welcoming\"); tree.put(120, \"=> you to \"); tree.put(140, \"=> computer science portal\"); tree.put(200, \"=> Geeks for Geeks\"); // Iterating over TreeMap using for-each loop for (Map.Entry<Integer, String> map : tree.entrySet()) // Displaying all entries- keys and values // using getKey() and getValue() method System.out.println(map.getKey() + \" \" + map.getValue()); }}", "e": 28101, "s": 27197, "text": null }, { "code": null, "e": 28187, "s": 28101, "text": "100 => Welcoming\n120 => you to \n140 => computer science portal\n200 => Geeks for Geeks" }, { "code": null, "e": 28354, "s": 28187, "text": "Method 2: Printing the key that is greater than or less than the specified value by using inbuilt functions: higherKey() method and lowerKey() method of TreeMap class" }, { "code": null, "e": 28506, "s": 28354, "text": "The higherKey() method of java.util.TreeMap class is used to return the least key strictly greater than the given key, or null if there is no such key." }, { "code": null, "e": 28514, "s": 28506, "text": "Syntax:" }, { "code": null, "e": 28540, "s": 28514, "text": "public K higherKey(K key)" }, { "code": null, "e": 28596, "s": 28540, "text": "Parameters: This method takes the key k as a parameter." }, { "code": null, "e": 28699, "s": 28596, "text": "Return Value: This method returns the least key greater than the key, or null if there is no such key." }, { "code": null, "e": 28864, "s": 28699, "text": "Exception: This method throws the NullPointerException if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys." }, { "code": null, "e": 29094, "s": 28864, "text": "The lowerKey() method is used to return the greatest key strictly less than to given key, passed as the parameter. In simpler words, this method is used to find the next greatest element after the element passed as the parameter." }, { "code": null, "e": 29102, "s": 29094, "text": "Syntax:" }, { "code": null, "e": 29135, "s": 29102, "text": "public K TreeMap.lowerKey(K key)" }, { "code": null, "e": 29223, "s": 29135, "text": "Parameters: This method takes a mandatory parameter key which is the key to be matched." }, { "code": null, "e": 29334, "s": 29223, "text": "Return Value: This method returns the greatest key strictly less than to key, or null if there is no such key." }, { "code": null, "e": 29343, "s": 29334, "text": "Example:" }, { "code": null, "e": 29348, "s": 29343, "text": "Java" }, { "code": "// Java Program to Get TreeMap Key, Value, then// Entry Greater or Less than the Specified Value// using lowerKey() and higherKey() of Tree class // Importing all classes of// java.util packageimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> tree = new TreeMap<Integer, String>(); // Inserting the Elements into TreeMap tree.put(100, \"=> Welcoming\"); tree.put(120, \"=> you to \"); tree.put(140, \"=> computer science portal\"); tree.put(200, \"=> Geeks for Geeks\"); // Returning the smallest key among all the keys // greater than 150 System.out.println(\"Smallest key among key > 150 : \" + tree.higherKey(150)); // Returning the greatest key among all the keys // smaller than 150 System.out.println(\"Greatest key among key < 150 : \" + tree.lowerKey(150)); }}", "e": 30373, "s": 29348, "text": null }, { "code": null, "e": 30443, "s": 30373, "text": "Smallest key among key > 150 : 200\nGreatest key among key < 150 : 140" }, { "code": null, "e": 30641, "s": 30443, "text": "Method 3: Printing the value corresponding to the key that is greater than or less than the specified key via higherEntry().getValue() function and lowerEntry().getValue() function of TreeMap class" }, { "code": null, "e": 31027, "s": 30641, "text": "The higherEntry() method of java.util.TreeMap class is used to return a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key whereas the lowerEntry() method of java.util.TreeMap class is used to return a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key." }, { "code": null, "e": 31036, "s": 31027, "text": "Example:" }, { "code": null, "e": 31041, "s": 31036, "text": "Java" }, { "code": "// Java Program to Get TreeMap Key, Value, or// Entry Greater or Less than the Specified Value// using higherEntry().getValue() function and// lowerEntry().getValue() // Importing all classes of// java.util packageimport java.util.*; class GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> tree = new TreeMap<Integer, String>(); // Inserting the Elements into TreeMap tree.put(100, \"=> Welcoming\"); tree.put(120, \"=> you to \"); tree.put(140, \"=> computer science portal\"); tree.put(200, \"=> Geeks for Geeks\"); // Returning the value corresponding to the key // which is smallest among the keys greater than 150 System.out.println( tree.higherEntry(150).getValue()); // Returning the value corresponding to the key // which is greatest among the keys smaller than 150 System.out.println(tree.lowerEntry(150).getValue()); }}", "e": 32067, "s": 31041, "text": null }, { "code": null, "e": 32113, "s": 32067, "text": "=> Geeks for Geeks\n=> computer science portal" }, { "code": null, "e": 32126, "s": 32113, "text": "java-TreeMap" }, { "code": null, "e": 32133, "s": 32126, "text": "Picked" }, { "code": null, "e": 32157, "s": 32133, "text": "Technical Scripter 2020" }, { "code": null, "e": 32162, "s": 32157, "text": "Java" }, { "code": null, "e": 32176, "s": 32162, "text": "Java Programs" }, { "code": null, "e": 32195, "s": 32176, "text": "Technical Scripter" }, { "code": null, "e": 32200, "s": 32195, "text": "Java" }, { "code": null, "e": 32298, "s": 32200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32349, "s": 32298, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 32379, "s": 32349, "text": "HashMap in Java with Examples" }, { "code": null, "e": 32398, "s": 32379, "text": "Interfaces in Java" }, { "code": null, "e": 32413, "s": 32398, "text": "Stream In Java" }, { "code": null, "e": 32444, "s": 32413, "text": "How to iterate any Map in Java" }, { "code": null, "e": 32472, "s": 32444, "text": "Initializing a List in Java" }, { "code": null, "e": 32516, "s": 32472, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 32542, "s": 32516, "text": "Java Programming Examples" }, { "code": null, "e": 32576, "s": 32542, "text": "Convert Double to Integer in Java" } ]
Filter DataFrame columns in R by given condition - GeeksforGeeks
24 Jun, 2021 In this article, we are going to see how to select DataFrame columns in R Programming Language by given condition. R data frame columns can be subjected to constraints, and produce smaller subsets. However, while the conditions are applied, the following properties are maintained : Rows of the data frame remain unmodified. Data frame attributes are preserved. Output columns are a subset of input columns, Method 1: Using indexing methods The aggregate methods can be applied over the columns of the data frame, and the columns satisfying the evaluation of expressions are returned as an output. The resultant data frame is a subset of the data frame where all rows are retained for the selected columns. The modified data frame has to be stored in a new variable in order to retain changes. For instance, colSums() is used to calculate the sum of all elements belonging to a column. Example 1: The following program returns the columns where the sum of its elements is greater than 10 : R # declaring a data framedata_frame = data.frame(col1 = c(0 : 4) , col2 = c(0, 2, -1, 4, 8), col3 = c(9 : 13)) print ("Original dataframe")print (data_frame) # where column sum is greater than 10data_frame_mod <- data_frame[colSums(data_frame)>10]print ("Modified dataframe")print (data_frame_mod) Output: [1] "Original dataframe" col1 col2 col3 1 0 0 9 2 1 2 10 3 2 -1 11 4 3 4 12 5 4 8 13 [1] "Modified dataframe" col2 col3 1 0 9 2 2 10 3 -1 11 4 4 12 5 8 13 Example 2: The below program checks if the modulo operation of col1 value with 2 is not equal to 0. R # declaring a data framedata_frame = data.frame(col1 = c(0 : 4) , col2 = c(0, 2, -1, 4, 8), col3 = c(9 : 13)) print ("Original dataframe")print (data_frame) # where column sum is greater than 10data_frame_mod <- data_frame[data_frame$col1 %% 2 != 0, ]print ("Modified dataframe")print (data_frame_mod) Output: [1] "Original dataframe" col1 col2 col3 1 0 0 9 2 1 2 10 3 2 -1 11 4 3 4 12 5 4 8 13 [1] "Modified dataframe" col1 col2 col3 2 1 2 10 4 3 4 12 Method 2: Using dplyr package The dplyr library can be installed and loaded into the working space which is used to perform data manipulation. install.packages("dplyr") The select_if() function is used to produce a subset of the data frame, retaining all rows that satisfy the specified conditions. The select_if() method in R can be applied to both grouped as well as ungrouped data. The expressions include comparison operators (==, >, >= ) , logical operators (&, |, !, xor()) , range operators (between(), near()) as well as NA value check against the column values. The subset data frame has to be retained in a separate variable. df %>% select_if(condition) Example 1: The following program returns the numerical columns of the dataframe, when subjected to the select_if() method : R library ("dplyr") # declaring a data framedata_frame = data.frame(col1 = c("b", "b", "d", "e", "e") , col2 = c(0, 2, 1, 4, 5), col3 = c(TRUE, FALSE, FALSE, TRUE, TRUE) col4 = c(1 : 5)) print ("Original dataframe")print (data_frame)print ("Modified dataframe") # selecting numeric columnsdata_frame %>% select_if(is.numeric) Output [1] "Original dataframe" col1 col2 col3 col4 1 b 0 TRUE 1 2 b 2 FALSE 2 3 d 1 FALSE 3 4 e 4 TRUE 4 5 e 5 TRUE 5 [1] "Modified dataframe" col2 col4 1 0 1 2 2 2 3 1 3 4 4 4 5 5 5 Example 2: The following program returns the columns where the sum of its elements is lesser than 10 : R library ("dplyr") # declaring a data framedata_frame = data.frame(col1 = c(-1, -2, -2, 0, 0) , col2 = c(0, 2, 1, 4, 5), col3 = c(1 : 5))print ("Original dataframe")print (data_frame)print ("Modified dataframe") # select columns where column sum is less than 10data_frame %>% select_if(colSums(data_frame) < 10) Output: [1] "Original dataframe" col1 col2 col3 1 -1 0 1 2 -2 2 2 3 -2 1 3 4 0 4 4 5 0 5 5 [1] "Modified dataframe" col1 1 -1 2 -2 3 -2 4 0 5 0 Method 3: Using subset() method The subset() method can be used to return a set of rows that satisfy the specified constraints. The subset() method doesn’t modify the order of occurrence of rows. Syntax: subset ( df , condition) Arguments : df – The dataframe condition – The constraints to be applied %in% operator can be used to check if the value occurs in a vector of values. Returns a boolean value depending on whether the element exists or not. val %in% vector R # declaring a data framedata_frame = data.frame(col1 = c(0 : 4) , col2 = c(0, 2, -1, 4, 8), col3 = c(9 : 13))print ("Original dataframe")print (data_frame) # where column sum is greater than 10data_frame_mod <- subset(data_frame, col3 %in% c(9, 10, 13))print ("Modified dataframe")print (data_frame_mod) Output: [1] "Original dataframe" col1 col2 col3 1 0 0 9 2 1 2 10 3 2 -1 11 4 3 4 12 5 4 8 13 [1] "Modified dataframe" col1 col2 col3 1 0 0 9 2 1 2 10 5 4 8 13 simranarora5sos Picked R DataFrame-Programs R-DataFrame 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 Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n24 Jun, 2021" }, { "code": null, "e": 26770, "s": 26487, "text": "In this article, we are going to see how to select DataFrame columns in R Programming Language by given condition. R data frame columns can be subjected to constraints, and produce smaller subsets. However, while the conditions are applied, the following properties are maintained :" }, { "code": null, "e": 26812, "s": 26770, "text": "Rows of the data frame remain unmodified." }, { "code": null, "e": 26849, "s": 26812, "text": "Data frame attributes are preserved." }, { "code": null, "e": 26895, "s": 26849, "text": "Output columns are a subset of input columns," }, { "code": null, "e": 26928, "s": 26895, "text": "Method 1: Using indexing methods" }, { "code": null, "e": 27374, "s": 26928, "text": "The aggregate methods can be applied over the columns of the data frame, and the columns satisfying the evaluation of expressions are returned as an output. The resultant data frame is a subset of the data frame where all rows are retained for the selected columns. The modified data frame has to be stored in a new variable in order to retain changes. For instance, colSums() is used to calculate the sum of all elements belonging to a column. " }, { "code": null, "e": 27479, "s": 27374, "text": "Example 1: The following program returns the columns where the sum of its elements is greater than 10 : " }, { "code": null, "e": 27481, "s": 27479, "text": "R" }, { "code": "# declaring a data framedata_frame = data.frame(col1 = c(0 : 4) , col2 = c(0, 2, -1, 4, 8), col3 = c(9 : 13)) print (\"Original dataframe\")print (data_frame) # where column sum is greater than 10data_frame_mod <- data_frame[colSums(data_frame)>10]print (\"Modified dataframe\")print (data_frame_mod)", "e": 27824, "s": 27481, "text": null }, { "code": null, "e": 27832, "s": 27824, "text": "Output:" }, { "code": null, "e": 28054, "s": 27832, "text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 0 0 9\n2 1 2 10\n3 2 -1 11\n4 3 4 12\n5 4 8 13\n[1] \"Modified dataframe\"\n col2 col3\n1 0 9\n2 2 10\n3 -1 11\n4 4 12\n5 8 13" }, { "code": null, "e": 28155, "s": 28054, "text": "Example 2: The below program checks if the modulo operation of col1 value with 2 is not equal to 0. " }, { "code": null, "e": 28157, "s": 28155, "text": "R" }, { "code": "# declaring a data framedata_frame = data.frame(col1 = c(0 : 4) , col2 = c(0, 2, -1, 4, 8), col3 = c(9 : 13)) print (\"Original dataframe\")print (data_frame) # where column sum is greater than 10data_frame_mod <- data_frame[data_frame$col1 %% 2 != 0, ]print (\"Modified dataframe\")print (data_frame_mod)", "e": 28505, "s": 28157, "text": null }, { "code": null, "e": 28513, "s": 28505, "text": "Output:" }, { "code": null, "e": 28714, "s": 28513, "text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 0 0 9\n2 1 2 10\n3 2 -1 11\n4 3 4 12\n5 4 8 13\n[1] \"Modified dataframe\"\n col1 col2 col3\n2 1 2 10\n4 3 4 12" }, { "code": null, "e": 28744, "s": 28714, "text": "Method 2: Using dplyr package" }, { "code": null, "e": 28857, "s": 28744, "text": "The dplyr library can be installed and loaded into the working space which is used to perform data manipulation." }, { "code": null, "e": 28883, "s": 28857, "text": "install.packages(\"dplyr\")" }, { "code": null, "e": 29351, "s": 28883, "text": "The select_if() function is used to produce a subset of the data frame, retaining all rows that satisfy the specified conditions. The select_if() method in R can be applied to both grouped as well as ungrouped data. The expressions include comparison operators (==, >, >= ) , logical operators (&, |, !, xor()) , range operators (between(), near()) as well as NA value check against the column values. The subset data frame has to be retained in a separate variable. " }, { "code": null, "e": 29379, "s": 29351, "text": "df %>% select_if(condition)" }, { "code": null, "e": 29503, "s": 29379, "text": "Example 1: The following program returns the numerical columns of the dataframe, when subjected to the select_if() method :" }, { "code": null, "e": 29505, "s": 29503, "text": "R" }, { "code": "library (\"dplyr\") # declaring a data framedata_frame = data.frame(col1 = c(\"b\", \"b\", \"d\", \"e\", \"e\") , col2 = c(0, 2, 1, 4, 5), col3 = c(TRUE, FALSE, FALSE, TRUE, TRUE) col4 = c(1 : 5)) print (\"Original dataframe\")print (data_frame)print (\"Modified dataframe\") # selecting numeric columnsdata_frame %>% select_if(is.numeric)", "e": 29898, "s": 29505, "text": null }, { "code": null, "e": 29905, "s": 29898, "text": "Output" }, { "code": null, "e": 30159, "s": 29905, "text": "[1] \"Original dataframe\"\n col1 col2 col3 col4\n1 b 0 TRUE 1\n2 b 2 FALSE 2\n3 d 1 FALSE 3\n4 e 4 TRUE 4\n5 e 5 TRUE 5\n[1] \"Modified dataframe\"\n col2 col4\n1 0 1\n2 2 2\n3 1 3\n4 4 4\n5 5 5" }, { "code": null, "e": 30263, "s": 30159, "text": "Example 2: The following program returns the columns where the sum of its elements is lesser than 10 : " }, { "code": null, "e": 30265, "s": 30263, "text": "R" }, { "code": "library (\"dplyr\") # declaring a data framedata_frame = data.frame(col1 = c(-1, -2, -2, 0, 0) , col2 = c(0, 2, 1, 4, 5), col3 = c(1 : 5))print (\"Original dataframe\")print (data_frame)print (\"Modified dataframe\") # select columns where column sum is less than 10data_frame %>% select_if(colSums(data_frame) < 10)", "e": 30622, "s": 30265, "text": null }, { "code": null, "e": 30630, "s": 30622, "text": "Output:" }, { "code": null, "e": 30837, "s": 30630, "text": "[1] \"Original dataframe\" \n col1 col2 col3 \n1 -1 0 1 \n2 -2 2 2 \n3 -2 1 3 \n4 0 4 4 \n5 0 5 5 \n[1] \"Modified dataframe\" \n col1\n1 -1 \n2 -2 \n3 -2 \n4 0 \n5 0" }, { "code": null, "e": 30869, "s": 30837, "text": "Method 3: Using subset() method" }, { "code": null, "e": 31034, "s": 30869, "text": "The subset() method can be used to return a set of rows that satisfy the specified constraints. The subset() method doesn’t modify the order of occurrence of rows. " }, { "code": null, "e": 31067, "s": 31034, "text": "Syntax: subset ( df , condition)" }, { "code": null, "e": 31080, "s": 31067, "text": "Arguments : " }, { "code": null, "e": 31099, "s": 31080, "text": "df – The dataframe" }, { "code": null, "e": 31141, "s": 31099, "text": "condition – The constraints to be applied" }, { "code": null, "e": 31291, "s": 31141, "text": "%in% operator can be used to check if the value occurs in a vector of values. Returns a boolean value depending on whether the element exists or not." }, { "code": null, "e": 31307, "s": 31291, "text": "val %in% vector" }, { "code": null, "e": 31309, "s": 31307, "text": "R" }, { "code": "# declaring a data framedata_frame = data.frame(col1 = c(0 : 4) , col2 = c(0, 2, -1, 4, 8), col3 = c(9 : 13))print (\"Original dataframe\")print (data_frame) # where column sum is greater than 10data_frame_mod <- subset(data_frame, col3 %in% c(9, 10, 13))print (\"Modified dataframe\")print (data_frame_mod)", "e": 31683, "s": 31309, "text": null }, { "code": null, "e": 31691, "s": 31683, "text": "Output:" }, { "code": null, "e": 31909, "s": 31691, "text": "[1] \"Original dataframe\"\n col1 col2 col3\n1 0 0 9\n2 1 2 10\n3 2 -1 11\n4 3 4 12\n5 4 8 13\n[1] \"Modified dataframe\"\n col1 col2 col3\n1 0 0 9\n2 1 2 10\n5 4 8 13" }, { "code": null, "e": 31925, "s": 31909, "text": "simranarora5sos" }, { "code": null, "e": 31932, "s": 31925, "text": "Picked" }, { "code": null, "e": 31953, "s": 31932, "text": "R DataFrame-Programs" }, { "code": null, "e": 31965, "s": 31953, "text": "R-DataFrame" }, { "code": null, "e": 31976, "s": 31965, "text": "R Language" }, { "code": null, "e": 31987, "s": 31976, "text": "R Programs" }, { "code": null, "e": 32085, "s": 31987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32137, "s": 32085, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32172, "s": 32137, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32210, "s": 32172, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32268, "s": 32210, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32311, "s": 32268, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32369, "s": 32311, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32412, "s": 32369, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32461, "s": 32412, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 32511, "s": 32461, "text": "How to filter R dataframe by multiple conditions?" } ]
Java Program to Find the Roots of Quadratic Equation - GeeksforGeeks
04 Dec, 2020 The roots of a function are the x-intercepts. By definition, the y-coordinate of points lying on the x-axis is zero. Therefore, to find the roots of a quadratic function, we set f (x) = 0, and solve the equation, ax2 + bx + c = 0. Conditions for a quadratic equation – ax^2 + bx + c = 0 where a, b, c are real numbers and cannot be zero ie, there value must be from {-∞ to -1} and {1 to ∞} A mathematical formula for finding the roots of a quadratic equation – roots = (-b ± √(b2-4ac)) / (2a) ± represents there are two roots. The roots of the quadratic equations are – first = (-b + √(b2-4ac)) / (2a) second = (-b - √(b2-4ac)) / (2a) The (b^2 – 4ac) which is the determinant, tells us about the nature of the roots – if (b^2 – 4ac) > 0, roots are real and differentif (b^2 – 4ac) == 0, roots are real and equalif (b^2 – 4ac) < 0, roots are complex and different if (b^2 – 4ac) > 0, roots are real and different if (b^2 – 4ac) == 0, roots are real and equal if (b^2 – 4ac) < 0, roots are complex and different Code to find roots of a quadratic equation: Java // Java program to find the roots of// quadratic equation public class Main { public static void main(String[] args) { // value of the constants a, b, c double a = 7.2, b = 5, c = 9; // declared the two roots double firstroot, secondroot; // determinant (b^2 - 4ac) double det = b * b - 4 * a * c; // check if determinant is greater than 0 if (det > 0) { // two real and distinct roots firstroot = (-b + Math.sqrt(det)) / (2 * a); secondroot = (-b - Math.sqrt(det)) / (2 * a); System.out.format( "First Root = %.2f and Second Root = %.2f", firstroot, secondroot); } // check if determinant is equal to 0 else if (det == 0) { // two real and equal roots // determinant is equal to 0 // so -b + 0 == -b firstroot = secondroot = -b / (2 * a); System.out.format( "First Root = Second Root = %.2f;", firstroot); } // if determinant is less than zero else { // roots are complex number and distinct double real = -b / (2 * a); double imaginary = Math.sqrt(-det) / (2 * a); System.out.printf("First Root = %.2f+%.2fi", real, imaginary); System.out.printf("\nSecond Root = %.2f-%.2fi", real, imaginary); } }} First Root = -0.35+1.06i Second Root = -0.35-1.06i 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": 25249, "s": 25221, "text": "\n04 Dec, 2020" }, { "code": null, "e": 25480, "s": 25249, "text": "The roots of a function are the x-intercepts. By definition, the y-coordinate of points lying on the x-axis is zero. Therefore, to find the roots of a quadratic function, we set f (x) = 0, and solve the equation, ax2 + bx + c = 0." }, { "code": null, "e": 25519, "s": 25480, "text": "Conditions for a quadratic equation – " }, { "code": null, "e": 25643, "s": 25519, "text": "ax^2 + bx + c = 0 \n\nwhere \na, b, c are real numbers and cannot be zero ie, there value must be from {-∞ to -1} and {1 to ∞}" }, { "code": null, "e": 25715, "s": 25643, "text": "A mathematical formula for finding the roots of a quadratic equation – " }, { "code": null, "e": 25782, "s": 25715, "text": "roots = (-b ± √(b2-4ac)) / (2a)\n\n± represents there are two roots." }, { "code": null, "e": 25826, "s": 25782, "text": "The roots of the quadratic equations are – " }, { "code": null, "e": 25891, "s": 25826, "text": "first = (-b + √(b2-4ac)) / (2a)\nsecond = (-b - √(b2-4ac)) / (2a)" }, { "code": null, "e": 25974, "s": 25891, "text": "The (b^2 – 4ac) which is the determinant, tells us about the nature of the roots –" }, { "code": null, "e": 26119, "s": 25974, "text": "if (b^2 – 4ac) > 0, roots are real and differentif (b^2 – 4ac) == 0, roots are real and equalif (b^2 – 4ac) < 0, roots are complex and different" }, { "code": null, "e": 26168, "s": 26119, "text": "if (b^2 – 4ac) > 0, roots are real and different" }, { "code": null, "e": 26214, "s": 26168, "text": "if (b^2 – 4ac) == 0, roots are real and equal" }, { "code": null, "e": 26266, "s": 26214, "text": "if (b^2 – 4ac) < 0, roots are complex and different" }, { "code": null, "e": 26310, "s": 26266, "text": "Code to find roots of a quadratic equation:" }, { "code": null, "e": 26315, "s": 26310, "text": "Java" }, { "code": "// Java program to find the roots of// quadratic equation public class Main { public static void main(String[] args) { // value of the constants a, b, c double a = 7.2, b = 5, c = 9; // declared the two roots double firstroot, secondroot; // determinant (b^2 - 4ac) double det = b * b - 4 * a * c; // check if determinant is greater than 0 if (det > 0) { // two real and distinct roots firstroot = (-b + Math.sqrt(det)) / (2 * a); secondroot = (-b - Math.sqrt(det)) / (2 * a); System.out.format( \"First Root = %.2f and Second Root = %.2f\", firstroot, secondroot); } // check if determinant is equal to 0 else if (det == 0) { // two real and equal roots // determinant is equal to 0 // so -b + 0 == -b firstroot = secondroot = -b / (2 * a); System.out.format( \"First Root = Second Root = %.2f;\", firstroot); } // if determinant is less than zero else { // roots are complex number and distinct double real = -b / (2 * a); double imaginary = Math.sqrt(-det) / (2 * a); System.out.printf(\"First Root = %.2f+%.2fi\", real, imaginary); System.out.printf(\"\\nSecond Root = %.2f-%.2fi\", real, imaginary); } }}", "e": 27831, "s": 26315, "text": null }, { "code": null, "e": 27882, "s": 27831, "text": "First Root = -0.35+1.06i\nSecond Root = -0.35-1.06i" }, { "code": null, "e": 27889, "s": 27882, "text": "Picked" }, { "code": null, "e": 27894, "s": 27889, "text": "Java" }, { "code": null, "e": 27908, "s": 27894, "text": "Java Programs" }, { "code": null, "e": 27913, "s": 27908, "text": "Java" }, { "code": null, "e": 28011, "s": 27913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28026, "s": 28011, "text": "Stream In Java" }, { "code": null, "e": 28047, "s": 28026, "text": "Constructors in Java" }, { "code": null, "e": 28066, "s": 28047, "text": "Exceptions in Java" }, { "code": null, "e": 28096, "s": 28066, "text": "Functional Interfaces in Java" }, { "code": null, "e": 28142, "s": 28096, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28168, "s": 28142, "text": "Java Programming Examples" }, { "code": null, "e": 28202, "s": 28168, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28249, "s": 28202, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 28281, "s": 28249, "text": "How to Iterate HashMap in Java?" } ]
Background Subtraction in an Image using Concept of Running Average - GeeksforGeeks
05 Nov, 2018 Background subtraction is a technique for separating out foreground elements from the background and is done by generating a foreground mask. This technique is used for detecting dynamically moving objects from static cameras. Background subtraction technique is important for object tracking. There are several techniques for background subtraction In this article, we discuss the concept of Running Average. The running average of a function is used to separate foreground from background. In this concept, the video sequence is analyzed over a particular set of frames. During this sequence of frames, the running average over the current frame and the previous frames is computed. This gives us the background model and any new object introduced in the during the sequencing of the video becomes the part of the foreground. Then, the current frame holds the newly introduced object with the background. Then the computation of the absolute difference between the background model (which is a function of time) and the current frame (which is newly introduced object) is done. Running average is computed using the equation given below : Prerequisites : A working web camera or a camera module for input. Download Python 3.x, Numpy and OpenCV 2.7.x version. Check if your OS is either 32 bit or 64 bit compatible and install accordingly. Check the running status of numpy and OpenCV How Running Average method works? The objective of the program is to detect active objects from the difference obtained from the reference frame and the current frame. We keep feeding each frame to the given function, and the function keeps finding the averages of all frames. Then we compute the absolute difference between the frames.The function used is cv2.accumulateWeighted(). cv2.accumulateWeighted(src, dst, alpha) The parameters passed in this function are : src: The source image. The image can be colored or grayscaled image and either 8-bit or 32-bit floating point.dst: The accumulator or the destination image. It is either 32-bit or 64-bit floating point.NOTE: It should have the same channels as that of the source image. Also, the value of dst should be predeclared initially.alpha: Weight of the input image. Alpha decides the speed of updating. If you set a lower value for this variable, running average will be performed over a larger amount of previous frames and vice-versa. src: The source image. The image can be colored or grayscaled image and either 8-bit or 32-bit floating point. dst: The accumulator or the destination image. It is either 32-bit or 64-bit floating point.NOTE: It should have the same channels as that of the source image. Also, the value of dst should be predeclared initially. alpha: Weight of the input image. Alpha decides the speed of updating. If you set a lower value for this variable, running average will be performed over a larger amount of previous frames and vice-versa. Code: # Python program to illustrate# Background subtraction using# concept of Running Averages # organize importsimport cv2import numpy as np # capture frames from a cameracap = cv2.VideoCapture(0) # read the frames from the camera_, img = cap.read() # modify the data type# setting to 32-bit floating pointaverageValue1 = np.float32(img) # loop runs if capturing has been initialized. while(1): # reads frames from a camera _, img = cap.read() # using the cv2.accumulateWeighted() function # that updates the running average cv2.accumulateWeighted(img, averageValue1, 0.02) # converting the matrix elements to absolute values # and converting the result to 8-bit. resultingFrames1 = cv2.convertScaleAbs(averageValue1) # Show two output windows # the input / original frames window cv2.imshow('InputWindow', img) # the window showing output of alpha value 0.02 cv2.imshow('averageValue1', resultingFrames1) # Wait for Esc key to stop the program k = cv2.waitKey(30) & 0xff if k == 27: break # Close the window cap.release() # De-allocate any associated memory usage cv2.destroyAllWindows() Output : As we can see clearly below, the hand blocks the background view. Now, we shake the foreground object i.e. our hand. We begin waving our hand. The Running average shows the background clearly below, Running Average with alpha 0.02 has caught it as a transparent hand, with main emphasis on the background Alternatively, we can use the cv.RunningAvg() for the same task with the parameters having the same meaning as that of the parameters of the cv2.accumulateweighted(). cv.RunningAvg(image, acc, alpha) References : https://docs.opencv.org/2.4/modules/imgproc/doc/motion_analysis_and_object_tracking.htmlhttps://en.wikipedia.org/wiki/Foreground_detectionhttps://docs.opencv.org/3.2.0/d1/dc5/tutorial_background_subtraction.html https://docs.opencv.org/2.4/modules/imgproc/doc/motion_analysis_and_object_tracking.html https://en.wikipedia.org/wiki/Foreground_detection https://docs.opencv.org/3.2.0/d1/dc5/tutorial_background_subtraction.html Image-Processing OpenCV Technical Scripter 2018 Advanced Computer Subject GBlog Project Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Reinforcement learning Decision Tree Decision Tree Introduction with example System Design Tutorial Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... DSA Sheet by Love Babbar Socket Programming in C/C++ GET and POST requests using Python Must Do Coding Questions for Product Based Companies
[ { "code": null, "e": 25915, "s": 25887, "text": "\n05 Nov, 2018" }, { "code": null, "e": 26265, "s": 25915, "text": "Background subtraction is a technique for separating out foreground elements from the background and is done by generating a foreground mask. This technique is used for detecting dynamically moving objects from static cameras. Background subtraction technique is important for object tracking. There are several techniques for background subtraction" }, { "code": null, "e": 27056, "s": 26265, "text": "In this article, we discuss the concept of Running Average. The running average of a function is used to separate foreground from background. In this concept, the video sequence is analyzed over a particular set of frames. During this sequence of frames, the running average over the current frame and the previous frames is computed. This gives us the background model and any new object introduced in the during the sequencing of the video becomes the part of the foreground. Then, the current frame holds the newly introduced object with the background. Then the computation of the absolute difference between the background model (which is a function of time) and the current frame (which is newly introduced object) is done. Running average is computed using the equation given below :" }, { "code": null, "e": 27094, "s": 27078, "text": "Prerequisites :" }, { "code": null, "e": 27145, "s": 27094, "text": "A working web camera or a camera module for input." }, { "code": null, "e": 27278, "s": 27145, "text": "Download Python 3.x, Numpy and OpenCV 2.7.x version. Check if your OS is either 32 bit or 64 bit compatible and install accordingly." }, { "code": null, "e": 27323, "s": 27278, "text": "Check the running status of numpy and OpenCV" }, { "code": null, "e": 27357, "s": 27323, "text": "How Running Average method works?" }, { "code": null, "e": 27706, "s": 27357, "text": "The objective of the program is to detect active objects from the difference obtained from the reference frame and the current frame. We keep feeding each frame to the given function, and the function keeps finding the averages of all frames. Then we compute the absolute difference between the frames.The function used is cv2.accumulateWeighted()." }, { "code": null, "e": 27749, "s": 27706, "text": "\ncv2.accumulateWeighted(src, dst, alpha)\n\n" }, { "code": null, "e": 27794, "s": 27749, "text": "The parameters passed in this function are :" }, { "code": null, "e": 28324, "s": 27794, "text": "src: The source image. The image can be colored or grayscaled image and either 8-bit or 32-bit floating point.dst: The accumulator or the destination image. It is either 32-bit or 64-bit floating point.NOTE: It should have the same channels as that of the source image. Also, the value of dst should be predeclared initially.alpha: Weight of the input image. Alpha decides the speed of updating. If you set a lower value for this variable, running average will be performed over a larger amount of previous frames and vice-versa." }, { "code": null, "e": 28435, "s": 28324, "text": "src: The source image. The image can be colored or grayscaled image and either 8-bit or 32-bit floating point." }, { "code": null, "e": 28651, "s": 28435, "text": "dst: The accumulator or the destination image. It is either 32-bit or 64-bit floating point.NOTE: It should have the same channels as that of the source image. Also, the value of dst should be predeclared initially." }, { "code": null, "e": 28856, "s": 28651, "text": "alpha: Weight of the input image. Alpha decides the speed of updating. If you set a lower value for this variable, running average will be performed over a larger amount of previous frames and vice-versa." }, { "code": null, "e": 28862, "s": 28856, "text": "Code:" }, { "code": "# Python program to illustrate# Background subtraction using# concept of Running Averages # organize importsimport cv2import numpy as np # capture frames from a cameracap = cv2.VideoCapture(0) # read the frames from the camera_, img = cap.read() # modify the data type# setting to 32-bit floating pointaverageValue1 = np.float32(img) # loop runs if capturing has been initialized. while(1): # reads frames from a camera _, img = cap.read() # using the cv2.accumulateWeighted() function # that updates the running average cv2.accumulateWeighted(img, averageValue1, 0.02) # converting the matrix elements to absolute values # and converting the result to 8-bit. resultingFrames1 = cv2.convertScaleAbs(averageValue1) # Show two output windows # the input / original frames window cv2.imshow('InputWindow', img) # the window showing output of alpha value 0.02 cv2.imshow('averageValue1', resultingFrames1) # Wait for Esc key to stop the program k = cv2.waitKey(30) & 0xff if k == 27: break # Close the window cap.release() # De-allocate any associated memory usage cv2.destroyAllWindows()", "e": 30039, "s": 28862, "text": null }, { "code": null, "e": 30048, "s": 30039, "text": "Output :" }, { "code": null, "e": 30114, "s": 30048, "text": "As we can see clearly below, the hand blocks the background view." }, { "code": null, "e": 30191, "s": 30114, "text": "Now, we shake the foreground object i.e. our hand. We begin waving our hand." }, { "code": null, "e": 30353, "s": 30191, "text": "The Running average shows the background clearly below, Running Average with alpha 0.02 has caught it as a transparent hand, with main emphasis on the background" }, { "code": null, "e": 30520, "s": 30353, "text": "Alternatively, we can use the cv.RunningAvg() for the same task with the parameters having the same meaning as that of the parameters of the cv2.accumulateweighted()." }, { "code": null, "e": 30556, "s": 30520, "text": "\ncv.RunningAvg(image, acc, alpha)\n\n" }, { "code": null, "e": 30569, "s": 30556, "text": "References :" }, { "code": null, "e": 30781, "s": 30569, "text": "https://docs.opencv.org/2.4/modules/imgproc/doc/motion_analysis_and_object_tracking.htmlhttps://en.wikipedia.org/wiki/Foreground_detectionhttps://docs.opencv.org/3.2.0/d1/dc5/tutorial_background_subtraction.html" }, { "code": null, "e": 30870, "s": 30781, "text": "https://docs.opencv.org/2.4/modules/imgproc/doc/motion_analysis_and_object_tracking.html" }, { "code": null, "e": 30921, "s": 30870, "text": "https://en.wikipedia.org/wiki/Foreground_detection" }, { "code": null, "e": 30995, "s": 30921, "text": "https://docs.opencv.org/3.2.0/d1/dc5/tutorial_background_subtraction.html" }, { "code": null, "e": 31012, "s": 30995, "text": "Image-Processing" }, { "code": null, "e": 31019, "s": 31012, "text": "OpenCV" }, { "code": null, "e": 31043, "s": 31019, "text": "Technical Scripter 2018" }, { "code": null, "e": 31069, "s": 31043, "text": "Advanced Computer Subject" }, { "code": null, "e": 31075, "s": 31069, "text": "GBlog" }, { "code": null, "e": 31083, "s": 31075, "text": "Project" }, { "code": null, "e": 31090, "s": 31083, "text": "Python" }, { "code": null, "e": 31109, "s": 31090, "text": "Technical Scripter" }, { "code": null, "e": 31207, "s": 31109, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31230, "s": 31207, "text": "ML | Linear Regression" }, { "code": null, "e": 31253, "s": 31230, "text": "Reinforcement learning" }, { "code": null, "e": 31267, "s": 31253, "text": "Decision Tree" }, { "code": null, "e": 31307, "s": 31267, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 31330, "s": 31307, "text": "System Design Tutorial" }, { "code": null, "e": 31404, "s": 31330, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 31429, "s": 31404, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31457, "s": 31429, "text": "Socket Programming in C/C++" }, { "code": null, "e": 31492, "s": 31457, "text": "GET and POST requests using Python" } ]
How to create a video to GIF converter using ReactJS ? - GeeksforGeeks
10 Feb, 2021 When you think about a GIF image, a video is a must convert into a .gif format to an image. For this project, we are using FFMPEG library utility written in the C programming language. With the support of web Assembly, it can run in browsers easily without any need for a server, also here we are using the ReactJS library to make it simple and more understandable. You can know about web Assembly from the below Links: WebAssembly – The next BIG thing! Also, you can learn about FFMPEG which is a free and open-source software project consisting of a large suite of libraries and programs for handling video, audio, and other multimedia files and streams you can check from the https://ffmpeg.org/ link. FFMPEG: FFmpeg.wasm is a WebAssembly port of FFmpeg, which you can install via npm and use within Node or the browser just like any other JavaScript module. Create a simple client-side transcoder that streams data into a video element. Before going to make this project you have a hands-on experience on ReactJS because we are using react hook that is useState. So, ok with that concept go further and create your directory for the project. Create our React app with snowpack by following the command:npx create-snowpack-app gifconverter –template @snowpack/app-template-react npx create-snowpack-app gifconverter –template @snowpack/app-template-react After installation above command then installs another package called FFMPEG by the following command:npm install @ffmpeg/ffmpeg @ffmpeg/core npm install @ffmpeg/ffmpeg @ffmpeg/core For our styling purpose, you install the styled component by the following command. It is most likely CSS, but as we play with JavaScript it creates the user-defined variable, in that variable, we can write CSS properties, it is also used for making components without making a new JSX file.npm i styled-components npm i styled-components Project Structure: All installation for the project is complete, and we are now going for developing our aiming project. Now you can see the project directory looks like the following and you’re all dependencies are installed successfully than good to go. Now you open your command prompt and type the following command to start your server by running the below command. Then your browser opens in port number 8080 where your app is running, If your browser looks like this then you are in the right place. cd gifconverter npm start Now open your project folder in your code editor and make a folder in src directory called components and under this folder make various JSX components file by following src/components: Button.jsx Dbutton.jsx Header.jsx Inputfile.jsx Inputvideo.jsx Resultimg.jsx After creating the above JSX components, Let’s go for add the code for our project: Filename- Button.jsx: This component is a convert button, when you click on it automatically changes the .mp4 file to .gif file. Javascript import React from "react";import styled from "styled-components"; const Btn = styled.button` background-color: #000; color: #fff; border-radius: 18px; border: 1px solid #000; outline: none; font-weight: 700; cursor: pointer; font-size: 1.2em; padding: 10px; min-width: 20%; transition: all 0.2s ease-in-out; :hover { background-color: #3f3f3f; color: #efefef; }`; export const Button = ({ convertToGif }) => { return <Btn onClick={convertToGif}>Convert</Btn>;}; Filename- Dbutton.jsx: This component is a download button where you can download the .gif image after the convert from the .mp4 file. Javascript import React from "react";import styled from "styled-components"; const Btn = styled.a` display: flex; left: 0; right: 0; margin: 20px auto; margin-top: -20px; background-color: #000; color: #fff; border-radius: 35.5px; border: 1px solid #000; outline: none; font-weight: 700; cursor: pointer; font-size: 1.2em; padding: 10px; padding-left: 50px; max-width: 10%; text-decoration: none; transition: all 0.2s ease-in-out; :hover { background-color: #3f3f3f; color: #efefef; }`; export const Dbutton = ({ gif, download }) => { return ( <Btn href={gif} download onClick={(e) => download(e)}> Download </Btn> );}; Filename- Header.jsx: Javascript import React from "react";import styled from "styled-components"; const H1 = styled.h1` margin: 0; padding: 12px; background-color: #000; color: #fff; font-family: sans-serif; font-size: 3em;`; export const Header = () => { return ( <div> <H1>video to gif converter</H1> </div> );}; Filename- Inputfile.jsx: This component used for getting user input of video file (.mp4 file) Javascript import React from "react";import styled from "styled-components"; const Section = styled.div` display: flex; left: 0; right: 0; margin: 50px auto; width: 30%; border: 2px dashed #000; border-radius: 18px; padding: 10px;`; export const Inputfile = ({ setVideo }) => { return ( <Section> <input type="file" onChange={(e) => setVideo(e.target.files?.item(0))} /> </Section> );}; Filename- Inputvideo.jsx: Javascript import React from "react";import styled from "styled-components"; const Video = styled.video` width: 40%; margin: 20px; border: 1px dashed #045ca3;`; export const Inputvideo = ({ video }) => { return <Video controls width="250" src={URL.createObjectURL(video)} />;}; Filename- Resultimage.jsx: This component is showing the .gif image which converter from a video file. Javascript import React from "react";import styled from "styled-components"; const Img = styled.img` width: 50%; height: 100%; border: 4px solid #000; margin: 40px auto;`; export const Resultimg = ({ gif }) => { return <Img src={gif} />;}; From the above individual components you can see there are many useState props are passed in the arrow function using curly bracket, don’t worry that state you can find in the App.jsx. I prefer to consider all hooks in the App.jsx. So, we are adding all code for our required components that are used for our project. After the adding of all the code, then we have to import the components file to the App.jsx Filename- App.jsx: Here is our App.jsx code. Let’s import our components into this file. In the below App.jsx , we are importing a library as discussed previously that is FFmpeg as createFFmpeg , fetchFile. We are in the last phase of our project to finalize is our project working well or not ?:) Then after refreshing, you can see what your GIF converter looks like in the following image. Javascript import React, { useState, useEffect } from "react";import "./App.css";import { createFFmpeg, fetchFile } from "@ffmpeg/ffmpeg";import { Button } from "./components/Button";import { Inputfile } from "./components/Inputfile";import { Header } from "./components/Header";import { Resultimg } from "./components/Resultimage";import { Inputvideo } from "./components/Inputvideo";import { Dbutton } from "./components/Dbutton"; // Create the FFmpeg instance and load itconst ffmpeg = createFFmpeg({ log: true }); function App() { const [ready, setReady] = useState(false); const [video, setVideo] = useState(); const [gif, setGif] = useState(); const load = async () => { await ffmpeg.load(); setReady(true); }; useEffect(() => { load(); }, []); const convertToGif = async () => { // Write the .mp4 to the FFmpeg file system ffmpeg.FS("writeFile", "video1.mp4", await fetchFile(video)); // Run the FFmpeg command-line tool, converting // the .mp4 into .gif file await ffmpeg.run( "-i", "video1.mp4", "-t", "2.5", "-ss", "2.0", "-f", "gif", "out.gif" ); // Read the .gif file back from the FFmpeg file system const data = ffmpeg.FS("readFile", "out.gif"); const url = URL.createObjectURL( new Blob([data.buffer], { type: "image/gif" }) ); setGif(url); }; const download = (e) => { console.log(e.target.href); fetch(e.target.href, { method: "GET", headers: {}, }) .then((response) => { response.arrayBuffer().then(function (buffer) { const url = window.URL.createObjectURL(new Blob([buffer])); const link = document.createElement("a"); link.href = url; link.setAttribute("download", "image.gif"); document.body.appendChild(link); link.click(); }); }) .catch((err) => { console.log(err); }); }; return ready ? ( <div className="App"> <Header /> {video && <Inputvideo video={video} />} <Inputfile setVideo={setVideo} /> <Button convertToGif={convertToGif} /> <h1>Result</h1> {gif && <Resultimg gif={gif} />} {gif && <Dbutton gif={gif} download={download} />} </div> ) : ( <p>Loading...</p> );} export default App; Output: If your browser gives this output, Then your project is running fine. Then choose a video file to convert into the image, After converting click on the convert button you can see it gives us a .gif format animated image. React-Questions Technical Scripter 2020 ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26096, "s": 26068, "text": "\n10 Feb, 2021" }, { "code": null, "e": 26463, "s": 26096, "text": "When you think about a GIF image, a video is a must convert into a .gif format to an image. For this project, we are using FFMPEG library utility written in the C programming language. With the support of web Assembly, it can run in browsers easily without any need for a server, also here we are using the ReactJS library to make it simple and more understandable. " }, { "code": null, "e": 26518, "s": 26463, "text": "You can know about web Assembly from the below Links: " }, { "code": null, "e": 26552, "s": 26518, "text": "WebAssembly – The next BIG thing!" }, { "code": null, "e": 26803, "s": 26552, "text": "Also, you can learn about FFMPEG which is a free and open-source software project consisting of a large suite of libraries and programs for handling video, audio, and other multimedia files and streams you can check from the https://ffmpeg.org/ link." }, { "code": null, "e": 27039, "s": 26803, "text": "FFMPEG: FFmpeg.wasm is a WebAssembly port of FFmpeg, which you can install via npm and use within Node or the browser just like any other JavaScript module. Create a simple client-side transcoder that streams data into a video element." }, { "code": null, "e": 27244, "s": 27039, "text": "Before going to make this project you have a hands-on experience on ReactJS because we are using react hook that is useState. So, ok with that concept go further and create your directory for the project." }, { "code": null, "e": 27380, "s": 27244, "text": "Create our React app with snowpack by following the command:npx create-snowpack-app gifconverter –template @snowpack/app-template-react" }, { "code": null, "e": 27456, "s": 27380, "text": "npx create-snowpack-app gifconverter –template @snowpack/app-template-react" }, { "code": null, "e": 27599, "s": 27456, "text": "After installation above command then installs another package called FFMPEG by the following command:npm install @ffmpeg/ffmpeg @ffmpeg/core" }, { "code": null, "e": 27640, "s": 27599, "text": "npm install @ffmpeg/ffmpeg @ffmpeg/core" }, { "code": null, "e": 27955, "s": 27640, "text": "For our styling purpose, you install the styled component by the following command. It is most likely CSS, but as we play with JavaScript it creates the user-defined variable, in that variable, we can write CSS properties, it is also used for making components without making a new JSX file.npm i styled-components" }, { "code": null, "e": 27979, "s": 27955, "text": "npm i styled-components" }, { "code": null, "e": 28235, "s": 27979, "text": "Project Structure: All installation for the project is complete, and we are now going for developing our aiming project. Now you can see the project directory looks like the following and you’re all dependencies are installed successfully than good to go." }, { "code": null, "e": 28486, "s": 28235, "text": "Now you open your command prompt and type the following command to start your server by running the below command. Then your browser opens in port number 8080 where your app is running, If your browser looks like this then you are in the right place." }, { "code": null, "e": 28512, "s": 28486, "text": "cd gifconverter\nnpm start" }, { "code": null, "e": 28682, "s": 28512, "text": "Now open your project folder in your code editor and make a folder in src directory called components and under this folder make various JSX components file by following" }, { "code": null, "e": 28698, "s": 28682, "text": "src/components:" }, { "code": null, "e": 28709, "s": 28698, "text": "Button.jsx" }, { "code": null, "e": 28721, "s": 28709, "text": "Dbutton.jsx" }, { "code": null, "e": 28732, "s": 28721, "text": "Header.jsx" }, { "code": null, "e": 28746, "s": 28732, "text": "Inputfile.jsx" }, { "code": null, "e": 28761, "s": 28746, "text": "Inputvideo.jsx" }, { "code": null, "e": 28794, "s": 28761, "text": "Resultimg.jsx " }, { "code": null, "e": 28878, "s": 28794, "text": "After creating the above JSX components, Let’s go for add the code for our project:" }, { "code": null, "e": 29008, "s": 28878, "text": "Filename- Button.jsx: This component is a convert button, when you click on it automatically changes the .mp4 file to .gif file. " }, { "code": null, "e": 29019, "s": 29008, "text": "Javascript" }, { "code": "import React from \"react\";import styled from \"styled-components\"; const Btn = styled.button` background-color: #000; color: #fff; border-radius: 18px; border: 1px solid #000; outline: none; font-weight: 700; cursor: pointer; font-size: 1.2em; padding: 10px; min-width: 20%; transition: all 0.2s ease-in-out; :hover { background-color: #3f3f3f; color: #efefef; }`; export const Button = ({ convertToGif }) => { return <Btn onClick={convertToGif}>Convert</Btn>;};", "e": 29503, "s": 29019, "text": null }, { "code": null, "e": 29638, "s": 29503, "text": "Filename- Dbutton.jsx: This component is a download button where you can download the .gif image after the convert from the .mp4 file." }, { "code": null, "e": 29649, "s": 29638, "text": "Javascript" }, { "code": "import React from \"react\";import styled from \"styled-components\"; const Btn = styled.a` display: flex; left: 0; right: 0; margin: 20px auto; margin-top: -20px; background-color: #000; color: #fff; border-radius: 35.5px; border: 1px solid #000; outline: none; font-weight: 700; cursor: pointer; font-size: 1.2em; padding: 10px; padding-left: 50px; max-width: 10%; text-decoration: none; transition: all 0.2s ease-in-out; :hover { background-color: #3f3f3f; color: #efefef; }`; export const Dbutton = ({ gif, download }) => { return ( <Btn href={gif} download onClick={(e) => download(e)}> Download </Btn> );};", "e": 30299, "s": 29649, "text": null }, { "code": null, "e": 30321, "s": 30299, "text": "Filename- Header.jsx:" }, { "code": null, "e": 30332, "s": 30321, "text": "Javascript" }, { "code": "import React from \"react\";import styled from \"styled-components\"; const H1 = styled.h1` margin: 0; padding: 12px; background-color: #000; color: #fff; font-family: sans-serif; font-size: 3em;`; export const Header = () => { return ( <div> <H1>video to gif converter</H1> </div> );};", "e": 30636, "s": 30332, "text": null }, { "code": null, "e": 30730, "s": 30636, "text": "Filename- Inputfile.jsx: This component used for getting user input of video file (.mp4 file)" }, { "code": null, "e": 30741, "s": 30730, "text": "Javascript" }, { "code": "import React from \"react\";import styled from \"styled-components\"; const Section = styled.div` display: flex; left: 0; right: 0; margin: 50px auto; width: 30%; border: 2px dashed #000; border-radius: 18px; padding: 10px;`; export const Inputfile = ({ setVideo }) => { return ( <Section> <input type=\"file\" onChange={(e) => setVideo(e.target.files?.item(0))} /> </Section> );};", "e": 31140, "s": 30741, "text": null }, { "code": null, "e": 31166, "s": 31140, "text": "Filename- Inputvideo.jsx:" }, { "code": null, "e": 31177, "s": 31166, "text": "Javascript" }, { "code": "import React from \"react\";import styled from \"styled-components\"; const Video = styled.video` width: 40%; margin: 20px; border: 1px dashed #045ca3;`; export const Inputvideo = ({ video }) => { return <Video controls width=\"250\" src={URL.createObjectURL(video)} />;};", "e": 31450, "s": 31177, "text": null }, { "code": null, "e": 31553, "s": 31450, "text": "Filename- Resultimage.jsx: This component is showing the .gif image which converter from a video file." }, { "code": null, "e": 31564, "s": 31553, "text": "Javascript" }, { "code": "import React from \"react\";import styled from \"styled-components\"; const Img = styled.img` width: 50%; height: 100%; border: 4px solid #000; margin: 40px auto;`; export const Resultimg = ({ gif }) => { return <Img src={gif} />;};", "e": 31800, "s": 31564, "text": null }, { "code": null, "e": 32033, "s": 31800, "text": "From the above individual components you can see there are many useState props are passed in the arrow function using curly bracket, don’t worry that state you can find in the App.jsx. I prefer to consider all hooks in the App.jsx. " }, { "code": null, "e": 32213, "s": 32033, "text": "So, we are adding all code for our required components that are used for our project. After the adding of all the code, then we have to import the components file to the App.jsx " }, { "code": null, "e": 32420, "s": 32213, "text": "Filename- App.jsx: Here is our App.jsx code. Let’s import our components into this file. In the below App.jsx , we are importing a library as discussed previously that is FFmpeg as createFFmpeg , fetchFile." }, { "code": null, "e": 32605, "s": 32420, "text": "We are in the last phase of our project to finalize is our project working well or not ?:) Then after refreshing, you can see what your GIF converter looks like in the following image." }, { "code": null, "e": 32616, "s": 32605, "text": "Javascript" }, { "code": "import React, { useState, useEffect } from \"react\";import \"./App.css\";import { createFFmpeg, fetchFile } from \"@ffmpeg/ffmpeg\";import { Button } from \"./components/Button\";import { Inputfile } from \"./components/Inputfile\";import { Header } from \"./components/Header\";import { Resultimg } from \"./components/Resultimage\";import { Inputvideo } from \"./components/Inputvideo\";import { Dbutton } from \"./components/Dbutton\"; // Create the FFmpeg instance and load itconst ffmpeg = createFFmpeg({ log: true }); function App() { const [ready, setReady] = useState(false); const [video, setVideo] = useState(); const [gif, setGif] = useState(); const load = async () => { await ffmpeg.load(); setReady(true); }; useEffect(() => { load(); }, []); const convertToGif = async () => { // Write the .mp4 to the FFmpeg file system ffmpeg.FS(\"writeFile\", \"video1.mp4\", await fetchFile(video)); // Run the FFmpeg command-line tool, converting // the .mp4 into .gif file await ffmpeg.run( \"-i\", \"video1.mp4\", \"-t\", \"2.5\", \"-ss\", \"2.0\", \"-f\", \"gif\", \"out.gif\" ); // Read the .gif file back from the FFmpeg file system const data = ffmpeg.FS(\"readFile\", \"out.gif\"); const url = URL.createObjectURL( new Blob([data.buffer], { type: \"image/gif\" }) ); setGif(url); }; const download = (e) => { console.log(e.target.href); fetch(e.target.href, { method: \"GET\", headers: {}, }) .then((response) => { response.arrayBuffer().then(function (buffer) { const url = window.URL.createObjectURL(new Blob([buffer])); const link = document.createElement(\"a\"); link.href = url; link.setAttribute(\"download\", \"image.gif\"); document.body.appendChild(link); link.click(); }); }) .catch((err) => { console.log(err); }); }; return ready ? ( <div className=\"App\"> <Header /> {video && <Inputvideo video={video} />} <Inputfile setVideo={setVideo} /> <Button convertToGif={convertToGif} /> <h1>Result</h1> {gif && <Resultimg gif={gif} />} {gif && <Dbutton gif={gif} download={download} />} </div> ) : ( <p>Loading...</p> );} export default App;", "e": 34908, "s": 32616, "text": null }, { "code": null, "e": 35137, "s": 34908, "text": "Output: If your browser gives this output, Then your project is running fine. Then choose a video file to convert into the image, After converting click on the convert button you can see it gives us a .gif format animated image." }, { "code": null, "e": 35153, "s": 35137, "text": "React-Questions" }, { "code": null, "e": 35177, "s": 35153, "text": "Technical Scripter 2020" }, { "code": null, "e": 35185, "s": 35177, "text": "ReactJS" }, { "code": null, "e": 35204, "s": 35185, "text": "Technical Scripter" }, { "code": null, "e": 35221, "s": 35204, "text": "Web Technologies" }, { "code": null, "e": 35319, "s": 35221, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35346, "s": 35319, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 35388, "s": 35346, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 35426, "s": 35388, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 35461, "s": 35426, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 35519, "s": 35461, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 35559, "s": 35519, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35592, "s": 35559, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35637, "s": 35592, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35699, "s": 35637, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Circular primes less than n - GeeksforGeeks
21 Apr, 2021 Find all circular primes less than given number n. A prime number is a Circular Prime Number if all of its possible rotations are itself prime numbers. Examples : 79 is a circular prime. as 79 and 97 are prime numbers. But 23 is not a circular prime. as 23 is prime but 32 is not a prime number. Algorithm: -> Find prime numbers up to n using Sieve of Sundaram algorithm. -> Now for every prime number from sieve method, one after another, we should check whether its all rotations are prime or not: -> If yes then print that prime number. -> If no then skip that prime number. Below is the implementation of the above algorithm : C++ Java Python3 C# PHP Javascript // C++ program to print primes smaller than n using// Sieve of Sundaram.#include <bits/stdc++.h>using namespace std; // Prototypes of the methods usedvoid SieveOfSundaram(bool marked[], int);int Rotate(int);int countDigits(int); // Print all circular primesvoid circularPrime(int n){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. // Since we want primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of the form i+j+2ij // from others where 1 <= i <= j bool marked[nNew + 1]; // Initialize all elements as not marked memset(marked, false, sizeof(marked)); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime cout << "2 "; // According to Sieve of sundaram If marked[i] is false // then 2*i + 1 is a prime number. // loop to check all prime numbers and their rotations for (int i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; int num = 2 * i + 1; num = Rotate(num); // function for rotation of prime // now we check for rotations of this prime number // if new rotation is prime check next rotation, // till new rotation becomes the actual prime number // and if new rotation if not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime then rotate // for next if (marked[(num - 1) / 2] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) cout << num << " "; }} // Sieve of Sundaram for generating prime numbervoid SieveOfSundaram(bool marked[], int nNew){ // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Rotate function to right rotate the numberint Rotate(int n){ int rem = n % 10; // find unit place number rem *= pow(10, countDigits(n)); // to put unit place // number as first digit. n /= 10; // remove unit digit n += rem; // add first digit to rest return n;} // Function to find total number of digitsint countDigits(int n){ int digit = 0; while (n /= 10) digit++; return digit;} // Driver program to test aboveint main(void){ int n = 100; circularPrime(n); return 0;} // Java program to print primes smaller// than n using Sieve of Sundaram.import java.util.Arrays;class GFG { // Print all circular primes static void circularPrime(int n) { // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x.Since we want // primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j boolean marked[] = new boolean[nNew + 1]; // Initialize all elements as not marked Arrays.fill(marked, false); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime System.out.print("2 "); // According to Sieve of sundaram If marked[i] is false // then 2*i + 1 is a prime number. // loop to check all prime numbers and their rotations for (int i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; int num = 2 * i + 1; num = Rotate(num); // function for rotation of prime // now we check for rotations of this prime number // if new rotation is prime check next rotation, // till new rotation becomes the actual prime number // and if new rotation if not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime then rotate // for next if (marked[(num - 1) / 2] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) System.out.print(num + " "); } } // Sieve of Sundaram for generating prime number static void SieveOfSundaram(boolean marked[], int nNew) { // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true; } // Function to find total number of digits static int countDigits(int n) { int digit = 0; while ((n /= 10) > 0) digit++; return digit; } // Rotate function to right rotate the number static int Rotate(int n) { int rem = n % 10; // find unit place number rem *= Math.pow(10, countDigits(n)); // to put unit place // number as first digit. n /= 10; // remove unit digit n += rem; // add first digit to rest return n; } // Driver code public static void main(String[] args) { int n = 100; circularPrime(n); }}// This code is contributed by Anant Agarwal. # Python3 program to print primes smaller# than n using Sieve of Sundaram. # Print all circular primesdef circularPrime(n): # In general Sieve of Sundaram, # produces primes smaller than # (2*x + 2) for a number given # number x. Since we want primes # smaller than n, we reduce n to half nNew = (n - 2) // 2 # This array is used to separate numbers # of the form i+j+2ij from others # where 1 <= i <= j marked = [False for i in range(nNew + 1)] SieveOfSundaram(marked, nNew) # If n > 2 then 2 is also a # circular prime print("2", end = ' ') # According to Sieve of sundaram # If marked[i] is false then # 2*i + 1 is a prime number. # Loop to check all prime numbers # and their rotations for i in range(1, nNew + 1): # Skip this number if not prime if (marked[i] == True): continue; num = 2 * i + 1 # Function for rotation of prime num = Rotate(num) # Now we check for rotations of this # prime number if new rotation is # prime check next rotation, till # new rotation becomes the actual # prime number and if new rotation # if not prime then break while (num != 2 * i + 1): # Check for even if (num % 2 == 0): break # If rotated number is prime # then rotate for next if (marked[(num - 1) // 2] == False): num = Rotate(num); else: break; # If checked number is circular # prime print it if (num == (2 * i + 1)): print(num, end = ' ') # Sieve of Sundaram for generating# prime numberdef SieveOfSundaram(marked, nNew): # Main logic of Sundaram. Mark # all numbers of the form # i + j + 2ij as true where 1 <= i <= j for i in range(1, nNew + 1): j = i while (i + j + 2 * i * j) <= nNew: marked[i + j + 2 * i * j] = True j += 1 # Rotate function to right rotate# the numberdef Rotate(n): # Find unit place number rem = n % 10 # To put unit place rem = rem * (10 ** (countDigits(n) - 1)) # Number as first digit. n = n // 10 # Remove unit digit n += rem # Add first digit to rest return n # Function to find total number of digitsdef countDigits(n): digit = 0 while n != 0: n = n // 10 digit += 1 return digit # Driver codeif __name__=="__main__": n = 100 circularPrime(n) # This code is contributed by rutvik_56 // C# program to print primes smaller// than n using Sieve of Sundaram.using System; class GFG { // Print all circular primes static void circularPrime(int n) { // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x.Since we want // primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j bool[] marked = new bool[nNew + 1]; // Initialize all elements as not marked // Arrays.fill(marked, false); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime Console.Write("2 "); // According to Sieve of sundaram If // marked[i] is false then 2*i + 1 is a // prime number. // loop to check all prime numbers // and their rotations for (int i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; int num = 2 * i + 1; // function for rotation of prime num = Rotate(num); // now we check for rotations of this prime number // if new rotation is prime check next rotation, // till new rotation becomes the actual prime number // and if new rotation if not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime // then rotate for next if (marked[(num - 1) / 2] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) Console.Write(num + " "); } } // Sieve of Sundaram for generating prime number static void SieveOfSundaram(bool[] marked, int nNew) { // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true; } // Function to find total number of digits static int countDigits(int n) { int digit = 0; while ((n /= 10) > 0) digit++; return digit; } // Rotate function to right rotate the number static int Rotate(int n) { // find unit place number int rem = n % 10; // to put unit place rem *= (int)Math.Pow(10, countDigits(n)); // number as first digit. n /= 10; // remove unit digit n += rem; // add first digit to rest return n; } // Driver code public static void Main() { int n = 100; circularPrime(n); }} // This code is contributed by vt_m. <?php// PHP program to print primes smaller than// n using Sieve of Sundaram. // Print all circular primesfunction circularPrime($n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half $nNew = (int)(($n - 2) / 2); // This array is used to separate numbers of // the form i+j+2ij from others where 1 <= i <= j $marked = array_fill(0, $nNew + 1, false); SieveOfSundaram($marked, $nNew); // if n > 2 then 2 is also a circular prime print("2 "); // According to Sieve of sundaram If marked[i] // is false then 2*i + 1 is a prime number. // loop to check all prime numbers // and their rotations for ($i = 1; $i <= $nNew; $i++) { // Skip this number if not prime if ($marked[$i] == true) continue; $num = 2 * $i + 1; $num = Rotate($num); // function for rotation of prime // now we check for rotations of this // prime number if new rotation is prime // check next rotation, till new rotation // becomes the actual prime number and if // new rotation if not prime then break while ($num != 2 * $i + 1) { if ($num % 2 == 0) // check for even break; // if rotated number is prime then // rotate for next if ($marked[(int)(($num - 1) / 2)] == false) $num = Rotate($num); else break; } // if checked number is circular // prime print it if ($num == (2 * $i + 1)) print($num." "); }} // Sieve of Sundaram for generating prime numberfunction SieveOfSundaram(&$marked, $nNew){ // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for ($i = 1; $i <= $nNew; $i++) for ($j = $i; ($i + $j + 2 * $i * $j) <= $nNew; $j++) $marked[$i + $j + 2 * $i * $j] = true;} // Rotate function to right rotate the numberfunction Rotate($n){ $rem = $n % 10; // find unit place number $rem *= pow(10, countDigits($n)); // to put unit place // number as first digit. $n = (int)($n / 10); // remove unit digit $n += $rem; // add first digit to rest return $n;} // Function to find total number of digitsfunction countDigits($n){ $digit = 0; $n = (int)($n / 10); while ($n) { $digit++; $n = (int)($n / 10); } return $digit;} // Driver Code$n = 100;circularPrime($n); // This code is contributed by mits?> <script> // Javascript program to print// primes smaller// than n using Sieve of Sundaram.// Print all circular primesfunction circularPrime(n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x.Since we want // primes smaller than n, we reduce n to half var nNew = (n - 2) / 2; // This array is used to // separate numbers of the // form i+j+2ij from others // where 1 <= i <= j marked = Array.from({length: nNew + 1}, (_, i) => false); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime document.write("2 "); // According to Sieve of sundaram // If marked[i] is false // then 2*i + 1 is a prime number. // loop to check all prime numbers // and their rotations for (i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; var num = 2 * i + 1; // function for rotation of prime num = Rotate(num); // now we check for rotations of // this prime number // if new rotation is prime check // next rotation, // till new rotation becomes // the actual prime number // and if new rotation if // not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime then rotate // for next if (marked[parseInt((num - 1) / 2)] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) document.write(num + " "); }} // Sieve of Sundaram for generating prime numberfunction SieveOfSundaram(marked , nNew){ // Main logic of Sundaram. Mark all numbers of the// form i + j + 2ij as true where 1 <= i <= j for (i = 1; i <= nNew; i++) for (j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Function to find total number of digitsfunction countDigits(n){ var digit = 0; while ((n = parseInt(n/10)) > 0) digit++; return digit;} // Rotate function to right rotate the numberfunction Rotate(n){ // find unit place number var rem = n % 10; // to put unit place rem *= Math.pow(10, countDigits(n)); // number as first digit. n = parseInt(n/10) // remove unit digit n += rem; // add first digit to rest return n;} // Driver codevar n = 100;circularPrime(n); // This code is contributed by Amit Katiyar </script> Output: 2 3 5 7 11 13 17 31 37 71 73 79 97 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Mithun Kumar rutvik_56 amit143katiyar Prime Number sieve Mathematical Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find sum of elements in a given array Program for Decimal to Binary Conversion Program for factorial of a number Operators in C / C++ The Knight's tour problem | Backtracking-1 Find minimum number of coins that make a given value Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 24664, "s": 24636, "text": "\n21 Apr, 2021" }, { "code": null, "e": 24816, "s": 24664, "text": "Find all circular primes less than given number n. A prime number is a Circular Prime Number if all of its possible rotations are itself prime numbers." }, { "code": null, "e": 24828, "s": 24816, "text": "Examples : " }, { "code": null, "e": 24963, "s": 24828, "text": "79 is a circular prime.\nas 79 and 97 are prime numbers.\n\nBut 23 is not a circular prime.\nas 23 is prime but 32 is not a prime number. " }, { "code": null, "e": 24975, "s": 24963, "text": "Algorithm: " }, { "code": null, "e": 25256, "s": 24975, "text": "-> Find prime numbers up to n using Sieve of Sundaram algorithm.\n-> Now for every prime number from sieve method,\n one after another, we should check whether its all\n rotations are prime or not:\n -> If yes then print that prime number.\n -> If no then skip that prime number." }, { "code": null, "e": 25309, "s": 25256, "text": "Below is the implementation of the above algorithm :" }, { "code": null, "e": 25313, "s": 25309, "text": "C++" }, { "code": null, "e": 25318, "s": 25313, "text": "Java" }, { "code": null, "e": 25326, "s": 25318, "text": "Python3" }, { "code": null, "e": 25329, "s": 25326, "text": "C#" }, { "code": null, "e": 25333, "s": 25329, "text": "PHP" }, { "code": null, "e": 25344, "s": 25333, "text": "Javascript" }, { "code": "// C++ program to print primes smaller than n using// Sieve of Sundaram.#include <bits/stdc++.h>using namespace std; // Prototypes of the methods usedvoid SieveOfSundaram(bool marked[], int);int Rotate(int);int countDigits(int); // Print all circular primesvoid circularPrime(int n){ // In general Sieve of Sundaram, produces primes smaller // than (2*x + 2) for a number given number x. // Since we want primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of the form i+j+2ij // from others where 1 <= i <= j bool marked[nNew + 1]; // Initialize all elements as not marked memset(marked, false, sizeof(marked)); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime cout << \"2 \"; // According to Sieve of sundaram If marked[i] is false // then 2*i + 1 is a prime number. // loop to check all prime numbers and their rotations for (int i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; int num = 2 * i + 1; num = Rotate(num); // function for rotation of prime // now we check for rotations of this prime number // if new rotation is prime check next rotation, // till new rotation becomes the actual prime number // and if new rotation if not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime then rotate // for next if (marked[(num - 1) / 2] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) cout << num << \" \"; }} // Sieve of Sundaram for generating prime numbervoid SieveOfSundaram(bool marked[], int nNew){ // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Rotate function to right rotate the numberint Rotate(int n){ int rem = n % 10; // find unit place number rem *= pow(10, countDigits(n)); // to put unit place // number as first digit. n /= 10; // remove unit digit n += rem; // add first digit to rest return n;} // Function to find total number of digitsint countDigits(int n){ int digit = 0; while (n /= 10) digit++; return digit;} // Driver program to test aboveint main(void){ int n = 100; circularPrime(n); return 0;}", "e": 28033, "s": 25344, "text": null }, { "code": "// Java program to print primes smaller// than n using Sieve of Sundaram.import java.util.Arrays;class GFG { // Print all circular primes static void circularPrime(int n) { // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x.Since we want // primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j boolean marked[] = new boolean[nNew + 1]; // Initialize all elements as not marked Arrays.fill(marked, false); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime System.out.print(\"2 \"); // According to Sieve of sundaram If marked[i] is false // then 2*i + 1 is a prime number. // loop to check all prime numbers and their rotations for (int i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; int num = 2 * i + 1; num = Rotate(num); // function for rotation of prime // now we check for rotations of this prime number // if new rotation is prime check next rotation, // till new rotation becomes the actual prime number // and if new rotation if not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime then rotate // for next if (marked[(num - 1) / 2] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) System.out.print(num + \" \"); } } // Sieve of Sundaram for generating prime number static void SieveOfSundaram(boolean marked[], int nNew) { // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true; } // Function to find total number of digits static int countDigits(int n) { int digit = 0; while ((n /= 10) > 0) digit++; return digit; } // Rotate function to right rotate the number static int Rotate(int n) { int rem = n % 10; // find unit place number rem *= Math.pow(10, countDigits(n)); // to put unit place // number as first digit. n /= 10; // remove unit digit n += rem; // add first digit to rest return n; } // Driver code public static void main(String[] args) { int n = 100; circularPrime(n); }}// This code is contributed by Anant Agarwal.", "e": 31023, "s": 28033, "text": null }, { "code": "# Python3 program to print primes smaller# than n using Sieve of Sundaram. # Print all circular primesdef circularPrime(n): # In general Sieve of Sundaram, # produces primes smaller than # (2*x + 2) for a number given # number x. Since we want primes # smaller than n, we reduce n to half nNew = (n - 2) // 2 # This array is used to separate numbers # of the form i+j+2ij from others # where 1 <= i <= j marked = [False for i in range(nNew + 1)] SieveOfSundaram(marked, nNew) # If n > 2 then 2 is also a # circular prime print(\"2\", end = ' ') # According to Sieve of sundaram # If marked[i] is false then # 2*i + 1 is a prime number. # Loop to check all prime numbers # and their rotations for i in range(1, nNew + 1): # Skip this number if not prime if (marked[i] == True): continue; num = 2 * i + 1 # Function for rotation of prime num = Rotate(num) # Now we check for rotations of this # prime number if new rotation is # prime check next rotation, till # new rotation becomes the actual # prime number and if new rotation # if not prime then break while (num != 2 * i + 1): # Check for even if (num % 2 == 0): break # If rotated number is prime # then rotate for next if (marked[(num - 1) // 2] == False): num = Rotate(num); else: break; # If checked number is circular # prime print it if (num == (2 * i + 1)): print(num, end = ' ') # Sieve of Sundaram for generating# prime numberdef SieveOfSundaram(marked, nNew): # Main logic of Sundaram. Mark # all numbers of the form # i + j + 2ij as true where 1 <= i <= j for i in range(1, nNew + 1): j = i while (i + j + 2 * i * j) <= nNew: marked[i + j + 2 * i * j] = True j += 1 # Rotate function to right rotate# the numberdef Rotate(n): # Find unit place number rem = n % 10 # To put unit place rem = rem * (10 ** (countDigits(n) - 1)) # Number as first digit. n = n // 10 # Remove unit digit n += rem # Add first digit to rest return n # Function to find total number of digitsdef countDigits(n): digit = 0 while n != 0: n = n // 10 digit += 1 return digit # Driver codeif __name__==\"__main__\": n = 100 circularPrime(n) # This code is contributed by rutvik_56", "e": 33643, "s": 31023, "text": null }, { "code": "// C# program to print primes smaller// than n using Sieve of Sundaram.using System; class GFG { // Print all circular primes static void circularPrime(int n) { // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x.Since we want // primes smaller than n, we reduce n to half int nNew = (n - 2) / 2; // This array is used to separate numbers of the // form i+j+2ij from others where 1 <= i <= j bool[] marked = new bool[nNew + 1]; // Initialize all elements as not marked // Arrays.fill(marked, false); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime Console.Write(\"2 \"); // According to Sieve of sundaram If // marked[i] is false then 2*i + 1 is a // prime number. // loop to check all prime numbers // and their rotations for (int i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; int num = 2 * i + 1; // function for rotation of prime num = Rotate(num); // now we check for rotations of this prime number // if new rotation is prime check next rotation, // till new rotation becomes the actual prime number // and if new rotation if not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime // then rotate for next if (marked[(num - 1) / 2] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) Console.Write(num + \" \"); } } // Sieve of Sundaram for generating prime number static void SieveOfSundaram(bool[] marked, int nNew) { // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for (int i = 1; i <= nNew; i++) for (int j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true; } // Function to find total number of digits static int countDigits(int n) { int digit = 0; while ((n /= 10) > 0) digit++; return digit; } // Rotate function to right rotate the number static int Rotate(int n) { // find unit place number int rem = n % 10; // to put unit place rem *= (int)Math.Pow(10, countDigits(n)); // number as first digit. n /= 10; // remove unit digit n += rem; // add first digit to rest return n; } // Driver code public static void Main() { int n = 100; circularPrime(n); }} // This code is contributed by vt_m.", "e": 36682, "s": 33643, "text": null }, { "code": "<?php// PHP program to print primes smaller than// n using Sieve of Sundaram. // Print all circular primesfunction circularPrime($n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a number // given number x. Since we want primes smaller // than n, we reduce n to half $nNew = (int)(($n - 2) / 2); // This array is used to separate numbers of // the form i+j+2ij from others where 1 <= i <= j $marked = array_fill(0, $nNew + 1, false); SieveOfSundaram($marked, $nNew); // if n > 2 then 2 is also a circular prime print(\"2 \"); // According to Sieve of sundaram If marked[i] // is false then 2*i + 1 is a prime number. // loop to check all prime numbers // and their rotations for ($i = 1; $i <= $nNew; $i++) { // Skip this number if not prime if ($marked[$i] == true) continue; $num = 2 * $i + 1; $num = Rotate($num); // function for rotation of prime // now we check for rotations of this // prime number if new rotation is prime // check next rotation, till new rotation // becomes the actual prime number and if // new rotation if not prime then break while ($num != 2 * $i + 1) { if ($num % 2 == 0) // check for even break; // if rotated number is prime then // rotate for next if ($marked[(int)(($num - 1) / 2)] == false) $num = Rotate($num); else break; } // if checked number is circular // prime print it if ($num == (2 * $i + 1)) print($num.\" \"); }} // Sieve of Sundaram for generating prime numberfunction SieveOfSundaram(&$marked, $nNew){ // Main logic of Sundaram. Mark all numbers of the // form i + j + 2ij as true where 1 <= i <= j for ($i = 1; $i <= $nNew; $i++) for ($j = $i; ($i + $j + 2 * $i * $j) <= $nNew; $j++) $marked[$i + $j + 2 * $i * $j] = true;} // Rotate function to right rotate the numberfunction Rotate($n){ $rem = $n % 10; // find unit place number $rem *= pow(10, countDigits($n)); // to put unit place // number as first digit. $n = (int)($n / 10); // remove unit digit $n += $rem; // add first digit to rest return $n;} // Function to find total number of digitsfunction countDigits($n){ $digit = 0; $n = (int)($n / 10); while ($n) { $digit++; $n = (int)($n / 10); } return $digit;} // Driver Code$n = 100;circularPrime($n); // This code is contributed by mits?>", "e": 39289, "s": 36682, "text": null }, { "code": "<script> // Javascript program to print// primes smaller// than n using Sieve of Sundaram.// Print all circular primesfunction circularPrime(n){ // In general Sieve of Sundaram, produces // primes smaller than (2*x + 2) for a // number given number x.Since we want // primes smaller than n, we reduce n to half var nNew = (n - 2) / 2; // This array is used to // separate numbers of the // form i+j+2ij from others // where 1 <= i <= j marked = Array.from({length: nNew + 1}, (_, i) => false); SieveOfSundaram(marked, nNew); // if n > 2 then 2 is also a circular prime document.write(\"2 \"); // According to Sieve of sundaram // If marked[i] is false // then 2*i + 1 is a prime number. // loop to check all prime numbers // and their rotations for (i = 1; i <= nNew; i++) { // Skip this number if not prime if (marked[i] == true) continue; var num = 2 * i + 1; // function for rotation of prime num = Rotate(num); // now we check for rotations of // this prime number // if new rotation is prime check // next rotation, // till new rotation becomes // the actual prime number // and if new rotation if // not prime then break while (num != 2 * i + 1) { if (num % 2 == 0) // check for even break; // if rotated number is prime then rotate // for next if (marked[parseInt((num - 1) / 2)] == false) num = Rotate(num); else break; } // if checked number is circular prime print it if (num == (2 * i + 1)) document.write(num + \" \"); }} // Sieve of Sundaram for generating prime numberfunction SieveOfSundaram(marked , nNew){ // Main logic of Sundaram. Mark all numbers of the// form i + j + 2ij as true where 1 <= i <= j for (i = 1; i <= nNew; i++) for (j = i; (i + j + 2 * i * j) <= nNew; j++) marked[i + j + 2 * i * j] = true;} // Function to find total number of digitsfunction countDigits(n){ var digit = 0; while ((n = parseInt(n/10)) > 0) digit++; return digit;} // Rotate function to right rotate the numberfunction Rotate(n){ // find unit place number var rem = n % 10; // to put unit place rem *= Math.pow(10, countDigits(n)); // number as first digit. n = parseInt(n/10) // remove unit digit n += rem; // add first digit to rest return n;} // Driver codevar n = 100;circularPrime(n); // This code is contributed by Amit Katiyar </script>", "e": 41965, "s": 39289, "text": null }, { "code": null, "e": 41974, "s": 41965, "text": "Output: " }, { "code": null, "e": 42009, "s": 41974, "text": "2 3 5 7 11 13 17 31 37 71 73 79 97" }, { "code": null, "e": 42445, "s": 42009, "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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 42450, "s": 42445, "text": "vt_m" }, { "code": null, "e": 42463, "s": 42450, "text": "Mithun Kumar" }, { "code": null, "e": 42473, "s": 42463, "text": "rutvik_56" }, { "code": null, "e": 42488, "s": 42473, "text": "amit143katiyar" }, { "code": null, "e": 42501, "s": 42488, "text": "Prime Number" }, { "code": null, "e": 42507, "s": 42501, "text": "sieve" }, { "code": null, "e": 42520, "s": 42507, "text": "Mathematical" }, { "code": null, "e": 42533, "s": 42520, "text": "Mathematical" }, { "code": null, "e": 42546, "s": 42533, "text": "Prime Number" }, { "code": null, "e": 42552, "s": 42546, "text": "sieve" }, { "code": null, "e": 42650, "s": 42552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42674, "s": 42650, "text": "Merge two sorted arrays" }, { "code": null, "e": 42717, "s": 42674, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 42731, "s": 42717, "text": "Prime Numbers" }, { "code": null, "e": 42780, "s": 42731, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 42821, "s": 42780, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 42855, "s": 42821, "text": "Program for factorial of a number" }, { "code": null, "e": 42876, "s": 42855, "text": "Operators in C / C++" }, { "code": null, "e": 42919, "s": 42876, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 42972, "s": 42919, "text": "Find minimum number of coins that make a given value" } ]
Ways to sum to N using Natural Numbers up to K with repetitions allowed - GeeksforGeeks
13 Sep, 2021 Given two integers N and K, the task is to find the total number of ways of representing N as the sum of positive integers in the range [1, K], where each integer can be chosen multiple times. Examples: Input: N = 8, K = 2Output: 5Explanation: All possible ways of representing N as sum of positive integers less than or equal to K are: {1, 1, 1, 1, 1, 1, 1, 1}, the sum is 8.{2, 1, 1, 1, 1, 1, 1}, the sum is 8.{2, 2, 1, 1, 1, 1}, the sum is 8.2, 2, 2, 1, 1}, the sum is 8.{2, 2, 2, 2}}, the sum is 8. {1, 1, 1, 1, 1, 1, 1, 1}, the sum is 8. {2, 1, 1, 1, 1, 1, 1}, the sum is 8. {2, 2, 1, 1, 1, 1}, the sum is 8. 2, 2, 2, 1, 1}, the sum is 8. {2, 2, 2, 2}}, the sum is 8. Therefore, the total number of ways is 5. Input: N = 2, K = 2Output: 2 Naive Approach: The simplest approach to solve the given problem is to generate all possible combinations of choosing integers over the range [1, K] and count those combinations whose sum is N. Time Complexity: O(KN)Auxiliary Space: O(1) Efficient Approach: The above approach has Overlapping Subproblems and an Optimal Substructure. Hence, in order to optimize, Dynamic Programming is needed to be performed based on the following observations: Considering dp[i] stores the total number of ways for representing i as the sum of integers lying in the range [1, K], then the transition of states can be defined as:For i in the range [1, K] and for every j in the range [1, N]The value of dp[j] is equal to (dp[j]+ dp[j – i]), for all j ≥ i. For i in the range [1, K] and for every j in the range [1, N] The value of dp[j] is equal to (dp[j]+ dp[j – i]), for all j ≥ i. Follow the steps below to solve the problem: Initialize an array, say dp[], with all elements as 0, to store all the recursive states. Initialize dp[0] as 1. Now, iterate over the range [1, K] using a variable i and perform the following steps: Iterate over the range [1, N], using a variable j, and update the value of dp[j] as dp[j]+ dp[j – i], if j ≥ i. Iterate over the range [1, N], using a variable j, and update the value of dp[j] as dp[j]+ dp[j – i], if j ≥ i. After completing the above steps, print the value of dp[N] as the result. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the total number of// ways to represent N as the sum of// integers over the range [1, K]int NumberOfways(int N, int K){ // Initialize a list vector<int> dp(N + 1, 0); // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for (int row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for (int col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return(dp[N]);} // Driver Codeint main(){ int N = 8; int K = 2; cout << (NumberOfways(N, K));} // This code is contributed by mohit kumar 29. // Java program for the above approachimport java.util.*; class GFG{ // Function to find the total number of// ways to represent N as the sum of// integers over the range [1, K]static int NumberOfways(int N, int K){ // Initialize a list int[] dp = new int[N + 1]; // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for(int row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for(int col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return(dp[N]);} // Driver codepublic static void main(String[] args){ // Given inputs int N = 8; int K = 2; System.out.println(NumberOfways(N, K));}} // This code is contributed by offbeat # Python program for the above approach # Function to find the total number of# ways to represent N as the sum of# integers over the range [1, K]def NumberOfways(N, K): # Initialize a list dp = [0] * (N + 1) # Update dp[0] to 1 dp[0] = 1 # Iterate over the range [1, K + 1] for row in range(1, K + 1): # Iterate over the range [1, N + 1] for col in range(1, N + 1): # If col is greater # than or equal to row if (col >= row): # Update current # dp[col] state dp[col] = dp[col] + dp[col - row] # Return the total number of ways return(dp[N]) # Driver Code N = 8K = 2 print(NumberOfways(N, K)) // C# program for the above approachusing System;class GFG{ // Function to find the total number of // ways to represent N as the sum of // integers over the range [1, K] static int NumberOfways(int N, int K) { // Initialize a list int[] dp = new int[(N + 1)]; // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for (int row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for (int col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return (dp[N]); } // Driver Code public static void Main() { int N = 8; int K = 2; Console.WriteLine(NumberOfways(N, K)); }} // This code is contributed by ukasp. <script>// Javascript implementation for the above approach // Function to find the total number of// ways to represent N as the sum of// integers over the range [1, K]function NumberOfways(N, K){ // Initialize a list let dp = Array.from({length: N +1}, (_, i) => 0); // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for(let row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for(let col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return(dp[N]);} // Driver Code // Given inputs let N = 8; let K = 2; document.write(NumberOfways(N, K)); </script> 5 Time Complexity: O(N * K)Auxiliary Space: O(N) mohit kumar 29 ukasp offbeat sanjoy_62 simranarora5sos Natural Numbers Permutation and Combination Combinatorial Dynamic Programming Mathematical Dynamic Programming Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Python program to get all subsets of given size of a set Heap's Algorithm for generating permutations Print all distinct permutations of a given string with duplicates Make all combinations of size k 0-1 Knapsack Problem | DP-10 Program for Fibonacci numbers Largest Sum Contiguous Subarray Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16
[ { "code": null, "e": 26997, "s": 26969, "text": "\n13 Sep, 2021" }, { "code": null, "e": 27190, "s": 26997, "text": "Given two integers N and K, the task is to find the total number of ways of representing N as the sum of positive integers in the range [1, K], where each integer can be chosen multiple times." }, { "code": null, "e": 27200, "s": 27190, "text": "Examples:" }, { "code": null, "e": 27334, "s": 27200, "text": "Input: N = 8, K = 2Output: 5Explanation: All possible ways of representing N as sum of positive integers less than or equal to K are:" }, { "code": null, "e": 27500, "s": 27334, "text": "{1, 1, 1, 1, 1, 1, 1, 1}, the sum is 8.{2, 1, 1, 1, 1, 1, 1}, the sum is 8.{2, 2, 1, 1, 1, 1}, the sum is 8.2, 2, 2, 1, 1}, the sum is 8.{2, 2, 2, 2}}, the sum is 8." }, { "code": null, "e": 27540, "s": 27500, "text": "{1, 1, 1, 1, 1, 1, 1, 1}, the sum is 8." }, { "code": null, "e": 27577, "s": 27540, "text": "{2, 1, 1, 1, 1, 1, 1}, the sum is 8." }, { "code": null, "e": 27611, "s": 27577, "text": "{2, 2, 1, 1, 1, 1}, the sum is 8." }, { "code": null, "e": 27641, "s": 27611, "text": "2, 2, 2, 1, 1}, the sum is 8." }, { "code": null, "e": 27670, "s": 27641, "text": "{2, 2, 2, 2}}, the sum is 8." }, { "code": null, "e": 27712, "s": 27670, "text": "Therefore, the total number of ways is 5." }, { "code": null, "e": 27741, "s": 27712, "text": "Input: N = 2, K = 2Output: 2" }, { "code": null, "e": 27936, "s": 27741, "text": "Naive Approach: The simplest approach to solve the given problem is to generate all possible combinations of choosing integers over the range [1, K] and count those combinations whose sum is N. " }, { "code": null, "e": 27980, "s": 27936, "text": "Time Complexity: O(KN)Auxiliary Space: O(1)" }, { "code": null, "e": 28188, "s": 27980, "text": "Efficient Approach: The above approach has Overlapping Subproblems and an Optimal Substructure. Hence, in order to optimize, Dynamic Programming is needed to be performed based on the following observations:" }, { "code": null, "e": 28482, "s": 28188, "text": "Considering dp[i] stores the total number of ways for representing i as the sum of integers lying in the range [1, K], then the transition of states can be defined as:For i in the range [1, K] and for every j in the range [1, N]The value of dp[j] is equal to (dp[j]+ dp[j – i]), for all j ≥ i." }, { "code": null, "e": 28544, "s": 28482, "text": "For i in the range [1, K] and for every j in the range [1, N]" }, { "code": null, "e": 28610, "s": 28544, "text": "The value of dp[j] is equal to (dp[j]+ dp[j – i]), for all j ≥ i." }, { "code": null, "e": 28655, "s": 28610, "text": "Follow the steps below to solve the problem:" }, { "code": null, "e": 28745, "s": 28655, "text": "Initialize an array, say dp[], with all elements as 0, to store all the recursive states." }, { "code": null, "e": 28768, "s": 28745, "text": "Initialize dp[0] as 1." }, { "code": null, "e": 28967, "s": 28768, "text": "Now, iterate over the range [1, K] using a variable i and perform the following steps: Iterate over the range [1, N], using a variable j, and update the value of dp[j] as dp[j]+ dp[j – i], if j ≥ i." }, { "code": null, "e": 29079, "s": 28967, "text": "Iterate over the range [1, N], using a variable j, and update the value of dp[j] as dp[j]+ dp[j – i], if j ≥ i." }, { "code": null, "e": 29153, "s": 29079, "text": "After completing the above steps, print the value of dp[N] as the result." }, { "code": null, "e": 29204, "s": 29153, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 29208, "s": 29204, "text": "C++" }, { "code": null, "e": 29213, "s": 29208, "text": "Java" }, { "code": null, "e": 29220, "s": 29213, "text": "Python" }, { "code": null, "e": 29223, "s": 29220, "text": "C#" }, { "code": null, "e": 29234, "s": 29223, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the total number of// ways to represent N as the sum of// integers over the range [1, K]int NumberOfways(int N, int K){ // Initialize a list vector<int> dp(N + 1, 0); // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for (int row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for (int col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return(dp[N]);} // Driver Codeint main(){ int N = 8; int K = 2; cout << (NumberOfways(N, K));} // This code is contributed by mohit kumar 29.", "e": 30166, "s": 29234, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find the total number of// ways to represent N as the sum of// integers over the range [1, K]static int NumberOfways(int N, int K){ // Initialize a list int[] dp = new int[N + 1]; // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for(int row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for(int col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return(dp[N]);} // Driver codepublic static void main(String[] args){ // Given inputs int N = 8; int K = 2; System.out.println(NumberOfways(N, K));}} // This code is contributed by offbeat", "e": 31176, "s": 30166, "text": null }, { "code": "# Python program for the above approach # Function to find the total number of# ways to represent N as the sum of# integers over the range [1, K]def NumberOfways(N, K): # Initialize a list dp = [0] * (N + 1) # Update dp[0] to 1 dp[0] = 1 # Iterate over the range [1, K + 1] for row in range(1, K + 1): # Iterate over the range [1, N + 1] for col in range(1, N + 1): # If col is greater # than or equal to row if (col >= row): # Update current # dp[col] state dp[col] = dp[col] + dp[col - row] # Return the total number of ways return(dp[N]) # Driver Code N = 8K = 2 print(NumberOfways(N, K))", "e": 31964, "s": 31176, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to find the total number of // ways to represent N as the sum of // integers over the range [1, K] static int NumberOfways(int N, int K) { // Initialize a list int[] dp = new int[(N + 1)]; // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for (int row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for (int col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return (dp[N]); } // Driver Code public static void Main() { int N = 8; int K = 2; Console.WriteLine(NumberOfways(N, K)); }} // This code is contributed by ukasp.", "e": 33005, "s": 31964, "text": null }, { "code": "<script>// Javascript implementation for the above approach // Function to find the total number of// ways to represent N as the sum of// integers over the range [1, K]function NumberOfways(N, K){ // Initialize a list let dp = Array.from({length: N +1}, (_, i) => 0); // Update dp[0] to 1 dp[0] = 1; // Iterate over the range [1, K + 1] for(let row = 1; row < K + 1; row++) { // Iterate over the range [1, N + 1] for(let col = 1; col < N + 1; col++) { // If col is greater // than or equal to row if (col >= row) // Update current // dp[col] state dp[col] = dp[col] + dp[col - row]; } } // Return the total number of ways return(dp[N]);} // Driver Code // Given inputs let N = 8; let K = 2; document.write(NumberOfways(N, K)); </script>", "e": 33945, "s": 33005, "text": null }, { "code": null, "e": 33947, "s": 33945, "text": "5" }, { "code": null, "e": 33996, "s": 33949, "text": "Time Complexity: O(N * K)Auxiliary Space: O(N)" }, { "code": null, "e": 34011, "s": 33996, "text": "mohit kumar 29" }, { "code": null, "e": 34017, "s": 34011, "text": "ukasp" }, { "code": null, "e": 34025, "s": 34017, "text": "offbeat" }, { "code": null, "e": 34035, "s": 34025, "text": "sanjoy_62" }, { "code": null, "e": 34051, "s": 34035, "text": "simranarora5sos" }, { "code": null, "e": 34067, "s": 34051, "text": "Natural Numbers" }, { "code": null, "e": 34095, "s": 34067, "text": "Permutation and Combination" }, { "code": null, "e": 34109, "s": 34095, "text": "Combinatorial" }, { "code": null, "e": 34129, "s": 34109, "text": "Dynamic Programming" }, { "code": null, "e": 34142, "s": 34129, "text": "Mathematical" }, { "code": null, "e": 34162, "s": 34142, "text": "Dynamic Programming" }, { "code": null, "e": 34175, "s": 34162, "text": "Mathematical" }, { "code": null, "e": 34189, "s": 34175, "text": "Combinatorial" }, { "code": null, "e": 34287, "s": 34189, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34324, "s": 34287, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 34381, "s": 34324, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 34426, "s": 34381, "text": "Heap's Algorithm for generating permutations" }, { "code": null, "e": 34492, "s": 34426, "text": "Print all distinct permutations of a given string with duplicates" }, { "code": null, "e": 34524, "s": 34492, "text": "Make all combinations of size k" }, { "code": null, "e": 34553, "s": 34524, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 34583, "s": 34553, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34615, "s": 34583, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 34646, "s": 34615, "text": "Bellman–Ford Algorithm | DP-23" } ]
Explain about CYK Algorithm for Context Free Grammar
CKY means Cocke-Kasami-Younger. It is one of the earliest recognition and parsing algorithms. The standard version of CKY can only recognize languages defined by context-free grammars in Chomsky Normal Form (CNF). It is also possible to extend the CKY algorithm to handle some grammars which are not in CNF (Hard to understand). Based on a “dynamic programming” approach − Build solutions compositionally from sub-solutions Build solutions compositionally from sub-solutions It uses the grammar directly. It uses the grammar directly. Begin for ( i = 1 to n do ) Vi1 { A | A → a is a production where i th symbol of x is a } for ( j = 2 to n do ) for ( i = 1 to n - j + 1 do ) Begin Vij = φ For k = 1 to j - 1 do Vij = Vij ∪ { A | A → BC is a production where B is in Vik and C is in V(i + k)(j - k) } End End CYK algorithm is used to find whether the given Context free grammar generates a given string or not. The given Context free grammar (CFG) − S --> AB | BC A --> BA | a B --> CC | b C --> AB | a The string need to check is w =ababa The length of string |w| = 5 S is present in the last cell so the string is valid. First letter a can be find By the variable A or C. For b, variable B can find the terminal b. So, B will sit in the 2nd field in the first row. First letter a can be find By the variable A or C. For b, variable B can find the terminal b. So, B will sit in the 2nd field in the first row. For row2 We need to make a pair of two terminals and it will reduce the 1 cell . As in row2 the row1's field will be made a pair like we will have ab,ba,ab,ba. For row2 We need to make a pair of two terminals and it will reduce the 1 cell . As in row2 the row1's field will be made a pair like we will have ab,ba,ab,ba. So, in this need to find the variable which will find the ab and that variable will be placed in field row2, column1. For a, we have A, C which will find it. And for b we have B. So, for ab it will make a pair in sequence like AB, CB. So, in this need to find the variable which will find the ab and that variable will be placed in field row2, column1. For a, we have A, C which will find it. And for b we have B. So, for ab it will make a pair in sequence like AB, CB. Now we need to check whether these two productions AB, CB are there in the given grammar or not. AB can be found by S and C. Now we need to check whether these two productions AB, CB are there in the given grammar or not. AB can be found by S and C. So, S,C production will be placed there. So, S,C production will be placed there. Similarly for ba it will take B for b and A,C for a. So, the production will be BA,BC. And BA, BC can be find by the production S, A. So, this will be placed at row2, column2. Then again row2column3 is ab so, same as of row2column1. And row2column4 will ba will be same as row2Column2. Similarly for ba it will take B for b and A,C for a. So, the production will be BA,BC. And BA, BC can be find by the production S, A. So, this will be placed at row2, column2. Then again row2column3 is ab so, same as of row2column1. And row2column4 will ba will be same as row2Column2. Similarly, the next rows need to find the terminals aba,bab,aba And in sequence order the variable which can find it will be B for aba, S,C for bab and B for aba. Similarly, the next rows need to find the terminals aba,bab,aba And in sequence order the variable which can find it will be B for aba, S,C for bab and B for aba. Now row4 four terminals will be clubbed together as abab,baba. And its production will be B. In the last term ababa all five will be clubbed together and its production will be S, C, A. Now row4 four terminals will be clubbed together as abab,baba. And its production will be B. In the last term ababa all five will be clubbed together and its production will be S, C, A. If the last one has S that is the starting state then the given string is accepted. So, the membership is true for a given string. If the last one has S that is the starting state then the given string is accepted. So, the membership is true for a given string. Also you need to see that if three terminals are clubbed together then its production can be found as (ab a) or (a ba). Similarly for four terminals clubbed one (a bab) or (aba b) or (ab ab). Similarly for five (ab aba) or (aba ba) or (abab a) .... Also you need to see that if three terminals are clubbed together then its production can be found as (ab a) or (a ba). Similarly for four terminals clubbed one (a bab) or (aba b) or (ab ab). Similarly for five (ab aba) or (aba ba) or (abab a) ....
[ { "code": null, "e": 1276, "s": 1062, "text": "CKY means Cocke-Kasami-Younger. It is one of the earliest recognition and parsing algorithms. The standard version of CKY can only recognize languages defined by context-free grammars in Chomsky Normal Form (CNF)." }, { "code": null, "e": 1391, "s": 1276, "text": "It is also possible to extend the CKY algorithm to handle some grammars which are not in CNF (Hard to understand)." }, { "code": null, "e": 1435, "s": 1391, "text": "Based on a “dynamic programming” approach −" }, { "code": null, "e": 1486, "s": 1435, "text": "Build solutions compositionally from sub-solutions" }, { "code": null, "e": 1537, "s": 1486, "text": "Build solutions compositionally from sub-solutions" }, { "code": null, "e": 1567, "s": 1537, "text": "It uses the grammar directly." }, { "code": null, "e": 1597, "s": 1567, "text": "It uses the grammar directly." }, { "code": null, "e": 1923, "s": 1597, "text": "Begin\n for ( i = 1 to n do )\n Vi1 { A | A → a is a production where i th symbol of x is a }\n for ( j = 2 to n do )\n for ( i = 1 to n - j + 1 do )\n Begin\n Vij = φ\n For k = 1 to j - 1 do\n Vij = Vij ∪ { A | A → BC is a production where B is in Vik and C is in V(i + k)(j - k) }\n End\nEnd" }, { "code": null, "e": 2025, "s": 1923, "text": "CYK algorithm is used to find whether the given Context free grammar generates a given string or not." }, { "code": null, "e": 2064, "s": 2025, "text": "The given Context free grammar (CFG) −" }, { "code": null, "e": 2117, "s": 2064, "text": "S --> AB | BC\nA --> BA | a\nB --> CC | b\nC --> AB | a" }, { "code": null, "e": 2154, "s": 2117, "text": "The string need to check is w =ababa" }, { "code": null, "e": 2183, "s": 2154, "text": "The length of string |w| = 5" }, { "code": null, "e": 2237, "s": 2183, "text": "S is present in the last cell so the string is valid." }, { "code": null, "e": 2381, "s": 2237, "text": "First letter a can be find By the variable A or C. For b, variable B can find the terminal b. So, B will sit in the 2nd field in the first row." }, { "code": null, "e": 2525, "s": 2381, "text": "First letter a can be find By the variable A or C. For b, variable B can find the terminal b. So, B will sit in the 2nd field in the first row." }, { "code": null, "e": 2685, "s": 2525, "text": "For row2 We need to make a pair of two terminals and it will reduce the 1 cell . As in row2 the row1's field will be made a pair like we will have ab,ba,ab,ba." }, { "code": null, "e": 2845, "s": 2685, "text": "For row2 We need to make a pair of two terminals and it will reduce the 1 cell . As in row2 the row1's field will be made a pair like we will have ab,ba,ab,ba." }, { "code": null, "e": 3080, "s": 2845, "text": "So, in this need to find the variable which will find the ab and that variable will be placed in field row2, column1. For a, we have A, C which will find it. And for b we have B. So, for ab it will make a pair in sequence like AB, CB." }, { "code": null, "e": 3315, "s": 3080, "text": "So, in this need to find the variable which will find the ab and that variable will be placed in field row2, column1. For a, we have A, C which will find it. And for b we have B. So, for ab it will make a pair in sequence like AB, CB." }, { "code": null, "e": 3440, "s": 3315, "text": "Now we need to check whether these two productions AB, CB are there in the given grammar or not. AB can be found by S and C." }, { "code": null, "e": 3565, "s": 3440, "text": "Now we need to check whether these two productions AB, CB are there in the given grammar or not. AB can be found by S and C." }, { "code": null, "e": 3606, "s": 3565, "text": "So, S,C production will be placed there." }, { "code": null, "e": 3647, "s": 3606, "text": "So, S,C production will be placed there." }, { "code": null, "e": 3933, "s": 3647, "text": "Similarly for ba it will take B for b and A,C for a. So, the production will be BA,BC. And BA, BC can be find by the production S, A. So, this will be placed at row2, column2. Then again row2column3 is ab so, same as of row2column1. And row2column4 will ba will be same as row2Column2." }, { "code": null, "e": 4219, "s": 3933, "text": "Similarly for ba it will take B for b and A,C for a. So, the production will be BA,BC. And BA, BC can be find by the production S, A. So, this will be placed at row2, column2. Then again row2column3 is ab so, same as of row2column1. And row2column4 will ba will be same as row2Column2." }, { "code": null, "e": 4382, "s": 4219, "text": "Similarly, the next rows need to find the terminals aba,bab,aba And in sequence order the variable which can find it will be B for aba, S,C for bab and B for aba." }, { "code": null, "e": 4545, "s": 4382, "text": "Similarly, the next rows need to find the terminals aba,bab,aba And in sequence order the variable which can find it will be B for aba, S,C for bab and B for aba." }, { "code": null, "e": 4731, "s": 4545, "text": "Now row4 four terminals will be clubbed together as abab,baba. And its production will be B. In the last term ababa all five will be clubbed together and its production will be S, C, A." }, { "code": null, "e": 4917, "s": 4731, "text": "Now row4 four terminals will be clubbed together as abab,baba. And its production will be B. In the last term ababa all five will be clubbed together and its production will be S, C, A." }, { "code": null, "e": 5048, "s": 4917, "text": "If the last one has S that is the starting state then the given string is accepted. So, the membership is true for a given string." }, { "code": null, "e": 5179, "s": 5048, "text": "If the last one has S that is the starting state then the given string is accepted. So, the membership is true for a given string." }, { "code": null, "e": 5428, "s": 5179, "text": "Also you need to see that if three terminals are clubbed together then its production can be found as (ab a) or (a ba). Similarly for four terminals clubbed one (a bab) or (aba b) or (ab ab). Similarly for five (ab aba) or (aba ba) or (abab a) ...." }, { "code": null, "e": 5677, "s": 5428, "text": "Also you need to see that if three terminals are clubbed together then its production can be found as (ab a) or (a ba). Similarly for four terminals clubbed one (a bab) or (aba b) or (ab ab). Similarly for five (ab aba) or (aba ba) or (abab a) ...." } ]
How to convert timestamp string to datetime object in Python?
You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp. import datetime timestamp = datetime.datetime.fromtimestamp(1500000000) print(timestamp.strftime('%Y-%m-%d %H:%M:%S')) This will give the output − 2017-07-14 08:10:00
[ { "code": null, "e": 1271, "s": 1062, "text": "You can use the fromtimestamp function from the datetime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the datetime object corresponding to the timestamp. " }, { "code": null, "e": 1390, "s": 1271, "text": "import datetime\ntimestamp = datetime.datetime.fromtimestamp(1500000000)\nprint(timestamp.strftime('%Y-%m-%d %H:%M:%S'))" }, { "code": null, "e": 1418, "s": 1390, "text": "This will give the output −" }, { "code": null, "e": 1438, "s": 1418, "text": "2017-07-14 08:10:00" } ]
How to validate Indian Passport number using Regular Expression - GeeksforGeeks
27 Jan, 2021 Given a string str of alphanumeric characters, the task is to check whether the given string is valid passport number or not by using Regular Expression. The valid passport number of India must satisfy the following conditions: It should be eight characters long.The first character should be an upper case alphabet.The next two characters should be a number, but the first character should be any number from 1-9 and the second character should be any number from 0-9.It should be zero or one white space character.The next four characters should be any number from 0-9.The last character should be any number from 1-9. It should be eight characters long. The first character should be an upper case alphabet. The next two characters should be a number, but the first character should be any number from 1-9 and the second character should be any number from 0-9. It should be zero or one white space character. The next four characters should be any number from 0-9. The last character should be any number from 1-9. Examples: Input: str = “A2096457”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore it is a valid passport number of India. Input: str = “12096457”; Output: false Explanation: The given string doesn’t starts with an upper case alphabet. Therefore it is not a valid passport number of India. Input: str = “A209645704”; Output: false Explanation: The given string contains 10 characters. Therefore it is not a valid passport number of India. Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. Get the String.Create a regular expression to check valid passport number of India as mentioned below: Get the String. Create a regular expression to check valid passport number of India as mentioned below: regex = “^[A-PR-WYa-pr-wy][1-9]\\d\\s?\\d{4}[1-9]$”; Where: ^ represents the starting of the string.[A-PR-WYa-pr-wy] represents the string should be starts with A-Z excluding Q, X, and Z.[1-9] represents the second character should be any number from 1-9.\\d represents the third character should be any number from 0-9.\\s? represents the string should be zero or one white space character.\\d{4} represents the next four characters should be any number from 0-9.[1-9] represents the last character should be any number from 1-9.$ represents the ending of the string.Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().Return true if the string matches with the given regular expression, else return false. Where: ^ represents the starting of the string.[A-PR-WYa-pr-wy] represents the string should be starts with A-Z excluding Q, X, and Z.[1-9] represents the second character should be any number from 1-9.\\d represents the third character should be any number from 0-9.\\s? represents the string should be zero or one white space character.\\d{4} represents the next four characters should be any number from 0-9.[1-9] represents the last character should be any number from 1-9.$ represents the ending of the string. ^ represents the starting of the string. [A-PR-WYa-pr-wy] represents the string should be starts with A-Z excluding Q, X, and Z. [1-9] represents the second character should be any number from 1-9. \\d represents the third character should be any number from 0-9. \\s? represents the string should be zero or one white space character. \\d{4} represents the next four characters should be any number from 0-9. [1-9] represents the last character should be any number from 1-9. $ represents the ending of the string. Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher(). Return true if the string matches with the given regular expression, else return false. Below is the implementation of the above approach: Java Python3 C++ // Java program to validate// passport number of India// using regular expression import java.util.regex.*; class GFG { // Function to validate // passport number of India // using regular expression public static boolean isValidPassportNo(String str) { // Regex to check valid. // passport number of India String regex = "^[A-PR-WYa-pr-wy][1-9]\\d" + "\\s?\\d{4}[1-9]$"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = "A21 90457"; System.out.println(isValidPassportNo(str1)); // Test Case 2: String str2 = "A0296457"; System.out.println(isValidPassportNo(str2)); // Test Case 3: String str3 = "Q2096453"; System.out.println(isValidPassportNo(str3)); // Test Case 4: String str4 = "12096457"; System.out.println(isValidPassportNo(str4)); // Test Case 5: String str5 = "A209645704"; System.out.println(isValidPassportNo(str5)); }} # Python3 program to validate passport# number of India using regular expressionimport re # Function to validate the pin code# of India. def isValidPassportNo(string): # Regex to check valid pin code # of India. regex = "^[A-PR-WYa-pr-wy][1-9]\\d" +\ "\\s?\\d{4}[1-9]$" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (string == ''): return False # Pattern class contains matcher() # method to find matching between # given string and regular expression. m = re.match(p, string) # Return True if the string # matched the ReGex else False if m is None: return False else: return True # Driver code.if __name__ == "__main__": # Test Case 1 str1 = "A21 90457" print(isValidPassportNo(str1)) # Test Case 2: str2 = "A0296457" print(isValidPassportNo(str2)) # Test Case 3: str3 = "Q2096453" print(isValidPassportNo(str3)) # Test Case 4: str4 = "12096457" print(isValidPassportNo(str4)) # Test Case 5: str5 = "A209645704" print(isValidPassportNo(str5)) # This code is contributed by AnkitRai01 // C++ program to validate the// passport number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the passport numberbool isValidPassportNo(string str){ // Regex to check valid passport number const regex pattern( "^[A-PR-WYa-pr-wy][1-9]" "\\d\\s?\\d{4}[1-9]$"); // If the passport number // is empty return false if (str.empty()) { return false; } // Return true if the passport number // matched the ReGex if (regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = "A21 90457"; cout << isValidPassportNo(str1) << endl; // Test Case 2: string str2 = "A0296457"; cout << isValidPassportNo(str2) << endl; // Test Case 3: string str3 = "Q2096453"; cout << isValidPassportNo(str3) << endl; // Test Case 4: string str4 = "12096457"; cout << isValidPassportNo(str4) << endl; // Test Case 5: string str5 = "A209645704"; cout << isValidPassportNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra true false false false false ankthon yuvraj_chandra CPP-regex java-regular-expression regular-expression Pattern Searching Strings Strings Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Boyer Moore Algorithm for Pattern Searching Check if an URL is valid or not using Regular Expression Search a Word in a 2D Grid of characters How to check if string contains only digits in Java Count N-length strings consisting only of vowels sorted lexicographically Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 C++ Data Types Write a program to print all permutations of a given string
[ { "code": null, "e": 25158, "s": 25130, "text": "\n27 Jan, 2021" }, { "code": null, "e": 25387, "s": 25158, "text": "Given a string str of alphanumeric characters, the task is to check whether the given string is valid passport number or not by using Regular Expression. The valid passport number of India must satisfy the following conditions: " }, { "code": null, "e": 25780, "s": 25387, "text": "It should be eight characters long.The first character should be an upper case alphabet.The next two characters should be a number, but the first character should be any number from 1-9 and the second character should be any number from 0-9.It should be zero or one white space character.The next four characters should be any number from 0-9.The last character should be any number from 1-9." }, { "code": null, "e": 25816, "s": 25780, "text": "It should be eight characters long." }, { "code": null, "e": 25870, "s": 25816, "text": "The first character should be an upper case alphabet." }, { "code": null, "e": 26024, "s": 25870, "text": "The next two characters should be a number, but the first character should be any number from 1-9 and the second character should be any number from 0-9." }, { "code": null, "e": 26072, "s": 26024, "text": "It should be zero or one white space character." }, { "code": null, "e": 26128, "s": 26072, "text": "The next four characters should be any number from 0-9." }, { "code": null, "e": 26178, "s": 26128, "text": "The last character should be any number from 1-9." }, { "code": null, "e": 26189, "s": 26178, "text": "Examples: " }, { "code": null, "e": 26354, "s": 26189, "text": "Input: str = “A2096457”; Output: true Explanation: The given string satisfies all the above mentioned conditions. Therefore it is a valid passport number of India. " }, { "code": null, "e": 26522, "s": 26354, "text": "Input: str = “12096457”; Output: false Explanation: The given string doesn’t starts with an upper case alphabet. Therefore it is not a valid passport number of India. " }, { "code": null, "e": 26672, "s": 26522, "text": "Input: str = “A209645704”; Output: false Explanation: The given string contains 10 characters. Therefore it is not a valid passport number of India. " }, { "code": null, "e": 26803, "s": 26672, "text": "Approach: The idea is to use Regular Expression to solve this problem. The following steps can be followed to compute the answer. " }, { "code": null, "e": 26907, "s": 26803, "text": "Get the String.Create a regular expression to check valid passport number of India as mentioned below: " }, { "code": null, "e": 26923, "s": 26907, "text": "Get the String." }, { "code": null, "e": 27012, "s": 26923, "text": "Create a regular expression to check valid passport number of India as mentioned below: " }, { "code": null, "e": 27066, "s": 27012, "text": "regex = “^[A-PR-WYa-pr-wy][1-9]\\\\d\\\\s?\\\\d{4}[1-9]$”; " }, { "code": null, "e": 27774, "s": 27066, "text": "Where: ^ represents the starting of the string.[A-PR-WYa-pr-wy] represents the string should be starts with A-Z excluding Q, X, and Z.[1-9] represents the second character should be any number from 1-9.\\\\d represents the third character should be any number from 0-9.\\\\s? represents the string should be zero or one white space character.\\\\d{4} represents the next four characters should be any number from 0-9.[1-9] represents the last character should be any number from 1-9.$ represents the ending of the string.Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher().Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 28290, "s": 27774, "text": "Where: ^ represents the starting of the string.[A-PR-WYa-pr-wy] represents the string should be starts with A-Z excluding Q, X, and Z.[1-9] represents the second character should be any number from 1-9.\\\\d represents the third character should be any number from 0-9.\\\\s? represents the string should be zero or one white space character.\\\\d{4} represents the next four characters should be any number from 0-9.[1-9] represents the last character should be any number from 1-9.$ represents the ending of the string." }, { "code": null, "e": 28331, "s": 28290, "text": "^ represents the starting of the string." }, { "code": null, "e": 28419, "s": 28331, "text": "[A-PR-WYa-pr-wy] represents the string should be starts with A-Z excluding Q, X, and Z." }, { "code": null, "e": 28488, "s": 28419, "text": "[1-9] represents the second character should be any number from 1-9." }, { "code": null, "e": 28554, "s": 28488, "text": "\\\\d represents the third character should be any number from 0-9." }, { "code": null, "e": 28626, "s": 28554, "text": "\\\\s? represents the string should be zero or one white space character." }, { "code": null, "e": 28700, "s": 28626, "text": "\\\\d{4} represents the next four characters should be any number from 0-9." }, { "code": null, "e": 28767, "s": 28700, "text": "[1-9] represents the last character should be any number from 1-9." }, { "code": null, "e": 28806, "s": 28767, "text": "$ represents the ending of the string." }, { "code": null, "e": 28912, "s": 28806, "text": "Match the given string with the Regular Expression. In Java, this can be done by using Pattern.matcher()." }, { "code": null, "e": 29000, "s": 28912, "text": "Return true if the string matches with the given regular expression, else return false." }, { "code": null, "e": 29052, "s": 29000, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29057, "s": 29052, "text": "Java" }, { "code": null, "e": 29065, "s": 29057, "text": "Python3" }, { "code": null, "e": 29069, "s": 29065, "text": "C++" }, { "code": "// Java program to validate// passport number of India// using regular expression import java.util.regex.*; class GFG { // Function to validate // passport number of India // using regular expression public static boolean isValidPassportNo(String str) { // Regex to check valid. // passport number of India String regex = \"^[A-PR-WYa-pr-wy][1-9]\\\\d\" + \"\\\\s?\\\\d{4}[1-9]$\"; // Compile the ReGex Pattern p = Pattern.compile(regex); // If the string is empty // return false if (str == null) { return false; } // Find match between given string // and regular expression // using Pattern.matcher() Matcher m = p.matcher(str); // Return if the string // matched the ReGex return m.matches(); } // Driver code public static void main(String args[]) { // Test Case 1: String str1 = \"A21 90457\"; System.out.println(isValidPassportNo(str1)); // Test Case 2: String str2 = \"A0296457\"; System.out.println(isValidPassportNo(str2)); // Test Case 3: String str3 = \"Q2096453\"; System.out.println(isValidPassportNo(str3)); // Test Case 4: String str4 = \"12096457\"; System.out.println(isValidPassportNo(str4)); // Test Case 5: String str5 = \"A209645704\"; System.out.println(isValidPassportNo(str5)); }}", "e": 30546, "s": 29069, "text": null }, { "code": "# Python3 program to validate passport# number of India using regular expressionimport re # Function to validate the pin code# of India. def isValidPassportNo(string): # Regex to check valid pin code # of India. regex = \"^[A-PR-WYa-pr-wy][1-9]\\\\d\" +\\ \"\\\\s?\\\\d{4}[1-9]$\" # Compile the ReGex p = re.compile(regex) # If the string is empty # return false if (string == ''): return False # Pattern class contains matcher() # method to find matching between # given string and regular expression. m = re.match(p, string) # Return True if the string # matched the ReGex else False if m is None: return False else: return True # Driver code.if __name__ == \"__main__\": # Test Case 1 str1 = \"A21 90457\" print(isValidPassportNo(str1)) # Test Case 2: str2 = \"A0296457\" print(isValidPassportNo(str2)) # Test Case 3: str3 = \"Q2096453\" print(isValidPassportNo(str3)) # Test Case 4: str4 = \"12096457\" print(isValidPassportNo(str4)) # Test Case 5: str5 = \"A209645704\" print(isValidPassportNo(str5)) # This code is contributed by AnkitRai01", "e": 31707, "s": 30546, "text": null }, { "code": "// C++ program to validate the// passport number// using Regular Expression#include <iostream>#include <regex>using namespace std; // Function to validate the passport numberbool isValidPassportNo(string str){ // Regex to check valid passport number const regex pattern( \"^[A-PR-WYa-pr-wy][1-9]\" \"\\\\d\\\\s?\\\\d{4}[1-9]$\"); // If the passport number // is empty return false if (str.empty()) { return false; } // Return true if the passport number // matched the ReGex if (regex_match(str, pattern)) { return true; } else { return false; }} // Driver Codeint main(){ // Test Case 1: string str1 = \"A21 90457\"; cout << isValidPassportNo(str1) << endl; // Test Case 2: string str2 = \"A0296457\"; cout << isValidPassportNo(str2) << endl; // Test Case 3: string str3 = \"Q2096453\"; cout << isValidPassportNo(str3) << endl; // Test Case 4: string str4 = \"12096457\"; cout << isValidPassportNo(str4) << endl; // Test Case 5: string str5 = \"A209645704\"; cout << isValidPassportNo(str5) << endl; return 0;} // This code is contributed by yuvraj_chandra", "e": 32873, "s": 31707, "text": null }, { "code": null, "e": 32903, "s": 32873, "text": "true\nfalse\nfalse\nfalse\nfalse\n" }, { "code": null, "e": 32911, "s": 32903, "text": "ankthon" }, { "code": null, "e": 32926, "s": 32911, "text": "yuvraj_chandra" }, { "code": null, "e": 32936, "s": 32926, "text": "CPP-regex" }, { "code": null, "e": 32960, "s": 32936, "text": "java-regular-expression" }, { "code": null, "e": 32979, "s": 32960, "text": "regular-expression" }, { "code": null, "e": 32997, "s": 32979, "text": "Pattern Searching" }, { "code": null, "e": 33005, "s": 32997, "text": "Strings" }, { "code": null, "e": 33013, "s": 33005, "text": "Strings" }, { "code": null, "e": 33031, "s": 33013, "text": "Pattern Searching" }, { "code": null, "e": 33129, "s": 33031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33173, "s": 33129, "text": "Boyer Moore Algorithm for Pattern Searching" }, { "code": null, "e": 33230, "s": 33173, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 33271, "s": 33230, "text": "Search a Word in a 2D Grid of characters" }, { "code": null, "e": 33323, "s": 33271, "text": "How to check if string contains only digits in Java" }, { "code": null, "e": 33397, "s": 33323, "text": "Count N-length strings consisting only of vowels sorted lexicographically" }, { "code": null, "e": 33443, "s": 33397, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 33468, "s": 33443, "text": "Reverse a string in Java" }, { "code": null, "e": 33502, "s": 33468, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 33517, "s": 33502, "text": "C++ Data Types" } ]
How do I get an ISO 8601 date in string format in Python?
To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'. You can use it as follows − from datetime import datetime my_date = datetime.now() print(my_date.isoformat()) This will give the output − 2018-01-02T22:08:12.510696 In older python versions, you can use the strftime function to format the datetime object such that you get the desired result. from datetime import datetime my_date = datetime.now() print(my_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z')) This will give the output − 2018-01-02T22:10:05.284208
[ { "code": null, "e": 1302, "s": 1062, "text": "To get an ISO 8601 date in string format in Python 3, you can simply use the isoformat function. It returns the date in the ISO 8601 format. For example, if you give it the date 31/12/2017, it'll give you the string '2017-12-31T00:00:00'. " }, { "code": null, "e": 1330, "s": 1302, "text": "You can use it as follows −" }, { "code": null, "e": 1412, "s": 1330, "text": "from datetime import datetime\nmy_date = datetime.now()\nprint(my_date.isoformat())" }, { "code": null, "e": 1440, "s": 1412, "text": "This will give the output −" }, { "code": null, "e": 1467, "s": 1440, "text": "2018-01-02T22:08:12.510696" }, { "code": null, "e": 1596, "s": 1467, "text": "In older python versions, you can use the strftime function to format the datetime object such that you get the desired result. " }, { "code": null, "e": 1701, "s": 1596, "text": "from datetime import datetime\nmy_date = datetime.now()\nprint(my_date.strftime('%Y-%m-%dT%H:%M:%S.%f%z'))" }, { "code": null, "e": 1729, "s": 1701, "text": "This will give the output −" }, { "code": null, "e": 1756, "s": 1729, "text": "2018-01-02T22:10:05.284208" } ]
Avoiding class data shared among the instances in Python
When we instantiate a class in Python, all its variables and functions also get inherited to the new instantiated class. But there may be e occasions when we do not want some of the variables of the parent class to be inherited by the child class. In this article, we will explore two ways to do that. In the below example we show how the variables are instance heated from a given class and how the variables are shared across all the instantiated classes. Live Demo class MyClass: listA= [] # Instantiate Both the classes x = MyClass() y = MyClass() # Manipulate both the classes x.listA.append(10) y.listA.append(20) x.listA.append(30) y.listA.append(40) # Print Results print("Instance X: ",x.listA) print("Instance Y: ",y.listA) Running the above code gives us the following result − Instance X: [10, 20, 30, 40] Instance Y: [10, 20, 30, 40] We can use the I need a method to make the variables inside a class as private. These variables will not be shared across the classes when the parent class is instantiated. Live Demo class MyClass: def __init__(self): self.listA = [] # Instantiate Both the classes x = MyClass() y = MyClass() # Manipulate both the classes x.listA.append(10) y.listA.append(20) x.listA.append(30) y.listA.append(40) # Print Results print("Instance X: ",x.listA) print("Instance Y: ",y.listA) Running the above code gives us the following result − Instance X: [10, 30] Instance Y: [20, 40] In this approach, we will re-declare the variables outside the class. As the variables get initialized again that do not get shared across the instantiated classes. Live Demo class MyClass: listA = [] # Instantiate Both the classes x = MyClass() y = MyClass() x.listA = [] y.listA = [] # Manipulate both the classes x.listA.append(10) y.listA.append(20) x.listA.append(30) y.listA.append(40) # Print Results print("Instance X: ",x.listA) print("Instance Y: ",y.listA) Output Running the above code gives us the following result − Instance X: [10, 30] Instance Y: [20, 40]
[ { "code": null, "e": 1364, "s": 1062, "text": "When we instantiate a class in Python, all its variables and functions also get inherited to the new instantiated class. But there may be e occasions when we do not want some of the variables of the parent class to be inherited by the child class. In this article, we will explore two ways to do that." }, { "code": null, "e": 1520, "s": 1364, "text": "In the below example we show how the variables are instance heated from a given class and how the variables are shared across all the instantiated classes." }, { "code": null, "e": 1531, "s": 1520, "text": " Live Demo" }, { "code": null, "e": 1803, "s": 1531, "text": "class MyClass:\n listA= []\n\n# Instantiate Both the classes\nx = MyClass()\ny = MyClass()\n\n# Manipulate both the classes\nx.listA.append(10)\ny.listA.append(20)\nx.listA.append(30)\ny.listA.append(40)\n\n# Print Results\nprint(\"Instance X: \",x.listA)\nprint(\"Instance Y: \",y.listA)" }, { "code": null, "e": 1858, "s": 1803, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1916, "s": 1858, "text": "Instance X: [10, 20, 30, 40]\nInstance Y: [10, 20, 30, 40]" }, { "code": null, "e": 2089, "s": 1916, "text": "We can use the I need a method to make the variables inside a class as private. These variables will not be shared across the classes when the parent class is instantiated." }, { "code": null, "e": 2100, "s": 2089, "text": " Live Demo" }, { "code": null, "e": 2404, "s": 2100, "text": "class MyClass:\n def __init__(self):\n self.listA = []\n\n# Instantiate Both the classes\nx = MyClass()\ny = MyClass()\n\n# Manipulate both the classes\nx.listA.append(10)\ny.listA.append(20)\nx.listA.append(30)\ny.listA.append(40)\n\n# Print Results\nprint(\"Instance X: \",x.listA)\nprint(\"Instance Y: \",y.listA)" }, { "code": null, "e": 2459, "s": 2404, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2501, "s": 2459, "text": "Instance X: [10, 30]\nInstance Y: [20, 40]" }, { "code": null, "e": 2666, "s": 2501, "text": "In this approach, we will re-declare the variables outside the class. As the variables get initialized again that do not get shared across the instantiated classes." }, { "code": null, "e": 2677, "s": 2666, "text": " Live Demo" }, { "code": null, "e": 2983, "s": 2677, "text": "class MyClass:\n listA = []\n\n# Instantiate Both the classes\nx = MyClass()\ny = MyClass()\n\nx.listA = []\ny.listA = []\n# Manipulate both the classes\nx.listA.append(10)\ny.listA.append(20)\nx.listA.append(30)\ny.listA.append(40)\n\n# Print Results\nprint(\"Instance X: \",x.listA)\nprint(\"Instance Y: \",y.listA)\nOutput" }, { "code": null, "e": 3038, "s": 2983, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 3080, "s": 3038, "text": "Instance X: [10, 30]\nInstance Y: [20, 40]" } ]
Flip Effect with CSS
The flip effect is used to create a mirror image of the object. The following parameters can be used in this filter To set flip effect Live Demo <html> <head> </head> <body> <img src = "/css/images/logo.png" alt = "CSS Logo" style = "Filter: FlipH"> <img src = "/css/images/logo.png" alt = "CSS Logo" style = "Filter: FlipV"> <p>Text Example:</p> <div style = "width: 300; height: 50; font-size: 30pt; font-family: Arial Black; color:red; Filter: FlipV">CSS Tutorials</div> </body> </html>
[ { "code": null, "e": 1178, "s": 1062, "text": "The flip effect is used to create a mirror image of the object. The following parameters can be used in this filter" }, { "code": null, "e": 1197, "s": 1178, "text": "To set flip effect" }, { "code": null, "e": 1207, "s": 1197, "text": "Live Demo" }, { "code": null, "e": 1633, "s": 1207, "text": "<html>\n <head>\n </head>\n <body>\n <img src = \"/css/images/logo.png\" alt = \"CSS Logo\" style = \"Filter: FlipH\">\n <img src = \"/css/images/logo.png\" alt = \"CSS Logo\" style = \"Filter: FlipV\">\n <p>Text Example:</p>\n <div style = \"width: 300;\n height: 50;\n font-size: 30pt;\n font-family: Arial Black;\n color:red;\n Filter: FlipV\">CSS Tutorials</div>\n </body>\n</html>" } ]
How To Select Multiple Columns From PySpark DataFrames | Towards Data Science
When working with Spark, we typically need to deal with a fairly large number of rows and columns and thus, we sometimes have to work only with a small subset of columns. In today’s short guide we will explore different ways for selecting columns from PySpark DataFrames. Specifically, we will discuss how to select multiple columns by column name by index with the use of regular expressions First, let’s create an example DataFrame that we’ll reference throughout this article to demonstrate a few concepts. from pyspark.sql import SparkSession# Create an instance of spark sessionspark_session = SparkSession.builder \ .master('local[1]') \ .appName('Example') \ .getOrCreate()# Create an example DataFramedf = spark_session.createDataFrame( [ (1, 'a', True, 1.0, 5), (2, 'b', False, 2.0, None), (3, 'c', False, 3.0, 4), (4, 'd', True, 4.0, 3), ], ['colA', 'colB', 'colC', 'colD', 'E'])df.show()+----+----+-----+----+----+|colA|colB| colC|colD| E|+----+----+-----+----+----+| 1| a| true| 1.0| 5|| 2| b|false| 2.0|null|| 3| c|false| 3.0| 4|| 4| d| true| 4.0| 3|+----+----+-----+----+----+ In order to select multiple column from an existing PySpark DataFrame you can simply specify the column names you wish to retrieve to the pyspark.sql.DataFrame.select method. For example, df.select('colA', 'colC').show()+----+-----+|colA| colC|+----+-----+| 1| true|| 2|false|| 3|false|| 4| true|+----+-----+ Alternatively, if the columns you wish to retrieve are stored in a list, you can use the following notation: col_names = ['colA', 'colC']df.select(*col_names).show()+----+-----+|colA| colC|+----+-----+| 1| true|| 2|false|| 3|false|| 4| true|+----+-----+ Now if you want to select columns based on their index, then you can simply slice the result from df.columns that returns a list of column names. For example, in order to retrieve the first three columns then the following expression should do the trick: df.select(df.columns[:3]).show()+----+----+-----+|colA|colB| colC|+----+----+-----+| 1| a| true|| 2| b|false|| 3| c|false|| 4| d| true|+----+----+-----+ Alternatively, if you want to fetch the 2nd and 3rd column only, then df.columns[1:3] will do the trick: df.select(df.columns[1:3]).show()+----+-----+|colB| colC|+----+-----+| a| true|| b|false|| c|false|| d| true|+----+-----+ Finally, in order to select multiple columns that match a specific regular expression then you can make use of pyspark.sql.DataFrame.colRegex method. For instance, in order to fetch all the columns that start with or contain col, then the following will do the trick: df.select(df.colRegex("`(col)+?.+`")).show()+----+----+-----+----+|colA|colB| colC|colD|+----+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+----+----+-----+----+ Similarly, we can use the following regex in order to select all columns but colA : df.select(df.colRegex("`(colA)?+.+`")).show()+----+-----+----+----+|colB| colC|colD| E|+----+-----+----+----+| a| true| 1.0| 5|| b|false| 2.0|null|| c|false| 3.0| 4|| d| true| 4.0| 3|+----+-----+----+----+ In today’s short guide we discussed how to perform column selection in PySpark DataFrames. We explored how to select multiple columns by specifying the column name or index. Additionally, we saw in action how to perform column selection with the use of regular expressions. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You may also like
[ { "code": null, "e": 343, "s": 172, "text": "When working with Spark, we typically need to deal with a fairly large number of rows and columns and thus, we sometimes have to work only with a small subset of columns." }, { "code": null, "e": 505, "s": 343, "text": "In today’s short guide we will explore different ways for selecting columns from PySpark DataFrames. Specifically, we will discuss how to select multiple columns" }, { "code": null, "e": 520, "s": 505, "text": "by column name" }, { "code": null, "e": 529, "s": 520, "text": "by index" }, { "code": null, "e": 565, "s": 529, "text": "with the use of regular expressions" }, { "code": null, "e": 682, "s": 565, "text": "First, let’s create an example DataFrame that we’ll reference throughout this article to demonstrate a few concepts." }, { "code": null, "e": 1329, "s": 682, "text": "from pyspark.sql import SparkSession# Create an instance of spark sessionspark_session = SparkSession.builder \\ .master('local[1]') \\ .appName('Example') \\ .getOrCreate()# Create an example DataFramedf = spark_session.createDataFrame( [ (1, 'a', True, 1.0, 5), (2, 'b', False, 2.0, None), (3, 'c', False, 3.0, 4), (4, 'd', True, 4.0, 3), ], ['colA', 'colB', 'colC', 'colD', 'E'])df.show()+----+----+-----+----+----+|colA|colB| colC|colD| E|+----+----+-----+----+----+| 1| a| true| 1.0| 5|| 2| b|false| 2.0|null|| 3| c|false| 3.0| 4|| 4| d| true| 4.0| 3|+----+----+-----+----+----+" }, { "code": null, "e": 1517, "s": 1329, "text": "In order to select multiple column from an existing PySpark DataFrame you can simply specify the column names you wish to retrieve to the pyspark.sql.DataFrame.select method. For example," }, { "code": null, "e": 1646, "s": 1517, "text": "df.select('colA', 'colC').show()+----+-----+|colA| colC|+----+-----+| 1| true|| 2|false|| 3|false|| 4| true|+----+-----+" }, { "code": null, "e": 1755, "s": 1646, "text": "Alternatively, if the columns you wish to retrieve are stored in a list, you can use the following notation:" }, { "code": null, "e": 1908, "s": 1755, "text": "col_names = ['colA', 'colC']df.select(*col_names).show()+----+-----+|colA| colC|+----+-----+| 1| true|| 2|false|| 3|false|| 4| true|+----+-----+" }, { "code": null, "e": 2163, "s": 1908, "text": "Now if you want to select columns based on their index, then you can simply slice the result from df.columns that returns a list of column names. For example, in order to retrieve the first three columns then the following expression should do the trick:" }, { "code": null, "e": 2332, "s": 2163, "text": "df.select(df.columns[:3]).show()+----+----+-----+|colA|colB| colC|+----+----+-----+| 1| a| true|| 2| b|false|| 3| c|false|| 4| d| true|+----+----+-----+" }, { "code": null, "e": 2437, "s": 2332, "text": "Alternatively, if you want to fetch the 2nd and 3rd column only, then df.columns[1:3] will do the trick:" }, { "code": null, "e": 2567, "s": 2437, "text": "df.select(df.columns[1:3]).show()+----+-----+|colB| colC|+----+-----+| a| true|| b|false|| c|false|| d| true|+----+-----+" }, { "code": null, "e": 2835, "s": 2567, "text": "Finally, in order to select multiple columns that match a specific regular expression then you can make use of pyspark.sql.DataFrame.colRegex method. For instance, in order to fetch all the columns that start with or contain col, then the following will do the trick:" }, { "code": null, "e": 3056, "s": 2835, "text": "df.select(df.colRegex(\"`(col)+?.+`\")).show()+----+----+-----+----+|colA|colB| colC|colD|+----+----+-----+----+| 1| a| true| 1.0|| 2| b|false| 2.0|| 3| c|false| 3.0|| 4| d| true| 4.0|+----+----+-----+----+" }, { "code": null, "e": 3140, "s": 3056, "text": "Similarly, we can use the following regex in order to select all columns but colA :" }, { "code": null, "e": 3362, "s": 3140, "text": "df.select(df.colRegex(\"`(colA)?+.+`\")).show()+----+-----+----+----+|colB| colC|colD| E|+----+-----+----+----+| a| true| 1.0| 5|| b|false| 2.0|null|| c|false| 3.0| 4|| d| true| 4.0| 3|+----+-----+----+----+" }, { "code": null, "e": 3636, "s": 3362, "text": "In today’s short guide we discussed how to perform column selection in PySpark DataFrames. We explored how to select multiple columns by specifying the column name or index. Additionally, we saw in action how to perform column selection with the use of regular expressions." }, { "code": null, "e": 3753, "s": 3636, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read." } ]
TD in Reinforcement Learning, the Easy Way | by Ziad SALLOUM | Towards Data Science
Update: The best way of learning and practicing TD method is by going to http://rl-lab.com/gridworld-td Suppose you are driving your car equipped with a GPS. At the start of your journey the GPS gives you an estimate of the arrival time (based on statistical data), as you drive and you hit traffic jams (or not), it refines its estimate and gives you other arrival times. You notice that at each portion of the trip you are provided with some estimate about the arrival time. Now suppose that your GPS does not give you any estimate but stores the data until you arrive then gives you a detailed report on how much time each part of the road took. Would this be useful for you ? The answer will be: it depends on what you want to do. But for sure you will appreciate having early on feedback even if it was not very accurate. This is the difference between Monte Carlo and Temporal Difference.The latter method of the example is Monte Carlo based, because it waits until the arrival to destination then compute the estimate of each portion of the trip. While the former is Temporal Difference. As a matter of fact, if you merge Monte Carlo (MC) and Dynamic Programming (DP) methods you obtain Temporal Difference (TD) method. Note: TD will be noted as TD(0) which means it will look ahead one step. TD(0) is particular case of TD(n). Recall that in MC we play a whole episode until the end then we compute the discounted reward for each state that appeared in the episode. We do large number of episodes then we average the different values that we obtain for each state. In DP we randomly initialize all the states, and then we iteratively compute the value of each state based on the (previously computed) values of the surrounding states. We keep doing this until we notice that there is no considerable improvement in any state value. We have seen that in MC we play the episode until the end, then we move backward to assign each state the discounted return G of the episode. But this means we have to wait until the end to know the value of G.However in TD(0), we update the current state based on the estimate of the next state. Remember the example with the GPS, at one point the GPS might notice that your speed dropped to 10Km/h so it updates its estimate of arrival time by +30min for example, but this might be a very brief slowdown and in few minutes you are accelerating again, and the GPS updates its estimate by -20min.Same with TD(0), V(s) is updated according the following formula: This is an incremental average computation. Check “Incremental Average Computation” at the end of the article for details. Clearly the estimate of V(s) won’t be accurate based on one episode only.Same as your car trip that day! You won’t have a good estimate of the total time nor the time of each portion by doing it only once. Probably that day you were lucky, there was no traffic jam, or on the opposite you were unlucky and you got stuck in an out of the ordinary jam due to a car accident.But if you do the trip everyday (playing more episodes) you will be able to refine your estimates by each passing day. The algorithm (in pseudo code) for policy evaluation in TD(0) is as follows: Evaluate_Policy(policy): randomly_initialize_non_terminal_states_values()Loop number_of_episodes: let s = start_state() # Play episode until the end Loop until game_over(): let a = get_action(policy, s, 0.1) # get action to perform on state s according # to the given policy 90% of the time, and a # random action 10% of the time. let (s', r) = make_move(s, a) #make move from s using a and get #the new state s' and the reward r # incrementally compute the average at V(s). Notice that V(s) # depends on an estimate of V(s') and not on the return # G as in MC let V(s) = V(s) + alpha * [r + gamma * V(s') - V(s)] let s = s' End LoopEnd Loop Policy control in TD(0) has two implementations: SARSA and Q-Learning. SARSA is an On-Policy method, which means it computes the Q-value according to a certain policy and then the agent follows that policy. Q-Learning is an Off-Policy method. It consists of computing the Q-value according to a greedy policy, but the agent does not necessarily follow the greedy policy. As usual when it comes to performing actions you need to compute Action-State function (Q-value) because it maps state and action to estimate.In Monte Carlo article we explained why V(s) alone is not helpful to determine the optimal policy (the plan, or the action to take at each state).So suppose we are at state s and we want to compute the Q-value based on state s and action a, as we have seen earlier that TD(0) uses incremental average to compute the value of any state. This average computation, is expressed in terms of value of next state.Since we are computing Q-value, then we have to get the Q-value of the next state s’. However Q needs two parameters which are the state and the action. The way SARSA resolves this, in order get that Q-value, is to choose an action a’ (based on epsilon-greedy method) at state s’ and then when the agent arrives at s’ it we will perform action a’. The figure below gives an example SARSA. In the left grid the agent is at state s, it computes the value of action going North (blue arrow), to be able to do the computation it needs the Q-value at s’ going East (grey arrow). The right grid shows when the agent moved to state s’, it follows the action previously decided by the policy and computes the Q-value of the action going East (blue arrow)... The following is the pseudo code of SARSA: SARRA(): #initialization for each state s in AllNonTerminalStates: for each action a in Actions(s): Q(s,a) = random() for each s in TerminalStates: Q(s,_) = 0 #Q(s) = 0 for all actions in s Loop number_of_episodes: let s = start_state() # get action to perform on state s according # to the given policy 90% of the time, and a # random action 10% of the time. let a = get_epsilon_greedy_action(s, 0.1) # Play episode until the end Loop until game_over(): # make move from s using a and get the new state s' # and the reward r let (s', r) = make_move(s, a) # choose action to perform on state s' # a' will be used executed in the next iteration # but for the moment it will be used to get Q(s', a') let a' = get_epsilon_greedy_action(s', 0.1) # incrementally compute the average at Q(s,a) let Q(s, a) = Q(s, a) + alpha*[r + gamma * Q(s', a') - Q(s, a)] let s = s' # move to the next state let a = a' # use the same action a' as determined above End Loop End Loop Q-learning is similar to SARSA except that when computing Q(s,a) it uses the greedy policy in determining the Q(s’,a’) from the next state s’.Remember that the greedy policy selects the action that gives the highest Q-value.However, and this is important, it does not necessarily follow that greedy policy. The image blow illustrates the mechanism of Q-Learning: The left grid shows the agent at state s computing the value of Q when going North (blue arrow). For this purpose it uses in the computation the Q-value determined by the greedy policy at state s’ (orange arrow).The right grid shows the agent moving to the state s’, but does not necessarily follow the action determined by the greedy policy (orange arrow), instead it chooses a random action (blue arrow). The algorithm of Q-learning is like the following: QLearning(): #initialization for each state s in AllNonTerminalStates: for each action a in Actions(s): Q(s,a) = random() for each s in TerminalStates: Q(s,_) = 0 #Q(s) = 0 for all actions in s Loop number_of_episodes: let s = start_state() # Play episode until the end Loop until game_over(): # get action to perform on state s according # to the given policy 90% of the time, and a # random action 10% of the time. let a = get_epsilon_greedy_action(s, 0.1) # make move from s using a and get the new state s' # and the reward r let (s', r) = make_move(s, a) # choose the max Q-value (qmax) on state s' let qmax = get_max_qvalue_on_state(s') # incrementally compute the average at Q(s,a) let Q(s, a) = Q(s, a) + alpha*[r + gamma * qmax - Q(s, a)] let s = s' # move to the next state End LoopEnd Loop This paragraph shows how the incremental average computation is derived.The terms of the average are arranged in a way to have both A(n+1) and A(n). Notice that 1/(n+1) represents the term alpha in the State-Value and Action-Value functions. Temporal Difference is better than Dynamic Programming method because it does not require a model of the environment, nor the rewards and probability distributions. TD has also advantage over Monte Carlo methods since no need to wait until the end of the episode to know the return, only one time step is required. Reinforcement Learning Policy for Developers Q vs V in Reinforcement Learning, the Easy Way Math Behind Reinforcement Learning, the Easy Way Monte Carlo in Reinforcement Learning, the Easy Way Dynamic Programming in Reinforcement Learning, the Easy Way
[ { "code": null, "e": 276, "s": 172, "text": "Update: The best way of learning and practicing TD method is by going to http://rl-lab.com/gridworld-td" }, { "code": null, "e": 545, "s": 276, "text": "Suppose you are driving your car equipped with a GPS. At the start of your journey the GPS gives you an estimate of the arrival time (based on statistical data), as you drive and you hit traffic jams (or not), it refines its estimate and gives you other arrival times." }, { "code": null, "e": 649, "s": 545, "text": "You notice that at each portion of the trip you are provided with some estimate about the arrival time." }, { "code": null, "e": 852, "s": 649, "text": "Now suppose that your GPS does not give you any estimate but stores the data until you arrive then gives you a detailed report on how much time each part of the road took. Would this be useful for you ?" }, { "code": null, "e": 999, "s": 852, "text": "The answer will be: it depends on what you want to do. But for sure you will appreciate having early on feedback even if it was not very accurate." }, { "code": null, "e": 1267, "s": 999, "text": "This is the difference between Monte Carlo and Temporal Difference.The latter method of the example is Monte Carlo based, because it waits until the arrival to destination then compute the estimate of each portion of the trip. While the former is Temporal Difference." }, { "code": null, "e": 1399, "s": 1267, "text": "As a matter of fact, if you merge Monte Carlo (MC) and Dynamic Programming (DP) methods you obtain Temporal Difference (TD) method." }, { "code": null, "e": 1507, "s": 1399, "text": "Note: TD will be noted as TD(0) which means it will look ahead one step. TD(0) is particular case of TD(n)." }, { "code": null, "e": 1745, "s": 1507, "text": "Recall that in MC we play a whole episode until the end then we compute the discounted reward for each state that appeared in the episode. We do large number of episodes then we average the different values that we obtain for each state." }, { "code": null, "e": 2012, "s": 1745, "text": "In DP we randomly initialize all the states, and then we iteratively compute the value of each state based on the (previously computed) values of the surrounding states. We keep doing this until we notice that there is no considerable improvement in any state value." }, { "code": null, "e": 2674, "s": 2012, "text": "We have seen that in MC we play the episode until the end, then we move backward to assign each state the discounted return G of the episode. But this means we have to wait until the end to know the value of G.However in TD(0), we update the current state based on the estimate of the next state. Remember the example with the GPS, at one point the GPS might notice that your speed dropped to 10Km/h so it updates its estimate of arrival time by +30min for example, but this might be a very brief slowdown and in few minutes you are accelerating again, and the GPS updates its estimate by -20min.Same with TD(0), V(s) is updated according the following formula:" }, { "code": null, "e": 2797, "s": 2674, "text": "This is an incremental average computation. Check “Incremental Average Computation” at the end of the article for details." }, { "code": null, "e": 3288, "s": 2797, "text": "Clearly the estimate of V(s) won’t be accurate based on one episode only.Same as your car trip that day! You won’t have a good estimate of the total time nor the time of each portion by doing it only once. Probably that day you were lucky, there was no traffic jam, or on the opposite you were unlucky and you got stuck in an out of the ordinary jam due to a car accident.But if you do the trip everyday (playing more episodes) you will be able to refine your estimates by each passing day." }, { "code": null, "e": 3365, "s": 3288, "text": "The algorithm (in pseudo code) for policy evaluation in TD(0) is as follows:" }, { "code": null, "e": 4137, "s": 3365, "text": "Evaluate_Policy(policy): randomly_initialize_non_terminal_states_values()Loop number_of_episodes: let s = start_state() # Play episode until the end Loop until game_over(): let a = get_action(policy, s, 0.1) # get action to perform on state s according # to the given policy 90% of the time, and a # random action 10% of the time. let (s', r) = make_move(s, a) #make move from s using a and get #the new state s' and the reward r # incrementally compute the average at V(s). Notice that V(s) # depends on an estimate of V(s') and not on the return # G as in MC let V(s) = V(s) + alpha * [r + gamma * V(s') - V(s)] let s = s' End LoopEnd Loop" }, { "code": null, "e": 4208, "s": 4137, "text": "Policy control in TD(0) has two implementations: SARSA and Q-Learning." }, { "code": null, "e": 4344, "s": 4208, "text": "SARSA is an On-Policy method, which means it computes the Q-value according to a certain policy and then the agent follows that policy." }, { "code": null, "e": 4508, "s": 4344, "text": "Q-Learning is an Off-Policy method. It consists of computing the Q-value according to a greedy policy, but the agent does not necessarily follow the greedy policy." }, { "code": null, "e": 5210, "s": 4508, "text": "As usual when it comes to performing actions you need to compute Action-State function (Q-value) because it maps state and action to estimate.In Monte Carlo article we explained why V(s) alone is not helpful to determine the optimal policy (the plan, or the action to take at each state).So suppose we are at state s and we want to compute the Q-value based on state s and action a, as we have seen earlier that TD(0) uses incremental average to compute the value of any state. This average computation, is expressed in terms of value of next state.Since we are computing Q-value, then we have to get the Q-value of the next state s’. However Q needs two parameters which are the state and the action." }, { "code": null, "e": 5405, "s": 5210, "text": "The way SARSA resolves this, in order get that Q-value, is to choose an action a’ (based on epsilon-greedy method) at state s’ and then when the agent arrives at s’ it we will perform action a’." }, { "code": null, "e": 5446, "s": 5405, "text": "The figure below gives an example SARSA." }, { "code": null, "e": 5807, "s": 5446, "text": "In the left grid the agent is at state s, it computes the value of action going North (blue arrow), to be able to do the computation it needs the Q-value at s’ going East (grey arrow). The right grid shows when the agent moved to state s’, it follows the action previously decided by the policy and computes the Q-value of the action going East (blue arrow)..." }, { "code": null, "e": 5850, "s": 5807, "text": "The following is the pseudo code of SARSA:" }, { "code": null, "e": 6919, "s": 5850, "text": "SARRA(): #initialization for each state s in AllNonTerminalStates: for each action a in Actions(s): Q(s,a) = random() for each s in TerminalStates: Q(s,_) = 0 #Q(s) = 0 for all actions in s Loop number_of_episodes: let s = start_state() # get action to perform on state s according # to the given policy 90% of the time, and a # random action 10% of the time. let a = get_epsilon_greedy_action(s, 0.1) # Play episode until the end Loop until game_over(): # make move from s using a and get the new state s' # and the reward r let (s', r) = make_move(s, a) # choose action to perform on state s' # a' will be used executed in the next iteration # but for the moment it will be used to get Q(s', a') let a' = get_epsilon_greedy_action(s', 0.1) # incrementally compute the average at Q(s,a) let Q(s, a) = Q(s, a) + alpha*[r + gamma * Q(s', a') - Q(s, a)] let s = s' # move to the next state let a = a' # use the same action a' as determined above End Loop End Loop" }, { "code": null, "e": 7226, "s": 6919, "text": "Q-learning is similar to SARSA except that when computing Q(s,a) it uses the greedy policy in determining the Q(s’,a’) from the next state s’.Remember that the greedy policy selects the action that gives the highest Q-value.However, and this is important, it does not necessarily follow that greedy policy." }, { "code": null, "e": 7282, "s": 7226, "text": "The image blow illustrates the mechanism of Q-Learning:" }, { "code": null, "e": 7689, "s": 7282, "text": "The left grid shows the agent at state s computing the value of Q when going North (blue arrow). For this purpose it uses in the computation the Q-value determined by the greedy policy at state s’ (orange arrow).The right grid shows the agent moving to the state s’, but does not necessarily follow the action determined by the greedy policy (orange arrow), instead it chooses a random action (blue arrow)." }, { "code": null, "e": 7740, "s": 7689, "text": "The algorithm of Q-learning is like the following:" }, { "code": null, "e": 8638, "s": 7740, "text": "QLearning(): #initialization for each state s in AllNonTerminalStates: for each action a in Actions(s): Q(s,a) = random() for each s in TerminalStates: Q(s,_) = 0 #Q(s) = 0 for all actions in s Loop number_of_episodes: let s = start_state() # Play episode until the end Loop until game_over(): # get action to perform on state s according # to the given policy 90% of the time, and a # random action 10% of the time. let a = get_epsilon_greedy_action(s, 0.1) # make move from s using a and get the new state s' # and the reward r let (s', r) = make_move(s, a) # choose the max Q-value (qmax) on state s' let qmax = get_max_qvalue_on_state(s') # incrementally compute the average at Q(s,a) let Q(s, a) = Q(s, a) + alpha*[r + gamma * qmax - Q(s, a)] let s = s' # move to the next state End LoopEnd Loop" }, { "code": null, "e": 8787, "s": 8638, "text": "This paragraph shows how the incremental average computation is derived.The terms of the average are arranged in a way to have both A(n+1) and A(n)." }, { "code": null, "e": 8880, "s": 8787, "text": "Notice that 1/(n+1) represents the term alpha in the State-Value and Action-Value functions." }, { "code": null, "e": 9195, "s": 8880, "text": "Temporal Difference is better than Dynamic Programming method because it does not require a model of the environment, nor the rewards and probability distributions. TD has also advantage over Monte Carlo methods since no need to wait until the end of the episode to know the return, only one time step is required." }, { "code": null, "e": 9240, "s": 9195, "text": "Reinforcement Learning Policy for Developers" }, { "code": null, "e": 9287, "s": 9240, "text": "Q vs V in Reinforcement Learning, the Easy Way" }, { "code": null, "e": 9336, "s": 9287, "text": "Math Behind Reinforcement Learning, the Easy Way" }, { "code": null, "e": 9388, "s": 9336, "text": "Monte Carlo in Reinforcement Learning, the Easy Way" } ]
GATE | GATE-CS-2009 | Question 10 - GeeksforGeeks
28 Jun, 2021 What is the number of swaps required to sort n elements using selection sort, in the worst case?(A) (n)(B) (n log n)(C) (n^2 )(D) (n^2 log n)(A) Theta(n)(B) Theta(nLogn)(C) Theta(n*n)(D) Theta(n*nLogn)Answer: (A)Explanation: Here is Selection Sort algorithm for sorting in ascending order. 1. Find the minimum value in the list 2. Swap it with the value in the first position 3. Repeat the steps above for the remainder of the list (starting at the second position and advancing each time) As we can see from the algorithm, selection sort performs swap only after finding the appropriate position of the current picked element. So there are O(n) swaps performed in selection sort.Because swaps require writing to the array, selection sort is preferable if writing to memory is significantly more expensive than reading. This is generally the case if the items are huge but the keys are small. Another example where writing times are crucial is an array stored in EEPROM or Flash. There is no other algorithm with less data movement. References:http://en.wikipedia.org/wiki/Selection_sortQuiz of this Question GATE-CS-2009 GATE-GATE-CS-2009 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63 GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | GATE-CS-2007 | Question 64
[ { "code": null, "e": 24466, "s": 24438, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24756, "s": 24466, "text": "What is the number of swaps required to sort n elements using selection sort, in the worst case?(A) (n)(B) (n log n)(C) (n^2 )(D) (n^2 log n)(A) Theta(n)(B) Theta(nLogn)(C) Theta(n*n)(D) Theta(n*nLogn)Answer: (A)Explanation: Here is Selection Sort algorithm for sorting in ascending order." }, { "code": null, "e": 24971, "s": 24756, "text": " 1. Find the minimum value in the list\n 2. Swap it with the value in the first position\n 3. Repeat the steps above for the remainder of the list (starting at\n the second position and advancing each time)" }, { "code": null, "e": 25514, "s": 24971, "text": "As we can see from the algorithm, selection sort performs swap only after finding the appropriate position of the current picked element. So there are O(n) swaps performed in selection sort.Because swaps require writing to the array, selection sort is preferable if writing to memory is significantly more expensive than reading. This is generally the case if the items are huge but the keys are small. Another example where writing times are crucial is an array stored in EEPROM or Flash. There is no other algorithm with less data movement." }, { "code": null, "e": 25590, "s": 25514, "text": "References:http://en.wikipedia.org/wiki/Selection_sortQuiz of this Question" }, { "code": null, "e": 25603, "s": 25590, "text": "GATE-CS-2009" }, { "code": null, "e": 25621, "s": 25603, "text": "GATE-GATE-CS-2009" }, { "code": null, "e": 25626, "s": 25621, "text": "GATE" }, { "code": null, "e": 25724, "s": 25626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25733, "s": 25724, "text": "Comments" }, { "code": null, "e": 25746, "s": 25733, "text": "Old Comments" }, { "code": null, "e": 25780, "s": 25746, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 25813, "s": 25780, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 25855, "s": 25813, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25897, "s": 25855, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 25939, "s": 25897, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 25973, "s": 25939, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 26007, "s": 25973, "text": "GATE | GATE-IT-2004 | Question 83" }, { "code": null, "e": 26049, "s": 26007, "text": "GATE | GATE-CS-2016 (Set 1) | Question 63" }, { "code": null, "e": 26091, "s": 26049, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" } ]
PySide2 - Create Tooltip - GeeksforGeeks
29 Aug, 2020 In this article, we are going to learn how to create a tooltip. A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element. In order to make it, we use setToolTip() function which is defined in PySide2.QtWidgets. Steps to create tooltip: 1. Import PySide2 Widgets and Gui modules in your code2. Create window with title and font setting3. Set tooltip ‘Our Main Window’ to entire window4. Set icons in two states active and disable with tooltip as “Active Icon” and “Disable Icon” respectively. Input Image : Python3 # import system moduleimport sys # import QtWidget Modulesfrom PySide2.QtWidgets import QApplication, QWidget, QLabel, QToolTip # import QtGui modulesfrom PySide2.QtGui import QIcon, QPixmap, QFont class Window(QWidget): def __init__(self): super().__init__() # set window title self.setWindowTitle("GeeksforGeeks - ToolTip") # set window geometry self.setGeometry(300, 300, 500, 400) # set tooltip font and font type QToolTip.setFont(QFont("Decorative", 30, QFont.Bold)) # set tooltip self.setToolTip('Our Main Window') def setIconModes(self): # set icon icon1 = QIcon("geeksforgeeks.png") # set label label1 = QLabel('Sample', self) # set image in Active state pixmap1 = icon1.pixmap(100, 100, QIcon.Active, QIcon.On) # set Pixmap label1.setPixmap(pixmap1) # set tooltip text label1.setToolTip("Active Icon") # set icon icon2 = QIcon("geeksforgeeks.png") # set label label2 = QLabel('Sample', self) # set image in Disabled state pixmap2 = icon2.pixmap(100, 100, QIcon.Disabled, QIcon.Off) # set P label2.setPixmap(pixmap2) label2.move(100, 0) label2.setToolTip("Disable Icon") myApp = QApplication(sys.argv)window = Window()window.setIconModes()window.show() myApp.exec_()sys.exit(0) Output Image: Active State: Disable State: Python-gui Python-PySide2 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 Python | os.path.join() method Defaultdict in Python Selecting rows in pandas DataFrame based on conditions Python | Get unique values from a list Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n29 Aug, 2020" }, { "code": null, "e": 24570, "s": 24292, "text": "In this article, we are going to learn how to create a tooltip. A tooltip is often used to specify extra information about something when the user moves the mouse pointer over an element. In order to make it, we use setToolTip() function which is defined in PySide2.QtWidgets. " }, { "code": null, "e": 24595, "s": 24570, "text": "Steps to create tooltip:" }, { "code": null, "e": 24851, "s": 24595, "text": "1. Import PySide2 Widgets and Gui modules in your code2. Create window with title and font setting3. Set tooltip ‘Our Main Window’ to entire window4. Set icons in two states active and disable with tooltip as “Active Icon” and “Disable Icon” respectively." }, { "code": null, "e": 24866, "s": 24851, "text": "Input Image : " }, { "code": null, "e": 24874, "s": 24866, "text": "Python3" }, { "code": "# import system moduleimport sys # import QtWidget Modulesfrom PySide2.QtWidgets import QApplication, QWidget, QLabel, QToolTip # import QtGui modulesfrom PySide2.QtGui import QIcon, QPixmap, QFont class Window(QWidget): def __init__(self): super().__init__() # set window title self.setWindowTitle(\"GeeksforGeeks - ToolTip\") # set window geometry self.setGeometry(300, 300, 500, 400) # set tooltip font and font type QToolTip.setFont(QFont(\"Decorative\", 30, QFont.Bold)) # set tooltip self.setToolTip('Our Main Window') def setIconModes(self): # set icon icon1 = QIcon(\"geeksforgeeks.png\") # set label label1 = QLabel('Sample', self) # set image in Active state pixmap1 = icon1.pixmap(100, 100, QIcon.Active, QIcon.On) # set Pixmap label1.setPixmap(pixmap1) # set tooltip text label1.setToolTip(\"Active Icon\") # set icon icon2 = QIcon(\"geeksforgeeks.png\") # set label label2 = QLabel('Sample', self) # set image in Disabled state pixmap2 = icon2.pixmap(100, 100, QIcon.Disabled, QIcon.Off) # set P label2.setPixmap(pixmap2) label2.move(100, 0) label2.setToolTip(\"Disable Icon\") myApp = QApplication(sys.argv)window = Window()window.setIconModes()window.show() myApp.exec_()sys.exit(0)", "e": 26306, "s": 24874, "text": null }, { "code": null, "e": 26321, "s": 26306, "text": "Output Image: " }, { "code": null, "e": 26336, "s": 26321, "text": "Active State: " }, { "code": null, "e": 26351, "s": 26336, "text": "Disable State:" }, { "code": null, "e": 26362, "s": 26351, "text": "Python-gui" }, { "code": null, "e": 26377, "s": 26362, "text": "Python-PySide2" }, { "code": null, "e": 26384, "s": 26377, "text": "Python" }, { "code": null, "e": 26482, "s": 26384, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26514, "s": 26482, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26556, "s": 26514, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26612, "s": 26556, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26654, "s": 26612, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26685, "s": 26654, "text": "Python | os.path.join() method" }, { "code": null, "e": 26707, "s": 26685, "text": "Defaultdict in Python" }, { "code": null, "e": 26762, "s": 26707, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26801, "s": 26762, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26830, "s": 26801, "text": "Create a directory in Python" } ]
Geek-onacci Number - GeeksforGeeks
30 Apr, 2021 Given four integers A, B, C and N, where A, B, C represents the first three numbers of the geekonacci series, the task is to find the Nth term of the geekonacci series. The Nth term of the geekonacci series is the sum of its previous three terms in the series i.e., sum of (N – 1)th, (N – 2)th, and (N – 3)th geekonacci numbers. Examples: Input: A = 1, B = 3, C = 2, N = 4Output: 6Explanation: The geekonacci series is 1, 3, 2, 6, 11, 19, ......Therefore, the 4th geekonacci number is 6. Input: A = 1, B = 3, C = 2, N = 6Output: 19 Approach: The given problem can be solved by generating the geekonacci series upto N terms and print the Nth term of the series obtained. Follow the steps below to solve this problem: Initialize an array arr[] of size N and initialize arr[0] = A, arr[1] = B, and arr[2] = C. Iterate over the range [3, N – 1] and update the value of each every ith element, i.e. arr[i] as (arr[i – 1] + arr[i – 2] + arr[i – 3]) to get the ith term of the geekonacci series. After completing the above steps, print the value of arr[N – 1] as the resultant Nth number of the geekonacci series. Below is the implementation of the above approach: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Function to calculate the// N-th Geek-onacci Numberint find(int A, int B, int C, int N){ // Stores the geekonacci series int arr[N]; // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (int i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1];} // Driver Codeint main(){ int A = 1, B = 3, C = 2, N = 4; cout<<(find(A, B, C, N)); return 0;} // This code is contributed by mohit kumar 29. // Java program for the above approach import java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to calculate the // N-th Geek-onacci Number static int find(int A, int B, int C, int N) { // Stores the geekonacci series int[] arr = new int[N]; // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (int i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1]; } // Driver Code public static void main(String[] args) { int A = 1, B = 3, C = 2, N = 4; System.out.print(find(A, B, C, N)); }} # Python3 program for the above approach # Function to calculate the# N-th Geek-onacci Numberdef find(A, B, C, N) : # Stores the geekonacci series arr = [0] * N # Store the first three # terms of the series arr[0] = A arr[1] = B arr[2] = C # Iterate over the range [3, N] for i in range(3, N): # Update the value of arr[i] # as the sum of previous 3 # terms in the series arr[i] = (arr[i - 1] + arr[i - 2] + arr[i - 3]) # Return the last element # of arr[] as the N-th term return arr[N - 1] # Driver CodeA = 1B = 3C = 2N = 4 print(find(A, B, C, N)) # This code is contributed by sanjoy_62. // C# program for the above approachusing System; class GFG{ // Function to calculate the // N-th Geek-onacci Number static int find(int A, int B, int C, int N) { // Stores the geekonacci series int[] arr = new int[N]; // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (int i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1]; } // Driver Code public static void Main(string[] args) { int A = 1, B = 3, C = 2, N = 4; Console.Write(find(A, B, C, N)); }} // This code is contributed by code_hunt. <script> // Javascript program for the above approach // Function to calculate the // N-th Geek-onacci Number function find(A, B, C, N) { // Stores the geekonacci series let arr = new Array(N).fill(0); // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (let i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1]; } // Driver code let A = 1, B = 3, C = 2, N = 4; document.write(find(A, B, C, N)); </script> 6 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 code_hunt sanjoy_62 chinmoy1997pal series Dynamic Programming Mathematical Dynamic Programming Mathematical series 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 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Longest Palindromic Substring | Set 1 Matrix Chain Multiplication | DP-8 C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7 Program to find GCD or HCF of two numbers
[ { "code": null, "e": 25412, "s": 25384, "text": "\n30 Apr, 2021" }, { "code": null, "e": 25581, "s": 25412, "text": "Given four integers A, B, C and N, where A, B, C represents the first three numbers of the geekonacci series, the task is to find the Nth term of the geekonacci series." }, { "code": null, "e": 25741, "s": 25581, "text": "The Nth term of the geekonacci series is the sum of its previous three terms in the series i.e., sum of (N – 1)th, (N – 2)th, and (N – 3)th geekonacci numbers." }, { "code": null, "e": 25751, "s": 25741, "text": "Examples:" }, { "code": null, "e": 25900, "s": 25751, "text": "Input: A = 1, B = 3, C = 2, N = 4Output: 6Explanation: The geekonacci series is 1, 3, 2, 6, 11, 19, ......Therefore, the 4th geekonacci number is 6." }, { "code": null, "e": 25944, "s": 25900, "text": "Input: A = 1, B = 3, C = 2, N = 6Output: 19" }, { "code": null, "e": 26128, "s": 25944, "text": "Approach: The given problem can be solved by generating the geekonacci series upto N terms and print the Nth term of the series obtained. Follow the steps below to solve this problem:" }, { "code": null, "e": 26219, "s": 26128, "text": "Initialize an array arr[] of size N and initialize arr[0] = A, arr[1] = B, and arr[2] = C." }, { "code": null, "e": 26401, "s": 26219, "text": "Iterate over the range [3, N – 1] and update the value of each every ith element, i.e. arr[i] as (arr[i – 1] + arr[i – 2] + arr[i – 3]) to get the ith term of the geekonacci series." }, { "code": null, "e": 26519, "s": 26401, "text": "After completing the above steps, print the value of arr[N – 1] as the resultant Nth number of the geekonacci series." }, { "code": null, "e": 26570, "s": 26519, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26574, "s": 26570, "text": "C++" }, { "code": null, "e": 26579, "s": 26574, "text": "Java" }, { "code": null, "e": 26587, "s": 26579, "text": "Python3" }, { "code": null, "e": 26590, "s": 26587, "text": "C#" }, { "code": null, "e": 26601, "s": 26590, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function to calculate the// N-th Geek-onacci Numberint find(int A, int B, int C, int N){ // Stores the geekonacci series int arr[N]; // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (int i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1];} // Driver Codeint main(){ int A = 1, B = 3, C = 2, N = 4; cout<<(find(A, B, C, N)); return 0;} // This code is contributed by mohit kumar 29.", "e": 27402, "s": 26601, "text": null }, { "code": "// Java program for the above approach import java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to calculate the // N-th Geek-onacci Number static int find(int A, int B, int C, int N) { // Stores the geekonacci series int[] arr = new int[N]; // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (int i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1]; } // Driver Code public static void main(String[] args) { int A = 1, B = 3, C = 2, N = 4; System.out.print(find(A, B, C, N)); }}", "e": 28389, "s": 27402, "text": null }, { "code": "# Python3 program for the above approach # Function to calculate the# N-th Geek-onacci Numberdef find(A, B, C, N) : # Stores the geekonacci series arr = [0] * N # Store the first three # terms of the series arr[0] = A arr[1] = B arr[2] = C # Iterate over the range [3, N] for i in range(3, N): # Update the value of arr[i] # as the sum of previous 3 # terms in the series arr[i] = (arr[i - 1] + arr[i - 2] + arr[i - 3]) # Return the last element # of arr[] as the N-th term return arr[N - 1] # Driver CodeA = 1B = 3C = 2N = 4 print(find(A, B, C, N)) # This code is contributed by sanjoy_62.", "e": 29087, "s": 28389, "text": null }, { "code": "// C# program for the above approachusing System; class GFG{ // Function to calculate the // N-th Geek-onacci Number static int find(int A, int B, int C, int N) { // Stores the geekonacci series int[] arr = new int[N]; // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (int i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1]; } // Driver Code public static void Main(string[] args) { int A = 1, B = 3, C = 2, N = 4; Console.Write(find(A, B, C, N)); }} // This code is contributed by code_hunt.", "e": 29937, "s": 29087, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to calculate the // N-th Geek-onacci Number function find(A, B, C, N) { // Stores the geekonacci series let arr = new Array(N).fill(0); // Store the first three // terms of the series arr[0] = A; arr[1] = B; arr[2] = C; // Iterate over the range [3, N] for (let i = 3; i < N; i++) { // Update the value of arr[i] // as the sum of previous 3 // terms in the series arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3]; } // Return the last element // of arr[] as the N-th term return arr[N - 1]; } // Driver code let A = 1, B = 3, C = 2, N = 4; document.write(find(A, B, C, N)); </script>", "e": 30794, "s": 29937, "text": null }, { "code": null, "e": 30796, "s": 30794, "text": "6" }, { "code": null, "e": 30841, "s": 30798, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 30856, "s": 30841, "text": "mohit kumar 29" }, { "code": null, "e": 30866, "s": 30856, "text": "code_hunt" }, { "code": null, "e": 30876, "s": 30866, "text": "sanjoy_62" }, { "code": null, "e": 30891, "s": 30876, "text": "chinmoy1997pal" }, { "code": null, "e": 30898, "s": 30891, "text": "series" }, { "code": null, "e": 30918, "s": 30898, "text": "Dynamic Programming" }, { "code": null, "e": 30931, "s": 30918, "text": "Mathematical" }, { "code": null, "e": 30951, "s": 30931, "text": "Dynamic Programming" }, { "code": null, "e": 30964, "s": 30951, "text": "Mathematical" }, { "code": null, "e": 30971, "s": 30964, "text": "series" }, { "code": null, "e": 31069, "s": 30971, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31078, "s": 31069, "text": "Comments" }, { "code": null, "e": 31091, "s": 31078, "text": "Old Comments" }, { "code": null, "e": 31122, "s": 31091, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 31155, "s": 31122, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 31223, "s": 31155, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 31261, "s": 31223, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 31296, "s": 31261, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 31311, "s": 31296, "text": "C++ Data Types" }, { "code": null, "e": 31371, "s": 31311, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31414, "s": 31371, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 31433, "s": 31414, "text": "Coin Change | DP-7" } ]
Handling Categorical Data, The Right Way | by Eugenio Zuccarelli | Towards Data Science
Categorical data is simply information aggregated into groups rather than being in numeric formats, such as Gender, Sex or Education Level. They are present in almost all real-life datasets, yet the current algorithms still struggle to deal with them. Take, for instance, XGBoost or most SKlearn models. If you try and train them with categorical data, you’ll immediately get an error. Currently, many resources advertise a wide variety of solutions that might seem to work at first, but are deeply wrong once thought through. This is especially true for non-ordinal categorical data, meaning that the classes are not ordered (As it might be for Good=0, Better=1, Best=2). A bit of clarity is needed to distinguish the approaches that Data Scientists should use from those that simply make the models run. One of the simplest and most common solutions advertised to transform categorical variables is Label Encoding. It consists of substituting each group with a corresponding number and keeping such numbering consistent throughout the feature. This solution makes the models run, and it is one of the most commonly used by aspiring Data Scientists. However, its simplicity comes with many issues. Numbers hold relationships. For instance, four is twice two, and, when converting categories into numbers directly, these relationships are created despite not existing between the original categories. Looking at the example before, United Kingdom becomes twice France, and France plus United States equals Germany. Well, that’s not exactly right... This is especially an issue for algorithms, such as K-Means, where a distance measure is calculated when running the model. One-Hot Encoding is the most common, correct way to deal with non-ordinal categorical data. It consists of creating an additional feature for each group of the categorical feature and mark each observation belonging (Value=1) or not (Value=0) to that group. This approach is able to encode categorical features properly, despite some minor drawbacks. Specifically, the presence of a high number of binary values is not ideal for distance-based algorithms, such as Clustering models. In addition, the high number of additionally generated features introduces the curse of dimensionality. This means that due to the now high dimensionality of the dataset, the dataset becomes much more sparse. In other words, in Machine Learning problems, you’d need at least a few samples per each feature combination. Increasing the number of features means that we might encounter cases of not having enough observations for each feature combination. A lesser known, but very effective way of handling categorical variables, is Target Encoding. It consists of substituting each group in a categorical feature with the average response in the target variable. The process to obtain the Target Encoding is relatively straightforward and it can be summarised as: Group the data by categoryCalculate the average of the target variable per each groupAssign the average to each observation belonging to that group Group the data by category Calculate the average of the target variable per each group Assign the average to each observation belonging to that group This can be achieved in a few lines of code: encodings = data.groupby('Country')['Target Variable'].mean().reset_index()data = data.merge(encodings, how='left', on='Country')data.drop('Country', axis=1, inplace=True) Alternatively, we can also use the category_encoders library to use the TargetEncoder functionality. Target Encoding is a powerful solution also because it avoids generating a high number of features, as is the case for One-Hot Encoding, keeping the dimensionality of the dataset as the original one. Handling categorical features is a common task for Data Scientists, but, often, people do not exactly know what are the best practices to correctly tackle them. For non-ordinal categories, Label Encoding, which consists of substituting a category with a relatively random integer, should be avoided at all costs. Instead, One-Hot-Encoding and Target Encoding are preferable solutions. One-Hot Encoding is probably the most common solution, performing well in real-life scenarios. Target Encoding is a lesser-known but promising technique, which also keeps the dimensionality of the dataset consistent, improving performance. To read more articles like this, follow me on Twitter, LinkedIn or my Website.
[ { "code": null, "e": 424, "s": 172, "text": "Categorical data is simply information aggregated into groups rather than being in numeric formats, such as Gender, Sex or Education Level. They are present in almost all real-life datasets, yet the current algorithms still struggle to deal with them." }, { "code": null, "e": 558, "s": 424, "text": "Take, for instance, XGBoost or most SKlearn models. If you try and train them with categorical data, you’ll immediately get an error." }, { "code": null, "e": 978, "s": 558, "text": "Currently, many resources advertise a wide variety of solutions that might seem to work at first, but are deeply wrong once thought through. This is especially true for non-ordinal categorical data, meaning that the classes are not ordered (As it might be for Good=0, Better=1, Best=2). A bit of clarity is needed to distinguish the approaches that Data Scientists should use from those that simply make the models run." }, { "code": null, "e": 1218, "s": 978, "text": "One of the simplest and most common solutions advertised to transform categorical variables is Label Encoding. It consists of substituting each group with a corresponding number and keeping such numbering consistent throughout the feature." }, { "code": null, "e": 1371, "s": 1218, "text": "This solution makes the models run, and it is one of the most commonly used by aspiring Data Scientists. However, its simplicity comes with many issues." }, { "code": null, "e": 1687, "s": 1371, "text": "Numbers hold relationships. For instance, four is twice two, and, when converting categories into numbers directly, these relationships are created despite not existing between the original categories. Looking at the example before, United Kingdom becomes twice France, and France plus United States equals Germany." }, { "code": null, "e": 1721, "s": 1687, "text": "Well, that’s not exactly right..." }, { "code": null, "e": 1845, "s": 1721, "text": "This is especially an issue for algorithms, such as K-Means, where a distance measure is calculated when running the model." }, { "code": null, "e": 2103, "s": 1845, "text": "One-Hot Encoding is the most common, correct way to deal with non-ordinal categorical data. It consists of creating an additional feature for each group of the categorical feature and mark each observation belonging (Value=1) or not (Value=0) to that group." }, { "code": null, "e": 2781, "s": 2103, "text": "This approach is able to encode categorical features properly, despite some minor drawbacks. Specifically, the presence of a high number of binary values is not ideal for distance-based algorithms, such as Clustering models. In addition, the high number of additionally generated features introduces the curse of dimensionality. This means that due to the now high dimensionality of the dataset, the dataset becomes much more sparse. In other words, in Machine Learning problems, you’d need at least a few samples per each feature combination. Increasing the number of features means that we might encounter cases of not having enough observations for each feature combination." }, { "code": null, "e": 2989, "s": 2781, "text": "A lesser known, but very effective way of handling categorical variables, is Target Encoding. It consists of substituting each group in a categorical feature with the average response in the target variable." }, { "code": null, "e": 3090, "s": 2989, "text": "The process to obtain the Target Encoding is relatively straightforward and it can be summarised as:" }, { "code": null, "e": 3238, "s": 3090, "text": "Group the data by categoryCalculate the average of the target variable per each groupAssign the average to each observation belonging to that group" }, { "code": null, "e": 3265, "s": 3238, "text": "Group the data by category" }, { "code": null, "e": 3325, "s": 3265, "text": "Calculate the average of the target variable per each group" }, { "code": null, "e": 3388, "s": 3325, "text": "Assign the average to each observation belonging to that group" }, { "code": null, "e": 3433, "s": 3388, "text": "This can be achieved in a few lines of code:" }, { "code": null, "e": 3605, "s": 3433, "text": "encodings = data.groupby('Country')['Target Variable'].mean().reset_index()data = data.merge(encodings, how='left', on='Country')data.drop('Country', axis=1, inplace=True)" }, { "code": null, "e": 3706, "s": 3605, "text": "Alternatively, we can also use the category_encoders library to use the TargetEncoder functionality." }, { "code": null, "e": 3906, "s": 3706, "text": "Target Encoding is a powerful solution also because it avoids generating a high number of features, as is the case for One-Hot Encoding, keeping the dimensionality of the dataset as the original one." }, { "code": null, "e": 4067, "s": 3906, "text": "Handling categorical features is a common task for Data Scientists, but, often, people do not exactly know what are the best practices to correctly tackle them." }, { "code": null, "e": 4219, "s": 4067, "text": "For non-ordinal categories, Label Encoding, which consists of substituting a category with a relatively random integer, should be avoided at all costs." }, { "code": null, "e": 4531, "s": 4219, "text": "Instead, One-Hot-Encoding and Target Encoding are preferable solutions. One-Hot Encoding is probably the most common solution, performing well in real-life scenarios. Target Encoding is a lesser-known but promising technique, which also keeps the dimensionality of the dataset consistent, improving performance." } ]
How to get objects by ID, Class, Tag, and Attribute in jQuery?
Here’s how you can get objects by ID Selector (#id), by Class Selector (.class), by Tag, and Attribute (.attr()). Get Object by Class Selector The element class selector selects all the elements which match with the given class of the elements. Live Demo <html> <head> <title>jQuery Selector</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function() { $(".big").css("background-color", "yellow"); }); </script> </head> <body> <div class = "big" id="div1"> <p>This is first division of the DOM.</p> </div> <div class = "medium" id = "div2"> <p>This is second division of the DOM.</p> </div> </body> </html> Get Object by ID Selector The element ID selector selects a single element with the given id attribute: Live Demo <html> <head> <title>jQuery Selector</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(function(){ $("#submit").click(function(){ alert($('input:radio:checked').val()); }); }); </script> </head> <body> <form id="myForm"> Select a number:<br> <input type="radio" name="q1" value="1">1 <input type="radio" name="q1" value="2">2 <input type="radio" name="q1" value="3">3<br> <button id="submit">Result</button> </form> </body> </html> Get Object by Tag For this, pass the name of the specific tag i.e. <a> tag below: Live Demo <html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("a").click(function(){ $("a.active").removeClass("active"); $(this).addClass("active"); }); }); </script> <style> .active { font-size: 22px; } </style> </head> <body> <a href="#" class="">One</a> <a href="#" class="">Two</a> <p>Click any of the link above and you can see the changes.</p> </body> </html> Get Object by Attribute Using the .attr(), you can get any attribute of any tag. Here’s an example showing how to get an attribute value: Live Demo <html> <head> <title>jQuery Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("img").attr("height", "200"); }); }); </script> </head> <body> <img src="/green/images/logo.png" alt="logo" width="450" height="160"><br> <button>Change the height</button> </body> </html>
[ { "code": null, "e": 1176, "s": 1062, "text": "Here’s how you can get objects by ID Selector (#id), by Class Selector (.class), by Tag, and Attribute (.attr())." }, { "code": null, "e": 1205, "s": 1176, "text": "Get Object by Class Selector" }, { "code": null, "e": 1307, "s": 1205, "text": "The element class selector selects all the elements which match with the given class of the elements." }, { "code": null, "e": 1317, "s": 1307, "text": "Live Demo" }, { "code": null, "e": 1870, "s": 1317, "text": "<html>\n <head>\n <title>jQuery Selector</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n \n <script>\n $(document).ready(function() { \n $(\".big\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n \n <body>\n\n <div class = \"big\" id=\"div1\">\n <p>This is first division of the DOM.</p>\n </div>\n\n <div class = \"medium\" id = \"div2\">\n <p>This is second division of the DOM.</p>\n </div>\n\n </body>\n</html>" }, { "code": null, "e": 1896, "s": 1870, "text": "Get Object by ID Selector" }, { "code": null, "e": 1974, "s": 1896, "text": "The element ID selector selects a single element with the given id attribute:" }, { "code": null, "e": 1984, "s": 1974, "text": "Live Demo" }, { "code": null, "e": 2627, "s": 1984, "text": "<html>\n <head>\n <title>jQuery Selector</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(function(){\n $(\"#submit\").click(function(){ \n alert($('input:radio:checked').val());\n });\n });\n </script>\n </head>\n <body>\n <form id=\"myForm\">\n Select a number:<br>\n <input type=\"radio\" name=\"q1\" value=\"1\">1\n <input type=\"radio\" name=\"q1\" value=\"2\">2\n <input type=\"radio\" name=\"q1\" value=\"3\">3<br>\n <button id=\"submit\">Result</button>\n </form>\n </body>\n</html>" }, { "code": null, "e": 2645, "s": 2627, "text": "Get Object by Tag" }, { "code": null, "e": 2709, "s": 2645, "text": "For this, pass the name of the specific tag i.e. <a> tag below:" }, { "code": null, "e": 2719, "s": 2709, "text": "Live Demo" }, { "code": null, "e": 3325, "s": 2719, "text": "<html>\n <head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\"a\").click(function(){\n $(\"a.active\").removeClass(\"active\");\n $(this).addClass(\"active\");\n });\n });\n </script>\n <style>\n .active {\n font-size: 22px; \n }\n </style>\n </head>\n <body>\n <a href=\"#\" class=\"\">One</a>\n <a href=\"#\" class=\"\">Two</a>\n <p>Click any of the link above and you can see the changes.</p>\n </body>\n</html>" }, { "code": null, "e": 3349, "s": 3325, "text": "Get Object by Attribute" }, { "code": null, "e": 3463, "s": 3349, "text": "Using the .attr(), you can get any attribute of any tag. Here’s an example showing how to get an attribute value:" }, { "code": null, "e": 3473, "s": 3463, "text": "Live Demo" }, { "code": null, "e": 3968, "s": 3473, "text": "<html>\n\n <head>\n <title>jQuery Example</title>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n\n <script>\n $(document).ready(function(){\n $(\"button\").click(function(){\n $(\"img\").attr(\"height\", \"200\");\n });\n });\n </script>\n </head>\n \n <body>\n <img src=\"/green/images/logo.png\" alt=\"logo\" width=\"450\" height=\"160\"><br>\n <button>Change the height</button>\n </body>\n \n</html>" } ]
How to change the Tkinter label text? - GeeksforGeeks
22 Jul, 2021 Prerequisites: Introduction to tkinter Tkinter is a standard GUI (Graphical user interface) package for python. It provides a fast and easy way of creating a GUI application. To create a tkinter application: Importing the module — tkinter Create the main window (container) Add any number of widgets to the main window. Apply the event Trigger on the widgets. Widgets are the controlling tools for any GUI application. Here widget’s main role is to provide a good variety of control. Some widgets are buttons, labels, text boxes, and many more. One of its widgets is the label, which is responsible for implementing a display box-section for text and images. Click here For knowing more about the Tkinter label widget. Now, let’ see how To change the text of the label: Method 1: Using Label.config() method. Syntax: Label.config(text) Parameter: text– The text to display in the label. This method is used for performing an overwriting over label widget. Example: Python3 # importing everything from tkinterfrom tkinter import * # creating the tkinter windowMain_window = Tk() # variablemy_text = "GeeksforGeeks updated !!!" # function define for# updating the my_label# widget contentdef counter(): # use global variable global my_text # configure my_label.config(text = my_text) # create a button widget and attached # with counter function my_button = Button(Main_window, text = "Please update", command = counter) # create a Label widgetmy_label = Label(Main_window, text = "geeksforgeeks") # place the widgets# in the gui windowmy_label.pack()my_button.pack() # Start the GUIMain_window.mainloop() Output: Method 2: Using StringVar() class. Syntax: StringVar() Return: String variable object This class is used the for setting the values and changing it according to the requirements. Python3 # importing everything from tkinterfrom tkinter import * # create gui windowMain_window = Tk() # set the configuration# of the windowMain_window.geometry("220x100") # define a function# for setting the new textdef java(): my_string_var.set("You must go with Java") # define a function# for setting the new textdef python(): my_string_var.set("You must go with Python") # create a Button widget and attached # with java function btn_1 = Button(Main_window, text = "I love Android", command = java) # create a Button widget and attached # with python functionbtn_2 = Button(Main_window, text = "I love Machine Learning", command = python) # create a StringVar classmy_string_var = StringVar() # set the textmy_string_var.set("What should I learn") # create a label widgetmy_label = Label(Main_window, textvariable = my_string_var) # place widgets into# the gui windowbtn_1.pack()btn_2.pack()my_label.pack() # Start the GUI Main_window.mainloop() manikarora059 Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23925, "s": 23897, "text": "\n22 Jul, 2021" }, { "code": null, "e": 23964, "s": 23925, "text": "Prerequisites: Introduction to tkinter" }, { "code": null, "e": 24100, "s": 23964, "text": "Tkinter is a standard GUI (Graphical user interface) package for python. It provides a fast and easy way of creating a GUI application." }, { "code": null, "e": 24133, "s": 24100, "text": "To create a tkinter application:" }, { "code": null, "e": 24164, "s": 24133, "text": "Importing the module — tkinter" }, { "code": null, "e": 24199, "s": 24164, "text": "Create the main window (container)" }, { "code": null, "e": 24245, "s": 24199, "text": "Add any number of widgets to the main window." }, { "code": null, "e": 24285, "s": 24245, "text": "Apply the event Trigger on the widgets." }, { "code": null, "e": 24471, "s": 24285, "text": "Widgets are the controlling tools for any GUI application. Here widget’s main role is to provide a good variety of control. Some widgets are buttons, labels, text boxes, and many more. " }, { "code": null, "e": 24645, "s": 24471, "text": "One of its widgets is the label, which is responsible for implementing a display box-section for text and images. Click here For knowing more about the Tkinter label widget." }, { "code": null, "e": 24696, "s": 24645, "text": "Now, let’ see how To change the text of the label:" }, { "code": null, "e": 24735, "s": 24696, "text": "Method 1: Using Label.config() method." }, { "code": null, "e": 24762, "s": 24735, "text": "Syntax: Label.config(text)" }, { "code": null, "e": 24814, "s": 24762, "text": "Parameter: text– The text to display in the label. " }, { "code": null, "e": 24883, "s": 24814, "text": "This method is used for performing an overwriting over label widget." }, { "code": null, "e": 24892, "s": 24883, "text": "Example:" }, { "code": null, "e": 24900, "s": 24892, "text": "Python3" }, { "code": "# importing everything from tkinterfrom tkinter import * # creating the tkinter windowMain_window = Tk() # variablemy_text = \"GeeksforGeeks updated !!!\" # function define for# updating the my_label# widget contentdef counter(): # use global variable global my_text # configure my_label.config(text = my_text) # create a button widget and attached # with counter function my_button = Button(Main_window, text = \"Please update\", command = counter) # create a Label widgetmy_label = Label(Main_window, text = \"geeksforgeeks\") # place the widgets# in the gui windowmy_label.pack()my_button.pack() # Start the GUIMain_window.mainloop()", "e": 25605, "s": 24900, "text": null }, { "code": null, "e": 25615, "s": 25605, "text": " Output:" }, { "code": null, "e": 25654, "s": 25619, "text": "Method 2: Using StringVar() class." }, { "code": null, "e": 25676, "s": 25656, "text": "Syntax: StringVar()" }, { "code": null, "e": 25707, "s": 25676, "text": "Return: String variable object" }, { "code": null, "e": 25802, "s": 25707, "text": " This class is used the for setting the values and changing it according to the requirements. " }, { "code": null, "e": 25810, "s": 25802, "text": "Python3" }, { "code": "# importing everything from tkinterfrom tkinter import * # create gui windowMain_window = Tk() # set the configuration# of the windowMain_window.geometry(\"220x100\") # define a function# for setting the new textdef java(): my_string_var.set(\"You must go with Java\") # define a function# for setting the new textdef python(): my_string_var.set(\"You must go with Python\") # create a Button widget and attached # with java function btn_1 = Button(Main_window, text = \"I love Android\", command = java) # create a Button widget and attached # with python functionbtn_2 = Button(Main_window, text = \"I love Machine Learning\", command = python) # create a StringVar classmy_string_var = StringVar() # set the textmy_string_var.set(\"What should I learn\") # create a label widgetmy_label = Label(Main_window, textvariable = my_string_var) # place widgets into# the gui windowbtn_1.pack()btn_2.pack()my_label.pack() # Start the GUI Main_window.mainloop()", "e": 26838, "s": 25810, "text": null }, { "code": null, "e": 26856, "s": 26842, "text": "manikarora059" }, { "code": null, "e": 26871, "s": 26856, "text": "Python-tkinter" }, { "code": null, "e": 26878, "s": 26871, "text": "Python" }, { "code": null, "e": 26976, "s": 26878, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26985, "s": 26976, "text": "Comments" }, { "code": null, "e": 26998, "s": 26985, "text": "Old Comments" }, { "code": null, "e": 27030, "s": 26998, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27086, "s": 27030, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27128, "s": 27086, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27170, "s": 27128, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27206, "s": 27170, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 27245, "s": 27206, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27267, "s": 27245, "text": "Defaultdict in Python" }, { "code": null, "e": 27298, "s": 27267, "text": "Python | os.path.join() method" }, { "code": null, "e": 27325, "s": 27298, "text": "Python Classes and Objects" } ]
LCM of N numbers modulo M - GeeksforGeeks
20 Sep, 2021 Given an array arr[] of integers, the task is to find the LCM of all the elements of the array modulo M where M = 109 + 7.Examples: Input: arr[] = {10000000, 12345, 159873} Output: 780789722 LCM of (10000000, 12345, 159873) is 1315754790000000 1315754790000000 % 1000000007 = 780789722Input: arr[] = {10, 13, 15} Output: 390 Approach: If you have gone through the post that calculates LCM of array elements, the first approach that comes to mind is to take modulo at every step when LCM of ans and arr[i] is being calculated. ans = 1 // For i = 1 to n – 1 ans = lcm(ans, arr[i]) % 1000000007 // Wrong approach However, this approach is wrong and the mistake can be realized in the following example: Take M = 41 and arr[] = {13, 18, 30}Incorrect solution: LCM(13, 18, 30) % 41 LCM(LCM(13, 18) % 41, 30) % 41 LCM(234 % 41, 30) % 41 LCM(29, 30) % 41 870 % 41 9Correct solution: LCM(13, 18, 30) % 41 LCM(LCM(13, 18), 30) % 41 LCM(234, 30) % 41 1170 % 41 22 Note: Whenever the LCM of 2 numbers becomes > M, the approach doesn’t work.The correct approach is to prime factorize the elements of the array and keep track of the highest power of every prime for each element. LCM will be the product of these primes raised to their highest power in the array.Illustration: Let elements be [36, 480, 500, 343] Prime factorization results: 36 = 22 * 32 480 = 25 * 3 * 5 500 = 22 * 53 343 = 73 Highest power of 2 amongt all array elements = Max(2, 5, 2, 0) = 5 Highest power of 3 amongt all array elements = Max(2, 1, 0, 0) = 2 Highest power of 5 amongt all array elements = Max(0, 1, 3, 0) = 3 Highest power of 7 amongt all array elements = Max(0, 0, 0, 3) = 3Therefore, LCM = 25 * 32 * 53 * 73 = 12348000 Let p be a prime factor of an element of the array and x be its highest power in the whole array. Then, Using the above formula, we can easily calculate the LCM of the whole array and our problem of MOD will also be solved. Simplifying the expression, we get: Since modulo operation is distributive over multiplication, we can safely write the following expression. Now, the problem arises as to how to compute prime factors and their powers efficiently. For that, we can use the sieve of Eratosthenes. Refer to this post: Using Sieve to compute prime factors and their powers.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to compute LCM of array elements modulo M#include <bits/stdc++.h>#define F first#define S second#define MAX 10000003using namespace std; typedef long long ll;const int mod = 1000000007; int prime[MAX];unordered_map<int, int> max_map; // Function to return a^nint power(int a, int n){ if (n == 0) return 1; int p = power(a, n / 2) % mod; p = (p * p) % mod; if (n & 1) p = (p * a) % mod; return p;} // Function to find the smallest prime factors// of numbers upto MAXvoid sieve(){ prime[0] = prime[1] = 1; for (int i = 2; i < MAX; i++) { if (prime[i] == 0) { for (int j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } prime[i] = i; } }} // Function to return the LCM modulo Mll lcmModuloM(const int* ar, int n){ for (int i = 0; i < n; i++) { int num = ar[i]; unordered_map<int, int> temp; // Temp stores mapping of prime factor to // its power for the current element while (num > 1) { // Factor is the smallest prime factor of num int factor = prime[num]; // Increase count of factor in temp temp[factor]++; // Reduce num by its prime factor num /= factor; } for (auto it : temp) { // Store the highest power of every prime // found till now in a new map max_map max_map[it.first] = max(max_map[it.first], it.second); } } ll ans = 1; for (auto it : max_map) { // LCM is product of primes to their highest powers modulo M ans = (ans * power(it.F, it.S)) % mod; } return ans;} // Driver codeint main(){ sieve(); int arr[] = { 36, 500, 480, 343 }; int n = sizeof(arr) / sizeof(arr[0]); cout << lcmModuloM(arr, n); return 0;} // Java program to compute LCM of// array elements modulo Mimport java.util.*; class GFG{ final static int MAX = 10000003;final static int mod = 1000000007;static int[] prime = new int[MAX]; // Function to return a^n public static int power(int a, int n){ if(n == 0) return 1; int p = power(a, n / 2) % mod; p = (p * p) % mod; if((n & 1) > 0) p = (p * a) % mod; return p;} // Function to find the smallest prime// factors of numbers upto MAXpublic static void sieve(){ prime[0] = 1; prime[1] = 1; for(int i = 2; i < MAX; i++) { if(prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if(prime[j] == 0) { prime[j] = i; } } prime[i] = i; } } } // Function to return the LCM modulo M public static long lcmModuloM(int[] arr, int n){ HashMap<Integer, Integer> maxMap = new HashMap<>(); for(int i = 0; i < n; i++) { HashMap<Integer, Integer> temp = new HashMap<>(); int num = arr[i]; // Temp stores mapping of prime // factor to its power for the // current element while(num > 1) { // Factor is the smallest prime // factor of num int factor = prime[num]; if(temp.containsKey(factor)) temp.put(factor, temp.get(factor) + 1); else temp.put(factor, 1); // Factor is the smallest prime // factor of num num = num / factor; } for(Map.Entry<Integer, Integer> m : temp.entrySet()) { if(maxMap.containsKey(m.getKey())) { int maxPower = Math.max(m.getValue(), maxMap.get( m.getKey())); maxMap.put(m.getKey(), maxPower); } else { maxMap.put(m.getKey(),m.getValue()); } } } long ans = 1; for(Map.Entry<Integer, Integer> m : maxMap.entrySet()) { // LCM is product of primes to their // highest powers modulo M ans = (ans * power(m.getKey(), m.getValue()) % mod); } return ans;} // Driver code public static void main(String[] args){ sieve(); int[] arr = new int[]{36, 500, 480, 343 }; int n = arr.length; System.out.println(lcmModuloM(arr, n));}} // This code is contributed by parshavnahta97 # Python3 program to compute LCM of# array elements modulo MMAX = 10000003 mod = 1000000007 prime = [0 for i in range(MAX)] max_map = dict() # function to return a^ndef power(a, n): if n == 0: return 1 p = power(a, n // 2) % mod p = (p * p) % mod if n & 1: p = (p * a) % mod return p # function to find the smallest prime# factors of numbers upto MAXdef sieve(): prime[0], prime[1] = 1, 1 for i in range(2, MAX): if prime[i] == 0: for j in range(i * 2, MAX, i): if prime[j] == 0: prime[j] = i prime[i] = i # function to return the LCM modulo Mdef lcmModuloM(arr, n): for i in range(n): num = arr[i] temp = dict() # temp stores mapping of prime factors # to its power for the current element while num > 1: # factor is the smallest prime # factor of num factor = prime[num] # Increase count of factor in temp if factor in temp.keys(): temp[factor] += 1 else: temp[factor] = 1 # Reduce num by its prime factor num = num // factor for i in temp: # store the highest power of every prime # found till now in a new map max_map if i in max_map.keys(): max_map[i] = max(max_map[i], temp[i]) else: max_map[i] = temp[i] ans = 1 for i in max_map: # LCM is product of primes to their # highest powers modulo M ans = (ans * power(i, max_map[i])) % mod return ans # Driver codesieve()arr = [36, 500, 480, 343]n = len(arr)print(lcmModuloM(arr, n)) # This code is contributed# by Mohit kumar 29 // C# program to compute LCM of// array elements modulo Musing System;using System.Collections.Generic;class GFG{ readonly static int MAX = 10000003;readonly static int mod = 1000000007;static int[] prime = new int[MAX]; // Function to return a^n public static int power(int a, int n){ if(n == 0) return 1; int p = power(a, n / 2) % mod; p = (p * p) % mod; if((n & 1) > 0) p = (p * a) % mod; return p;} // Function to find the smallest// prime factors of numbers upto// MAXpublic static void sieve(){ prime[0] = 1; prime[1] = 1; for(int i = 2; i < MAX; i++) { if(prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if(prime[j] == 0) { prime[j] = i; } } prime[i] = i; } } } // Function to return the// LCM modulo M public static long lcmModuloM(int[] arr, int n){ Dictionary<int, int> maxMap = new Dictionary<int, int>(); for(int i = 0; i < n; i++) { Dictionary<int, int> temp = new Dictionary<int, int>(); int num = arr[i]; // Temp stores mapping of prime // factor to its power for the // current element while(num > 1) { // Factor is the smallest // prime factor of num int factor = prime[num]; if(temp.ContainsKey(factor)) temp[factor]++; else temp.Add(factor, 1); // Factor is the smallest // prime factor of num num = num / factor; } foreach(KeyValuePair<int, int> m in temp) { if(maxMap.ContainsKey(m.Key)) { int maxPower = Math.Max(m.Value, maxMap[m.Key]); maxMap[m.Key] = maxPower; } else { maxMap.Add(m.Key,m.Value); } } } long ans = 1; foreach(KeyValuePair<int, int> m in maxMap) { // LCM is product of primes to their // highest powers modulo M ans = (ans * power(m.Key, m.Value) % mod); } return ans;} // Driver code public static void Main(String[] args){ sieve(); int[] arr = new int[]{36, 500, 480, 343}; int n = arr.Length; Console.WriteLine(lcmModuloM(arr, n));}} // This code is contributed by 29AjayKumar <script> // Javascript program to compute LCM of// array elements modulo Mlet MAX = 10000003;let mod = 1000000007;let prime = new Array(MAX);for(let i = 0; i < MAX; i++){ prime[i] = 0;} // Function to return a^n function power(a, n){ if(n == 0) return 1; let p = power(a, n / 2) % mod; p = (p * p) % mod; if((n & 1) > 0) p = (p * a) % mod; return p;} // Function to find the smallest prime// factors of numbers upto MAXfunction sieve(){ prime[0] = 1; prime[1] = 1; for(let i = 2; i < MAX; i++) { if(prime[i] == 0) { for(let j = i * 2; j < MAX; j += i) { if(prime[j] == 0) { prime[j] = i; } } prime[i] = i; } }} // Function to return the LCM modulo M function lcmModuloM(arr,n){ let maxMap = new Map(); for(let i = 0; i < n; i++) { let temp = new Map(); let num = arr[i]; // Temp stores mapping of prime // factor to its power for the // current element while(num > 1) { // Factor is the smallest prime // factor of num let factor = prime[num]; if(temp.has(factor)) temp.set(factor, temp.get(factor) + 1); else temp.set(factor, 1); // Factor is the smallest prime // factor of num num = num / factor; } for(let [key, value] of temp.entries()) { if(maxMap.has(key)) { let maxPower = Math.max(value, maxMap.get( key)); maxMap.set(key, maxPower); } else { maxMap.set(key,value); } } } let ans = 1; for(let [key, value] of maxMap.entries()) { // LCM is product of primes to their // highest powers modulo M ans = (ans * power(key, value) % mod); } return ans;} // Driver code sieve();let arr = [36, 500, 480, 343];let n = arr.length;document.write(lcmModuloM(arr, n)); // This code is contributed by unknown2108.</script> 12348000 The above code works for the following constraints: References: https://stackoverflow.com/questions/16633449/calculate-lcm-of-n-numbers-modulo-1000000007 mohit kumar 29 parshavnahta97 29AjayKumar unknown2108 gulshankumarar231 GCD-LCM Modular Arithmetic Technical Scripter 2018 Competitive Programming Mathematical Technical Scripter Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Formatted output in Java Algorithm Library | C++ Magicians STL Algorithm Use of FLAG in programming Setting up Sublime Text for C++ Competitive Programming Environment How to overcome Time Limit Exceed(TLE)? Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24551, "s": 24523, "text": "\n20 Sep, 2021" }, { "code": null, "e": 24684, "s": 24551, "text": "Given an array arr[] of integers, the task is to find the LCM of all the elements of the array modulo M where M = 109 + 7.Examples: " }, { "code": null, "e": 24879, "s": 24684, "text": "Input: arr[] = {10000000, 12345, 159873} Output: 780789722 LCM of (10000000, 12345, 159873) is 1315754790000000 1315754790000000 % 1000000007 = 780789722Input: arr[] = {10, 13, 15} Output: 390 " }, { "code": null, "e": 25082, "s": 24879, "text": "Approach: If you have gone through the post that calculates LCM of array elements, the first approach that comes to mind is to take modulo at every step when LCM of ans and arr[i] is being calculated. " }, { "code": null, "e": 25168, "s": 25082, "text": "ans = 1 // For i = 1 to n – 1 ans = lcm(ans, arr[i]) % 1000000007 // Wrong approach " }, { "code": null, "e": 25260, "s": 25168, "text": "However, this approach is wrong and the mistake can be realized in the following example: " }, { "code": null, "e": 25515, "s": 25260, "text": "Take M = 41 and arr[] = {13, 18, 30}Incorrect solution: LCM(13, 18, 30) % 41 LCM(LCM(13, 18) % 41, 30) % 41 LCM(234 % 41, 30) % 41 LCM(29, 30) % 41 870 % 41 9Correct solution: LCM(13, 18, 30) % 41 LCM(LCM(13, 18), 30) % 41 LCM(234, 30) % 41 1170 % 41 22 " }, { "code": null, "e": 25827, "s": 25515, "text": "Note: Whenever the LCM of 2 numbers becomes > M, the approach doesn’t work.The correct approach is to prime factorize the elements of the array and keep track of the highest power of every prime for each element. LCM will be the product of these primes raised to their highest power in the array.Illustration: " }, { "code": null, "e": 26260, "s": 25827, "text": "Let elements be [36, 480, 500, 343] Prime factorization results: 36 = 22 * 32 480 = 25 * 3 * 5 500 = 22 * 53 343 = 73 Highest power of 2 amongt all array elements = Max(2, 5, 2, 0) = 5 Highest power of 3 amongt all array elements = Max(2, 1, 0, 0) = 2 Highest power of 5 amongt all array elements = Max(0, 1, 3, 0) = 3 Highest power of 7 amongt all array elements = Max(0, 0, 0, 3) = 3Therefore, LCM = 25 * 32 * 53 * 73 = 12348000 " }, { "code": null, "e": 26364, "s": 26260, "text": "Let p be a prime factor of an element of the array and x be its highest power in the whole array. Then," }, { "code": null, "e": 26520, "s": 26364, "text": "Using the above formula, we can easily calculate the LCM of the whole array and our problem of MOD will also be solved. Simplifying the expression, we get:" }, { "code": null, "e": 26627, "s": 26520, "text": "Since modulo operation is distributive over multiplication, we can safely write the following expression. " }, { "code": null, "e": 26891, "s": 26627, "text": "Now, the problem arises as to how to compute prime factors and their powers efficiently. For that, we can use the sieve of Eratosthenes. Refer to this post: Using Sieve to compute prime factors and their powers.Below is the implementation of the above approach: " }, { "code": null, "e": 26895, "s": 26891, "text": "C++" }, { "code": null, "e": 26900, "s": 26895, "text": "Java" }, { "code": null, "e": 26908, "s": 26900, "text": "Python3" }, { "code": null, "e": 26911, "s": 26908, "text": "C#" }, { "code": null, "e": 26922, "s": 26911, "text": "Javascript" }, { "code": "// C++ program to compute LCM of array elements modulo M#include <bits/stdc++.h>#define F first#define S second#define MAX 10000003using namespace std; typedef long long ll;const int mod = 1000000007; int prime[MAX];unordered_map<int, int> max_map; // Function to return a^nint power(int a, int n){ if (n == 0) return 1; int p = power(a, n / 2) % mod; p = (p * p) % mod; if (n & 1) p = (p * a) % mod; return p;} // Function to find the smallest prime factors// of numbers upto MAXvoid sieve(){ prime[0] = prime[1] = 1; for (int i = 2; i < MAX; i++) { if (prime[i] == 0) { for (int j = i * 2; j < MAX; j += i) { if (prime[j] == 0) { prime[j] = i; } } prime[i] = i; } }} // Function to return the LCM modulo Mll lcmModuloM(const int* ar, int n){ for (int i = 0; i < n; i++) { int num = ar[i]; unordered_map<int, int> temp; // Temp stores mapping of prime factor to // its power for the current element while (num > 1) { // Factor is the smallest prime factor of num int factor = prime[num]; // Increase count of factor in temp temp[factor]++; // Reduce num by its prime factor num /= factor; } for (auto it : temp) { // Store the highest power of every prime // found till now in a new map max_map max_map[it.first] = max(max_map[it.first], it.second); } } ll ans = 1; for (auto it : max_map) { // LCM is product of primes to their highest powers modulo M ans = (ans * power(it.F, it.S)) % mod; } return ans;} // Driver codeint main(){ sieve(); int arr[] = { 36, 500, 480, 343 }; int n = sizeof(arr) / sizeof(arr[0]); cout << lcmModuloM(arr, n); return 0;}", "e": 28824, "s": 26922, "text": null }, { "code": "// Java program to compute LCM of// array elements modulo Mimport java.util.*; class GFG{ final static int MAX = 10000003;final static int mod = 1000000007;static int[] prime = new int[MAX]; // Function to return a^n public static int power(int a, int n){ if(n == 0) return 1; int p = power(a, n / 2) % mod; p = (p * p) % mod; if((n & 1) > 0) p = (p * a) % mod; return p;} // Function to find the smallest prime// factors of numbers upto MAXpublic static void sieve(){ prime[0] = 1; prime[1] = 1; for(int i = 2; i < MAX; i++) { if(prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if(prime[j] == 0) { prime[j] = i; } } prime[i] = i; } } } // Function to return the LCM modulo M public static long lcmModuloM(int[] arr, int n){ HashMap<Integer, Integer> maxMap = new HashMap<>(); for(int i = 0; i < n; i++) { HashMap<Integer, Integer> temp = new HashMap<>(); int num = arr[i]; // Temp stores mapping of prime // factor to its power for the // current element while(num > 1) { // Factor is the smallest prime // factor of num int factor = prime[num]; if(temp.containsKey(factor)) temp.put(factor, temp.get(factor) + 1); else temp.put(factor, 1); // Factor is the smallest prime // factor of num num = num / factor; } for(Map.Entry<Integer, Integer> m : temp.entrySet()) { if(maxMap.containsKey(m.getKey())) { int maxPower = Math.max(m.getValue(), maxMap.get( m.getKey())); maxMap.put(m.getKey(), maxPower); } else { maxMap.put(m.getKey(),m.getValue()); } } } long ans = 1; for(Map.Entry<Integer, Integer> m : maxMap.entrySet()) { // LCM is product of primes to their // highest powers modulo M ans = (ans * power(m.getKey(), m.getValue()) % mod); } return ans;} // Driver code public static void main(String[] args){ sieve(); int[] arr = new int[]{36, 500, 480, 343 }; int n = arr.length; System.out.println(lcmModuloM(arr, n));}} // This code is contributed by parshavnahta97", "e": 31526, "s": 28824, "text": null }, { "code": "# Python3 program to compute LCM of# array elements modulo MMAX = 10000003 mod = 1000000007 prime = [0 for i in range(MAX)] max_map = dict() # function to return a^ndef power(a, n): if n == 0: return 1 p = power(a, n // 2) % mod p = (p * p) % mod if n & 1: p = (p * a) % mod return p # function to find the smallest prime# factors of numbers upto MAXdef sieve(): prime[0], prime[1] = 1, 1 for i in range(2, MAX): if prime[i] == 0: for j in range(i * 2, MAX, i): if prime[j] == 0: prime[j] = i prime[i] = i # function to return the LCM modulo Mdef lcmModuloM(arr, n): for i in range(n): num = arr[i] temp = dict() # temp stores mapping of prime factors # to its power for the current element while num > 1: # factor is the smallest prime # factor of num factor = prime[num] # Increase count of factor in temp if factor in temp.keys(): temp[factor] += 1 else: temp[factor] = 1 # Reduce num by its prime factor num = num // factor for i in temp: # store the highest power of every prime # found till now in a new map max_map if i in max_map.keys(): max_map[i] = max(max_map[i], temp[i]) else: max_map[i] = temp[i] ans = 1 for i in max_map: # LCM is product of primes to their # highest powers modulo M ans = (ans * power(i, max_map[i])) % mod return ans # Driver codesieve()arr = [36, 500, 480, 343]n = len(arr)print(lcmModuloM(arr, n)) # This code is contributed# by Mohit kumar 29", "e": 33388, "s": 31526, "text": null }, { "code": "// C# program to compute LCM of// array elements modulo Musing System;using System.Collections.Generic;class GFG{ readonly static int MAX = 10000003;readonly static int mod = 1000000007;static int[] prime = new int[MAX]; // Function to return a^n public static int power(int a, int n){ if(n == 0) return 1; int p = power(a, n / 2) % mod; p = (p * p) % mod; if((n & 1) > 0) p = (p * a) % mod; return p;} // Function to find the smallest// prime factors of numbers upto// MAXpublic static void sieve(){ prime[0] = 1; prime[1] = 1; for(int i = 2; i < MAX; i++) { if(prime[i] == 0) { for(int j = i * 2; j < MAX; j += i) { if(prime[j] == 0) { prime[j] = i; } } prime[i] = i; } } } // Function to return the// LCM modulo M public static long lcmModuloM(int[] arr, int n){ Dictionary<int, int> maxMap = new Dictionary<int, int>(); for(int i = 0; i < n; i++) { Dictionary<int, int> temp = new Dictionary<int, int>(); int num = arr[i]; // Temp stores mapping of prime // factor to its power for the // current element while(num > 1) { // Factor is the smallest // prime factor of num int factor = prime[num]; if(temp.ContainsKey(factor)) temp[factor]++; else temp.Add(factor, 1); // Factor is the smallest // prime factor of num num = num / factor; } foreach(KeyValuePair<int, int> m in temp) { if(maxMap.ContainsKey(m.Key)) { int maxPower = Math.Max(m.Value, maxMap[m.Key]); maxMap[m.Key] = maxPower; } else { maxMap.Add(m.Key,m.Value); } } } long ans = 1; foreach(KeyValuePair<int, int> m in maxMap) { // LCM is product of primes to their // highest powers modulo M ans = (ans * power(m.Key, m.Value) % mod); } return ans;} // Driver code public static void Main(String[] args){ sieve(); int[] arr = new int[]{36, 500, 480, 343}; int n = arr.Length; Console.WriteLine(lcmModuloM(arr, n));}} // This code is contributed by 29AjayKumar", "e": 35804, "s": 33388, "text": null }, { "code": "<script> // Javascript program to compute LCM of// array elements modulo Mlet MAX = 10000003;let mod = 1000000007;let prime = new Array(MAX);for(let i = 0; i < MAX; i++){ prime[i] = 0;} // Function to return a^n function power(a, n){ if(n == 0) return 1; let p = power(a, n / 2) % mod; p = (p * p) % mod; if((n & 1) > 0) p = (p * a) % mod; return p;} // Function to find the smallest prime// factors of numbers upto MAXfunction sieve(){ prime[0] = 1; prime[1] = 1; for(let i = 2; i < MAX; i++) { if(prime[i] == 0) { for(let j = i * 2; j < MAX; j += i) { if(prime[j] == 0) { prime[j] = i; } } prime[i] = i; } }} // Function to return the LCM modulo M function lcmModuloM(arr,n){ let maxMap = new Map(); for(let i = 0; i < n; i++) { let temp = new Map(); let num = arr[i]; // Temp stores mapping of prime // factor to its power for the // current element while(num > 1) { // Factor is the smallest prime // factor of num let factor = prime[num]; if(temp.has(factor)) temp.set(factor, temp.get(factor) + 1); else temp.set(factor, 1); // Factor is the smallest prime // factor of num num = num / factor; } for(let [key, value] of temp.entries()) { if(maxMap.has(key)) { let maxPower = Math.max(value, maxMap.get( key)); maxMap.set(key, maxPower); } else { maxMap.set(key,value); } } } let ans = 1; for(let [key, value] of maxMap.entries()) { // LCM is product of primes to their // highest powers modulo M ans = (ans * power(key, value) % mod); } return ans;} // Driver code sieve();let arr = [36, 500, 480, 343];let n = arr.length;document.write(lcmModuloM(arr, n)); // This code is contributed by unknown2108.</script>", "e": 38173, "s": 35804, "text": null }, { "code": null, "e": 38182, "s": 38173, "text": "12348000" }, { "code": null, "e": 38237, "s": 38184, "text": "The above code works for the following constraints: " }, { "code": null, "e": 38342, "s": 38239, "text": "References: https://stackoverflow.com/questions/16633449/calculate-lcm-of-n-numbers-modulo-1000000007 " }, { "code": null, "e": 38359, "s": 38344, "text": "mohit kumar 29" }, { "code": null, "e": 38374, "s": 38359, "text": "parshavnahta97" }, { "code": null, "e": 38386, "s": 38374, "text": "29AjayKumar" }, { "code": null, "e": 38398, "s": 38386, "text": "unknown2108" }, { "code": null, "e": 38416, "s": 38398, "text": "gulshankumarar231" }, { "code": null, "e": 38424, "s": 38416, "text": "GCD-LCM" }, { "code": null, "e": 38443, "s": 38424, "text": "Modular Arithmetic" }, { "code": null, "e": 38467, "s": 38443, "text": "Technical Scripter 2018" }, { "code": null, "e": 38491, "s": 38467, "text": "Competitive Programming" }, { "code": null, "e": 38504, "s": 38491, "text": "Mathematical" }, { "code": null, "e": 38523, "s": 38504, "text": "Technical Scripter" }, { "code": null, "e": 38536, "s": 38523, "text": "Mathematical" }, { "code": null, "e": 38555, "s": 38536, "text": "Modular Arithmetic" }, { "code": null, "e": 38653, "s": 38555, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38662, "s": 38653, "text": "Comments" }, { "code": null, "e": 38675, "s": 38662, "text": "Old Comments" }, { "code": null, "e": 38700, "s": 38675, "text": "Formatted output in Java" }, { "code": null, "e": 38748, "s": 38700, "text": "Algorithm Library | C++ Magicians STL Algorithm" }, { "code": null, "e": 38775, "s": 38748, "text": "Use of FLAG in programming" }, { "code": null, "e": 38843, "s": 38775, "text": "Setting up Sublime Text for C++ Competitive Programming Environment" }, { "code": null, "e": 38883, "s": 38843, "text": "How to overcome Time Limit Exceed(TLE)?" }, { "code": null, "e": 38913, "s": 38883, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 38973, "s": 38913, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 38988, "s": 38973, "text": "C++ Data Types" }, { "code": null, "e": 39031, "s": 38988, "text": "Set in C++ Standard Template Library (STL)" } ]
What is dependency inversion principle and how to implement in C#?
High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstractions should not depend on details. Details should depend on abstractions.This principle is primarily concerned with reducing dependencies among the code modules. Code Before Dependency Inversion using System; namespace SolidPrinciples.Dependency.Invertion.Before{ public class Email{ public string ToAddress { get; set; } public string Subject { get; set; } public string Content { get; set; } public void SendEmail(){ //Send email } } public class SMS{ public string PhoneNumber { get; set; } public string Message { get; set; } public void SendSMS(){ //Send sms } } public class Notification{ private Email _email; private SMS _sms; public Notification(){ _email = new Email(); _sms = new SMS(); } public void Send(){ _email.SendEmail(); _sms.SendSMS(); } } } Code After Dependency Inversion using System.Collections.Generic; namespace SolidPrinciples.Dependency.Invertion.Before{ public interface IMessage{ void SendMessage(); } public class Email: IMessage{ public string ToAddress { get; set; } public string Subject { get; set; } public string Content { get; set; } public void SendMessage(){ //Send email } } public class SMS: IMessage{ public string PhoneNumber { get; set; } public string Message { get; set; } public void SendMessage(){ //Send Sms } } public class Notification{ private ICollection<IMessage> _messages; public Notification(ICollection<IMessage> messages){ this._messages = messages; } public void Send(){ foreach (var message in _messages){ message.SendMessage(); } } } }
[ { "code": null, "e": 1326, "s": 1062, "text": "High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstractions should not depend on details. Details should depend on abstractions.This principle is primarily concerned with reducing dependencies among the code modules." }, { "code": null, "e": 1359, "s": 1326, "text": "Code Before Dependency Inversion" }, { "code": null, "e": 2088, "s": 1359, "text": "using System;\nnamespace SolidPrinciples.Dependency.Invertion.Before{\n public class Email{\n public string ToAddress { get; set; }\n public string Subject { get; set; }\n public string Content { get; set; }\n public void SendEmail(){\n //Send email\n }\n }\n public class SMS{\n public string PhoneNumber { get; set; }\n public string Message { get; set; }\n public void SendSMS(){\n //Send sms\n }\n }\n public class Notification{\n private Email _email;\n private SMS _sms;\n public Notification(){\n _email = new Email();\n _sms = new SMS();\n }\n public void Send(){\n _email.SendEmail();\n _sms.SendSMS();\n }\n }\n}" }, { "code": null, "e": 2120, "s": 2088, "text": "Code After Dependency Inversion" }, { "code": null, "e": 2996, "s": 2120, "text": "using System.Collections.Generic;\nnamespace SolidPrinciples.Dependency.Invertion.Before{\n public interface IMessage{\n void SendMessage();\n }\n public class Email: IMessage{\n public string ToAddress { get; set; }\n public string Subject { get; set; }\n public string Content { get; set; }\n public void SendMessage(){\n //Send email\n }\n }\n public class SMS: IMessage{\n public string PhoneNumber { get; set; }\n public string Message { get; set; }\n public void SendMessage(){\n //Send Sms\n }\n }\n public class Notification{\n private ICollection<IMessage> _messages;\n public Notification(ICollection<IMessage> messages){\n this._messages = messages;\n }\n public void Send(){\n foreach (var message in _messages){\n message.SendMessage();\n }\n }\n }\n}" } ]
How to work with images in Bokeh (Python)?
To work with images in Bokeh, use image_url() method and pass a list of images. Configure the default output state to generate output saved to a file when :func:'show' is called. Create a new Figure for plotting. Render the images loaded from the given URLs. Immediately display a Bokeh object or application. from bokeh.plotting import figure, show, output_file output_file('image.html') p = figure(x_range=(0, 1), y_range=(0, 1)) p.image_url(url=['bird.jpg'], x=0, y=1, w=0.8, h=0.6) show(p)
[ { "code": null, "e": 1142, "s": 1062, "text": "To work with images in Bokeh, use image_url() method and pass a list of images." }, { "code": null, "e": 1241, "s": 1142, "text": "Configure the default output state to generate output saved to a file when :func:'show' is called." }, { "code": null, "e": 1275, "s": 1241, "text": "Create a new Figure for plotting." }, { "code": null, "e": 1321, "s": 1275, "text": "Render the images loaded from the given URLs." }, { "code": null, "e": 1372, "s": 1321, "text": "Immediately display a Bokeh object or application." }, { "code": null, "e": 1558, "s": 1372, "text": "from bokeh.plotting import figure, show, output_file\n\noutput_file('image.html')\n\np = figure(x_range=(0, 1), y_range=(0, 1))\np.image_url(url=['bird.jpg'], x=0, y=1, w=0.8, h=0.6)\nshow(p)" } ]
Minimum rotations required to get the same String | Set-2 - GeeksforGeeks
15 Jun, 2021 Given a string, we need to find the minimum number of rotations required to get the same string. In this case, we will only consider Left rotations. Examples: Input : s = “geeks” Output : 5 Input : s = “aaaa” Output :1 Naive approach: The basic approach is to keep rotating the string from the first position and count the number of rotations until we get the initial string. Efficient Approach : We will follow the basic approach but will try to reduce the time taken in generating rotations.The idea is as follows: Generate a new string of double size of the input string as: newString = original string excluding first character + original string with the first character. + denotes concatenation here. If original string is str = “abcd”, new string will be “bcdabcd”. Now, the task remains to search for the original string in the newly generated string and the index where the string is found in the number of rotations required. For string matching, we will use KMP algorithm which performs string matching in linear time. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;void computeLPSArray(char* pat, int M, int* lps); // Prints occurrences of txt[] in pat[]int KMPSearch(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); // Create lps[] that will hold the longest // prefix suffix values for pattern int lps[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] int i = 0; int j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j; j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } }} // Fills lps[] for given pattern pat[0..M-1]void computeLPSArray(char* pat, int M, int* lps){ // Length of the previous longest prefix suffix int len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } }} // Returns count of rotations to get the// same string backint countRotations(string s){ // Form a string excluding the first character // and concatenating the string at the end string s1 = s.substr(1, s.size() - 1) + s; // Convert the string to character array char pat[s.length()], text[s1.length()]; strcpy(pat, s.c_str()); strcpy(text, s1.c_str()); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text);} // Driver codeint main(){ string s1 = "geeks"; cout << countRotations(s1); return 0;} // Java implementation of the above approachclass GFG{ // Prints occurrences of txt[] in pat[]static int KMPSearch(char []pat, char []txt){ int M = pat.length; int N = txt.length; // Create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] int i = 0; int j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j + 1; //j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return 0;} // Fills lps[] for given pattern pat[0..M-1]static void computeLPSArray(char []pat, int M, int []lps){ // Length of the previous longest prefix suffix int len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } }} // Returns count of rotations to get the// same String backstatic int countRotations(String s){ // Form a String excluding the first character // and concatenating the String at the end String s1 = s.substring(1, s.length() - 1) + s; // Convert the String to character array char []pat = s.toCharArray(); char []text = s1.toCharArray(); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text);} // Driver codepublic static void main(String []args){ String s1 = "geeks"; System.out.print(countRotations(s1));}} // This code is contributed by rutvik_56. # Python3 implementation of the above approach # Prints occurrences of txt[] in pat[]def KMPSearch(pat, txt): M = len(pat) N = len(txt) # Create lps[] that will hold the longest # prefix suffix values for pattern lps = [0] * M # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) # Index for txt[] , # index for pat[] i = 0 j = 0 while i < N: if pat[j] == txt[i]: j += 1 i += 1 if j == M: return i - j j = lps[j - 1] # Mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j - 1] else: i = i + 1 # Fills lps[] for given pattern pat[0..M-1]def computeLPSArray(pat, M, lps): # Length of the previous longest prefix suffix _len = 0 # lps[0] is always 0 lps[0] = 0 # The loop calculates lps[i] for i = 1 to M-1 i = 1 while i < M: if pat[i] == pat[_len]: _len += 1 lps[i] = _len i += 1 # (pat[i] != pat[_len]) else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if _len != 0: _len = lps[_len - 1] else: lps[i] = 0 i += 1 # Returns count of rotations to get the# same string backdef countRotations(s): # Form a string excluding the first character # and concatenating the string at the end s1 = s[1 : len(s)] + s # Convert the string to character array pat = s[:] text = s1[:] # Use the KMP search algorithm # to find it in O(N) time return 1 + KMPSearch(pat, text) # Driver codes1 = "geeks"print(countRotations(s1)) # This code is contributed by divyamohan123 // C# implementation of the above approachusing System; class GFG{ // Prints occurrences of txt[] in pat[]static int KMPSearch(char []pat, char []txt){ int M = pat.Length; int N = txt.Length; // Create lps[] that will hold the longest // prefix suffix values for pattern int []lps = new int[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] int i = 0; int j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j ; //j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return 0;} // Fills lps[] for given pattern pat[0..M-1]static void computeLPSArray(char []pat, int M, int []lps){ // Length of the previous longest // prefix suffix int len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] // for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } }} // Returns count of rotations to get the// same string backstatic int countRotations(string s){ // Form a string excluding the first character // and concatenating the string at the end string s1 = s.Substring(1, s.Length - 1) + s; // Convert the string to character array char []pat = s.ToCharArray(); char []text = s1.ToCharArray(); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text);} // Driver codepublic static void Main(params string []args){ string s1 = "geeks"; Console.Write(countRotations(s1));}} // This code is contributed by pratham76 <script> // JavaScript implementation of the above approach // Prints occurrences of txt[] in pat[] function KMPSearch(pat, txt) { let M = pat.length; let N = txt.length; // Create lps[] that will hold the longest // prefix suffix values for pattern let lps = new Array(M); lps.fill(0); // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] let i = 0; let j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j ; //j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return 0; } // Fills lps[] for given pattern pat[0..M-1] function computeLPSArray(pat, M, lps) { // Length of the previous longest // prefix suffix let len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] // for i = 1 to M-1 let i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } } // Returns count of rotations to get the // same string back function countRotations(s) { // Form a string excluding the first character // and concatenating the string at the end let s1 = s.substring(1, s.length) + s; // Convert the string to character array let pat = s.split(''); let text = s1.split(''); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text); } let s1 = "geeks"; document.write(countRotations(s1)); </script> 5 Time Complexity : O(N). divyamohan123 rutvik_56 pratham76 simranarora5sos divyeshrabadiya07 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 pin code of India using Regular Expression How to check Aadhaar number is valid or not using Regular Expression How to validate time in 24-hour format using Regular Expression Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to reverse an array or string Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25017, "s": 24989, "text": "\n15 Jun, 2021" }, { "code": null, "e": 25166, "s": 25017, "text": "Given a string, we need to find the minimum number of rotations required to get the same string. In this case, we will only consider Left rotations." }, { "code": null, "e": 25177, "s": 25166, "text": "Examples: " }, { "code": null, "e": 25208, "s": 25177, "text": "Input : s = “geeks” Output : 5" }, { "code": null, "e": 25238, "s": 25208, "text": "Input : s = “aaaa” Output :1 " }, { "code": null, "e": 25395, "s": 25238, "text": "Naive approach: The basic approach is to keep rotating the string from the first position and count the number of rotations until we get the initial string." }, { "code": null, "e": 25538, "s": 25395, "text": "Efficient Approach : We will follow the basic approach but will try to reduce the time taken in generating rotations.The idea is as follows: " }, { "code": null, "e": 25599, "s": 25538, "text": "Generate a new string of double size of the input string as:" }, { "code": null, "e": 25743, "s": 25599, "text": "newString = original string excluding first character \n + original string with the first character.\n\n+ denotes concatenation here. " }, { "code": null, "e": 25809, "s": 25743, "text": "If original string is str = “abcd”, new string will be “bcdabcd”." }, { "code": null, "e": 25972, "s": 25809, "text": "Now, the task remains to search for the original string in the newly generated string and the index where the string is found in the number of rotations required." }, { "code": null, "e": 26066, "s": 25972, "text": "For string matching, we will use KMP algorithm which performs string matching in linear time." }, { "code": null, "e": 26119, "s": 26066, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26123, "s": 26119, "text": "C++" }, { "code": null, "e": 26128, "s": 26123, "text": "Java" }, { "code": null, "e": 26136, "s": 26128, "text": "Python3" }, { "code": null, "e": 26139, "s": 26136, "text": "C#" }, { "code": null, "e": 26150, "s": 26139, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;void computeLPSArray(char* pat, int M, int* lps); // Prints occurrences of txt[] in pat[]int KMPSearch(char* pat, char* txt){ int M = strlen(pat); int N = strlen(txt); // Create lps[] that will hold the longest // prefix suffix values for pattern int lps[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] int i = 0; int j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j; j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } }} // Fills lps[] for given pattern pat[0..M-1]void computeLPSArray(char* pat, int M, int* lps){ // Length of the previous longest prefix suffix int len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } }} // Returns count of rotations to get the// same string backint countRotations(string s){ // Form a string excluding the first character // and concatenating the string at the end string s1 = s.substr(1, s.size() - 1) + s; // Convert the string to character array char pat[s.length()], text[s1.length()]; strcpy(pat, s.c_str()); strcpy(text, s1.c_str()); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text);} // Driver codeint main(){ string s1 = \"geeks\"; cout << countRotations(s1); return 0;}", "e": 28481, "s": 26150, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Prints occurrences of txt[] in pat[]static int KMPSearch(char []pat, char []txt){ int M = pat.length; int N = txt.length; // Create lps[] that will hold the longest // prefix suffix values for pattern int lps[] = new int[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] int i = 0; int j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j + 1; //j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] characters, // they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return 0;} // Fills lps[] for given pattern pat[0..M-1]static void computeLPSArray(char []pat, int M, int []lps){ // Length of the previous longest prefix suffix int len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } }} // Returns count of rotations to get the// same String backstatic int countRotations(String s){ // Form a String excluding the first character // and concatenating the String at the end String s1 = s.substring(1, s.length() - 1) + s; // Convert the String to character array char []pat = s.toCharArray(); char []text = s1.toCharArray(); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text);} // Driver codepublic static void main(String []args){ String s1 = \"geeks\"; System.out.print(countRotations(s1));}} // This code is contributed by rutvik_56.", "e": 30855, "s": 28481, "text": null }, { "code": "# Python3 implementation of the above approach # Prints occurrences of txt[] in pat[]def KMPSearch(pat, txt): M = len(pat) N = len(txt) # Create lps[] that will hold the longest # prefix suffix values for pattern lps = [0] * M # Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps) # Index for txt[] , # index for pat[] i = 0 j = 0 while i < N: if pat[j] == txt[i]: j += 1 i += 1 if j == M: return i - j j = lps[j - 1] # Mismatch after j matches elif i < N and pat[j] != txt[i]: # Do not match lps[0..lps[j-1]] characters, # they will match anyway if j != 0: j = lps[j - 1] else: i = i + 1 # Fills lps[] for given pattern pat[0..M-1]def computeLPSArray(pat, M, lps): # Length of the previous longest prefix suffix _len = 0 # lps[0] is always 0 lps[0] = 0 # The loop calculates lps[i] for i = 1 to M-1 i = 1 while i < M: if pat[i] == pat[_len]: _len += 1 lps[i] = _len i += 1 # (pat[i] != pat[_len]) else: # This is tricky. Consider the example. # AAACAAAA and i = 7. The idea is similar # to search step. if _len != 0: _len = lps[_len - 1] else: lps[i] = 0 i += 1 # Returns count of rotations to get the# same string backdef countRotations(s): # Form a string excluding the first character # and concatenating the string at the end s1 = s[1 : len(s)] + s # Convert the string to character array pat = s[:] text = s1[:] # Use the KMP search algorithm # to find it in O(N) time return 1 + KMPSearch(pat, text) # Driver codes1 = \"geeks\"print(countRotations(s1)) # This code is contributed by divyamohan123", "e": 32793, "s": 30855, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Prints occurrences of txt[] in pat[]static int KMPSearch(char []pat, char []txt){ int M = pat.Length; int N = txt.Length; // Create lps[] that will hold the longest // prefix suffix values for pattern int []lps = new int[M]; // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] int i = 0; int j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j ; //j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return 0;} // Fills lps[] for given pattern pat[0..M-1]static void computeLPSArray(char []pat, int M, int []lps){ // Length of the previous longest // prefix suffix int len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] // for i = 1 to M-1 int i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } }} // Returns count of rotations to get the// same string backstatic int countRotations(string s){ // Form a string excluding the first character // and concatenating the string at the end string s1 = s.Substring(1, s.Length - 1) + s; // Convert the string to character array char []pat = s.ToCharArray(); char []text = s1.ToCharArray(); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text);} // Driver codepublic static void Main(params string []args){ string s1 = \"geeks\"; Console.Write(countRotations(s1));}} // This code is contributed by pratham76", "e": 35263, "s": 32793, "text": null }, { "code": "<script> // JavaScript implementation of the above approach // Prints occurrences of txt[] in pat[] function KMPSearch(pat, txt) { let M = pat.length; let N = txt.length; // Create lps[] that will hold the longest // prefix suffix values for pattern let lps = new Array(M); lps.fill(0); // Preprocess the pattern (calculate lps[] array) computeLPSArray(pat, M, lps); // Index for txt[] , // index for pat[] let i = 0; let j = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) { return i - j ; //j = lps[j - 1]; } // Mismatch after j matches else if (i < N && pat[j] != txt[i]) { // Do not match lps[0..lps[j-1]] // characters, they will match anyway if (j != 0) j = lps[j - 1]; else i = i + 1; } } return 0; } // Fills lps[] for given pattern pat[0..M-1] function computeLPSArray(pat, M, lps) { // Length of the previous longest // prefix suffix let len = 0; // lps[0] is always 0 lps[0] = 0; // The loop calculates lps[i] // for i = 1 to M-1 let i = 1; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i] = len; i++; } // (pat[i] != pat[len]) else { // This is tricky. Consider the example. // AAACAAAA and i = 7. The idea is similar // to search step. if (len != 0) { len = lps[len - 1]; } else { lps[i] = 0; i++; } } } } // Returns count of rotations to get the // same string back function countRotations(s) { // Form a string excluding the first character // and concatenating the string at the end let s1 = s.substring(1, s.length) + s; // Convert the string to character array let pat = s.split(''); let text = s1.split(''); // Use the KMP search algorithm // to find it in O(N) time return 1 + KMPSearch(pat, text); } let s1 = \"geeks\"; document.write(countRotations(s1)); </script>", "e": 37869, "s": 35263, "text": null }, { "code": null, "e": 37871, "s": 37869, "text": "5" }, { "code": null, "e": 37898, "s": 37873, "text": "Time Complexity : O(N). " }, { "code": null, "e": 37912, "s": 37898, "text": "divyamohan123" }, { "code": null, "e": 37922, "s": 37912, "text": "rutvik_56" }, { "code": null, "e": 37932, "s": 37922, "text": "pratham76" }, { "code": null, "e": 37948, "s": 37932, "text": "simranarora5sos" }, { "code": null, "e": 37966, "s": 37948, "text": "divyeshrabadiya07" }, { "code": null, "e": 37984, "s": 37966, "text": "Pattern Searching" }, { "code": null, "e": 37992, "s": 37984, "text": "Strings" }, { "code": null, "e": 38000, "s": 37992, "text": "Strings" }, { "code": null, "e": 38018, "s": 38000, "text": "Pattern Searching" }, { "code": null, "e": 38116, "s": 38018, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38125, "s": 38116, "text": "Comments" }, { "code": null, "e": 38138, "s": 38125, "text": "Old Comments" }, { "code": null, "e": 38188, "s": 38138, "text": "How to validate HTML tag using Regular Expression" }, { "code": null, "e": 38255, "s": 38188, "text": "Build a DFA to accept Binary strings that starts or ends with \"01\"" }, { "code": null, "e": 38314, "s": 38255, "text": "How to validate pin code of India using Regular Expression" }, { "code": null, "e": 38383, "s": 38314, "text": "How to check Aadhaar number is valid or not using Regular Expression" }, { "code": null, "e": 38447, "s": 38383, "text": "How to validate time in 24-hour format using Regular Expression" }, { "code": null, "e": 38472, "s": 38447, "text": "Reverse a string in Java" }, { "code": null, "e": 38506, "s": 38472, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 38552, "s": 38506, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 38612, "s": 38552, "text": "Write a program to print all permutations of a given string" } ]
What are The Different Protection Levels in Android Permission? - GeeksforGeeks
19 Sep, 2021 When building an Android application, we require different Android device components such as the camera, GPS, and so on. So, in order to use these capabilities of our Android smartphone, we must first obtain permission from the user to use something on their phone. You cannot utilize any of those functionalities directly. Furthermore, permission has different protection levels; for example, if the permission’s protection level is very low, you do not need to ask the user to use that permission. You may use it right away. However, for hazardous permissions, you must expressly obtain the user’s permission. In this geeks for geeks article, we will learn about the various layers of authorization protection. Normally, if we want to add certain user permissions, we enter the following code in our AndroidManifest.xml file: <uses-permission android:name="android.permission.VIBRATE" /> The preceding line enables access to the vibration or the haptic motor of the device. Using permission is not an easy process; you must decide if you need to explicitly ask the user for permission or whether you may take permission immediately. This choice is dependent on the permission’s degree of protection. The three permission protection levels in Android are as follows: Normal PermissionsSignature PermissionsDangerous Permissions Normal Permissions Signature Permissions Dangerous Permissions These are the three primary permissions protection levels; however, there is an additional security level known as the Special Permission. Let’s take a look at them one at a time. The permission falls within the Normal Permission category if there is little or no danger to the user’s privacy. For example, if you want to acquire the data and time, these things do not entail any user privacy, and you do not need to ask the user to use date or time in this situation. You may utilize this feature directly by adding permission to the AndroidManifest.xml file. The system will automatically provide authorization to your app during the installation process. Normal Permissions include the following permissions: ACCESS_LOCATION_EXTRA_COMMANDSACCESS_NETWORK_STATECHANGE_NETWORK_STATEACCESS_WIFI_STATECHANGE_WIFI_STATECHANGE_WIFI_MULTICAST_STATEBLUETOOTHBLUETOOTH_ADMININTERNETSET_ALARMSET_WALLPAPERVIBRATEWAKE_LOCK ACCESS_LOCATION_EXTRA_COMMANDS ACCESS_NETWORK_STATE CHANGE_NETWORK_STATE ACCESS_WIFI_STATE CHANGE_WIFI_STATE CHANGE_WIFI_MULTICAST_STATE BLUETOOTH BLUETOOTH_ADMIN INTERNET SET_ALARM SET_WALLPAPER VIBRATE WAKE_LOCK The Android system gives these rights during installation, but there is a catch. The app requesting permission must be signed with the same signature as the app defining the needed permission. Some of the Signature permissions are as follows: BIND_ACCESSIBILITY_SERVICEBIND_AUTOFILL_SERVICEBIND_CARRIER_SERVICEBIND_DEVICE_ADMINBIND_INPUT_METHODBIND_NFC_SERVICEBIND_TV_INPUTBIND_WALLPAPERREAD_VOICEMAILWRITE_SETTINGSWRITE_VOICEMAIL BIND_ACCESSIBILITY_SERVICE BIND_AUTOFILL_SERVICE BIND_CARRIER_SERVICE BIND_DEVICE_ADMIN BIND_INPUT_METHOD BIND_NFC_SERVICE BIND_TV_INPUT BIND_WALLPAPER READ_VOICEMAIL WRITE_SETTINGS WRITE_VOICEMAIL Permissions that are dangerous include those that affect user data in some way. For example, if you wish to read contacts from the phone or access the phone’s file storage, these rights fall under the Dangerous category since they involve the user’s privacy. To utilize Dangerous permissions, you must first expressly seek permission by displaying an alert dialogue or any other dialogue. If the user refuses the permission, your application will be unable to utilize that permission. Some of the Dangerous permissions are as follows: READ_CALENDARWRITE_CALENDARCAMERAREAD_CALL_LOGWRITE_CALL_LOGREAD_CONTACTSWRITE_CONTACTSGET_ACCOUNTSACCESS_FINE_LOCATIONACCESS_COARSE_LOCATIONSEND_SMSRECEIVE_SMS READ_CALENDAR WRITE_CALENDAR CAMERA READ_CALL_LOG WRITE_CALL_LOG READ_CONTACTS WRITE_CONTACTS GET_ACCOUNTS ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION SEND_SMS RECEIVE_SMS These are the permits that are neither Normal nor Dangerous in nature. Most apps should not utilize these rights since they are extremely sensitive and require user consent before being used. To utilize this permission, declare it in the AndroidManifest.xml file and then submit an intent requesting user authorization. Some of the special permissions are as follows: WRITE_SETTINGSSYSTEM_ALERT_WINDOW WRITE_SETTINGS SYSTEM_ALERT_WINDOW In this article, we learned about the various degrees of protection available in permissions. Normal permissions, Signature permissions, and Dangerous permissions are the three types. Picked Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android GridView in Android with Example Android Listview in Java with Example How to Change the Background Color After Clicking the Button in Android? How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Fragment Lifecycle in Android How to Add Image to Drawable Folder in Android Studio? Animation in Android with Example
[ { "code": null, "e": 25116, "s": 25088, "text": "\n19 Sep, 2021" }, { "code": null, "e": 25829, "s": 25116, "text": "When building an Android application, we require different Android device components such as the camera, GPS, and so on. So, in order to use these capabilities of our Android smartphone, we must first obtain permission from the user to use something on their phone. You cannot utilize any of those functionalities directly. Furthermore, permission has different protection levels; for example, if the permission’s protection level is very low, you do not need to ask the user to use that permission. You may use it right away. However, for hazardous permissions, you must expressly obtain the user’s permission. In this geeks for geeks article, we will learn about the various layers of authorization protection." }, { "code": null, "e": 25944, "s": 25829, "text": "Normally, if we want to add certain user permissions, we enter the following code in our AndroidManifest.xml file:" }, { "code": null, "e": 26006, "s": 25944, "text": "<uses-permission android:name=\"android.permission.VIBRATE\" />" }, { "code": null, "e": 26092, "s": 26006, "text": "The preceding line enables access to the vibration or the haptic motor of the device." }, { "code": null, "e": 26384, "s": 26092, "text": "Using permission is not an easy process; you must decide if you need to explicitly ask the user for permission or whether you may take permission immediately. This choice is dependent on the permission’s degree of protection. The three permission protection levels in Android are as follows:" }, { "code": null, "e": 26445, "s": 26384, "text": "Normal PermissionsSignature PermissionsDangerous Permissions" }, { "code": null, "e": 26464, "s": 26445, "text": "Normal Permissions" }, { "code": null, "e": 26486, "s": 26464, "text": "Signature Permissions" }, { "code": null, "e": 26508, "s": 26486, "text": "Dangerous Permissions" }, { "code": null, "e": 26688, "s": 26508, "text": "These are the three primary permissions protection levels; however, there is an additional security level known as the Special Permission. Let’s take a look at them one at a time." }, { "code": null, "e": 27220, "s": 26688, "text": "The permission falls within the Normal Permission category if there is little or no danger to the user’s privacy. For example, if you want to acquire the data and time, these things do not entail any user privacy, and you do not need to ask the user to use date or time in this situation. You may utilize this feature directly by adding permission to the AndroidManifest.xml file. The system will automatically provide authorization to your app during the installation process. Normal Permissions include the following permissions:" }, { "code": null, "e": 27422, "s": 27220, "text": "ACCESS_LOCATION_EXTRA_COMMANDSACCESS_NETWORK_STATECHANGE_NETWORK_STATEACCESS_WIFI_STATECHANGE_WIFI_STATECHANGE_WIFI_MULTICAST_STATEBLUETOOTHBLUETOOTH_ADMININTERNETSET_ALARMSET_WALLPAPERVIBRATEWAKE_LOCK" }, { "code": null, "e": 27453, "s": 27422, "text": "ACCESS_LOCATION_EXTRA_COMMANDS" }, { "code": null, "e": 27474, "s": 27453, "text": "ACCESS_NETWORK_STATE" }, { "code": null, "e": 27495, "s": 27474, "text": "CHANGE_NETWORK_STATE" }, { "code": null, "e": 27513, "s": 27495, "text": "ACCESS_WIFI_STATE" }, { "code": null, "e": 27531, "s": 27513, "text": "CHANGE_WIFI_STATE" }, { "code": null, "e": 27559, "s": 27531, "text": "CHANGE_WIFI_MULTICAST_STATE" }, { "code": null, "e": 27569, "s": 27559, "text": "BLUETOOTH" }, { "code": null, "e": 27585, "s": 27569, "text": "BLUETOOTH_ADMIN" }, { "code": null, "e": 27594, "s": 27585, "text": "INTERNET" }, { "code": null, "e": 27604, "s": 27594, "text": "SET_ALARM" }, { "code": null, "e": 27618, "s": 27604, "text": "SET_WALLPAPER" }, { "code": null, "e": 27626, "s": 27618, "text": "VIBRATE" }, { "code": null, "e": 27636, "s": 27626, "text": "WAKE_LOCK" }, { "code": null, "e": 27880, "s": 27636, "text": "The Android system gives these rights during installation, but there is a catch. The app requesting permission must be signed with the same signature as the app defining the needed permission. Some of the Signature permissions are as follows:" }, { "code": null, "e": 28068, "s": 27880, "text": "BIND_ACCESSIBILITY_SERVICEBIND_AUTOFILL_SERVICEBIND_CARRIER_SERVICEBIND_DEVICE_ADMINBIND_INPUT_METHODBIND_NFC_SERVICEBIND_TV_INPUTBIND_WALLPAPERREAD_VOICEMAILWRITE_SETTINGSWRITE_VOICEMAIL" }, { "code": null, "e": 28095, "s": 28068, "text": "BIND_ACCESSIBILITY_SERVICE" }, { "code": null, "e": 28117, "s": 28095, "text": "BIND_AUTOFILL_SERVICE" }, { "code": null, "e": 28138, "s": 28117, "text": "BIND_CARRIER_SERVICE" }, { "code": null, "e": 28156, "s": 28138, "text": "BIND_DEVICE_ADMIN" }, { "code": null, "e": 28174, "s": 28156, "text": "BIND_INPUT_METHOD" }, { "code": null, "e": 28191, "s": 28174, "text": "BIND_NFC_SERVICE" }, { "code": null, "e": 28205, "s": 28191, "text": "BIND_TV_INPUT" }, { "code": null, "e": 28220, "s": 28205, "text": "BIND_WALLPAPER" }, { "code": null, "e": 28235, "s": 28220, "text": "READ_VOICEMAIL" }, { "code": null, "e": 28250, "s": 28235, "text": "WRITE_SETTINGS" }, { "code": null, "e": 28266, "s": 28250, "text": "WRITE_VOICEMAIL" }, { "code": null, "e": 28801, "s": 28266, "text": "Permissions that are dangerous include those that affect user data in some way. For example, if you wish to read contacts from the phone or access the phone’s file storage, these rights fall under the Dangerous category since they involve the user’s privacy. To utilize Dangerous permissions, you must first expressly seek permission by displaying an alert dialogue or any other dialogue. If the user refuses the permission, your application will be unable to utilize that permission. Some of the Dangerous permissions are as follows:" }, { "code": null, "e": 28962, "s": 28801, "text": "READ_CALENDARWRITE_CALENDARCAMERAREAD_CALL_LOGWRITE_CALL_LOGREAD_CONTACTSWRITE_CONTACTSGET_ACCOUNTSACCESS_FINE_LOCATIONACCESS_COARSE_LOCATIONSEND_SMSRECEIVE_SMS" }, { "code": null, "e": 28976, "s": 28962, "text": "READ_CALENDAR" }, { "code": null, "e": 28991, "s": 28976, "text": "WRITE_CALENDAR" }, { "code": null, "e": 28998, "s": 28991, "text": "CAMERA" }, { "code": null, "e": 29012, "s": 28998, "text": "READ_CALL_LOG" }, { "code": null, "e": 29027, "s": 29012, "text": "WRITE_CALL_LOG" }, { "code": null, "e": 29041, "s": 29027, "text": "READ_CONTACTS" }, { "code": null, "e": 29056, "s": 29041, "text": "WRITE_CONTACTS" }, { "code": null, "e": 29069, "s": 29056, "text": "GET_ACCOUNTS" }, { "code": null, "e": 29090, "s": 29069, "text": "ACCESS_FINE_LOCATION" }, { "code": null, "e": 29113, "s": 29090, "text": "ACCESS_COARSE_LOCATION" }, { "code": null, "e": 29122, "s": 29113, "text": "SEND_SMS" }, { "code": null, "e": 29134, "s": 29122, "text": "RECEIVE_SMS" }, { "code": null, "e": 29502, "s": 29134, "text": "These are the permits that are neither Normal nor Dangerous in nature. Most apps should not utilize these rights since they are extremely sensitive and require user consent before being used. To utilize this permission, declare it in the AndroidManifest.xml file and then submit an intent requesting user authorization. Some of the special permissions are as follows:" }, { "code": null, "e": 29536, "s": 29502, "text": "WRITE_SETTINGSSYSTEM_ALERT_WINDOW" }, { "code": null, "e": 29551, "s": 29536, "text": "WRITE_SETTINGS" }, { "code": null, "e": 29571, "s": 29551, "text": "SYSTEM_ALERT_WINDOW" }, { "code": null, "e": 29755, "s": 29571, "text": "In this article, we learned about the various degrees of protection available in permissions. Normal permissions, Signature permissions, and Dangerous permissions are the three types." }, { "code": null, "e": 29762, "s": 29755, "text": "Picked" }, { "code": null, "e": 29770, "s": 29762, "text": "Android" }, { "code": null, "e": 29778, "s": 29770, "text": "Android" }, { "code": null, "e": 29876, "s": 29778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29885, "s": 29876, "text": "Comments" }, { "code": null, "e": 29898, "s": 29885, "text": "Old Comments" }, { "code": null, "e": 29937, "s": 29898, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29979, "s": 29937, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 30012, "s": 29979, "text": "GridView in Android with Example" }, { "code": null, "e": 30050, "s": 30012, "text": "Android Listview in Java with Example" }, { "code": null, "e": 30123, "s": 30050, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 30173, "s": 30123, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 30224, "s": 30173, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 30254, "s": 30224, "text": "Fragment Lifecycle in Android" }, { "code": null, "e": 30309, "s": 30254, "text": "How to Add Image to Drawable Folder in Android Studio?" } ]
How to delete empty files and folders using PowerShell?
To delete empty files and folders, we need to first retrieve the list and which has been shown in the earlier articles. In this article, we are using the logic that if we find an empty file or folder we will delete them. To implement that logic, use the below script. gci C:\Temp -Recurse | foreach { if($_.Length -eq 0){ Write-Output "Removing Empty File $($_.FullName)" $_.FullName | Remove-Item -Force } if( $_.psiscontainer -eq $true){ if((gci $_.FullName) -eq $null){ Write-Output "Removing Empty folder $($_.FullName)" $_.FullName | Remove-Item -Force } } The above command will remove empty files and folders/sub-folders from the C:\temp path. You will see the output something like this.
[ { "code": null, "e": 1182, "s": 1062, "text": "To delete empty files and folders, we need to first retrieve the list and which has been shown in the earlier articles." }, { "code": null, "e": 1330, "s": 1182, "text": "In this article, we are using the logic that if we find an empty file or folder we will delete them. To implement that logic, use the below script." }, { "code": null, "e": 1675, "s": 1330, "text": "gci C:\\Temp -Recurse | foreach {\n if($_.Length -eq 0){\n Write-Output \"Removing Empty File $($_.FullName)\"\n $_.FullName | Remove-Item -Force\n }\n if( $_.psiscontainer -eq $true){\n if((gci $_.FullName) -eq $null){\n Write-Output \"Removing Empty folder $($_.FullName)\"\n $_.FullName | Remove-Item -Force\n }\n}" }, { "code": null, "e": 1764, "s": 1675, "text": "The above command will remove empty files and folders/sub-folders from the C:\\temp path." }, { "code": null, "e": 1809, "s": 1764, "text": "You will see the output something like this." } ]
What, Why and How of (De)Serialization in Python | by Xiaoxu Gao | Towards Data Science
The first time I heard about the word serialization and deserialization, I had no idea what they mean and felt these terms quite “intimidating”. After a few days, I started to pick up this concept, but was confused by their correlation with encoding and decoding. In this article, I want to walk you through this concept as if you are a newbie. By the end of the article, you will find out that it’s not as difficult as you might think. We create plenty of objects in Python every day, and these objects will eventually disappear if the program dies. Sometimes we want to store the state of an object in a file or in a database, or transmit it across the network for using it in the future. This helps us to reuse the object in different programs or even in different environments. But the problem we might face is the compatibility. Imagine that you’ve created an object in Python, how could it be reused by a Java program? Boolean values in Python look like True and False, but in Java, they are represented using true and false. There must be a “middle man” creating a universal language that both programs understand — which is a sequence of bytes. The process of converting a structured object into a sequence of bytes which can be stored in a file system or database or sent through the network is called serialization. The reversed process is called deserialization, which means reconverting a sequence of bytes into a structured object. Creating an object via deserialization is usually faster than initializing from a class. Storing the state of an object in a file or database can save time to process huge datasets in many data science projects. For example, you only need to pre-process the dataset once and save the model into a disk. Later you just need to deserialize it and reuse the pre-cooked model as many times as you want. This is definitely preferred to pre-processing it each time. The side effect of it is that the serialized object might be too big to be loaded into memory, so several chunked objects are more preferred. Besides, you can apply encryption and compression to your data stream to level up the security and boost your performance even more. To serialize a complex data structure, a serialization format is needed. It converts the object into a certain format that can be stored and transmitted. There are two groups of serialization format: text-based and binary-based. As the name suggests, a text-based serialization is the process of serializing an object in a human-readable format, while binary-based is in a not human-readable format. Encoding & Decoding As stated in the introduction part, I didn’t really know the differences between encoding and serialization earlier in time. In short, encoding is a way of translating characters to bits using an encoding schema like UTF-8, while serialization is a long process that also stores the bits into a file, database or send them to the network. So I see encoding as a part of the serialization process. If you would like to learn more about Python encodings, I recommend you to read this thorough article from RealPython. realpython.com Back to the serialization format, typical text-based serialization formats are CSV, JSON, XML, YAML, TOML, etc. Binary-based formats are protobuf and Avro. Python also has several packages like pickle, numpy and pandas that supports serializing custom objects into byte format. To let you feel the differences among several serialization formats, I use the same example throughout the article. Let’s say I have a class Article with attributes author, publication, publish_date, topics, word_count and is_vip. I want to store the state of many objects in a file and share it with a consumer. CSV CSV is probably the simplest serialization format. It stands for Comma-Separated Values. It is well suited to storing tabulated data (flat data). As you can see in this example, it doesn’t work very well with nested data structures. In the code, I first use asdict function from dataclasses to convert an Article object into a dictionary, then use csv.DictWriter to write that dictionary into a csv file. Actually we have just finished a serialization process. How simple it is! At a very high level, serialization is nothing more than writing data to disk, while deserialization means reading data into memory. But as you might notice that attribute topic which is supposed to be a list is represented as a string in csv file. This is due to the fact that csv only supports flat data, which means when reading the file, an extra step is required to convert string topic back to a list. Besides, csv file doesn’t store type information, so everything is interpreted as string, like attribute word_count. If I read article.csv file and print the row, I would get a dictionary object with every attribute in string format. In conclusion, csv file can store the attributes and values of a flat object, but can’t always store the correct information of data type. To solve this problem, we need more flexible formats. JSON A good alternative is JSON. JSON is the most widespread format for data serialization due to its human-readable syntax, compatibility with almost every programming language, and support of nested data structures and multiple data types. We can write the same article object into a JSON file using the built-in library json. dump() serializes an object into a JSON formatted string, and then write it to the file object. json uses JSONEncoder class to convert a Python type into a JSON type (e.g. True => true, False => false, None => null). It’s possible to extend JSONEncoder and serialize other types. I would recommend another great article from RealPython on the topic of JSON data in Python. realpython.com On the other hand, the deserialization process would be simply reading the JSON file and recreate a dictionary object. As you can see, the recreated object is the same as the original one. Not so surprisingly, JSON is a better choice than csv in this example because it holds more characteristics of the object than csv, thus is able to fully restore the object. But a potential problem with JSON is that you have to load the complete file into memory, while you can iterate the rows in a csv without giving too much pressure on memory. Of course, you can create multiple chunks to relief the memory, but it’s just something you have to keep in mind. Another format comparable to JSON is YAML. I’ve talked about their differences in this article. YAML also supports nested data structures and different data types. XML The next text-based format is XML, which is used for representing nested information in a tree-like structure. It’s widely used in Web and Service-Oriented Architecture. An XML file doesn’t include any type information, but you can standardize and validate an XML file through a schema, so-called XSD. Python provides a built-in library xml.etree.ElementTree to help us create or read XML files, but the conversion from a dictionary to a tree element is not as straightforward as the previous formats. In this code example, I implement a simple dict2xml adapter myself. Accordingly, its XSD file can look like this, where each element is bound to a type. In addition to the built-in data types, you can define your own data type with xs:restriction such as xs:maxLength, xs:pattern etc. <xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name="article"> <xs:complexType> <xs:sequence> <xs:element type="xs:string" name="author"/> <xs:element type="xs:string" name="publication"/> <xs:element type="xs:date" name="publish_date"/> <xs:element type="xs:string" name="topics" maxOccurs="unbounded" minOccurs="0"/> <xs:element type="xs:integer" name="word_count"/> <xs:element type="xs:boolean" name="is_vip"/> </xs:sequence> </xs:complexType> </xs:element></xs:schema> Unfortunately, xml.etree.ElementTree doesn’t support XSD validation. A good alternative could be lxml. Back to the example, let’s deserialize (read) the XML file. Due to the uncertainty of data types, every element value is interpreted as string in Python. iterparse from cElementTree returns an iterator, which is useful when you want to read a large XML file and don’t want to load everything in memory. In conclusion, XML is a schema-based serialization format. But no matter what the type is in XSD file, Python always reads it as a string. Thus, a custom adapter is required to convert an XML data type to a Python data type. BSON So far, we’ve looked into 3 text-based serialization formats. Next, let’s look at binary-based serialization format. This format is not human-readable, but it can effectively compress the data, and is used a lot for intercommunication and storage in distributed systems. BSON (binary JSON) is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays. BSON also allows representation of data types that are not part of JSON spec. BSON is mainly used in MongoDB database. When you install pymongo, bson is part of the library. The way to encode and decode using BSON is as straightforward as JSON. A BSON record takes a bit more space than JSON is because it also contains the meta info of the record such as data type and length. On the other hand, BSON provides a few advantages over using JSON: BSON supports more types than JSON, for instance, bytes and date.BSON records are easy to traverse and query due to additional metadata. It allows value retrieval without reading the entire documents. BSON supports more types than JSON, for instance, bytes and date. BSON records are easy to traverse and query due to additional metadata. It allows value retrieval without reading the entire documents. Avro Another famous binary-based serialization format is Avro. Avro is a fast schema-based serialization format. A schema must be provided during serialization and deserialization. Due to its high-performance, it’s used most often with Apache Kafka. Avro schema is defined in JSON format which makes it language independent and can be stored in nearly every environment. The schema describes records using a rich type systems that allows both data definition and documentations. By having schemas, it’s possible to model the data and create a catalogue of all the entities. Such catalogue can be served on a schema registry, making schemas available for consumption by consumers and producers. Here is an example of Avro schema for Article entity. Avro is supported in many programming languages, including Python. In this example, I’m using fast-avro, a CPython based library. It’s approved that fast-avro is way faster than the pure Python implementation library avro. fast-avro provides writer/reader and schemaless_writer/schemaless_reader. The first option inserts the schema into .avro file as a file header, while the second doesn’t. Pickle Alright, after showing different serialization formats, I’d like to introduce you a couple of handy Python libraries that can serialize a Python object. One of them is Pickle. “Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation. In terms of what can be pickled and unpickled, here is the list on Python doc. The unpickled object belongs to the type Article and can be used right away. However, as stated here, Pickle module is not secure due to the possibility of code injection. Tools like Bandit will not let it go through the security checks, so never unpickle objects from untrusted sources. Pandas / Numpy Famous data manipulation libraries like Pandas and Numpy also offer pickle-like functions. This can become handy if DataFrame or np.ndarry is agreed as a common data type between producers and consumers. If you know more Python libraries that can serialize data into different formats, please leave a comment below to share with us. Last but not least, let’s look at the performance of each serialization format/library. These tests were executed on a Macbook with 8-Core i9. In this example, I want to write 100 article objects into a file, and then recreate these objects in a different function. In the end, I use assert to compare the recreated objects to the original objects. The full implementation can be found here. The graph tells us: pickle is the winner in this performance testing. It’s probably because an article object can be directly serialized without being converted to a JSON first.BSON performs better than JSON in both serialization and deserialization. The same for numpy v.s pandas.Deserialization of csv took more time is due to the steps to converting attributes from string to its original types (e.g. int or bool).As the only schema-based serialization format, the performance of avro is quite impressive.The slowness of XML can be blamed on the implementation. Please let me know how I can improve it. :) pickle is the winner in this performance testing. It’s probably because an article object can be directly serialized without being converted to a JSON first. BSON performs better than JSON in both serialization and deserialization. The same for numpy v.s pandas. Deserialization of csv took more time is due to the steps to converting attributes from string to its original types (e.g. int or bool). As the only schema-based serialization format, the performance of avro is quite impressive. The slowness of XML can be blamed on the implementation. Please let me know how I can improve it. :) First of all, thanks for finishing reading such a long article. Congratulations! You survived (I survived too)! :) In this article, we went through many possibilities of serializing and deserializing a Python object. Until now, you must not feel these 2 terms intimidating anymore, as to some extend, it’s just a fancy way to say reading and writing. There are pros and cons on each serialization format. You should think about whether you want text-based or binary-based, schema-based or non-schema-based, what is your data format? dictionary, DataFrame or Python object? Do you want to save only the value or also the type? Do you care about the performance and memory? I hope this article can help you make a smart decision. Please leave your comments below if you have any thought.
[ { "code": null, "e": 484, "s": 47, "text": "The first time I heard about the word serialization and deserialization, I had no idea what they mean and felt these terms quite “intimidating”. After a few days, I started to pick up this concept, but was confused by their correlation with encoding and decoding. In this article, I want to walk you through this concept as if you are a newbie. By the end of the article, you will find out that it’s not as difficult as you might think." }, { "code": null, "e": 829, "s": 484, "text": "We create plenty of objects in Python every day, and these objects will eventually disappear if the program dies. Sometimes we want to store the state of an object in a file or in a database, or transmit it across the network for using it in the future. This helps us to reuse the object in different programs or even in different environments." }, { "code": null, "e": 1200, "s": 829, "text": "But the problem we might face is the compatibility. Imagine that you’ve created an object in Python, how could it be reused by a Java program? Boolean values in Python look like True and False, but in Java, they are represented using true and false. There must be a “middle man” creating a universal language that both programs understand — which is a sequence of bytes." }, { "code": null, "e": 1581, "s": 1200, "text": "The process of converting a structured object into a sequence of bytes which can be stored in a file system or database or sent through the network is called serialization. The reversed process is called deserialization, which means reconverting a sequence of bytes into a structured object. Creating an object via deserialization is usually faster than initializing from a class." }, { "code": null, "e": 2094, "s": 1581, "text": "Storing the state of an object in a file or database can save time to process huge datasets in many data science projects. For example, you only need to pre-process the dataset once and save the model into a disk. Later you just need to deserialize it and reuse the pre-cooked model as many times as you want. This is definitely preferred to pre-processing it each time. The side effect of it is that the serialized object might be too big to be loaded into memory, so several chunked objects are more preferred." }, { "code": null, "e": 2227, "s": 2094, "text": "Besides, you can apply encryption and compression to your data stream to level up the security and boost your performance even more." }, { "code": null, "e": 2627, "s": 2227, "text": "To serialize a complex data structure, a serialization format is needed. It converts the object into a certain format that can be stored and transmitted. There are two groups of serialization format: text-based and binary-based. As the name suggests, a text-based serialization is the process of serializing an object in a human-readable format, while binary-based is in a not human-readable format." }, { "code": null, "e": 2647, "s": 2627, "text": "Encoding & Decoding" }, { "code": null, "e": 3163, "s": 2647, "text": "As stated in the introduction part, I didn’t really know the differences between encoding and serialization earlier in time. In short, encoding is a way of translating characters to bits using an encoding schema like UTF-8, while serialization is a long process that also stores the bits into a file, database or send them to the network. So I see encoding as a part of the serialization process. If you would like to learn more about Python encodings, I recommend you to read this thorough article from RealPython." }, { "code": null, "e": 3178, "s": 3163, "text": "realpython.com" }, { "code": null, "e": 3456, "s": 3178, "text": "Back to the serialization format, typical text-based serialization formats are CSV, JSON, XML, YAML, TOML, etc. Binary-based formats are protobuf and Avro. Python also has several packages like pickle, numpy and pandas that supports serializing custom objects into byte format." }, { "code": null, "e": 3769, "s": 3456, "text": "To let you feel the differences among several serialization formats, I use the same example throughout the article. Let’s say I have a class Article with attributes author, publication, publish_date, topics, word_count and is_vip. I want to store the state of many objects in a file and share it with a consumer." }, { "code": null, "e": 3773, "s": 3769, "text": "CSV" }, { "code": null, "e": 4178, "s": 3773, "text": "CSV is probably the simplest serialization format. It stands for Comma-Separated Values. It is well suited to storing tabulated data (flat data). As you can see in this example, it doesn’t work very well with nested data structures. In the code, I first use asdict function from dataclasses to convert an Article object into a dictionary, then use csv.DictWriter to write that dictionary into a csv file." }, { "code": null, "e": 4385, "s": 4178, "text": "Actually we have just finished a serialization process. How simple it is! At a very high level, serialization is nothing more than writing data to disk, while deserialization means reading data into memory." }, { "code": null, "e": 4894, "s": 4385, "text": "But as you might notice that attribute topic which is supposed to be a list is represented as a string in csv file. This is due to the fact that csv only supports flat data, which means when reading the file, an extra step is required to convert string topic back to a list. Besides, csv file doesn’t store type information, so everything is interpreted as string, like attribute word_count. If I read article.csv file and print the row, I would get a dictionary object with every attribute in string format." }, { "code": null, "e": 5087, "s": 4894, "text": "In conclusion, csv file can store the attributes and values of a flat object, but can’t always store the correct information of data type. To solve this problem, we need more flexible formats." }, { "code": null, "e": 5092, "s": 5087, "text": "JSON" }, { "code": null, "e": 5329, "s": 5092, "text": "A good alternative is JSON. JSON is the most widespread format for data serialization due to its human-readable syntax, compatibility with almost every programming language, and support of nested data structures and multiple data types." }, { "code": null, "e": 5696, "s": 5329, "text": "We can write the same article object into a JSON file using the built-in library json. dump() serializes an object into a JSON formatted string, and then write it to the file object. json uses JSONEncoder class to convert a Python type into a JSON type (e.g. True => true, False => false, None => null). It’s possible to extend JSONEncoder and serialize other types." }, { "code": null, "e": 5789, "s": 5696, "text": "I would recommend another great article from RealPython on the topic of JSON data in Python." }, { "code": null, "e": 5804, "s": 5789, "text": "realpython.com" }, { "code": null, "e": 5993, "s": 5804, "text": "On the other hand, the deserialization process would be simply reading the JSON file and recreate a dictionary object. As you can see, the recreated object is the same as the original one." }, { "code": null, "e": 6341, "s": 5993, "text": "Not so surprisingly, JSON is a better choice than csv in this example because it holds more characteristics of the object than csv, thus is able to fully restore the object. But a potential problem with JSON is that you have to load the complete file into memory, while you can iterate the rows in a csv without giving too much pressure on memory." }, { "code": null, "e": 6455, "s": 6341, "text": "Of course, you can create multiple chunks to relief the memory, but it’s just something you have to keep in mind." }, { "code": null, "e": 6619, "s": 6455, "text": "Another format comparable to JSON is YAML. I’ve talked about their differences in this article. YAML also supports nested data structures and different data types." }, { "code": null, "e": 6623, "s": 6619, "text": "XML" }, { "code": null, "e": 6925, "s": 6623, "text": "The next text-based format is XML, which is used for representing nested information in a tree-like structure. It’s widely used in Web and Service-Oriented Architecture. An XML file doesn’t include any type information, but you can standardize and validate an XML file through a schema, so-called XSD." }, { "code": null, "e": 7193, "s": 6925, "text": "Python provides a built-in library xml.etree.ElementTree to help us create or read XML files, but the conversion from a dictionary to a tree element is not as straightforward as the previous formats. In this code example, I implement a simple dict2xml adapter myself." }, { "code": null, "e": 7410, "s": 7193, "text": "Accordingly, its XSD file can look like this, where each element is bound to a type. In addition to the built-in data types, you can define your own data type with xs:restriction such as xs:maxLength, xs:pattern etc." }, { "code": null, "e": 8031, "s": 7410, "text": "<xs:schema attributeFormDefault=\"unqualified\" elementFormDefault=\"qualified\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"> <xs:element name=\"article\"> <xs:complexType> <xs:sequence> <xs:element type=\"xs:string\" name=\"author\"/> <xs:element type=\"xs:string\" name=\"publication\"/> <xs:element type=\"xs:date\" name=\"publish_date\"/> <xs:element type=\"xs:string\" name=\"topics\" maxOccurs=\"unbounded\" minOccurs=\"0\"/> <xs:element type=\"xs:integer\" name=\"word_count\"/> <xs:element type=\"xs:boolean\" name=\"is_vip\"/> </xs:sequence> </xs:complexType> </xs:element></xs:schema>" }, { "code": null, "e": 8134, "s": 8031, "text": "Unfortunately, xml.etree.ElementTree doesn’t support XSD validation. A good alternative could be lxml." }, { "code": null, "e": 8437, "s": 8134, "text": "Back to the example, let’s deserialize (read) the XML file. Due to the uncertainty of data types, every element value is interpreted as string in Python. iterparse from cElementTree returns an iterator, which is useful when you want to read a large XML file and don’t want to load everything in memory." }, { "code": null, "e": 8662, "s": 8437, "text": "In conclusion, XML is a schema-based serialization format. But no matter what the type is in XSD file, Python always reads it as a string. Thus, a custom adapter is required to convert an XML data type to a Python data type." }, { "code": null, "e": 8667, "s": 8662, "text": "BSON" }, { "code": null, "e": 8938, "s": 8667, "text": "So far, we’ve looked into 3 text-based serialization formats. Next, let’s look at binary-based serialization format. This format is not human-readable, but it can effectively compress the data, and is used a lot for intercommunication and storage in distributed systems." }, { "code": null, "e": 9157, "s": 8938, "text": "BSON (binary JSON) is a binary-encoded serialization of JSON-like documents. Like JSON, BSON supports the embedding of documents and arrays. BSON also allows representation of data types that are not part of JSON spec." }, { "code": null, "e": 9324, "s": 9157, "text": "BSON is mainly used in MongoDB database. When you install pymongo, bson is part of the library. The way to encode and decode using BSON is as straightforward as JSON." }, { "code": null, "e": 9457, "s": 9324, "text": "A BSON record takes a bit more space than JSON is because it also contains the meta info of the record such as data type and length." }, { "code": null, "e": 9524, "s": 9457, "text": "On the other hand, BSON provides a few advantages over using JSON:" }, { "code": null, "e": 9725, "s": 9524, "text": "BSON supports more types than JSON, for instance, bytes and date.BSON records are easy to traverse and query due to additional metadata. It allows value retrieval without reading the entire documents." }, { "code": null, "e": 9791, "s": 9725, "text": "BSON supports more types than JSON, for instance, bytes and date." }, { "code": null, "e": 9927, "s": 9791, "text": "BSON records are easy to traverse and query due to additional metadata. It allows value retrieval without reading the entire documents." }, { "code": null, "e": 9932, "s": 9927, "text": "Avro" }, { "code": null, "e": 10177, "s": 9932, "text": "Another famous binary-based serialization format is Avro. Avro is a fast schema-based serialization format. A schema must be provided during serialization and deserialization. Due to its high-performance, it’s used most often with Apache Kafka." }, { "code": null, "e": 10621, "s": 10177, "text": "Avro schema is defined in JSON format which makes it language independent and can be stored in nearly every environment. The schema describes records using a rich type systems that allows both data definition and documentations. By having schemas, it’s possible to model the data and create a catalogue of all the entities. Such catalogue can be served on a schema registry, making schemas available for consumption by consumers and producers." }, { "code": null, "e": 10675, "s": 10621, "text": "Here is an example of Avro schema for Article entity." }, { "code": null, "e": 10898, "s": 10675, "text": "Avro is supported in many programming languages, including Python. In this example, I’m using fast-avro, a CPython based library. It’s approved that fast-avro is way faster than the pure Python implementation library avro." }, { "code": null, "e": 11068, "s": 10898, "text": "fast-avro provides writer/reader and schemaless_writer/schemaless_reader. The first option inserts the schema into .avro file as a file header, while the second doesn’t." }, { "code": null, "e": 11075, "s": 11068, "text": "Pickle" }, { "code": null, "e": 11251, "s": 11075, "text": "Alright, after showing different serialization formats, I’d like to introduce you a couple of handy Python libraries that can serialize a Python object. One of them is Pickle." }, { "code": null, "e": 11387, "s": 11251, "text": "“Pickling” is the process whereby a Python object hierarchy is converted into a byte stream, and “unpickling” is the inverse operation." }, { "code": null, "e": 11466, "s": 11387, "text": "In terms of what can be pickled and unpickled, here is the list on Python doc." }, { "code": null, "e": 11543, "s": 11466, "text": "The unpickled object belongs to the type Article and can be used right away." }, { "code": null, "e": 11754, "s": 11543, "text": "However, as stated here, Pickle module is not secure due to the possibility of code injection. Tools like Bandit will not let it go through the security checks, so never unpickle objects from untrusted sources." }, { "code": null, "e": 11769, "s": 11754, "text": "Pandas / Numpy" }, { "code": null, "e": 11973, "s": 11769, "text": "Famous data manipulation libraries like Pandas and Numpy also offer pickle-like functions. This can become handy if DataFrame or np.ndarry is agreed as a common data type between producers and consumers." }, { "code": null, "e": 12102, "s": 11973, "text": "If you know more Python libraries that can serialize data into different formats, please leave a comment below to share with us." }, { "code": null, "e": 12245, "s": 12102, "text": "Last but not least, let’s look at the performance of each serialization format/library. These tests were executed on a Macbook with 8-Core i9." }, { "code": null, "e": 12494, "s": 12245, "text": "In this example, I want to write 100 article objects into a file, and then recreate these objects in a different function. In the end, I use assert to compare the recreated objects to the original objects. The full implementation can be found here." }, { "code": null, "e": 12514, "s": 12494, "text": "The graph tells us:" }, { "code": null, "e": 13103, "s": 12514, "text": "pickle is the winner in this performance testing. It’s probably because an article object can be directly serialized without being converted to a JSON first.BSON performs better than JSON in both serialization and deserialization. The same for numpy v.s pandas.Deserialization of csv took more time is due to the steps to converting attributes from string to its original types (e.g. int or bool).As the only schema-based serialization format, the performance of avro is quite impressive.The slowness of XML can be blamed on the implementation. Please let me know how I can improve it. :)" }, { "code": null, "e": 13261, "s": 13103, "text": "pickle is the winner in this performance testing. It’s probably because an article object can be directly serialized without being converted to a JSON first." }, { "code": null, "e": 13366, "s": 13261, "text": "BSON performs better than JSON in both serialization and deserialization. The same for numpy v.s pandas." }, { "code": null, "e": 13503, "s": 13366, "text": "Deserialization of csv took more time is due to the steps to converting attributes from string to its original types (e.g. int or bool)." }, { "code": null, "e": 13595, "s": 13503, "text": "As the only schema-based serialization format, the performance of avro is quite impressive." }, { "code": null, "e": 13696, "s": 13595, "text": "The slowness of XML can be blamed on the implementation. Please let me know how I can improve it. :)" }, { "code": null, "e": 14047, "s": 13696, "text": "First of all, thanks for finishing reading such a long article. Congratulations! You survived (I survived too)! :) In this article, we went through many possibilities of serializing and deserializing a Python object. Until now, you must not feel these 2 terms intimidating anymore, as to some extend, it’s just a fancy way to say reading and writing." }, { "code": null, "e": 14368, "s": 14047, "text": "There are pros and cons on each serialization format. You should think about whether you want text-based or binary-based, schema-based or non-schema-based, what is your data format? dictionary, DataFrame or Python object? Do you want to save only the value or also the type? Do you care about the performance and memory?" } ]
How to create geometric progression series in R?
A geometric progression series is a sequence of numbers in which all the numbers after the first can be found by multiplying the previous one by a fixed number. To generate a geometric progression series in R, we can use seq function. For example, to generate a geometric progression series of 2 by having the difference of multiplication value equal to 1 up to 5 can be found as 2^seq(0,5,by=1) and the output would be 1, 2, 4, 8, 16, 32. 2^seq(0,5,by=1) [1] 1 2 4 8 16 32 2^seq(0,5,by=2) [1] 1 4 16 2^seq(0,10,by=1) [1] 1 2 4 8 16 32 64 128 256 512 1024 2^seq(0,10,by=2) [1] 1 4 16 64 256 1024 2^seq(0,20,by=1) [1] 1 2 4 8 16 32 64 128 256 [10] 512 1024 2048 4096 8192 16384 32768 65536 131072 [19] 262144 524288 1048576 2^seq(0,20,by=2) [1] 1 4 16 64 256 1024 4096 16384 65536 [10] 262144 1048576 2^seq(0,30,by=1) [1] 1 2 4 8 16 32 [7] 64 128 256 512 1024 2048 [13] 4096 8192 16384 32768 65536 131072 [19] 262144 524288 1048576 2097152 4194304 8388608 [25] 16777216 33554432 67108864 134217728 268435456 536870912 [31] 1073741824 2^seq(0,30,by=2) [1] 1 4 16 64 256 1024 [7] 4096 16384 65536 262144 1048576 4194304 [13] 16777216 67108864 268435456 1073741824 2^seq(0,30,by=5) [1] 1 32 1024 32768 1048576 33554432 1073741824 2^seq(0,35,by=1) [1] 1 2 4 8 16 32 [7] 64 128 256 512 1024 2048 [13] 4096 8192 16384 32768 65536 131072 [19] 262144 524288 1048576 2097152 4194304 8388608 [25] 16777216 33554432 67108864 134217728 268435456 536870912 [31] 1073741824 2147483648 4294967296 8589934592 17179869184 34359738368 2^seq(0,35,by=5) [1] 1 32 1024 32768 1048576 33554432 [7] 1073741824 34359738368 2^seq(0,35,by=7) [1] 1 128 16384 2097152 268435456 34359738368 2^seq(0,39,by=1) [1] 1 2 4 8 16 [6] 32 64 128 256 512 [11] 1024 2048 4096 8192 16384 [16] 32768 65536 131072 262144 524288 [21] 1048576 2097152 4194304 8388608 16777216 [26] 33554432 67108864 134217728 268435456 536870912 [31] 1073741824 2147483648 4294967296 8589934592 17179869184 [36] 34359738368 68719476736 137438953472 274877906944 549755813888 2^seq(0,100,by=1) [1] 1.000000e+00 2.000000e+00 4.000000e+00 8.000000e+00 1.600000e+01 [6] 3.200000e+01 6.400000e+01 1.280000e+02 2.560000e+02 5.120000e+02 [11] 1.024000e+03 2.048000e+03 4.096000e+03 8.192000e+03 1.638400e+04 [16] 3.276800e+04 6.553600e+04 1.310720e+05 2.621440e+05 5.242880e+05 [21] 1.048576e+06 2.097152e+06 4.194304e+06 8.388608e+06 1.677722e+07 [26] 3.355443e+07 6.710886e+07 1.342177e+08 2.684355e+08 5.368709e+08 [31] 1.073742e+09 2.147484e+09 4.294967e+09 8.589935e+09 1.717987e+10 [36] 3.435974e+10 6.871948e+10 1.374390e+11 2.748779e+11 5.497558e+11 [41] 1.099512e+12 2.199023e+12 4.398047e+12 8.796093e+12 1.759219e+13 [46] 3.518437e+13 7.036874e+13 1.407375e+14 2.814750e+14 5.629500e+14 [51] 1.125900e+15 2.251800e+15 4.503600e+15 9.007199e+15 1.801440e+16 [56] 3.602880e+16 7.205759e+16 1.441152e+17 2.882304e+17 5.764608e+17 [61] 1.152922e+18 2.305843e+18 4.611686e+18 9.223372e+18 1.844674e+19 [66] 3.689349e+19 7.378698e+19 1.475740e+20 2.951479e+20 5.902958e+20 [71] 1.180592e+21 2.361183e+21 4.722366e+21 9.444733e+21 1.888947e+22 [76] 3.777893e+22 7.555786e+22 1.511157e+23 3.022315e+23 6.044629e+23 [81] 1.208926e+24 2.417852e+24 4.835703e+24 9.671407e+24 1.934281e+25 [86] 3.868563e+25 7.737125e+25 1.547425e+26 3.094850e+26 6.189700e+26 [91] 1.237940e+27 2.475880e+27 4.951760e+27 9.903520e+27 1.980704e+28 [96] 3.961408e+28 7.922816e+28 1.584563e+29 3.169127e+29 6.338253e+29 [101] 1.267651e+30 2^seq(0,100,by=2) [1] 1.000000e+00 4.000000e+00 1.600000e+01 6.400000e+01 2.560000e+02 [6] 1.024000e+03 4.096000e+03 1.638400e+04 6.553600e+04 2.621440e+05 [11] 1.048576e+06 4.194304e+06 1.677722e+07 6.710886e+07 2.684355e+08 [16] 1.073742e+09 4.294967e+09 1.717987e+10 6.871948e+10 2.748779e+11 [21] 1.099512e+12 4.398047e+12 1.759219e+13 7.036874e+13 2.814750e+14 [26] 1.125900e+15 4.503600e+15 1.801440e+16 7.205759e+16 2.882304e+17 [31] 1.152922e+18 4.611686e+18 1.844674e+19 7.378698e+19 2.951479e+20 [36] 1.180592e+21 4.722366e+21 1.888947e+22 7.555786e+22 3.022315e+23 [41] 1.208926e+24 4.835703e+24 1.934281e+25 7.737125e+25 3.094850e+26 [46] 1.237940e+27 4.951760e+27 1.980704e+28 7.922816e+28 3.169127e+29 [51] 1.267651e+30 2^seq(0,100,by=4) [1] 1.000000e+00 1.600000e+01 2.560000e+02 4.096000e+03 6.553600e+04 [6] 1.048576e+06 1.677722e+07 2.684355e+08 4.294967e+09 6.871948e+10 [11] 1.099512e+12 1.759219e+13 2.814750e+14 4.503600e+15 7.205759e+16 [16] 1.152922e+18 1.844674e+19 2.951479e+20 4.722366e+21 7.555786e+22 [21] 1.208926e+24 1.934281e+25 3.094850e+26 4.951760e+27 7.922816e+28 [26] 1.267651e+30 2^seq(0,100,by=5) [1] 1.000000e+00 3.200000e+01 1.024000e+03 3.276800e+04 1.048576e+06 [6] 3.355443e+07 1.073742e+09 3.435974e+10 1.099512e+12 3.518437e+13 [11] 1.125900e+15 3.602880e+16 1.152922e+18 3.689349e+19 1.180592e+21 [16] 3.777893e+22 1.208926e+24 3.868563e+25 1.237940e+27 3.961408e+28 [21] 1.267651e+30
[ { "code": null, "e": 1502, "s": 1062, "text": "A geometric progression series is a sequence of numbers in which all the numbers after the first can be found by multiplying the previous one by a fixed number. To generate a geometric progression series in R, we can use seq function. For example, to generate a geometric progression series of 2 by having the difference of multiplication value equal to 1 up to 5 can be found as 2^seq(0,5,by=1) and the output would be 1, 2, 4, 8, 16, 32." }, { "code": null, "e": 5940, "s": 1502, "text": "2^seq(0,5,by=1)\n[1] 1 2 4 8 16 32\n2^seq(0,5,by=2)\n[1] 1 4 16\n2^seq(0,10,by=1)\n[1] 1 2 4 8 16 32 64 128 256 512 1024\n2^seq(0,10,by=2)\n[1] 1 4 16 64 256 1024\n2^seq(0,20,by=1)\n[1] 1 2 4 8 16 32 64 128 256\n[10] 512 1024 2048 4096 8192 16384 32768 65536 131072\n[19] 262144 524288 1048576\n2^seq(0,20,by=2)\n[1] 1 4 16 64 256 1024 4096 16384 65536\n[10] 262144 1048576\n2^seq(0,30,by=1)\n[1] 1 2 4 8 16 32\n[7] 64 128 256 512 1024 2048\n[13] 4096 8192 16384 32768 65536 131072\n[19] 262144 524288 1048576 2097152 4194304 8388608\n[25] 16777216 33554432 67108864 134217728 268435456 536870912\n[31] 1073741824\n2^seq(0,30,by=2)\n[1] 1 4 16 64 256 1024\n[7] 4096 16384 65536 262144 1048576 4194304\n[13] 16777216 67108864 268435456 1073741824\n2^seq(0,30,by=5)\n[1] 1 32 1024 32768 1048576 33554432 1073741824\n2^seq(0,35,by=1)\n[1] 1 2 4 8 16 32\n[7] 64 128 256 512 1024 2048\n[13] 4096 8192 16384 32768 65536 131072\n[19] 262144 524288 1048576 2097152 4194304 8388608\n[25] 16777216 33554432 67108864 134217728 268435456 536870912\n[31] 1073741824 2147483648 4294967296 8589934592 17179869184 34359738368\n2^seq(0,35,by=5)\n[1] 1 32 1024 32768 1048576 33554432\n[7] 1073741824 34359738368\n2^seq(0,35,by=7)\n[1] 1 128 16384 2097152 268435456 34359738368\n2^seq(0,39,by=1)\n[1] 1 2 4 8 16\n[6] 32 64 128 256 512\n[11] 1024 2048 4096 8192 16384\n[16] 32768 65536 131072 262144 524288\n[21] 1048576 2097152 4194304 8388608 16777216\n[26] 33554432 67108864 134217728 268435456 536870912\n[31] 1073741824 2147483648 4294967296 8589934592 17179869184\n[36] 34359738368 68719476736 137438953472 274877906944 549755813888\n2^seq(0,100,by=1)\n[1] 1.000000e+00 2.000000e+00 4.000000e+00 8.000000e+00 1.600000e+01\n[6] 3.200000e+01 6.400000e+01 1.280000e+02 2.560000e+02 5.120000e+02\n[11] 1.024000e+03 2.048000e+03 4.096000e+03 8.192000e+03 1.638400e+04\n[16] 3.276800e+04 6.553600e+04 1.310720e+05 2.621440e+05 5.242880e+05\n[21] 1.048576e+06 2.097152e+06 4.194304e+06 8.388608e+06 1.677722e+07\n[26] 3.355443e+07 6.710886e+07 1.342177e+08 2.684355e+08 5.368709e+08\n[31] 1.073742e+09 2.147484e+09 4.294967e+09 8.589935e+09 1.717987e+10\n[36] 3.435974e+10 6.871948e+10 1.374390e+11 2.748779e+11 5.497558e+11\n[41] 1.099512e+12 2.199023e+12 4.398047e+12 8.796093e+12 1.759219e+13\n[46] 3.518437e+13 7.036874e+13 1.407375e+14 2.814750e+14 5.629500e+14\n[51] 1.125900e+15 2.251800e+15 4.503600e+15 9.007199e+15 1.801440e+16\n[56] 3.602880e+16 7.205759e+16 1.441152e+17 2.882304e+17 5.764608e+17\n[61] 1.152922e+18 2.305843e+18 4.611686e+18 9.223372e+18 1.844674e+19\n[66] 3.689349e+19 7.378698e+19 1.475740e+20 2.951479e+20 5.902958e+20\n[71] 1.180592e+21 2.361183e+21 4.722366e+21 9.444733e+21 1.888947e+22\n[76] 3.777893e+22 7.555786e+22 1.511157e+23 3.022315e+23 6.044629e+23\n[81] 1.208926e+24 2.417852e+24 4.835703e+24 9.671407e+24 1.934281e+25\n[86] 3.868563e+25 7.737125e+25 1.547425e+26 3.094850e+26 6.189700e+26\n[91] 1.237940e+27 2.475880e+27 4.951760e+27 9.903520e+27 1.980704e+28\n[96] 3.961408e+28 7.922816e+28 1.584563e+29 3.169127e+29 6.338253e+29\n[101] 1.267651e+30\n2^seq(0,100,by=2)\n[1] 1.000000e+00 4.000000e+00 1.600000e+01 6.400000e+01 2.560000e+02\n[6] 1.024000e+03 4.096000e+03 1.638400e+04 6.553600e+04 2.621440e+05\n[11] 1.048576e+06 4.194304e+06 1.677722e+07 6.710886e+07 2.684355e+08\n[16] 1.073742e+09 4.294967e+09 1.717987e+10 6.871948e+10 2.748779e+11\n[21] 1.099512e+12 4.398047e+12 1.759219e+13 7.036874e+13 2.814750e+14\n[26] 1.125900e+15 4.503600e+15 1.801440e+16 7.205759e+16 2.882304e+17\n[31] 1.152922e+18 4.611686e+18 1.844674e+19 7.378698e+19 2.951479e+20\n[36] 1.180592e+21 4.722366e+21 1.888947e+22 7.555786e+22 3.022315e+23\n[41] 1.208926e+24 4.835703e+24 1.934281e+25 7.737125e+25 3.094850e+26\n[46] 1.237940e+27 4.951760e+27 1.980704e+28 7.922816e+28 3.169127e+29\n[51] 1.267651e+30\n2^seq(0,100,by=4)\n[1] 1.000000e+00 1.600000e+01 2.560000e+02 4.096000e+03 6.553600e+04\n[6] 1.048576e+06 1.677722e+07 2.684355e+08 4.294967e+09 6.871948e+10\n[11] 1.099512e+12 1.759219e+13 2.814750e+14 4.503600e+15 7.205759e+16\n[16] 1.152922e+18 1.844674e+19 2.951479e+20 4.722366e+21 7.555786e+22\n[21] 1.208926e+24 1.934281e+25 3.094850e+26 4.951760e+27 7.922816e+28\n[26] 1.267651e+30\n2^seq(0,100,by=5)\n[1] 1.000000e+00 3.200000e+01 1.024000e+03 3.276800e+04 1.048576e+06\n[6] 3.355443e+07 1.073742e+09 3.435974e+10 1.099512e+12 3.518437e+13\n[11] 1.125900e+15 3.602880e+16 1.152922e+18 3.689349e+19 1.180592e+21\n[16] 3.777893e+22 1.208926e+24 3.868563e+25 1.237940e+27 3.961408e+28\n[21] 1.267651e+30" } ]
What is the correct use of schema.org SiteNavigationElement in HTML?
The schema.org SiteNavigationElement extends WebPageElement. It is used to mark-up links that would make amazing contextual links. <nav role = "navigation" itemscope itemtype = "http://schema.org/SiteNavigationElement"> <ul> <li> <a href = "https://example.com/" title = "Link to home page" itemprop = "url"> <span itemprop="name">Home page</span> </a> </li> <li> <a href = "https://examplecom/demo" title="Link to demo page" itemprop = "url"> <span itemprop = "name">My demo page</span> </a> </li> </ul>
[ { "code": null, "e": 1193, "s": 1062, "text": "The schema.org SiteNavigationElement extends WebPageElement. It is used to mark-up links that would make amazing contextual links." }, { "code": null, "e": 1621, "s": 1193, "text": "<nav role = \"navigation\" itemscope itemtype = \"http://schema.org/SiteNavigationElement\">\n<ul>\n <li>\n <a href = \"https://example.com/\" title = \"Link to home page\" itemprop = \"url\">\n <span itemprop=\"name\">Home page</span>\n </a>\n </li>\n <li>\n <a href = \"https://examplecom/demo\" title=\"Link to demo page\" itemprop = \"url\">\n <span itemprop = \"name\">My demo page</span>\n </a>\n </li>\n</ul>" } ]
Modulus function in C++ STL
In this article, we will be discussing the working, syntax, and examples of modulus functions in C++. modulus function object class in C++, which is defined in <functional> header file. modulus function is a binary function object class used to get the result of the modulus operation of the two arguments. This function works the same as the operator ‘% ‘. Template struct modulus : binary_function { T operator() (const T& a, const T& b) const {return a%b; } }; The function accepts the following parameter(s) − T − This is the type of the argument passed to function call. T − This is the type of the argument passed to function call. Live Demo #include <iostream> #include <algorithm> #include <functional&g; using namespace std; int main(){ //create an array int arr[] = { 10, 20, 35, 45, 50, 61 }; int rem[6]; transform(arr, arr + 6, rem,bind2nd(modulus<int>(), 2)); for (int i = 0; i < 5; i++){ cout << arr[i] << " is a "<<(rem[i] == 0 ? "even" : "odd")<<"\n"; } return 0; } If we run the above code it will generate the following output − 10 is a even 20 is a even 35 is a odd 45 is a odd 50 is a even
[ { "code": null, "e": 1164, "s": 1062, "text": "In this article, we will be discussing the working, syntax, and examples of modulus functions in C++." }, { "code": null, "e": 1420, "s": 1164, "text": "modulus function object class in C++, which is defined in <functional> header file. modulus\nfunction is a binary function object class used to get the result of the modulus operation of the\ntwo arguments. This function works the same as the operator ‘% ‘." }, { "code": null, "e": 1529, "s": 1420, "text": "Template struct modulus : binary_function\n{\n T operator() (const T& a, const T& b) const {return a%b; }\n};" }, { "code": null, "e": 1579, "s": 1529, "text": "The function accepts the following parameter(s) −" }, { "code": null, "e": 1641, "s": 1579, "text": "T − This is the type of the argument passed to function call." }, { "code": null, "e": 1703, "s": 1641, "text": "T − This is the type of the argument passed to function call." }, { "code": null, "e": 1714, "s": 1703, "text": " Live Demo" }, { "code": null, "e": 2075, "s": 1714, "text": "#include <iostream>\n#include <algorithm>\n#include <functional&g;\nusing namespace std;\nint main(){\n //create an array\n int arr[] = { 10, 20, 35, 45, 50, 61 };\n int rem[6];\n transform(arr, arr + 6, rem,bind2nd(modulus<int>(), 2));\n for (int i = 0; i < 5; i++){\n cout << arr[i] << \" is a \"<<(rem[i] == 0 ? \"even\" : \"odd\")<<\"\\n\";\n }\n return 0;\n}" }, { "code": null, "e": 2140, "s": 2075, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2203, "s": 2140, "text": "10 is a even\n20 is a even\n35 is a odd\n45 is a odd\n50 is a even" } ]
Java log10() with example - GeeksforGeeks
29 Mar, 2018 The java.lang.Math.log10() is one of the Java Math Library method which is used to return the base 10logarithmic value of given double value as a parameter. There are various cases : If the argument is positive double value, Math.log10() method will return the logarithm of a givenvalue. If the argument is NaN or less than zero, Math.log10() method will return NaN. If the argument is positive infinity, Math.log10() method will return the result as Positive Infinity. If the argument is positive or negative zero, Math.log10() method will return the result as NegativeInfinity.Syntax :public static double log10(double a)Parameter :a : User inputReturn :This method returns the base 10 logarithm of a.Example :To show working of java.lang.Math.log10() method.// Java program to demonstrate working// of java.lang.Math.log10() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 1000; double b = 145.256; double c = -6.04; double d = 1.0 / 0; double e = 0; // A power of 10 as input System.out.println(Math.log10(a)); // positive double value as argument, // output double value System.out.println(Math.log10(b)); // negative integer as argument, // output NAN System.out.println(Math.log10(c)); // positive infinity as argument, // output Infinity System.out.println(Math.log10(d)); // positive zero as argument, // output -Infinity System.out.println(Math.log10(e)); }}Output:3.0 2.1621340805671756 NaN Infinity -Infinity My Personal Notes arrow_drop_upSave Syntax : public static double log10(double a) Parameter : a : User input Return : This method returns the base 10 logarithm of a. Example :To show working of java.lang.Math.log10() method. // Java program to demonstrate working// of java.lang.Math.log10() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 1000; double b = 145.256; double c = -6.04; double d = 1.0 / 0; double e = 0; // A power of 10 as input System.out.println(Math.log10(a)); // positive double value as argument, // output double value System.out.println(Math.log10(b)); // negative integer as argument, // output NAN System.out.println(Math.log10(c)); // positive infinity as argument, // output Infinity System.out.println(Math.log10(d)); // positive zero as argument, // output -Infinity System.out.println(Math.log10(e)); }} 3.0 2.1621340805671756 NaN Infinity -Infinity java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java LinkedList in Java
[ { "code": null, "e": 24085, "s": 24057, "text": "\n29 Mar, 2018" }, { "code": null, "e": 24268, "s": 24085, "text": "The java.lang.Math.log10() is one of the Java Math Library method which is used to return the base 10logarithmic value of given double value as a parameter. There are various cases :" }, { "code": null, "e": 24373, "s": 24268, "text": "If the argument is positive double value, Math.log10() method will return the logarithm of a givenvalue." }, { "code": null, "e": 24452, "s": 24373, "text": "If the argument is NaN or less than zero, Math.log10() method will return NaN." }, { "code": null, "e": 24555, "s": 24452, "text": "If the argument is positive infinity, Math.log10() method will return the result as Positive Infinity." }, { "code": null, "e": 25762, "s": 24555, "text": "If the argument is positive or negative zero, Math.log10() method will return the result as NegativeInfinity.Syntax :public static double log10(double a)Parameter :a : User inputReturn :This method returns the base 10 logarithm of a.Example :To show working of java.lang.Math.log10() method.// Java program to demonstrate working// of java.lang.Math.log10() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 1000; double b = 145.256; double c = -6.04; double d = 1.0 / 0; double e = 0; // A power of 10 as input System.out.println(Math.log10(a)); // positive double value as argument, // output double value System.out.println(Math.log10(b)); // negative integer as argument, // output NAN System.out.println(Math.log10(c)); // positive infinity as argument, // output Infinity System.out.println(Math.log10(d)); // positive zero as argument, // output -Infinity System.out.println(Math.log10(e)); }}Output:3.0\n2.1621340805671756\nNaN\nInfinity\n-Infinity\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 25771, "s": 25762, "text": "Syntax :" }, { "code": null, "e": 25808, "s": 25771, "text": "public static double log10(double a)" }, { "code": null, "e": 25820, "s": 25808, "text": "Parameter :" }, { "code": null, "e": 25835, "s": 25820, "text": "a : User input" }, { "code": null, "e": 25844, "s": 25835, "text": "Return :" }, { "code": null, "e": 25892, "s": 25844, "text": "This method returns the base 10 logarithm of a." }, { "code": null, "e": 25951, "s": 25892, "text": "Example :To show working of java.lang.Math.log10() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.log10() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = 1000; double b = 145.256; double c = -6.04; double d = 1.0 / 0; double e = 0; // A power of 10 as input System.out.println(Math.log10(a)); // positive double value as argument, // output double value System.out.println(Math.log10(b)); // negative integer as argument, // output NAN System.out.println(Math.log10(c)); // positive infinity as argument, // output Infinity System.out.println(Math.log10(d)); // positive zero as argument, // output -Infinity System.out.println(Math.log10(e)); }}", "e": 26779, "s": 25951, "text": null }, { "code": null, "e": 26826, "s": 26779, "text": "3.0\n2.1621340805671756\nNaN\nInfinity\n-Infinity\n" }, { "code": null, "e": 26836, "s": 26826, "text": "java-math" }, { "code": null, "e": 26841, "s": 26836, "text": "Java" }, { "code": null, "e": 26846, "s": 26841, "text": "Java" }, { "code": null, "e": 26944, "s": 26846, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26953, "s": 26944, "text": "Comments" }, { "code": null, "e": 26966, "s": 26953, "text": "Old Comments" }, { "code": null, "e": 27017, "s": 26966, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27047, "s": 27017, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27078, "s": 27047, "text": "How to iterate any Map in Java" }, { "code": null, "e": 27097, "s": 27078, "text": "Interfaces in Java" }, { "code": null, "e": 27129, "s": 27097, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27147, "s": 27129, "text": "ArrayList in Java" }, { "code": null, "e": 27167, "s": 27147, "text": "Stack Class in Java" }, { "code": null, "e": 27199, "s": 27167, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27223, "s": 27199, "text": "Singleton Class in Java" } ]
Stop Overusing “+” to Join Strings in Python | by Frank Andrade | Towards Data Science
One common task data scientists have to deal with when collecting and cleaning data is working with strings. This involves formatting as well as joining strings (also known as string concatenation). Joining strings in Python — and other programming languages — is as simple as using the plus operator +. You’ve probably used the code below hundreds of times to join strings in Python. >>> str1 = "Hello ">>> str2 = "World">>> str1 + str2"Hello World" This approach is fine. However, this becomes impractical when working with lists, dataframes, or if you’re aiming for readability. In this article, I‘ll show you 3 alternatives that will not only help you concatenate strings but also allow you easily join list elements, properly format strings in Python, and make debugging less complicated. Python f-string was introduced in Python 3.6 and allows us to join strings the same way the plus operator would do; however, f-strings use curly braces {} to store a value that will be formatted into a string. As an example let’s print the sentence “Python was created by Guido van Rossum and released in 1991” using f-string. In this case, we will use the name ‘Guido van Rossum’ and the year ‘1991’ as variables. Let’s have a look at the f-string syntax. >>> name = 'Guido van Rossum'>>> year = 1991>>> f'Python was created by {name} and released in {year}' It has a cleaner syntax than the + operator, isn’t it? You can also format text numbers or dates using f-string. Let’s say we get today’s date with the datetime library and we want to add it to a text. >>> import datetime>>> now = datetime.datetime.now()>>> f'Today is {now:%B} {now:%-d}, {now:%Y}' Python will print ‘Today is October 1, 2021’. As a side note, the %B, %-d and %Y are format codes. You can find other time format codes available in this Python strftime cheatsheet. Now let’s format a numeric value. >>> gpa = 3.355>>> f'His GPA is {gpa:.1f}' Python will round the number to the first decimal and print ‘His GPA is 3.4’In this example, the .f is a format code that represents “floating point numbers,” so in the example, above we specified 1 digit of precision. You can find more format codes like these on this link. Something cool about f-string is that developers keep adding new functionalities. Python introduced a brand new feature in Python 3.8 that added the = to f-strings. This simplifies the frequent print-debugging, so instead of writing the code below to print both a variable name and its value. >>> python_version = 3.8>>> f"python_version={python_version}"'python_version=3.8' You can now only write this: >>> f"{python_version=}"'python_version=3.8' When you want to join multiple strings stored in a list, the easiest option is to use the join() method. You only need to specify a separator before using the join() method. Let’s say we have the same sentence used before, but now each word is stored in a list calledwords. words = ['Python', 'was', 'created', 'by', 'Guido', 'van', 'Rossum', 'and', 'first', 'released', 'in', '1991'] We use the join method and an empty string ‘ ’ as a separator to build the sentence we had before. >>> ' '.join(words) The join() method is not only a useful way to concatenate list elements but is also preferred over the + operator because of its performance. Thejoin() method can be 4 times faster than using + to join strings in a list. We can use the str.format() to concatenate strings in Python. We only need to insert curly braces {} for every variable we want to add inside a string. The curly braces operator will help us format strings in Python. Let’s have a look. >>> name = 'Guido van Rossum'>>> year = 1991>>> "Python was created by {} and released in {}".format(name, year) One of the reasons why str.format() is preferred over the + operator is that we don’t have to explicitly convert integers into strings before concatenating. In the example above, we didn’t have to convert theyear variable into a string as we would do when using the + operator. Unfortunately, one disadvantage of using str.format() is that the code could get quite long when dealing with many variables and long strings. This is why f-string is preferred over str.format(). That’s it! Those are the 3 alternatives to joining strings with the + operator in Python. Use them wisely to write better Python code. Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF) If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to thousands of Python guides and Data science articles. If you sign up using my link, I’ll earn a small commission with no extra cost to you.
[ { "code": null, "e": 370, "s": 171, "text": "One common task data scientists have to deal with when collecting and cleaning data is working with strings. This involves formatting as well as joining strings (also known as string concatenation)." }, { "code": null, "e": 556, "s": 370, "text": "Joining strings in Python — and other programming languages — is as simple as using the plus operator +. You’ve probably used the code below hundreds of times to join strings in Python." }, { "code": null, "e": 622, "s": 556, "text": ">>> str1 = \"Hello \">>> str2 = \"World\">>> str1 + str2\"Hello World\"" }, { "code": null, "e": 753, "s": 622, "text": "This approach is fine. However, this becomes impractical when working with lists, dataframes, or if you’re aiming for readability." }, { "code": null, "e": 965, "s": 753, "text": "In this article, I‘ll show you 3 alternatives that will not only help you concatenate strings but also allow you easily join list elements, properly format strings in Python, and make debugging less complicated." }, { "code": null, "e": 1175, "s": 965, "text": "Python f-string was introduced in Python 3.6 and allows us to join strings the same way the plus operator would do; however, f-strings use curly braces {} to store a value that will be formatted into a string." }, { "code": null, "e": 1380, "s": 1175, "text": "As an example let’s print the sentence “Python was created by Guido van Rossum and released in 1991” using f-string. In this case, we will use the name ‘Guido van Rossum’ and the year ‘1991’ as variables." }, { "code": null, "e": 1422, "s": 1380, "text": "Let’s have a look at the f-string syntax." }, { "code": null, "e": 1525, "s": 1422, "text": ">>> name = 'Guido van Rossum'>>> year = 1991>>> f'Python was created by {name} and released in {year}'" }, { "code": null, "e": 1580, "s": 1525, "text": "It has a cleaner syntax than the + operator, isn’t it?" }, { "code": null, "e": 1727, "s": 1580, "text": "You can also format text numbers or dates using f-string. Let’s say we get today’s date with the datetime library and we want to add it to a text." }, { "code": null, "e": 1824, "s": 1727, "text": ">>> import datetime>>> now = datetime.datetime.now()>>> f'Today is {now:%B} {now:%-d}, {now:%Y}'" }, { "code": null, "e": 2006, "s": 1824, "text": "Python will print ‘Today is October 1, 2021’. As a side note, the %B, %-d and %Y are format codes. You can find other time format codes available in this Python strftime cheatsheet." }, { "code": null, "e": 2040, "s": 2006, "text": "Now let’s format a numeric value." }, { "code": null, "e": 2083, "s": 2040, "text": ">>> gpa = 3.355>>> f'His GPA is {gpa:.1f}'" }, { "code": null, "e": 2358, "s": 2083, "text": "Python will round the number to the first decimal and print ‘His GPA is 3.4’In this example, the .f is a format code that represents “floating point numbers,” so in the example, above we specified 1 digit of precision. You can find more format codes like these on this link." }, { "code": null, "e": 2651, "s": 2358, "text": "Something cool about f-string is that developers keep adding new functionalities. Python introduced a brand new feature in Python 3.8 that added the = to f-strings. This simplifies the frequent print-debugging, so instead of writing the code below to print both a variable name and its value." }, { "code": null, "e": 2734, "s": 2651, "text": ">>> python_version = 3.8>>> f\"python_version={python_version}\"'python_version=3.8'" }, { "code": null, "e": 2763, "s": 2734, "text": "You can now only write this:" }, { "code": null, "e": 2808, "s": 2763, "text": ">>> f\"{python_version=}\"'python_version=3.8'" }, { "code": null, "e": 2982, "s": 2808, "text": "When you want to join multiple strings stored in a list, the easiest option is to use the join() method. You only need to specify a separator before using the join() method." }, { "code": null, "e": 3082, "s": 2982, "text": "Let’s say we have the same sentence used before, but now each word is stored in a list calledwords." }, { "code": null, "e": 3193, "s": 3082, "text": "words = ['Python', 'was', 'created', 'by', 'Guido', 'van', 'Rossum', 'and', 'first', 'released', 'in', '1991']" }, { "code": null, "e": 3292, "s": 3193, "text": "We use the join method and an empty string ‘ ’ as a separator to build the sentence we had before." }, { "code": null, "e": 3312, "s": 3292, "text": ">>> ' '.join(words)" }, { "code": null, "e": 3533, "s": 3312, "text": "The join() method is not only a useful way to concatenate list elements but is also preferred over the + operator because of its performance. Thejoin() method can be 4 times faster than using + to join strings in a list." }, { "code": null, "e": 3750, "s": 3533, "text": "We can use the str.format() to concatenate strings in Python. We only need to insert curly braces {} for every variable we want to add inside a string. The curly braces operator will help us format strings in Python." }, { "code": null, "e": 3769, "s": 3750, "text": "Let’s have a look." }, { "code": null, "e": 3882, "s": 3769, "text": ">>> name = 'Guido van Rossum'>>> year = 1991>>> \"Python was created by {} and released in {}\".format(name, year)" }, { "code": null, "e": 4160, "s": 3882, "text": "One of the reasons why str.format() is preferred over the + operator is that we don’t have to explicitly convert integers into strings before concatenating. In the example above, we didn’t have to convert theyear variable into a string as we would do when using the + operator." }, { "code": null, "e": 4356, "s": 4160, "text": "Unfortunately, one disadvantage of using str.format() is that the code could get quite long when dealing with many variables and long strings. This is why f-string is preferred over str.format()." }, { "code": null, "e": 4491, "s": 4356, "text": "That’s it! Those are the 3 alternatives to joining strings with the + operator in Python. Use them wisely to write better Python code." }, { "code": null, "e": 4609, "s": 4491, "text": "Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)" } ]
PHP Function arguments
A function in PHP can be defined to accept input from calling environment/script in the form of arguments. These arguments are given as comma separeted list inside the parentheses in front of name of function. Note that while calling a function, same number of arguments must be passed to it. PHP supports calling a function by passing value, reference, arguments with default value and by passing variable number of arguments. In following example, a function is defined with two formal arguments. When this function is called by passing the arguments by value. Arguments of function become its local variables. Hence, any change in value of argument inside a function doesn't reflect outside it. Here, value of $x is changed inside the function, but if we check its value after call to function, it has not changed Live Demo <?php function add($x, $y){ $x= $x+$y ; echo $x . "\n"; } $x=10; $y=20; add($x,$y); //outside function $x has previous value. echo $x; ?> This will produce following result. − 30 10 In following example, add() function is defined to receive array as argument. Inside the function, array elements are traversed using foreach loop Live Demo <?php function add($arr){ $sum=0; foreach ($arr as $i){ $sum+=$i; } echo "sum = " .$sum; } add(array(1,2,3)); ?> This will produce following result. − sum = 6 Values are passed to a function's arguments by value. Hence, changes to argument's value inside function are not reflected outside it. When arguments are passed by reference, changes are carried to the argument's value outside it. In order to receive value by reference, the argument's name must be prefixed by $ symbol Live Demo <?php function swap(&$x, &$y){ $t=$x; $x=$y; $y=$t; echo "inside function x=$x y=$y\n"; } $x=5; $y=7; echo "before calling function x=$x y=$y\n"; swap($x, $y); echo "after calling function x=$x y=$y\n"; ?> This will produce following result. − before calling function x=5 y=7 inside function x=7 y=5 after calling function x=7 y=5 Values of variables xandy are interchanged in swap() function. Since, variables are passed by reference, the variables show modified values outside the function too PHP in fact is a dynamically typed language. Hence, it is not necessary to declare a variable with its type (as in C/C++ or Java). However, type declaration of arguments in a function llows the parser to detect incorrect data types passed to the function. //define a function with type hints function myfunction(type $arg1, type $arg2){ .. .. } All standard PHP data types including scalar types, array, class/interface, iterable and object are valid types for providing type hints in a function declaration Live Demo <?php function add(...$numbers){ $ttl=0; foreach ($numbers as $num){ $ttl=$ttl+$num; } return $ttl; } $total=add(10,15,20); echo "total= $total\n"; echo "total=". add(1,2,3,4,5). "\n"; ?> This will produce following result. − total= 45 total=15 It is also possible to obtain a list of arguments passed to a function with the help of func_get_args() function. We can run a PHP loop to traverse each value in the list of arguments passed. In that case the function definition doesn't have a formal argument. Live Demo <?php function add (int $x, int $y){ $z=$x+$y; echo "addition=$z\n"; } add(10,20); add(5.55, 6.66); ?> This will produce following result. − addition=30 addition=11 Note that in second call to add() function, floats are given as arguments, but still no error/warning is displayed. This is because PHP internally coerces float into integer for performing addition. In order to prevent such automatic type conversion, use declareconstruct with strict_types=1 Live Demo <?php declare(strict_types=1); function add (int $x, int $y){ $z=$x+$y; echo "addition=$z\n"; } add(10,20); add(5.55, 6.66); ?> Second call to add() function will now throw exception − addition=30 PHP Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, float given
[ { "code": null, "e": 1355, "s": 1062, "text": "A function in PHP can be defined to accept input from calling environment/script in the form of arguments. These arguments are given as comma separeted list inside the parentheses in front of name of function. Note that while calling a function, same number of arguments must be passed to it." }, { "code": null, "e": 1490, "s": 1355, "text": "PHP supports calling a function by passing value, reference, arguments with default value and by passing variable number of arguments." }, { "code": null, "e": 1760, "s": 1490, "text": "In following example, a function is defined with two formal arguments. When this function is called by passing the arguments by value. Arguments of function become its local variables. Hence, any change in value of argument inside a function doesn't reflect outside it." }, { "code": null, "e": 1879, "s": 1760, "text": "Here, value of $x is changed inside the function, but if we check its value after call to function, it has not changed" }, { "code": null, "e": 1890, "s": 1879, "text": " Live Demo" }, { "code": null, "e": 2034, "s": 1890, "text": "<?php\nfunction add($x, $y){\n $x= $x+$y ;\n echo $x . \"\\n\";\n}\n$x=10;\n$y=20;\nadd($x,$y);\n//outside function $x has previous value.\necho $x;\n?>" }, { "code": null, "e": 2072, "s": 2034, "text": "This will produce following result. −" }, { "code": null, "e": 2078, "s": 2072, "text": "30\n10" }, { "code": null, "e": 2225, "s": 2078, "text": "In following example, add() function is defined to receive array as argument. Inside the function, array elements are traversed using foreach loop" }, { "code": null, "e": 2236, "s": 2225, "text": " Live Demo" }, { "code": null, "e": 2367, "s": 2236, "text": "<?php\nfunction add($arr){\n $sum=0;\n foreach ($arr as $i){\n $sum+=$i;\n }\n echo \"sum = \" .$sum;\n}\nadd(array(1,2,3));\n?>" }, { "code": null, "e": 2405, "s": 2367, "text": "This will produce following result. −" }, { "code": null, "e": 2413, "s": 2405, "text": "sum = 6" }, { "code": null, "e": 2644, "s": 2413, "text": "Values are passed to a function's arguments by value. Hence, changes to argument's value inside function are not reflected outside it. When arguments are passed by reference, changes are carried to the argument's value outside it." }, { "code": null, "e": 2733, "s": 2644, "text": "In order to receive value by reference, the argument's name must be prefixed by $ symbol" }, { "code": null, "e": 2744, "s": 2733, "text": " Live Demo" }, { "code": null, "e": 2962, "s": 2744, "text": "<?php\nfunction swap(&$x, &$y){\n $t=$x;\n $x=$y;\n $y=$t;\n echo \"inside function x=$x y=$y\\n\";\n}\n$x=5;\n$y=7;\necho \"before calling function x=$x y=$y\\n\";\nswap($x, $y);\necho \"after calling function x=$x y=$y\\n\";\n?>" }, { "code": null, "e": 3000, "s": 2962, "text": "This will produce following result. −" }, { "code": null, "e": 3087, "s": 3000, "text": "before calling function x=5 y=7\ninside function x=7 y=5\nafter calling function x=7 y=5" }, { "code": null, "e": 3252, "s": 3087, "text": "Values of variables xandy are interchanged in swap() function. Since, variables are passed by reference, the variables show modified values outside the function too" }, { "code": null, "e": 3508, "s": 3252, "text": "PHP in fact is a dynamically typed language. Hence, it is not necessary to declare a variable with its type (as in C/C++ or Java). However, type declaration of arguments in a function llows the parser to detect incorrect data types passed to the function." }, { "code": null, "e": 3603, "s": 3508, "text": "//define a function with type hints\nfunction myfunction(type $arg1, type $arg2){\n ..\n ..\n}" }, { "code": null, "e": 3766, "s": 3603, "text": "All standard PHP data types including scalar types, array, class/interface, iterable and object are valid types for providing type hints in a function declaration" }, { "code": null, "e": 3777, "s": 3766, "text": " Live Demo" }, { "code": null, "e": 3983, "s": 3777, "text": "<?php\nfunction add(...$numbers){\n $ttl=0;\n foreach ($numbers as $num){\n $ttl=$ttl+$num;\n }\n return $ttl;\n}\n$total=add(10,15,20);\necho \"total= $total\\n\";\necho \"total=\". add(1,2,3,4,5). \"\\n\";\n?>" }, { "code": null, "e": 4021, "s": 3983, "text": "This will produce following result. −" }, { "code": null, "e": 4040, "s": 4021, "text": "total= 45\ntotal=15" }, { "code": null, "e": 4301, "s": 4040, "text": "It is also possible to obtain a list of arguments passed to a function with the help of func_get_args() function. We can run a PHP loop to traverse each value in the list of arguments passed. In that case the function definition doesn't have a formal argument." }, { "code": null, "e": 4312, "s": 4301, "text": " Live Demo" }, { "code": null, "e": 4421, "s": 4312, "text": "<?php\nfunction add (int $x, int $y){\n $z=$x+$y;\n echo \"addition=$z\\n\";\n}\nadd(10,20);\nadd(5.55, 6.66);\n?>" }, { "code": null, "e": 4459, "s": 4421, "text": "This will produce following result. −" }, { "code": null, "e": 4483, "s": 4459, "text": "addition=30\naddition=11" }, { "code": null, "e": 4775, "s": 4483, "text": "Note that in second call to add() function, floats are given as arguments, but still no error/warning is displayed. This is because PHP internally coerces float into integer for performing addition. In order to prevent such automatic type conversion, use declareconstruct with strict_types=1" }, { "code": null, "e": 4786, "s": 4775, "text": " Live Demo" }, { "code": null, "e": 4920, "s": 4786, "text": "<?php\ndeclare(strict_types=1);\nfunction add (int $x, int $y){\n $z=$x+$y;\n echo \"addition=$z\\n\";\n}\nadd(10,20);\nadd(5.55, 6.66);\n?>" }, { "code": null, "e": 4977, "s": 4920, "text": "Second call to add() function will now throw exception −" }, { "code": null, "e": 5094, "s": 4977, "text": "addition=30\nPHP Fatal error: Uncaught TypeError: Argument 1 passed to add() must be of the type integer, float given" } ]
Go Data Types
Data type is an important concept in programming. Data type specifies the size and type of variable values. Go is statically typed, meaning that once a variable type is defined, it can only store data of that type. Go has three basic data types: bool: represents a boolean value and is either true or false Numeric: represents integer types, floating point values, and complex types string: represents a string value This example shows some of the different data types in Go: Add the correct data type for the following variables: package main import ("fmt") func main() { var myNum = 90 var myWord = "Hello" var myBool = true } Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 108, "s": 0, "text": "Data type is an important concept in programming. Data type specifies the size and type of variable values." }, { "code": null, "e": 215, "s": 108, "text": "Go is statically typed, meaning that once a variable type is defined, it can only store data of that type." }, { "code": null, "e": 246, "s": 215, "text": "Go has three basic data types:" }, { "code": null, "e": 307, "s": 246, "text": "bool: represents a boolean value and is either true or false" }, { "code": null, "e": 386, "s": 307, "text": "Numeric: represents integer types, floating point values, \n and complex types" }, { "code": null, "e": 420, "s": 386, "text": "string: represents a string value" }, { "code": null, "e": 479, "s": 420, "text": "This example shows some of the different data types in Go:" }, { "code": null, "e": 534, "s": 479, "text": "Add the correct data type for the following variables:" }, { "code": null, "e": 649, "s": 534, "text": "package main \nimport (\"fmt\") \nfunc main() {\n var myNum = 90\n var myWord = \"Hello\"\n var myBool = true\n}\n" }, { "code": null, "e": 668, "s": 649, "text": "Start the Exercise" }, { "code": null, "e": 701, "s": 668, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 743, "s": 701, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 850, "s": 743, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 869, "s": 850, "text": "help@w3schools.com" } ]
How to use JavaScript to check if a number has a decimal place or it’s a whole number?
Use the Math.floor method to check whether a number has a decimal place or not. You can try to run the following code to check if a number has a decimal place or not − Live Demo <html> <head> <title>JavaScript Numbers</title> </head> <body> <script> var num = 10.2; if (num == Math.floor(num)) { alert("Whole Number") } else { alert("Decimal Number") } </script> </body> </html>
[ { "code": null, "e": 1142, "s": 1062, "text": "Use the Math.floor method to check whether a number has a decimal place or not." }, { "code": null, "e": 1230, "s": 1142, "text": "You can try to run the following code to check if a number has a decimal place or not −" }, { "code": null, "e": 1240, "s": 1230, "text": "Live Demo" }, { "code": null, "e": 1535, "s": 1240, "text": "<html>\n <head>\n <title>JavaScript Numbers</title>\n </head>\n \n <body>\n <script>\n var num = 10.2;\n if (num == Math.floor(num)) {\n alert(\"Whole Number\")\n } else {\n alert(\"Decimal Number\")\n }\n </script>\n </body>\n</html>" } ]
Decrypt Map Coordinates from given pair of strings based on given rules - GeeksforGeeks
27 Dec, 2021 Given a pair of lowercase strings string1[] and string2[] of size M and N, the task is to decrypt these strings according to the following rules. The last character of encrypted string denotes the direction latitude string(only two [n-North, s-South]) longitude string(other two [e-East, w-West]). Except for the last character the string denotes an integer value irrespective of whether it is a latitude string or longitude string. The Integer part of the coordinate can be decoded as (Count of letter with maximum occurrences – Count of letter with minimum occurrences in string). Examples: Input: string1[] = “babbeddcs”, string2[] = “aeeaecacw”Output: 2 South 1 WestExplanation: In the string1, the last character is s, so south, the most frequent character is b with frequency 3 and the least are a, e and c with 1. Similarly, for the other string i.e, string2. Input: string1[] = “ddcs”, string2[] = “aeew”Output: 1 South 1 West Approach: The idea to solve this problem is to count the maximum and minimum frequency of characters of each string and check the last character. Follow the steps below to solve this problem: Initialize the variables c1 and c2 as the last characters of the strings string1[] and string2[]. Initialize the vectors f1[26] and f2[26] with 0 to store the frequencies. Traverse the strings string1[] and string2[] and store the frequency of all characters of the string in vectors f1[] and f2[]. Initialize the variables ma1, mi1, ma2, and mi2 to store the maximum and minimum frequency occurring characters from both the strings string1[] and string2[]. Traverse the vectors f1[] and f2[] and store the values of ma1, mi1, ma2, and mi2. After performing the above steps, print the result from the above computations. Below is the implementation of the above approach. C++14 Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to decrypt the stringsvoid find(string string1, string string2){ // Size of the strings int M = string1.length(), N = string2.length(); // Last characters of the strings char c1 = string1[M - 1], c2 = string2[N - 1]; // Arrays to store the frequencies vector<int> f1(26, 0), f2(26, 0); // Calculate the frequency of characters // of both the strings for (int i = 0; i < M - 1; i++) f1[string1[i] - 'a']++; for (int i = 0; i < N - 1; i++) f2[string2[i] - 'a']++; // Variables to store the maximum and // minimum occurring character. int ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (int i = 0; i < 26; i++) { ma1 = max(ma1, f1[i]); if (f1[i] > 0) mi1 = min(mi1, f1[i]); ma2 = max(ma2, f2[i]); if (f2[i] > 0) mi2 = min(mi2, f2[i]); } // Print the result cout << ma1 - mi1 << " "; if (c1 == 's') cout << "South "; else cout << "North "; cout << ma2 - mi2; if (c2 == 'e') cout << " East "; else cout << " West ";} // Driver Codeint main(){ string string1 = "babbeddcs", string2 = "aeeaecacw"; find(string1, string2); return 0;} // Java code for the above approachimport java.io.*;class GFG{ // Function to decrypt the stringsstatic void find(String string1, String string2){ // Size of the strings int M = string1.length(); int N = string2.length(); // Last characters of the strings char c1 = string1.charAt(M - 1); char c2 = string2.charAt(N - 1); // Arrays to store the frequencies int []f1 = new int[26]; int []f2 = new int[26]; // Calculate the frequency of characters // of both the strings for (int i = 0; i < M - 1; i++) f1[string1.charAt(i) - 'a']++; for (int i = 0; i < N - 1; i++) f2[string2.charAt(i) - 'a']++; // Variables to store the maximum and // minimum occurring character. int ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (int i = 0; i < 26; i++) { ma1 = Math.max(ma1, f1[i]); if (f1[i] > 0) mi1 = Math.min(mi1, f1[i]); ma2 = Math.max(ma2, f2[i]); if (f2[i] > 0) mi2 = Math.min(mi2, f2[i]); } // Print the result System.out.print(ma1 - mi1 + " "); if (c1 == 's') System.out.print("South "); else System.out.print( "North "); System.out.print(ma2 - mi2); if (c2 == 'e') System.out.print( " East "); else System.out.print( " West ");} // Driver Code public static void main (String[] args) { String string1 = "babbeddcs"; String string2 = "aeeaecacw"; find(string1, string2); }} // This code is contributed by Potta Lokesh # Python3 program for the above approach # Function to decrypt the stringsdef find(string1, string2): # Size of the strings M = len(string1) N = len(string2) # Last characters of the strings c1 = string1[M - 1] c2 = string2[N - 1] # Arrays to store the frequencies f1 = [0 for _ in range(26)] f2 = [0 for _ in range(26)] # Calculate the frequency of characters # of both the strings for i in range(0, M - 1): f1[ord(string1[i]) - ord('a')] += 1 for i in range(0, N - 1): f2[ord(string2[i]) - ord('a')] += 1 # Variables to store the maximum and # minimum occurring character. ma1 = 0 mi1 = M ma2 = 0 mi2 = N for i in range(0, 26): ma1 = max(ma1, f1[i]) if (f1[i] > 0): mi1 = min(mi1, f1[i]) ma2 = max(ma2, f2[i]) if (f2[i] > 0): mi2 = min(mi2, f2[i]) # Print the result print(ma1 - mi1, end = " ") if (c1 == 's'): print("South", end = " ") else: print("North", end = " ") print(ma2 - mi2, end = "") if (c2 == 'e'): print(" East ", end = "") else: print(" West ") # Driver Codeif __name__ == "__main__": string1 = "babbeddcs" string2 = "aeeaecacw" find(string1, string2) # This code is contributed by rakeshsahni // C# Program to implement// the above approachusing System;class GFG{// Function to decrypt the stringsstatic void find(string string1, string string2){ // Size of the strings int M = string1.Length; int N = string2.Length; // Last characters of the strings char c1 = string1[M - 1]; char c2 = string2[N - 1]; // Arrays to store the frequencies int []f1 = new int[26]; int []f2 = new int[26]; for(int i = 0; i < 26; i++) { f1[i] = 0; f2[i] = 0; } // Calculate the frequency of characters // of both the strings for (int i = 0; i < M - 1; i++) f1[string1[i] - 'a']++; for (int i = 0; i < N - 1; i++) f2[string2[i] - 'a']++; // Variables to store the maximum and // minimum occurring character. int ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (int i = 0; i < 26; i++) { ma1 = Math.Max(ma1, f1[i]); if (f1[i] > 0) mi1 = Math.Min(mi1, f1[i]); ma2 = Math.Max(ma2, f2[i]); if (f2[i] > 0) mi2 = Math.Min(mi2, f2[i]); } // Print the result Console.Write(ma1 - mi1 + " "); if (c1 == 's') Console.Write("South "); else Console.Write("North "); Console.Write(ma2 - mi2); if (c2 == 'e') Console.Write(" East "); else Console.Write(" West ");} // Driver codepublic static void Main() { string string1 = "babbeddcs"; string string2 = "aeeaecacw"; find(string1, string2);}}// This code is contributed by Samim Hossain Mondal. <script>// Javascript program for the above approach // Function to decrypt the stringsfunction find(string1, string2){ // Size of the strings let M = string1.length; let N = string2.length; // Last characters of the strings let c1 = string1[M - 1]; let c2 = string2[N - 1]; // Arrays to store the frequencies let f1 = [], f2 = []; for(let i = 0; i < 26; i++) { f1[i] = 0; f2[i] = 0; } // Calculate the frequency of characters // of both the strings for (let i = 0; i < M - 1; i++) f1[string1.charCodeAt(i) - 97]++; for (let i = 0; i < N - 1; i++) f2[string2.charCodeAt(i) - 97]++; // Variables to store the maximum and // minimum occurring character. let ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (let i = 0; i < 26; i++) { ma1 = Math.max(ma1, f1[i]); if (f1[i] > 0) mi1 = Math.min(mi1, f1[i]); ma2 = Math.max(ma2, f2[i]); if (f2[i] > 0) mi2 = Math.min(mi2, f2[i]); } // Print the result document.write(ma1 - mi1 + " "); if (c1 == 's') document.write("South "); else document.write("North "); document.write(ma2 - mi2); if (c2 == 'e') document.write(" East "); else document.write(" West ");} // Driver Codelet string1 = "babbeddcs";let string2 = "aeeaecacw"; find(string1, string2); // This code is contributed by Samim Hossain Mondal.</script> 2 South 1 West Time Complexity: O(max(M, N))Auxiliary Space: O(1) lokeshpotta20 samim2000 rakeshsahni surinderdawra388 Hash Mathematical Strings Hash Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Hashing | Set 2 (Separate Chaining) Most frequent element in an array Sort string of characters Counting frequencies of array elements Sorting a Map by value in C++ STL Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25290, "s": 25262, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25875, "s": 25290, "text": "Given a pair of lowercase strings string1[] and string2[] of size M and N, the task is to decrypt these strings according to the following rules. The last character of encrypted string denotes the direction latitude string(only two [n-North, s-South]) longitude string(other two [e-East, w-West]). Except for the last character the string denotes an integer value irrespective of whether it is a latitude string or longitude string. The Integer part of the coordinate can be decoded as (Count of letter with maximum occurrences – Count of letter with minimum occurrences in string). " }, { "code": null, "e": 25885, "s": 25875, "text": "Examples:" }, { "code": null, "e": 26159, "s": 25885, "text": "Input: string1[] = “babbeddcs”, string2[] = “aeeaecacw”Output: 2 South 1 WestExplanation: In the string1, the last character is s, so south, the most frequent character is b with frequency 3 and the least are a, e and c with 1. Similarly, for the other string i.e, string2." }, { "code": null, "e": 26227, "s": 26159, "text": "Input: string1[] = “ddcs”, string2[] = “aeew”Output: 1 South 1 West" }, { "code": null, "e": 26419, "s": 26227, "text": "Approach: The idea to solve this problem is to count the maximum and minimum frequency of characters of each string and check the last character. Follow the steps below to solve this problem:" }, { "code": null, "e": 26517, "s": 26419, "text": "Initialize the variables c1 and c2 as the last characters of the strings string1[] and string2[]." }, { "code": null, "e": 26591, "s": 26517, "text": "Initialize the vectors f1[26] and f2[26] with 0 to store the frequencies." }, { "code": null, "e": 26718, "s": 26591, "text": "Traverse the strings string1[] and string2[] and store the frequency of all characters of the string in vectors f1[] and f2[]." }, { "code": null, "e": 26877, "s": 26718, "text": "Initialize the variables ma1, mi1, ma2, and mi2 to store the maximum and minimum frequency occurring characters from both the strings string1[] and string2[]." }, { "code": null, "e": 26960, "s": 26877, "text": "Traverse the vectors f1[] and f2[] and store the values of ma1, mi1, ma2, and mi2." }, { "code": null, "e": 27040, "s": 26960, "text": "After performing the above steps, print the result from the above computations." }, { "code": null, "e": 27091, "s": 27040, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 27097, "s": 27091, "text": "C++14" }, { "code": null, "e": 27102, "s": 27097, "text": "Java" }, { "code": null, "e": 27110, "s": 27102, "text": "Python3" }, { "code": null, "e": 27113, "s": 27110, "text": "C#" }, { "code": null, "e": 27124, "s": 27113, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to decrypt the stringsvoid find(string string1, string string2){ // Size of the strings int M = string1.length(), N = string2.length(); // Last characters of the strings char c1 = string1[M - 1], c2 = string2[N - 1]; // Arrays to store the frequencies vector<int> f1(26, 0), f2(26, 0); // Calculate the frequency of characters // of both the strings for (int i = 0; i < M - 1; i++) f1[string1[i] - 'a']++; for (int i = 0; i < N - 1; i++) f2[string2[i] - 'a']++; // Variables to store the maximum and // minimum occurring character. int ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (int i = 0; i < 26; i++) { ma1 = max(ma1, f1[i]); if (f1[i] > 0) mi1 = min(mi1, f1[i]); ma2 = max(ma2, f2[i]); if (f2[i] > 0) mi2 = min(mi2, f2[i]); } // Print the result cout << ma1 - mi1 << \" \"; if (c1 == 's') cout << \"South \"; else cout << \"North \"; cout << ma2 - mi2; if (c2 == 'e') cout << \" East \"; else cout << \" West \";} // Driver Codeint main(){ string string1 = \"babbeddcs\", string2 = \"aeeaecacw\"; find(string1, string2); return 0;}", "e": 28441, "s": 27124, "text": null }, { "code": "// Java code for the above approachimport java.io.*;class GFG{ // Function to decrypt the stringsstatic void find(String string1, String string2){ // Size of the strings int M = string1.length(); int N = string2.length(); // Last characters of the strings char c1 = string1.charAt(M - 1); char c2 = string2.charAt(N - 1); // Arrays to store the frequencies int []f1 = new int[26]; int []f2 = new int[26]; // Calculate the frequency of characters // of both the strings for (int i = 0; i < M - 1; i++) f1[string1.charAt(i) - 'a']++; for (int i = 0; i < N - 1; i++) f2[string2.charAt(i) - 'a']++; // Variables to store the maximum and // minimum occurring character. int ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (int i = 0; i < 26; i++) { ma1 = Math.max(ma1, f1[i]); if (f1[i] > 0) mi1 = Math.min(mi1, f1[i]); ma2 = Math.max(ma2, f2[i]); if (f2[i] > 0) mi2 = Math.min(mi2, f2[i]); } // Print the result System.out.print(ma1 - mi1 + \" \"); if (c1 == 's') System.out.print(\"South \"); else System.out.print( \"North \"); System.out.print(ma2 - mi2); if (c2 == 'e') System.out.print( \" East \"); else System.out.print( \" West \");} // Driver Code public static void main (String[] args) { String string1 = \"babbeddcs\"; String string2 = \"aeeaecacw\"; find(string1, string2); }} // This code is contributed by Potta Lokesh", "e": 29959, "s": 28441, "text": null }, { "code": "# Python3 program for the above approach # Function to decrypt the stringsdef find(string1, string2): # Size of the strings M = len(string1) N = len(string2) # Last characters of the strings c1 = string1[M - 1] c2 = string2[N - 1] # Arrays to store the frequencies f1 = [0 for _ in range(26)] f2 = [0 for _ in range(26)] # Calculate the frequency of characters # of both the strings for i in range(0, M - 1): f1[ord(string1[i]) - ord('a')] += 1 for i in range(0, N - 1): f2[ord(string2[i]) - ord('a')] += 1 # Variables to store the maximum and # minimum occurring character. ma1 = 0 mi1 = M ma2 = 0 mi2 = N for i in range(0, 26): ma1 = max(ma1, f1[i]) if (f1[i] > 0): mi1 = min(mi1, f1[i]) ma2 = max(ma2, f2[i]) if (f2[i] > 0): mi2 = min(mi2, f2[i]) # Print the result print(ma1 - mi1, end = \" \") if (c1 == 's'): print(\"South\", end = \" \") else: print(\"North\", end = \" \") print(ma2 - mi2, end = \"\") if (c2 == 'e'): print(\" East \", end = \"\") else: print(\" West \") # Driver Codeif __name__ == \"__main__\": string1 = \"babbeddcs\" string2 = \"aeeaecacw\" find(string1, string2) # This code is contributed by rakeshsahni", "e": 31264, "s": 29959, "text": null }, { "code": "// C# Program to implement// the above approachusing System;class GFG{// Function to decrypt the stringsstatic void find(string string1, string string2){ // Size of the strings int M = string1.Length; int N = string2.Length; // Last characters of the strings char c1 = string1[M - 1]; char c2 = string2[N - 1]; // Arrays to store the frequencies int []f1 = new int[26]; int []f2 = new int[26]; for(int i = 0; i < 26; i++) { f1[i] = 0; f2[i] = 0; } // Calculate the frequency of characters // of both the strings for (int i = 0; i < M - 1; i++) f1[string1[i] - 'a']++; for (int i = 0; i < N - 1; i++) f2[string2[i] - 'a']++; // Variables to store the maximum and // minimum occurring character. int ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (int i = 0; i < 26; i++) { ma1 = Math.Max(ma1, f1[i]); if (f1[i] > 0) mi1 = Math.Min(mi1, f1[i]); ma2 = Math.Max(ma2, f2[i]); if (f2[i] > 0) mi2 = Math.Min(mi2, f2[i]); } // Print the result Console.Write(ma1 - mi1 + \" \"); if (c1 == 's') Console.Write(\"South \"); else Console.Write(\"North \"); Console.Write(ma2 - mi2); if (c2 == 'e') Console.Write(\" East \"); else Console.Write(\" West \");} // Driver codepublic static void Main() { string string1 = \"babbeddcs\"; string string2 = \"aeeaecacw\"; find(string1, string2);}}// This code is contributed by Samim Hossain Mondal.", "e": 32783, "s": 31264, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to decrypt the stringsfunction find(string1, string2){ // Size of the strings let M = string1.length; let N = string2.length; // Last characters of the strings let c1 = string1[M - 1]; let c2 = string2[N - 1]; // Arrays to store the frequencies let f1 = [], f2 = []; for(let i = 0; i < 26; i++) { f1[i] = 0; f2[i] = 0; } // Calculate the frequency of characters // of both the strings for (let i = 0; i < M - 1; i++) f1[string1.charCodeAt(i) - 97]++; for (let i = 0; i < N - 1; i++) f2[string2.charCodeAt(i) - 97]++; // Variables to store the maximum and // minimum occurring character. let ma1 = 0, mi1 = M, ma2 = 0, mi2 = N; for (let i = 0; i < 26; i++) { ma1 = Math.max(ma1, f1[i]); if (f1[i] > 0) mi1 = Math.min(mi1, f1[i]); ma2 = Math.max(ma2, f2[i]); if (f2[i] > 0) mi2 = Math.min(mi2, f2[i]); } // Print the result document.write(ma1 - mi1 + \" \"); if (c1 == 's') document.write(\"South \"); else document.write(\"North \"); document.write(ma2 - mi2); if (c2 == 'e') document.write(\" East \"); else document.write(\" West \");} // Driver Codelet string1 = \"babbeddcs\";let string2 = \"aeeaecacw\"; find(string1, string2); // This code is contributed by Samim Hossain Mondal.</script>", "e": 34225, "s": 32783, "text": null }, { "code": null, "e": 34240, "s": 34225, "text": "2 South 1 West" }, { "code": null, "e": 34293, "s": 34242, "text": "Time Complexity: O(max(M, N))Auxiliary Space: O(1)" }, { "code": null, "e": 34307, "s": 34293, "text": "lokeshpotta20" }, { "code": null, "e": 34317, "s": 34307, "text": "samim2000" }, { "code": null, "e": 34329, "s": 34317, "text": "rakeshsahni" }, { "code": null, "e": 34346, "s": 34329, "text": "surinderdawra388" }, { "code": null, "e": 34351, "s": 34346, "text": "Hash" }, { "code": null, "e": 34364, "s": 34351, "text": "Mathematical" }, { "code": null, "e": 34372, "s": 34364, "text": "Strings" }, { "code": null, "e": 34377, "s": 34372, "text": "Hash" }, { "code": null, "e": 34385, "s": 34377, "text": "Strings" }, { "code": null, "e": 34398, "s": 34385, "text": "Mathematical" }, { "code": null, "e": 34496, "s": 34398, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34532, "s": 34496, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 34566, "s": 34532, "text": "Most frequent element in an array" }, { "code": null, "e": 34592, "s": 34566, "text": "Sort string of characters" }, { "code": null, "e": 34631, "s": 34592, "text": "Counting frequencies of array elements" }, { "code": null, "e": 34665, "s": 34631, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 34695, "s": 34665, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 34755, "s": 34695, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34770, "s": 34755, "text": "C++ Data Types" }, { "code": null, "e": 34813, "s": 34770, "text": "Set in C++ Standard Template Library (STL)" } ]
Display USD currency records with the correct format in MySQL
Use FORMAT() in MySQL to display USD currency records in the correct form. Let us first create a table − mysql> create table DemoTable -> ( -> Amount DECIMAL(15,4) -> ); Query OK, 0 rows affected (0.75 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(90948484); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(1000000000); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(1535353536); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(773646463); Query OK, 1 row affected (0.20 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output− +-----------------+ | Amount | +-----------------+ | 90948484.0000 | | 1000000000.0000 | | 1535353536.0000 | | 773646463.0000 | +-----------------+ 4 rows in set (0.00 sec) Here is the query to display currency records correctly in MySQL− mysql> select concat('USD ',format(Amount,2)) as Currency from DemoTable; This will produce the following output. Here, we are displaying USD currency records in the correct format− +----------------------+ | Currency | +----------------------+ | USD 90,948,484.00 | | USD 1,000,000,000.00 | | USD 1,535,353,536.00 | | USD 773,646,463.00 | +----------------------+ 4 rows in set (0.23 sec)
[ { "code": null, "e": 1167, "s": 1062, "text": "Use FORMAT() in MySQL to display USD currency records in the correct form. Let us first create a table −" }, { "code": null, "e": 1278, "s": 1167, "text": "mysql> create table DemoTable\n -> (\n -> Amount DECIMAL(15,4)\n -> );\nQuery OK, 0 rows affected (0.75 sec)" }, { "code": null, "e": 1334, "s": 1278, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1671, "s": 1334, "text": "mysql> insert into DemoTable values(90948484);\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable values(1000000000);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values(1535353536);\nQuery OK, 1 row affected (0.09 sec)\nmysql> insert into DemoTable values(773646463);\nQuery OK, 1 row affected (0.20 sec)" }, { "code": null, "e": 1731, "s": 1671, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1762, "s": 1731, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1802, "s": 1762, "text": "This will produce the following output−" }, { "code": null, "e": 1987, "s": 1802, "text": "+-----------------+\n| Amount |\n+-----------------+\n| 90948484.0000 |\n| 1000000000.0000 |\n| 1535353536.0000 |\n| 773646463.0000 |\n+-----------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2053, "s": 1987, "text": "Here is the query to display currency records correctly in MySQL−" }, { "code": null, "e": 2127, "s": 2053, "text": "mysql> select concat('USD ',format(Amount,2)) as Currency from DemoTable;" }, { "code": null, "e": 2235, "s": 2127, "text": "This will produce the following output. Here, we are displaying USD currency records in the correct format−" }, { "code": null, "e": 2460, "s": 2235, "text": "+----------------------+\n| Currency |\n+----------------------+\n| USD 90,948,484.00 |\n| USD 1,000,000,000.00 |\n| USD 1,535,353,536.00 |\n| USD 773,646,463.00 |\n+----------------------+\n4 rows in set (0.23 sec)" } ]
How to calculate sum in MongoDB with aggregate()?
To get the sum, use $sum along with aggregate(). Let us create a collection with documents − > db.demo337.insertOne({"Amount":100}); { "acknowledged" : true, "insertedId" : ObjectId("5e5231e5f8647eb59e56209b") } > db.demo337.insertOne({"Amount":500}); { "acknowledged" : true, "insertedId" : ObjectId("5e5231e9f8647eb59e56209c") } > db.demo337.insertOne({"Amount":400}); { "acknowledged" : true, "insertedId" : ObjectId("5e5231ebf8647eb59e56209d") } Display all documents from a collection with the help of find() method − > db.demo337.find(); This will produce the following output − { "_id" : ObjectId("5e5231e5f8647eb59e56209b"), "Amount" : 100 } { "_id" : ObjectId("5e5231e9f8647eb59e56209c"), "Amount" : 500 } { "_id" : ObjectId("5e5231ebf8647eb59e56209d"), "Amount" : 400 } Following is the query to calculate sum in MongoDB − > db.demo337.aggregate( ... [ ... { ... $group: ... { ... _id:null, ... totalAmount: { $sum:"$Amount" } ... } ... } ... ] ... ); This will produce the following output − { "_id" : null, "totalAmount" : 1000 }
[ { "code": null, "e": 1155, "s": 1062, "text": "To get the sum, use $sum along with aggregate(). Let us create a collection with documents −" }, { "code": null, "e": 1530, "s": 1155, "text": "> db.demo337.insertOne({\"Amount\":100});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e5231e5f8647eb59e56209b\")\n}\n> db.demo337.insertOne({\"Amount\":500});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e5231e9f8647eb59e56209c\")\n}\n> db.demo337.insertOne({\"Amount\":400});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e5231ebf8647eb59e56209d\")\n}" }, { "code": null, "e": 1603, "s": 1530, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1624, "s": 1603, "text": "> db.demo337.find();" }, { "code": null, "e": 1665, "s": 1624, "text": "This will produce the following output −" }, { "code": null, "e": 1860, "s": 1665, "text": "{ \"_id\" : ObjectId(\"5e5231e5f8647eb59e56209b\"), \"Amount\" : 100 }\n{ \"_id\" : ObjectId(\"5e5231e9f8647eb59e56209c\"), \"Amount\" : 500 }\n{ \"_id\" : ObjectId(\"5e5231ebf8647eb59e56209d\"), \"Amount\" : 400 }" }, { "code": null, "e": 1913, "s": 1860, "text": "Following is the query to calculate sum in MongoDB −" }, { "code": null, "e": 2111, "s": 1913, "text": "> db.demo337.aggregate(\n... [\n... {\n... $group:\n... {\n... _id:null,\n... totalAmount: { $sum:\"$Amount\" }\n... }\n... }\n... ]\n... );" }, { "code": null, "e": 2152, "s": 2111, "text": "This will produce the following output −" }, { "code": null, "e": 2191, "s": 2152, "text": "{ \"_id\" : null, \"totalAmount\" : 1000 }" } ]
Select distinct combinations from two columns in MySQL?
To select distinct combinations from two columns, you can use CASE statement. Let us create a table with some columns. The query to create a table is as follows − mysql> create table select_DistinctTwoColumns -> ( -> Id int NOT NULL AUTO_INCREMENT, -> FirstValue char(1), -> SecondValue char(1), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.57 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('s','t'); Query OK, 1 row affected (0.12 sec) mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('t','u'); Query OK, 1 row affected (0.24 sec) mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','v'); Query OK, 1 row affected (0.12 sec) mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','t'); Query OK, 1 row affected (0.16 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from select_DistinctTwoColumns; The following is the output − +----+------------+-------------+ | Id | FirstValue | SecondValue | +----+------------+-------------+ | 1 | s | t | | 2 | t | u | | 3 | u | v | | 4 | u | t | +----+------------+-------------+ 4 rows in set (0.00 sec) Here is the query to select distinct combinations from two column using case statement. The first column is ‘FirstValue’ and the second column name is ‘SecondValue’. The query is as follows − mysql> SELECT distinct -> CASE -> WHEN FirstValue<SecondValue THEN FirstValue -> ELSE SecondValue -> END AS FirstColumn, -> CASE -> WHEN FirstValue > SecondValue THEN FirstValue -> ELSE SecondValue -> END AS SecondColumn -> FROM select_DistinctTwoColumns; The following is the output: +-------------+--------------+ | FirstColumn | SecondColumn | +-------------+--------------+ | s | t | | t | u | | u | v | +-------------+--------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1181, "s": 1062, "text": "To select distinct combinations from two columns, you can use CASE statement. Let us create a table with some columns." }, { "code": null, "e": 1225, "s": 1181, "text": "The query to create a table is as follows −" }, { "code": null, "e": 1438, "s": 1225, "text": "mysql> create table select_DistinctTwoColumns\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> FirstValue char(1),\n -> SecondValue char(1),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.57 sec)" }, { "code": null, "e": 1531, "s": 1438, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2022, "s": 1531, "text": "mysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('s','t');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('t','u');\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','v');\nQuery OK, 1 row affected (0.12 sec)\n\nmysql> insert into select_DistinctTwoColumns(FirstValue,SecondValue) values('u','t');\nQuery OK, 1 row affected (0.16 sec)" }, { "code": null, "e": 2107, "s": 2022, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2154, "s": 2107, "text": "mysql> select *from select_DistinctTwoColumns;" }, { "code": null, "e": 2184, "s": 2154, "text": "The following is the output −" }, { "code": null, "e": 2477, "s": 2184, "text": "+----+------------+-------------+\n| Id | FirstValue | SecondValue |\n+----+------------+-------------+\n| 1 | s | t |\n| 2 | t | u |\n| 3 | u | v |\n| 4 | u | t |\n+----+------------+-------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2669, "s": 2477, "text": "Here is the query to select distinct combinations from two column using case statement. The first column is ‘FirstValue’ and the second column name is ‘SecondValue’. The query is as follows −" }, { "code": null, "e": 2970, "s": 2669, "text": "mysql> SELECT distinct\n -> CASE\n -> WHEN FirstValue<SecondValue THEN FirstValue\n -> ELSE SecondValue\n -> END AS FirstColumn,\n -> CASE\n -> WHEN FirstValue > SecondValue THEN FirstValue\n -> ELSE SecondValue\n -> END AS SecondColumn\n -> FROM select_DistinctTwoColumns;" }, { "code": null, "e": 2999, "s": 2970, "text": "The following is the output:" }, { "code": null, "e": 3241, "s": 2999, "text": "+-------------+--------------+\n| FirstColumn | SecondColumn |\n+-------------+--------------+\n| s | t |\n| t | u |\n| u | v |\n+-------------+--------------+\n3 rows in set (0.00 sec)" } ]
AngularJS Interview Questions
Dear readers, these AngularJS Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of AngularJS. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer − AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework. AngularJS is a powerful JavaScript based development framework to create RICH Internet Application (RIA). AngularJS is a powerful JavaScript based development framework to create RICH Internet Application (RIA). AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC (Model View Controller) way. AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC (Model View Controller) way. Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser. Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0. AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0. Data binding is the automatic synchronization of data between model and view components. ng-model directive is used in data binding. Scopes are objects that refer to the model. They act as glue between controller and view. Controllers are JavaScript functions that are bound to a particular scope. They are the prime actors in AngularJS framework and carry functions to operate on data and decide which view is to be updated to show the updated model based data. AngularJS come with several built-in services. For example $https: service is used to make XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once in app. Filters select a subset of items from an array and return a new array. Filters are used to show filtered items from a list of items based on defined criteria. Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ng-bind, ng-model, etc) to perform most of the task that developers have to do. Templates are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using "partials". It is concept of switching views. AngularJS based controller decides which view to render based on the business logic. Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state. Following are the advantages of AngularJS. AngularJS provides capability to create Single Page Application in a very clean and maintainable way. AngularJS provides capability to create Single Page Application in a very clean and maintainable way. AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience. AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience. AngularJS code is unit testable. AngularJS code is unit testable. AngularJS uses dependency injection and make use of separation of concerns. AngularJS uses dependency injection and make use of separation of concerns. AngularJS provides reusable components. AngularJS provides reusable components. With AngularJS, developer writes less code and gets more functionality. With AngularJS, developer writes less code and gets more functionality. In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing. In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing. AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets. AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets. Following are the disadvantages of AngularJS. Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure. Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure. Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more. Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more. Following are the three core directives of AngularJS. ng-app − This directive defines and links an AngularJS application to HTML. ng-app − This directive defines and links an AngularJS application to HTML. ng-model − This directive binds the values of AngularJS application data to HTML input controls. ng-model − This directive binds the values of AngularJS application data to HTML input controls. ng-bind − This directive binds the AngularJS Application data to HTML tags. ng-bind − This directive binds the AngularJS Application data to HTML tags. When the page is loaded in the browser, following things happen: HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded; the angular global object is created. Next, JavaScript which registers controller functions is executed. HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded; the angular global object is created. Next, JavaScript which registers controller functions is executed. Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function. Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function. Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page gets ready. Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page gets ready. Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts: Model − It is the lowest level of the pattern responsible for maintaining data. Model − It is the lowest level of the pattern responsible for maintaining data. View − It is responsible for displaying all or a portion of the data to the user. View − It is responsible for displaying all or a portion of the data to the user. Controller − It is a software Code that controls the interactions between the Model and View. Controller − It is a software Code that controls the interactions between the Model and View. ng-app directive defines and links an AngularJS application to HTML. It also indicate the start of the application. ng-model directive binds the values of AngularJS application data to HTML input controls. It creates a model variable which can be used with the html page and within the container control( for example, div) having ng-app directive. ng-bind directive binds the AngularJS Application data to HTML tags. ng-bind updates the model created by ng-model directive to be displayed in the html tag whenever user input something in the control or updates the html control's data when model data is updated by controller. ng-controller directive tells AngularJS what controller to use with this view. AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control. AngularJS being a pure javaScript based library integrates easily with HTML. Step 1 − Include angularjs javascript libray in the html page <head> <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> </head> Step 2 − Point to AngularJS app Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to html element or body element as shown below: <body ng-app = "myapp"> </body> ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application. ng-repeat directive repeats html elements for each item in a collection. Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behave in same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and outputs the data where they are used. Uppercase filter converts a text to upper case text. In below example, we've added uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters. Enter first name:<input type = "text" ng-model = "student.firstName"> Enter last name: <input type = "text" ng-model = "student.lastName"> Name in Upper Case: {{student.fullName() | uppercase}} Lowercase filter converts a text to lower case text. In below example, we've added lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters. Enter first name:<input type = "text" ng-model = "student.firstName"> Enter last name: <input type = "text" ng-model = "student.lastName"> Name in Upper Case: {{student.fullName() | lowercase}} Currency filter formats text in a currency format. In below example, we've added currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format. Enter fees: <input type = "text" ng-model = "student.fees"> fees: {{student.fees | currency}} filter filter is used to filter the array to a subset of it based on provided criteria. In below example, to display only required subjects, we've used subjectName as filter. Enter subject: <input type = "text" ng-model = "subjectName"> Subject: <ul> <li ng-repeat = "subject in student.subjects | filter: subjectName"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul> orderby filter orders the array based on provided criteria. In below example, to order subjects by marks, we've used orderBy marks. Subject: <ul> <li ng-repeat = "subject in student.subjects | orderBy:'marks'"> {{ subject.name + ', marks:' + subject.marks }} </li> </ul> ng-disabled directive disables a given control. In below example, we've added ng-disabled attribute to a HTML button and pass it a model. Then we've attached the model to an checkbox and can see the variation. <input type = "checkbox" ng-model = "enableDisableButton">Disable Button <button ng-disabled = "enableDisableButton">Click Me!</button> ng-show directive shows a given control. In below example, we've added ng-show attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation. <input type = "checkbox" ng-model = "showHide1">Show Button <button ng-show = "showHide1">Click Me!</button> ng-hide directive hides a given control. In below example, we've added ng-hide attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation. <input type = "checkbox" ng-model = "showHide2">Hide Button <button ng-hide = "showHide2">Click Me!</button> ng-click directive represents a AngularJS click event. In below example, we've added ng-click attribute to a HTML button and added an expression to updated a model. Then we can see the variation. <p>Total click: {{ clickCounter }}</p></td> <button ng-click = "clickCounter = clickCounter + 1">Click Me!</button> angular.module is used to create AngularJS modules along with its dependent modules. Consider the following example: var mainApp = angular.module("mainApp", []); Here we've declared an application mainApp module using angular.module function. We've passed an empty array to it. This array generally contains dependent modules declared earlier. AngularJS enriches form filling and validation. We can use $dirty and $invalid flags to do the validations in seamless way. Use novalidate with a form declaration to disable any browser specific validation. Following can be used to track error. $dirty − states that value has been changed. $dirty − states that value has been changed. $invalid − states that value entered is invalid. $invalid − states that value entered is invalid. $error − states the exact error. $error − states the exact error. Using AngularJS, we can embed HTML pages within a HTML page using ng-include directive. <div ng-app = "" ng-controller = "studentController"> <div ng-include = "'main.htm'"></div> <div ng-include = "'subjects.htm'"></div> </div> AngularJS provides $https: control which works as a service to make ajax call to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $https: can be used to get the data from server in the following manner: function studentController($scope,$https:) { var url = "data.txt"; $https:.get(url).success( function(response) { $scope.students = response; }); } $routeProvider is the key service which set the configuration of urls, maps them with the corresponding html page or ng-template, and attaches a controller with the same. Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables. Scopes are controllers specific. If we define nested controllers then child controller will inherit the scope of its parent controller. <script> var mainApp = angular.module("mainApp", []); mainApp.controller("shapeController", function($scope) { $scope.message = "In shape controller"; $scope.type = "Shape"; }); mainApp.controller("circleController", function($scope) { $scope.message = "In circle controller"; }); </script> Following are the important points to be considered in above example. We've set values to models in shapeController. We've set values to models in shapeController. We've overridden message in child controller circleController. When "message" is used within module of controller circleController, the overridden message will be used. We've overridden message in child controller circleController. When "message" is used within module of controller circleController, the overridden message will be used. Services are JavaScript functions and are responsible to do specific tasks only. Each service is responsible for a specific task for example, $https: is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol. Using service method, we define a service and then assign method to it. We've also injected an already available service to it. mainApp.service('CalcService', function(MathService) { this.square = function(a) { return MathService.multiply(a,a); } }); Using factory method, we first define a factory and then assign method to it. var mainApp = angular.module("mainApp", []); mainApp.factory('MathService', function() { var factory = {}; factory.multiply = function(a, b) { return a * b } return factory; }); factory method is used to define a factory which can later be used to create services as and when required whereas service method is used to create a service whose purpose is to do some defined task. AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies. value factory service provider constant provider is used by AngularJS internally to create services, factory etc. during config phase(phase during which AngularJS bootstraps itself). Below mention script can be used to create MathService that we've created earlier. Provider is a special factory method with a method get() which is used to return the value/service/factory. //define a module var mainApp = angular.module("mainApp", []); ... //create a service using provider which defines a method square to return square of a number. mainApp.config(function($provide) { $provide.provider('MathService', function() { this.$get = function() { var factory = {}; factory.multiply = function(a, b) { return a * b; } return factory; }; }); }); constants are used to pass values at config phase considering the fact that value cannot be used to be passed during config phase. mainApp.constant("configParam", "constant value"); Yes! In AngularJS we can create custom directive to extend AngularJS existing functionalities. Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive. AngularJS provides support to create custom directives for following type of elements. Element directives − Directive activates when a matching element is encountered. Element directives − Directive activates when a matching element is encountered. Attribute − Directive activates when a matching attribute is encountered. Attribute − Directive activates when a matching attribute is encountered. CSS − Directive activates when a matching css style is encountered. CSS − Directive activates when a matching css style is encountered. Comment − Directive activates when a matching comment is encountered. Comment − Directive activates when a matching comment is encountered. Internationalization is a way to show locale specific information on a website. For example, display content of a website in English language in United States and in Danish in France. AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script <script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script> Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-) 16 Lectures 1.5 hours Anadi Sharma 40 Lectures 2.5 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 3142, "s": 2699, "text": "Dear readers, these AngularJS Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of AngularJS. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer −" }, { "code": null, "e": 3316, "s": 3142, "text": "AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain. Following are the features of AngularJS framework." }, { "code": null, "e": 3422, "s": 3316, "text": "AngularJS is a powerful JavaScript based development framework to create RICH Internet Application (RIA)." }, { "code": null, "e": 3528, "s": 3422, "text": "AngularJS is a powerful JavaScript based development framework to create RICH Internet Application (RIA)." }, { "code": null, "e": 3662, "s": 3528, "text": "AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC (Model View Controller) way." }, { "code": null, "e": 3796, "s": 3662, "text": "AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC (Model View Controller) way." }, { "code": null, "e": 3932, "s": 3796, "text": "Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser." }, { "code": null, "e": 4068, "s": 3932, "text": "Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser." }, { "code": null, "e": 4218, "s": 4068, "text": "AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0." }, { "code": null, "e": 4368, "s": 4218, "text": "AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0." }, { "code": null, "e": 4501, "s": 4368, "text": "Data binding is the automatic synchronization of data between model and view components. ng-model directive is used in data binding." }, { "code": null, "e": 4591, "s": 4501, "text": "Scopes are objects that refer to the model. They act as glue between controller and view." }, { "code": null, "e": 4831, "s": 4591, "text": "Controllers are JavaScript functions that are bound to a particular scope. They are the prime actors in AngularJS framework and carry functions to operate on data and decide which view is to be updated to show the updated model based data." }, { "code": null, "e": 5025, "s": 4831, "text": "AngularJS come with several built-in services. For example $https: service is used to make XMLHttpRequests (Ajax calls). Services are singleton objects which are instantiated only once in app." }, { "code": null, "e": 5184, "s": 5025, "text": "Filters select a subset of items from an array and return a new array. Filters are used to show filtered items from a list of items based on defined criteria." }, { "code": null, "e": 5465, "s": 5184, "text": "Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ng-bind, ng-model, etc) to perform most of the task that developers have to do." }, { "code": null, "e": 5638, "s": 5465, "text": "Templates are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using \"partials\"." }, { "code": null, "e": 5757, "s": 5638, "text": "It is concept of switching views. AngularJS based controller decides which view to render based on the business logic." }, { "code": null, "e": 5926, "s": 5757, "text": "Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state." }, { "code": null, "e": 5969, "s": 5926, "text": "Following are the advantages of AngularJS." }, { "code": null, "e": 6071, "s": 5969, "text": "AngularJS provides capability to create Single Page Application in a very clean and maintainable way." }, { "code": null, "e": 6173, "s": 6071, "text": "AngularJS provides capability to create Single Page Application in a very clean and maintainable way." }, { "code": null, "e": 6275, "s": 6173, "text": "AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience." }, { "code": null, "e": 6377, "s": 6275, "text": "AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience." }, { "code": null, "e": 6410, "s": 6377, "text": "AngularJS code is unit testable." }, { "code": null, "e": 6443, "s": 6410, "text": "AngularJS code is unit testable." }, { "code": null, "e": 6519, "s": 6443, "text": "AngularJS uses dependency injection and make use of separation of concerns." }, { "code": null, "e": 6595, "s": 6519, "text": "AngularJS uses dependency injection and make use of separation of concerns." }, { "code": null, "e": 6635, "s": 6595, "text": "AngularJS provides reusable components." }, { "code": null, "e": 6675, "s": 6635, "text": "AngularJS provides reusable components." }, { "code": null, "e": 6747, "s": 6675, "text": "With AngularJS, developer writes less code and gets more functionality." }, { "code": null, "e": 6819, "s": 6747, "text": "With AngularJS, developer writes less code and gets more functionality." }, { "code": null, "e": 6926, "s": 6819, "text": "In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing." }, { "code": null, "e": 7033, "s": 6926, "text": "In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing." }, { "code": null, "e": 7151, "s": 7033, "text": "AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets." }, { "code": null, "e": 7269, "s": 7151, "text": "AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets." }, { "code": null, "e": 7315, "s": 7269, "text": "Following are the disadvantages of AngularJS." }, { "code": null, "e": 7492, "s": 7315, "text": "Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure." }, { "code": null, "e": 7669, "s": 7492, "text": "Not Secure − Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure." }, { "code": null, "e": 7788, "s": 7669, "text": "Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more." }, { "code": null, "e": 7907, "s": 7788, "text": "Not degradable − If your application user disables JavaScript then user will just see the basic page and nothing more." }, { "code": null, "e": 7961, "s": 7907, "text": "Following are the three core directives of AngularJS." }, { "code": null, "e": 8037, "s": 7961, "text": "ng-app − This directive defines and links an AngularJS application to HTML." }, { "code": null, "e": 8113, "s": 8037, "text": "ng-app − This directive defines and links an AngularJS application to HTML." }, { "code": null, "e": 8210, "s": 8113, "text": "ng-model − This directive binds the values of AngularJS application data to HTML input controls." }, { "code": null, "e": 8307, "s": 8210, "text": "ng-model − This directive binds the values of AngularJS application data to HTML input controls." }, { "code": null, "e": 8383, "s": 8307, "text": "ng-bind − This directive binds the AngularJS Application data to HTML tags." }, { "code": null, "e": 8459, "s": 8383, "text": "ng-bind − This directive binds the AngularJS Application data to HTML tags." }, { "code": null, "e": 8524, "s": 8459, "text": "When the page is loaded in the browser, following things happen:" }, { "code": null, "e": 8738, "s": 8524, "text": "HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded; the angular global object is created. Next, JavaScript which registers controller functions is executed." }, { "code": null, "e": 8952, "s": 8738, "text": "HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded; the angular global object is created. Next, JavaScript which registers controller functions is executed." }, { "code": null, "e": 9115, "s": 8952, "text": "Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function. " }, { "code": null, "e": 9278, "s": 9115, "text": "Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function. " }, { "code": null, "e": 9430, "s": 9278, "text": "Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page gets ready." }, { "code": null, "e": 9582, "s": 9430, "text": "Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page gets ready." }, { "code": null, "e": 9773, "s": 9582, "text": "Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts:" }, { "code": null, "e": 9853, "s": 9773, "text": "Model − It is the lowest level of the pattern responsible for maintaining data." }, { "code": null, "e": 9933, "s": 9853, "text": "Model − It is the lowest level of the pattern responsible for maintaining data." }, { "code": null, "e": 10015, "s": 9933, "text": "View − It is responsible for displaying all or a portion of the data to the user." }, { "code": null, "e": 10097, "s": 10015, "text": "View − It is responsible for displaying all or a portion of the data to the user." }, { "code": null, "e": 10191, "s": 10097, "text": "Controller − It is a software Code that controls the interactions between the Model and View." }, { "code": null, "e": 10285, "s": 10191, "text": "Controller − It is a software Code that controls the interactions between the Model and View." }, { "code": null, "e": 10401, "s": 10285, "text": "ng-app directive defines and links an AngularJS application to HTML. It also indicate the start of the application." }, { "code": null, "e": 10633, "s": 10401, "text": "ng-model directive binds the values of AngularJS application data to HTML input controls. It creates a model variable which can be used with the html page and within the container control( for example, div) having ng-app directive." }, { "code": null, "e": 10913, "s": 10633, "text": "ng-bind directive binds the AngularJS Application data to HTML tags. ng-bind updates the model created by ng-model directive to be displayed in the html tag whenever user input something in the control or updates the html control's data when model data is updated by controller." }, { "code": null, "e": 11291, "s": 10913, "text": "ng-controller directive tells AngularJS what controller to use with this view. AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control." }, { "code": null, "e": 11368, "s": 11291, "text": "AngularJS being a pure javaScript based library integrates easily with HTML." }, { "code": null, "e": 11430, "s": 11368, "text": "Step 1 − Include angularjs javascript libray in the html page" }, { "code": null, "e": 11544, "s": 11430, "text": "<head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"></script>\n</head>" }, { "code": null, "e": 11576, "s": 11544, "text": "Step 2 − Point to AngularJS app" }, { "code": null, "e": 11797, "s": 11576, "text": "Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to html element or body element as shown below:" }, { "code": null, "e": 11829, "s": 11797, "text": "<body ng-app = \"myapp\">\n</body>" }, { "code": null, "e": 11963, "s": 11829, "text": "ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application." }, { "code": null, "e": 12036, "s": 11963, "text": "ng-repeat directive repeats html elements for each item in a collection." }, { "code": null, "e": 12320, "s": 12036, "text": "Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behave in same way as ng-bind directives. AngularJS application expressions are pure JavaScript expressions and outputs the data where they are used." }, { "code": null, "e": 12373, "s": 12320, "text": "Uppercase filter converts a text to upper case text." }, { "code": null, "e": 12539, "s": 12373, "text": "In below example, we've added uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters." }, { "code": null, "e": 12733, "s": 12539, "text": "Enter first name:<input type = \"text\" ng-model = \"student.firstName\">\nEnter last name: <input type = \"text\" ng-model = \"student.lastName\">\nName in Upper Case: {{student.fullName() | uppercase}}" }, { "code": null, "e": 12786, "s": 12733, "text": "Lowercase filter converts a text to lower case text." }, { "code": null, "e": 12954, "s": 12786, "text": "In below example, we've added lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters." }, { "code": null, "e": 13148, "s": 12954, "text": "Enter first name:<input type = \"text\" ng-model = \"student.firstName\">\nEnter last name: <input type = \"text\" ng-model = \"student.lastName\">\nName in Upper Case: {{student.fullName() | lowercase}}" }, { "code": null, "e": 13199, "s": 13148, "text": "Currency filter formats text in a currency format." }, { "code": null, "e": 13371, "s": 13199, "text": "In below example, we've added currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format." }, { "code": null, "e": 13465, "s": 13371, "text": "Enter fees: <input type = \"text\" ng-model = \"student.fees\">\nfees: {{student.fees | currency}}" }, { "code": null, "e": 13553, "s": 13465, "text": "filter filter is used to filter the array to a subset of it based on provided criteria." }, { "code": null, "e": 13640, "s": 13553, "text": "In below example, to display only required subjects, we've used subjectName as filter." }, { "code": null, "e": 13857, "s": 13640, "text": "Enter subject: <input type = \"text\" ng-model = \"subjectName\">\nSubject:\n<ul>\n <li ng-repeat = \"subject in student.subjects | filter: subjectName\">\n {{ subject.name + ', marks:' + subject.marks }}\n </li>\n</ul>" }, { "code": null, "e": 13917, "s": 13857, "text": "orderby filter orders the array based on provided criteria." }, { "code": null, "e": 13989, "s": 13917, "text": "In below example, to order subjects by marks, we've used orderBy marks." }, { "code": null, "e": 14140, "s": 13989, "text": "Subject:\n<ul>\n <li ng-repeat = \"subject in student.subjects | orderBy:'marks'\">\n {{ subject.name + ', marks:' + subject.marks }}\n </li>\n</ul>" }, { "code": null, "e": 14188, "s": 14140, "text": "ng-disabled directive disables a given control." }, { "code": null, "e": 14350, "s": 14188, "text": "In below example, we've added ng-disabled attribute to a HTML button and pass it a model. Then we've attached the model to an checkbox and can see the variation." }, { "code": null, "e": 14486, "s": 14350, "text": "<input type = \"checkbox\" ng-model = \"enableDisableButton\">Disable Button\n<button ng-disabled = \"enableDisableButton\">Click Me!</button>" }, { "code": null, "e": 14527, "s": 14486, "text": "ng-show directive shows a given control." }, { "code": null, "e": 14684, "s": 14527, "text": "In below example, we've added ng-show attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation." }, { "code": null, "e": 14793, "s": 14684, "text": "<input type = \"checkbox\" ng-model = \"showHide1\">Show Button\n<button ng-show = \"showHide1\">Click Me!</button>" }, { "code": null, "e": 14834, "s": 14793, "text": "ng-hide directive hides a given control." }, { "code": null, "e": 14991, "s": 14834, "text": "In below example, we've added ng-hide attribute to a HTML button and pass it a model. Then we've attached the model to a checkbox and can see the variation." }, { "code": null, "e": 15100, "s": 14991, "text": "<input type = \"checkbox\" ng-model = \"showHide2\">Hide Button\n<button ng-hide = \"showHide2\">Click Me!</button>" }, { "code": null, "e": 15155, "s": 15100, "text": "ng-click directive represents a AngularJS click event." }, { "code": null, "e": 15296, "s": 15155, "text": "In below example, we've added ng-click attribute to a HTML button and added an expression to updated a model. Then we can see the variation." }, { "code": null, "e": 15412, "s": 15296, "text": "<p>Total click: {{ clickCounter }}</p></td>\n<button ng-click = \"clickCounter = clickCounter + 1\">Click Me!</button>" }, { "code": null, "e": 15529, "s": 15412, "text": "angular.module is used to create AngularJS modules along with its dependent modules. Consider the following example:" }, { "code": null, "e": 15574, "s": 15529, "text": "var mainApp = angular.module(\"mainApp\", []);" }, { "code": null, "e": 15756, "s": 15574, "text": "Here we've declared an application mainApp module using angular.module function. We've passed an empty array to it. This array generally contains dependent modules declared earlier." }, { "code": null, "e": 15963, "s": 15756, "text": "AngularJS enriches form filling and validation. We can use $dirty and $invalid flags to do the validations in seamless way. Use novalidate with a form declaration to disable any browser specific validation." }, { "code": null, "e": 16001, "s": 15963, "text": "Following can be used to track error." }, { "code": null, "e": 16046, "s": 16001, "text": "$dirty − states that value has been changed." }, { "code": null, "e": 16091, "s": 16046, "text": "$dirty − states that value has been changed." }, { "code": null, "e": 16140, "s": 16091, "text": "$invalid − states that value entered is invalid." }, { "code": null, "e": 16189, "s": 16140, "text": "$invalid − states that value entered is invalid." }, { "code": null, "e": 16222, "s": 16189, "text": "$error − states the exact error." }, { "code": null, "e": 16255, "s": 16222, "text": "$error − states the exact error." }, { "code": null, "e": 16343, "s": 16255, "text": "Using AngularJS, we can embed HTML pages within a HTML page using ng-include directive." }, { "code": null, "e": 16490, "s": 16343, "text": "<div ng-app = \"\" ng-controller = \"studentController\">\n <div ng-include = \"'main.htm'\"></div>\n <div ng-include = \"'subjects.htm'\"></div>\n</div>" }, { "code": null, "e": 16793, "s": 16490, "text": "AngularJS provides $https: control which works as a service to make ajax call to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $https: can be used to get the data from server in the following manner:" }, { "code": null, "e": 16957, "s": 16793, "text": "function studentController($scope,$https:) {\n var url = \"data.txt\";\n $https:.get(url).success( function(response) {\n $scope.students = response; \n });\n}" }, { "code": null, "e": 17128, "s": 16957, "text": "$routeProvider is the key service which set the configuration of urls, maps them with the corresponding html page or ng-template, and attaches a controller with the same." }, { "code": null, "e": 17369, "s": 17128, "text": "Scope is a special JavaScript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object. $rootScope is the parent of all of the scope variables." }, { "code": null, "e": 17505, "s": 17369, "text": "Scopes are controllers specific. If we define nested controllers then child controller will inherit the scope of its parent controller." }, { "code": null, "e": 17861, "s": 17505, "text": "<script>\n var mainApp = angular.module(\"mainApp\", []);\n\n mainApp.controller(\"shapeController\", function($scope) {\n $scope.message = \"In shape controller\";\n $scope.type = \"Shape\";\n });\n\t \n mainApp.controller(\"circleController\", function($scope) {\n $scope.message = \"In circle controller\"; \n });\n</script>" }, { "code": null, "e": 17931, "s": 17861, "text": "Following are the important points to be considered in above example." }, { "code": null, "e": 17978, "s": 17931, "text": "We've set values to models in shapeController." }, { "code": null, "e": 18025, "s": 17978, "text": "We've set values to models in shapeController." }, { "code": null, "e": 18194, "s": 18025, "text": "We've overridden message in child controller circleController. When \"message\" is used within module of controller circleController, the overridden message will be used." }, { "code": null, "e": 18363, "s": 18194, "text": "We've overridden message in child controller circleController. When \"message\" is used within module of controller circleController, the overridden message will be used." }, { "code": null, "e": 18675, "s": 18363, "text": "Services are JavaScript functions and are responsible to do specific tasks only. Each service is responsible for a specific task for example, $https: is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol." }, { "code": null, "e": 18803, "s": 18675, "text": "Using service method, we define a service and then assign method to it. We've also injected an already available service to it." }, { "code": null, "e": 18938, "s": 18803, "text": "mainApp.service('CalcService', function(MathService) {\n this.square = function(a) { \n return MathService.multiply(a,a); \n\t}\n});" }, { "code": null, "e": 19016, "s": 18938, "text": "Using factory method, we first define a factory and then assign method to it." }, { "code": null, "e": 19224, "s": 19016, "text": "var mainApp = angular.module(\"mainApp\", []);\nmainApp.factory('MathService', function() { \n var factory = {}; \n\t\t\n factory.multiply = function(a, b) {\n return a * b \n }\n return factory;\n}); " }, { "code": null, "e": 19424, "s": 19224, "text": "factory method is used to define a factory which can later be used to create services as and when required whereas service method is used to create a service whose purpose is to do some defined task." }, { "code": null, "e": 19578, "s": 19424, "text": "AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies." }, { "code": null, "e": 19584, "s": 19578, "text": "value" }, { "code": null, "e": 19592, "s": 19584, "text": "factory" }, { "code": null, "e": 19600, "s": 19592, "text": "service" }, { "code": null, "e": 19609, "s": 19600, "text": "provider" }, { "code": null, "e": 19618, "s": 19609, "text": "constant" }, { "code": null, "e": 19952, "s": 19618, "text": "provider is used by AngularJS internally to create services, factory etc. during config phase(phase during which AngularJS bootstraps itself). Below mention script can be used to create MathService that we've created earlier. Provider is a special factory method with a method get() which is used to return the value/service/factory." }, { "code": null, "e": 20391, "s": 19952, "text": "//define a module\nvar mainApp = angular.module(\"mainApp\", []);\n...\n//create a service using provider which defines a method square to return square of a number.\nmainApp.config(function($provide) {\n $provide.provider('MathService', function() {\n\t\n this.$get = function() {\n var factory = {}; \n factory.multiply = function(a, b) {\n return a * b; \n }\n return factory;\n };\n\t\t\n });\n});" }, { "code": null, "e": 20522, "s": 20391, "text": "constants are used to pass values at config phase considering the fact that value cannot be used to be passed during config phase." }, { "code": null, "e": 20574, "s": 20522, "text": "mainApp.constant(\"configParam\", \"constant value\");\n" }, { "code": null, "e": 20669, "s": 20574, "text": "Yes! In AngularJS we can create custom directive to extend AngularJS existing functionalities." }, { "code": null, "e": 21127, "s": 20669, "text": "Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using \"directive\" function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive." }, { "code": null, "e": 21214, "s": 21127, "text": "AngularJS provides support to create custom directives for following type of elements." }, { "code": null, "e": 21295, "s": 21214, "text": "Element directives − Directive activates when a matching element is encountered." }, { "code": null, "e": 21376, "s": 21295, "text": "Element directives − Directive activates when a matching element is encountered." }, { "code": null, "e": 21450, "s": 21376, "text": "Attribute − Directive activates when a matching attribute is encountered." }, { "code": null, "e": 21524, "s": 21450, "text": "Attribute − Directive activates when a matching attribute is encountered." }, { "code": null, "e": 21592, "s": 21524, "text": "CSS − Directive activates when a matching css style is encountered." }, { "code": null, "e": 21660, "s": 21592, "text": "CSS − Directive activates when a matching css style is encountered." }, { "code": null, "e": 21730, "s": 21660, "text": "Comment − Directive activates when a matching comment is encountered." }, { "code": null, "e": 21800, "s": 21730, "text": "Comment − Directive activates when a matching comment is encountered." }, { "code": null, "e": 21984, "s": 21800, "text": "Internationalization is a way to show locale specific information on a website. For example, display content of a website in English language in United States and in Danish in France." }, { "code": null, "e": 22273, "s": 21984, "text": "AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script" }, { "code": null, "e": 22362, "s": 22273, "text": "<script src = \"https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js\"></script> " }, { "code": null, "e": 22649, "s": 22362, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." }, { "code": null, "e": 22979, "s": 22649, "text": "Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)" }, { "code": null, "e": 23014, "s": 22979, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 23028, "s": 23014, "text": " Anadi Sharma" }, { "code": null, "e": 23063, "s": 23028, "text": "\n 40 Lectures \n 2.5 hours \n" }, { "code": null, "e": 23083, "s": 23063, "text": " Skillbakerystudios" }, { "code": null, "e": 23090, "s": 23083, "text": " Print" }, { "code": null, "e": 23101, "s": 23090, "text": " Add Notes" } ]
How To Change DataTypes In Pandas in 4 Minutes | by Benedikt Droste | Towards Data Science
When I worked with pandas for the first time, I didn’t have an overview of the different data types at first and didn’t think about them any further. At the latest when you want to do the first arithmetic operations, you will receive warnings and error messages, so you have to deal with the data types. We will have a look at the following commands: 1. to_numeric() — converts non numeric types to numeric types (see also to_datetime()) 2. astype() — converts almost any datatype to any other datatype We will first look at to_numeric()which is used to convert non-numeric data. astype() is the Swiss army knife which can convert almost anything to anything. Let ́s start! We start with creating a dataframe: >>> amount_list = [1,2,'3',2,'4',5]>>> cost_list = [1,2,'3',2,'4',5]>>> date_list = ['2020-01-03', '2020-02-03','2019-12-12','2019-11-14','2020-01-02','2020-02-03']>>> category_list = ['XZ',1,3,'PT','LM',4]>>> df = pd.DataFrame({'Date':date_list,'Items': 'Car Saxophone Curler Car Slingshot Duff'.split(), 'Customer': 'Homer Lisa Marge Lisa Bart Homer'.split(), 'Amount': amount_list, 'Costs': cost_list, 'Category':category_list})>>> df Date Items Customer Amount Costs Category0 2020-01-03 Car Homer 1 1 XZ1 2020-02-03 Saxophone Lisa 2 2 12 2019-12-12 Curler Marge 3 3 33 2019-11-14 Car Lisa 2 2 PT4 2020-01-02 Slingshot Bart 4 4 LM5 2020-02-03 Duff Homer 5 5 4 We have six columns in our dataframe. The first column contains dates, the second and third columns contain textual information, the 4th and 5th columns contain numerical information and the 6th column strings and numbers. Let’s check the data type of the fourth and fifth column: >>> df.dtypesDate objectItems objectCustomer objectAmount objectCosts objectCategory objectdtype: object As we can see, each column of our data set has the data type Object. This datatype is used when you have text or mixed columns of text and non-numeric values. We change now the datatype of the amount-column with pd.to_numeric(): >>> pd.to_numeric(df['Amount'])0 11 22 33 24 45 5Name: Amount, dtype: int64 The desired column can simply be included as an argument for the function and the output is a new generated column with datatype int64. If we had decimal places accordingly, Pandas would output the datatype float. It is important that the transformed column must be replaced with the old one or a new one must be created: >>> df['Amount'] = pd.to_numeric(df['Amount'])>>> df.dtypesDate objectItems objectCustomer objectAmount int64Costs objectCategory objectdtype: object With the .apply method it ́s also possible to convert multiple columns at once: >>> df[['Amount','Costs']] = df[['Amount','Costs']].apply(pd.to_numeric)>>> df.dtypesDate objectItems objectCustomer objectAmount int64Costs int64Category objectdtype: object That was easy, right? You probably noticed we left out the last column, though. There are obviously non-numeric values there, which are also not so easy to convert. If we just try it like before, we get an error message: >>> pd.to_numeric(df['Category'])Traceback (most recent call last): File "pandas\_libs\lib.pyx", line 1897, in pandas._libs.lib.maybe_convert_numericValueError: Unable to parse string "XZ"During handling of the above exception, another exception occurred: [...]ValueError: Unable to parse string "XZ" at position 0 to_numeric()accepts an error argument. We can use corce and ignore. With coerce all non-convertible values are stored as NaNs and with ignore the original values are kept, which means that our column will still have mixed datatypes: >>> pd.to_numeric(df['Category'], errors='coerce') 0 NaN1 1.02 3.03 NaN4 NaN5 4.0Name: Category, dtype: float64>>> pd.to_numeric(df['Category'], errors='ignore') 0 XZ1 12 33 PT4 LM5 4Name: Category, dtype: object As you may have noticed, Pandas automatically choose a numeric data type. In most cases, this is certainly sufficient and the decision between integer and float is enough. However, sometimes we have very large datasets where we should optimize memory usage. This can be achieved with downcasting: >>> pd.to_numeric(df['Amount'],downcast='integer') 0 11 22 33 24 45 5Name: Amount, dtype: int8 In this example, Pandas choose the smallest integer which can hold all values. Using the astype() method. you can specify in detail to which datatype the column should be converted. The argument can simply be appended to the column and Pandas will attempt to transform the data. We can take the example from before again: >>> df['Amount'].astype(int) 0 11 22 33 24 45 5Name: Amount, dtype: int32>>> df['Amount'].astype(float) 0 1.01 2.02 3.03 2.04 4.05 5.0Name: Amount, dtype: float64df['Amount'].astype(str) 0 11 22 33 24 45 5Name: Amount, dtype: object You can define the data type specifically: >>> df['Amount'].astype(np.int64) 0 11 22 33 24 45 5Name: Amount, dtype: int64 Also with astype() we can change several columns at once as before: >>> df[['Amount','Costs']].astype(int) Amount Costs0 1 11 2 22 3 33 2 24 4 45 5 5 A difference to to_numeric is that we can only use raise and ignore as arguments for error handling. Raise is the default option: errors are displayed and no transformation is performed. With ignore errors will be ignored and values that cannot be converted keep their original format: >>> df['Category'].astype(int, errors='ignore') 0 XZ1 12 33 PT4 LM5 4Name: Category, dtype: object We have seen how we can convert columns to pandas with to_numeric() and astype(). To_numeric() has more powerful functions for error handling, while astype() offers even more possibilities in the way of conversion. It is important to be aware of what happens to non-numeric values and use the error arguments wisely. If you enjoy Medium and Towards Data Science and didn’t sign up yet, feel free to use my referral link to join the community.
[ { "code": null, "e": 522, "s": 171, "text": "When I worked with pandas for the first time, I didn’t have an overview of the different data types at first and didn’t think about them any further. At the latest when you want to do the first arithmetic operations, you will receive warnings and error messages, so you have to deal with the data types. We will have a look at the following commands:" }, { "code": null, "e": 609, "s": 522, "text": "1. to_numeric() — converts non numeric types to numeric types (see also to_datetime())" }, { "code": null, "e": 674, "s": 609, "text": "2. astype() — converts almost any datatype to any other datatype" }, { "code": null, "e": 845, "s": 674, "text": "We will first look at to_numeric()which is used to convert non-numeric data. astype() is the Swiss army knife which can convert almost anything to anything. Let ́s start!" }, { "code": null, "e": 881, "s": 845, "text": "We start with creating a dataframe:" }, { "code": null, "e": 1704, "s": 881, "text": ">>> amount_list = [1,2,'3',2,'4',5]>>> cost_list = [1,2,'3',2,'4',5]>>> date_list = ['2020-01-03', '2020-02-03','2019-12-12','2019-11-14','2020-01-02','2020-02-03']>>> category_list = ['XZ',1,3,'PT','LM',4]>>> df = pd.DataFrame({'Date':date_list,'Items': 'Car Saxophone Curler Car Slingshot Duff'.split(), 'Customer': 'Homer Lisa Marge Lisa Bart Homer'.split(), 'Amount': amount_list, 'Costs': cost_list, 'Category':category_list})>>> df Date Items Customer Amount Costs Category0 2020-01-03 Car Homer 1 1 XZ1 2020-02-03 Saxophone Lisa 2 2 12 2019-12-12 Curler Marge 3 3 33 2019-11-14 Car Lisa 2 2 PT4 2020-01-02 Slingshot Bart 4 4 LM5 2020-02-03 Duff Homer 5 5 4" }, { "code": null, "e": 1927, "s": 1704, "text": "We have six columns in our dataframe. The first column contains dates, the second and third columns contain textual information, the 4th and 5th columns contain numerical information and the 6th column strings and numbers." }, { "code": null, "e": 1985, "s": 1927, "text": "Let’s check the data type of the fourth and fifth column:" }, { "code": null, "e": 2120, "s": 1985, "text": ">>> df.dtypesDate objectItems objectCustomer objectAmount objectCosts objectCategory objectdtype: object" }, { "code": null, "e": 2349, "s": 2120, "text": "As we can see, each column of our data set has the data type Object. This datatype is used when you have text or mixed columns of text and non-numeric values. We change now the datatype of the amount-column with pd.to_numeric():" }, { "code": null, "e": 2425, "s": 2349, "text": ">>> pd.to_numeric(df['Amount'])0 11 22 33 24 45 5Name: Amount, dtype: int64" }, { "code": null, "e": 2747, "s": 2425, "text": "The desired column can simply be included as an argument for the function and the output is a new generated column with datatype int64. If we had decimal places accordingly, Pandas would output the datatype float. It is important that the transformed column must be replaced with the old one or a new one must be created:" }, { "code": null, "e": 2928, "s": 2747, "text": ">>> df['Amount'] = pd.to_numeric(df['Amount'])>>> df.dtypesDate objectItems objectCustomer objectAmount int64Costs objectCategory objectdtype: object" }, { "code": null, "e": 3008, "s": 2928, "text": "With the .apply method it ́s also possible to convert multiple columns at once:" }, { "code": null, "e": 3215, "s": 3008, "text": ">>> df[['Amount','Costs']] = df[['Amount','Costs']].apply(pd.to_numeric)>>> df.dtypesDate objectItems objectCustomer objectAmount int64Costs int64Category objectdtype: object" }, { "code": null, "e": 3436, "s": 3215, "text": "That was easy, right? You probably noticed we left out the last column, though. There are obviously non-numeric values there, which are also not so easy to convert. If we just try it like before, we get an error message:" }, { "code": null, "e": 3752, "s": 3436, "text": ">>> pd.to_numeric(df['Category'])Traceback (most recent call last): File \"pandas\\_libs\\lib.pyx\", line 1897, in pandas._libs.lib.maybe_convert_numericValueError: Unable to parse string \"XZ\"During handling of the above exception, another exception occurred: [...]ValueError: Unable to parse string \"XZ\" at position 0" }, { "code": null, "e": 3985, "s": 3752, "text": "to_numeric()accepts an error argument. We can use corce and ignore. With coerce all non-convertible values are stored as NaNs and with ignore the original values are kept, which means that our column will still have mixed datatypes:" }, { "code": null, "e": 4243, "s": 3985, "text": ">>> pd.to_numeric(df['Category'], errors='coerce') 0 NaN1 1.02 3.03 NaN4 NaN5 4.0Name: Category, dtype: float64>>> pd.to_numeric(df['Category'], errors='ignore') 0 XZ1 12 33 PT4 LM5 4Name: Category, dtype: object" }, { "code": null, "e": 4540, "s": 4243, "text": "As you may have noticed, Pandas automatically choose a numeric data type. In most cases, this is certainly sufficient and the decision between integer and float is enough. However, sometimes we have very large datasets where we should optimize memory usage. This can be achieved with downcasting:" }, { "code": null, "e": 4661, "s": 4540, "text": ">>> pd.to_numeric(df['Amount'],downcast='integer') 0 11 22 33 24 45 5Name: Amount, dtype: int8" }, { "code": null, "e": 4740, "s": 4661, "text": "In this example, Pandas choose the smallest integer which can hold all values." }, { "code": null, "e": 4983, "s": 4740, "text": "Using the astype() method. you can specify in detail to which datatype the column should be converted. The argument can simply be appended to the column and Pandas will attempt to transform the data. We can take the example from before again:" }, { "code": null, "e": 5286, "s": 4983, "text": ">>> df['Amount'].astype(int) 0 11 22 33 24 45 5Name: Amount, dtype: int32>>> df['Amount'].astype(float) 0 1.01 2.02 3.03 2.04 4.05 5.0Name: Amount, dtype: float64df['Amount'].astype(str) 0 11 22 33 24 45 5Name: Amount, dtype: object" }, { "code": null, "e": 5329, "s": 5286, "text": "You can define the data type specifically:" }, { "code": null, "e": 5434, "s": 5329, "text": ">>> df['Amount'].astype(np.int64) 0 11 22 33 24 45 5Name: Amount, dtype: int64" }, { "code": null, "e": 5502, "s": 5434, "text": "Also with astype() we can change several columns at once as before:" }, { "code": null, "e": 5654, "s": 5502, "text": ">>> df[['Amount','Costs']].astype(int) Amount Costs0 1 11 2 22 3 33 2 24 4 45 5 5" }, { "code": null, "e": 5940, "s": 5654, "text": "A difference to to_numeric is that we can only use raise and ignore as arguments for error handling. Raise is the default option: errors are displayed and no transformation is performed. With ignore errors will be ignored and values that cannot be converted keep their original format:" }, { "code": null, "e": 6060, "s": 5940, "text": ">>> df['Category'].astype(int, errors='ignore') 0 XZ1 12 33 PT4 LM5 4Name: Category, dtype: object" }, { "code": null, "e": 6377, "s": 6060, "text": "We have seen how we can convert columns to pandas with to_numeric() and astype(). To_numeric() has more powerful functions for error handling, while astype() offers even more possibilities in the way of conversion. It is important to be aware of what happens to non-numeric values and use the error arguments wisely." } ]
Delete a Node from linked list without head pointer in C++
In this tutorial, we are going to learn how to delete a node without head pointer in a singly linked list. Let's see the steps to solve the problem. Write struct with data, and next pointer. Write struct with data, and next pointer. Write a function to insert the node into the singly linked list. Write a function to insert the node into the singly linked list. Initialize the singly linked list with dummy data. Initialize the singly linked list with dummy data. Take a node from the linked list using the next pointer. Take a node from the linked list using the next pointer. Move the delete node to the next node. Move the delete node to the next node. Let's see the code. Live Demo #include <bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; }; void deleteNodeWithoutHead(struct Node* deletingNode) { if (deletingNode == NULL) { return; } else { if (deletingNode->next == NULL) { cout << "Can't delete last node without head" << endl; return; } struct Node* temp = deletingNode->next; deletingNode->data = temp->data; deletingNode->next = temp->next; free(temp); } } void printLinkedList(Node* head) { Node* temp = head; while (temp) { cout << temp->data << " -> "; temp = temp->next; } } void insertNode(struct Node** head_ref, int new_data) { struct Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node; } int main() { struct Node* head = NULL; insertNode(&head, 1); insertNode(&head, 2); insertNode(&head, 3); insertNode(&head, 4); insertNode(&head, 5); insertNode(&head, 6); cout << "Linked List before deletion:" << endl; printLinkedList(head); Node* del = head->next; deleteNodeWithoutHead(del); cout << "\nLinked List after deletion:" << endl; printLinkedList(head); return 0; } If you run the above code, then you will get the following result. Linked List before deletion: 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Linked List after deletion: 6 -> 4 -> 3 -> 2 -> 1 -> If you have any queries in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1169, "s": 1062, "text": "In this tutorial, we are going to learn how to delete a node without head pointer in a singly linked list." }, { "code": null, "e": 1211, "s": 1169, "text": "Let's see the steps to solve the problem." }, { "code": null, "e": 1253, "s": 1211, "text": "Write struct with data, and next pointer." }, { "code": null, "e": 1295, "s": 1253, "text": "Write struct with data, and next pointer." }, { "code": null, "e": 1360, "s": 1295, "text": "Write a function to insert the node into the singly linked list." }, { "code": null, "e": 1425, "s": 1360, "text": "Write a function to insert the node into the singly linked list." }, { "code": null, "e": 1476, "s": 1425, "text": "Initialize the singly linked list with dummy data." }, { "code": null, "e": 1527, "s": 1476, "text": "Initialize the singly linked list with dummy data." }, { "code": null, "e": 1584, "s": 1527, "text": "Take a node from the linked list using the next pointer." }, { "code": null, "e": 1641, "s": 1584, "text": "Take a node from the linked list using the next pointer." }, { "code": null, "e": 1680, "s": 1641, "text": "Move the delete node to the next node." }, { "code": null, "e": 1719, "s": 1680, "text": "Move the delete node to the next node." }, { "code": null, "e": 1739, "s": 1719, "text": "Let's see the code." }, { "code": null, "e": 1750, "s": 1739, "text": " Live Demo" }, { "code": null, "e": 2992, "s": 1750, "text": "#include <bits/stdc++.h>\nusing namespace std;\nstruct Node {\n int data;\n struct Node* next;\n};\nvoid deleteNodeWithoutHead(struct Node* deletingNode) {\n if (deletingNode == NULL) {\n return;\n }\n else {\n if (deletingNode->next == NULL) {\n cout << \"Can't delete last node without head\" << endl;\n return;\n }\n struct Node* temp = deletingNode->next;\n deletingNode->data = temp->data;\n deletingNode->next = temp->next;\n free(temp);\n }\n}\nvoid printLinkedList(Node* head) {\n Node* temp = head;\n while (temp) {\n cout << temp->data << \" -> \";\n temp = temp->next;\n }\n}\nvoid insertNode(struct Node** head_ref, int new_data) {\n struct Node* new_node = new Node();\n new_node->data = new_data;\n new_node->next = (*head_ref);\n (*head_ref) = new_node;\n}\nint main() {\n struct Node* head = NULL;\n insertNode(&head, 1);\n insertNode(&head, 2);\n insertNode(&head, 3);\n insertNode(&head, 4);\n insertNode(&head, 5);\n insertNode(&head, 6);\n cout << \"Linked List before deletion:\" << endl;\n printLinkedList(head);\n Node* del = head->next;\n deleteNodeWithoutHead(del);\n cout << \"\\nLinked List after deletion:\" << endl;\n printLinkedList(head);\n return 0;\n}" }, { "code": null, "e": 3059, "s": 2992, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 3171, "s": 3059, "text": "Linked List before deletion:\n6 -> 5 -> 4 -> 3 -> 2 -> 1 ->\nLinked List after deletion:\n6 -> 4 -> 3 -> 2 -> 1 ->" }, { "code": null, "e": 3249, "s": 3171, "text": "If you have any queries in the tutorial, mention them in the comment section." } ]
NLP - Expand contractions in Text Processing - GeeksforGeeks
21 Feb, 2022 Text preprocessing is a crucial step in NLP. Cleaning our text data in order to convert it into a presentable form that is analyzable and predictable for our task is known as text preprocessing. In this article, we are going to discuss contractions and how to handle contractions in text. What are contractions? Contractions are words or combinations of words that are shortened by dropping letters and replacing them by an apostrophe. Nowadays, where everything is shifting online, we communicate with others more through text messages or posts on different social media like Facebook, Instagram, Whatsapp, Twitter, LinkedIn, etc. in the form of texts. With so many people to talk, we rely on abbreviations and shortened form of words for texting people. For example I’ll be there within 5 min. Are u not gng there? Am I mssng out on smthng? I’d like to see u near d park. In English contractions, we often drop the vowels from a word to form the contractions. Removing contractions contributes to text standardization and is useful when we are working on Twitter data, on reviews of a product as the words play an important role in sentiment analysis. How to expand contractions? 1. Using contractions library First, install the library. You can try this library on Google colab as installing the library becomes super smooth. Using pip: !pip install contractions In Jupyter notebook: import sys !{sys.executable} -m pip install contractions Python3 # import libraryimport contractions# contracted texttext = '''I'll be there within 5 min. Shouldn't you be there too? I'd love to see u there my dear. It's awesome to meet new friends. We've been waiting for this day for so long.''' # creating an empty listexpanded_words = [] for word in text.split(): # using contractions.fix to expand the shortened words expanded_words.append(contractions.fix(word)) expanded_text = ' '.join(expanded_words)print('Original text: ' + text)print('Expanded_text: ' + expanded_text) Output: Original text: I'll be there within 5 min. Shouldn't you be there too? I'd love to see u there my dear. It's awesome to meet new friends. We've been waiting for this day for so long. Expanded_text: I will be there within 5 min. should not you be there too? I would love to see you there my dear. it is awesome to meet new friends. we have been waiting for this day for so long. Removing contractions before forming word vectors helps in dimensionality reduction. Code 2: Simply using contractions.fix to expand the text. Python3 text = '''She'd like to know how I'd done that! She's going to the park and I don't think I'll be home for dinner. Theyre going to the zoo and she'll be home for dinner.''' contractions.fix(text) Output: 'she would like to know how I would done that! she is going to the park and I do not think I will be home for dinner. they are going to the zoo and she will be home for dinner.' Contractions can also be handled using other techniques like dictionary mapping, and also using pycontractions library. You can refer to the documentation of pycontractions library for learning more about this: https://pypi.org/project/pycontractions/ rkbhola5 Natural-language-processing Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ML | Linear Regression Python | Decision tree implementation Difference between Informed and Uninformed Search in AI Elbow Method for optimal value of k in KMeans Deploy Machine Learning Model using Flask Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24007, "s": 23979, "text": "\n21 Feb, 2022" }, { "code": null, "e": 24296, "s": 24007, "text": "Text preprocessing is a crucial step in NLP. Cleaning our text data in order to convert it into a presentable form that is analyzable and predictable for our task is known as text preprocessing. In this article, we are going to discuss contractions and how to handle contractions in text." }, { "code": null, "e": 24319, "s": 24296, "text": "What are contractions?" }, { "code": null, "e": 24443, "s": 24319, "text": "Contractions are words or combinations of words that are shortened by dropping letters and replacing them by an apostrophe." }, { "code": null, "e": 24763, "s": 24443, "text": "Nowadays, where everything is shifting online, we communicate with others more through text messages or posts on different social media like Facebook, Instagram, Whatsapp, Twitter, LinkedIn, etc. in the form of texts. With so many people to talk, we rely on abbreviations and shortened form of words for texting people." }, { "code": null, "e": 24881, "s": 24763, "text": "For example I’ll be there within 5 min. Are u not gng there? Am I mssng out on smthng? I’d like to see u near d park." }, { "code": null, "e": 25161, "s": 24881, "text": "In English contractions, we often drop the vowels from a word to form the contractions. Removing contractions contributes to text standardization and is useful when we are working on Twitter data, on reviews of a product as the words play an important role in sentiment analysis." }, { "code": null, "e": 25189, "s": 25161, "text": "How to expand contractions?" }, { "code": null, "e": 25219, "s": 25189, "text": "1. Using contractions library" }, { "code": null, "e": 25336, "s": 25219, "text": "First, install the library. You can try this library on Google colab as installing the library becomes super smooth." }, { "code": null, "e": 25347, "s": 25336, "text": "Using pip:" }, { "code": null, "e": 25373, "s": 25347, "text": "!pip install contractions" }, { "code": null, "e": 25394, "s": 25373, "text": "In Jupyter notebook:" }, { "code": null, "e": 25453, "s": 25394, "text": "import sys \n!{sys.executable} -m pip install contractions" }, { "code": null, "e": 25461, "s": 25453, "text": "Python3" }, { "code": "# import libraryimport contractions# contracted texttext = '''I'll be there within 5 min. Shouldn't you be there too? I'd love to see u there my dear. It's awesome to meet new friends. We've been waiting for this day for so long.''' # creating an empty listexpanded_words = [] for word in text.split(): # using contractions.fix to expand the shortened words expanded_words.append(contractions.fix(word)) expanded_text = ' '.join(expanded_words)print('Original text: ' + text)print('Expanded_text: ' + expanded_text)", "e": 26003, "s": 25461, "text": null }, { "code": null, "e": 26011, "s": 26003, "text": "Output:" }, { "code": null, "e": 26432, "s": 26011, "text": "Original text: I'll be there within 5 min. Shouldn't you be there too? \n I'd love to see u there my dear. It's awesome to meet new friends.\n We've been waiting for this day for so long.\nExpanded_text: I will be there within 5 min. should not you be there too? \n I would love to see you there my dear. it is awesome to meet new friends. \n we have been waiting for this day for so long." }, { "code": null, "e": 26517, "s": 26432, "text": "Removing contractions before forming word vectors helps in dimensionality reduction." }, { "code": null, "e": 26575, "s": 26517, "text": "Code 2: Simply using contractions.fix to expand the text." }, { "code": null, "e": 26583, "s": 26575, "text": "Python3" }, { "code": "text = '''She'd like to know how I'd done that! She's going to the park and I don't think I'll be home for dinner. Theyre going to the zoo and she'll be home for dinner.''' contractions.fix(text)", "e": 26797, "s": 26583, "text": null }, { "code": null, "e": 26805, "s": 26797, "text": "Output:" }, { "code": null, "e": 26986, "s": 26805, "text": "'she would like to know how I would done that! \n she is going to the park and I do not think I will be home for dinner.\n they are going to the zoo and she will be home for dinner.'" }, { "code": null, "e": 27238, "s": 26986, "text": "Contractions can also be handled using other techniques like dictionary mapping, and also using pycontractions library. You can refer to the documentation of pycontractions library for learning more about this: https://pypi.org/project/pycontractions/" }, { "code": null, "e": 27247, "s": 27238, "text": "rkbhola5" }, { "code": null, "e": 27275, "s": 27247, "text": "Natural-language-processing" }, { "code": null, "e": 27292, "s": 27275, "text": "Machine Learning" }, { "code": null, "e": 27299, "s": 27292, "text": "Python" }, { "code": null, "e": 27316, "s": 27299, "text": "Machine Learning" }, { "code": null, "e": 27414, "s": 27316, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27423, "s": 27414, "text": "Comments" }, { "code": null, "e": 27436, "s": 27423, "text": "Old Comments" }, { "code": null, "e": 27459, "s": 27436, "text": "ML | Linear Regression" }, { "code": null, "e": 27497, "s": 27459, "text": "Python | Decision tree implementation" }, { "code": null, "e": 27553, "s": 27497, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 27599, "s": 27553, "text": "Elbow Method for optimal value of k in KMeans" }, { "code": null, "e": 27641, "s": 27599, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 27669, "s": 27641, "text": "Read JSON file using Python" }, { "code": null, "e": 27719, "s": 27669, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 27741, "s": 27719, "text": "Python map() function" } ]
Why Gradient descent isn’t enough: A comprehensive introduction to optimization algorithms in neural networks | by vikashraj luhaniwal | Towards Data Science
The goal of neural networks is to minimize the loss, for producing better and accurate results. In order to minimize the loss, we need to update the internal learning parameters(especially weights and biases). These parameters are updated based on some update rule/function. Generally, we think about Gradient descent as an update rule. Now two types of questions arise w.r.t parameters update. How much/what data should be used for an update? What update rule should be used? This post revolves around these two questions and answers in the simplest way in the context of better optimization. In this post, I will present an intuitive vision of optimization algorithms, their different types, and variants. Additional NOTE This article assumes that the reader has basic knowledge about the concept of the neural network, forward and backward propagation, weight initalization, activation functions, etc. In case you are not familiar then I would recommend you to follow my other articles on these topics. Forward propagation in neural networks — Simplified math and code version Why better weight initialization is important in neural networks? Analyzing different types of activation functions in neural networks — which one to prefer? Optimization algorithm tries to minimize the loss(cost) by following some update rule. The loss is a mathematical function denoting the difference between the predicted value and actual value. Loss is dependent on the actual value which is derived with the help of learning parameters(weights and biases) and inputs. Therefore learning parameters are very important for better training and producing accurate results. To find out the optimal value of these parameters we need to continuously update them. There should be some update rule for this purpose. So we use various optimization algorithms to follow some update rule and each optimization algorithm has a different approach to calculate, update and find out the optimal value of model parameters. Based on our first question “How much data should be used for an update” optimization algorithms can be classified as Gradient Descent, Mini batch Gradient Descent, and Stochastic Gradient Descent. In fact, the basic algorithm is Gradient Descent. Mini-batch Gradient descent and Stochastic Gradient Descent are two different strategies based on the amount of the data taken. These two are also known as the variants of Gradient Descent. Gradient descent is most commonly used and popular iterative machine learning algorithm. It is also the foundation for other optimization algorithms. Gradient descent has the following update rule for weight parameter Since during backpropagation for updating the parameters, the derivative of loss w.r.t. a parameter is calculated. This derivative can be dependent on more than one variable so for its calculation multiplication chain rule is used. For this purpose, a Gradient is required. A gradient is a vector indicating the direction of increase. For gradient calculation, we need to calculate derivatives of loss w.r.t the parameters and update the parameters in the opposite direction of the gradient. The above ideal convex curve image displays the weight update in the opposite direction of the gradient. As we can notice for too large and small values of weights the loss is maximum and our goal is to minimize the loss so the weights are updated. If the gradient is negative then descent(dive) towards the positive side and if the gradient is positive then descent towards the negative side until the minimal value of gradient is found. Algorithm for Gradient descent using a single neuron with sigmoid activation function in Python def sigmoid(w,b,x): return 1.0 / (1.0 + np.exp(-w*x + b))def grad_w(w,b,x,y): fx = sigmoid(w,b,x) return (fx — y) * fx * (1-fx) * xdef grad_b(w,b,x,y): fx = sigmoid(w,b,x) return (fx — y) * fx * (1-fx)def do_gradient_descent(): w,b,eta = -2, -2, 1.0 max_epochs = 1000 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) w = w — eta * dw b = b — eta * db The above animation represents how the algorithm converges after 1000 epochs. The error surface used in this animation is as per the input. This error surface is animated in 2D space. For 2D, a contour map is used where the contours represent the third dimension i.e. error. The red regions represent the high values of error, more the intensity of the red region more the error. Similarly, the blue regions represent the low values of error, less the intensity of the blue region less the error. Standard Gradient descent updates the parameters only after each epoch i.e. after calculating the derivatives for all the observations it updates the parameters. This phenomenon may lead to the following caveats. It can be very slow for very large datasets because only one-time update for each epoch so large number of epochs is required to have a substantial number of updates. For large datasets, the vectorization of data doesn’t fit into memory. For non-convex surfaces, it may only find the local minimums. Now let see how different variations of gradient descent can address these challenges. Stochastic gradient descent updates the parameters for each observation which leads to more number of updates. So it is a faster approach which helps in quicker decision making. Algorithm for Stochastic Gradient descent using a single neuron with sigmoid activation function in Python def do_stochastic_gradient_descent(): w,b,eta = -2, -2, 1.0 max_epochs = 1000 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) w = w — eta * dw b = b — eta * db Quicker updates in different directions can be noticed in this animation. Here, lots of oscillations take place which causes the updates with higher variance i.e. noisy updates. These noisy updates help in finding new and better local minima. Disadvantages of SGD Because of the greedy approach, it only approximates (stochastics) the gradient. Due to frequent fluctuations, it will keep overshooting near to the desired exact minima. Now let see how another variant of gradient descent can address these challenges. Another variant of GD to address the problems of SGD, it lies in between GD and SGD. Mini-batch Gradient descent updates the parameters for a finite number of observations. These observations together are referred to a batch with some fixed size. Batch size is chosen as a multiple of 64 e.g. 64, 128, 256, etc. Many more updates take place in one epoch through Mini-batch GD. Algorithm for Mini-batch Gradient descent using a single neuron with sigmoid activation function in Python def do_mini_batch_gradient_descent(): w,b,eta = -2, -2, 1.0 max_epochs = 1000 mini_batch_size = 3 num_of_points_seen = 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) num_of_points_seen += 1 if num_of_points_seen % mini_batch_size == 0: w = w — eta * dw b = b — eta * db As we can see there are fewer oscillations in Mini-batch in contrast to SGD. Basic notations 1 epoch = one pass over the entire data 1 step = one update for parameters N = number of data points B = Mini-batch size Advantages of Mini-batch GD Updates are less noisy compared to SGD which leads to better convergence. A high number of updates in a single epoch compared to GD so less number of epochs are required for large datasets. Fits very well to the processor memory which makes computing faster. The error surface contains more sloppy as well less sloppy areas. During back propagation, there will be more update in parameters for the regions with more slope whereas less update in parameters for the regions with a gentle slope. More change in parameters leads to more change in loss, similarly less change in parameters leads to less change in the loss. If the parameter initialization lands in a gentle slope area then it requires a large number of epochs to navigate through these areas. It happens so because the gradient will be very small in gentle slope regions. So it moves with small baby steps in gentle regions. Consider a case with initialization in a flat surface as shown below where GD is used and the error is not reducing when the gradient is in the flat surface. Even after a large number of epochs for e.g. 10000 the algorithm is not converging. Due to this issue, the convergence is not achieved so easily and the learning takes too much time. To overcome this problem Momentum based gradient descent is used. Consider a case where in order to reach to your desired destination you are continuously being asked to follow the same direction and once you become confident that you are following the right direction then you start taking bigger steps and you keep getting momentum in that same direction. Similar to this if the gradient is in a flat surface for long term then rather than taking constant steps it should take bigger steps and keep the momentum continue. This approach is known as momentum based gradient descent. Momentum-based gradient descent update rule for weight parameter Gamma parameter(γ) is the momentum term which indicates how much acceleration you want. Here along with the current gradient (η∇w(t)), the movement is also done according to history (γV(t−1)) so the update becomes larger which leads to faster movement and faster convergence. v(t) is exponentially decaying weighted sum, as t increases γV(t−1) becomes smaller and smaller i.e. this equation holds the farther updates by a small magnitude and recent updates by a large magnitude. Momentum-based gradient descent in Python for sigmoid neuron def do_momentum_based_gradient_descent(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) v_w = gamma * v_w + eta * dw v_b = gamma * v_b + eta * db w = w — v_w b = b — v_b This algorithm adds momentum in the direction of consistent gradients and cancels the momentum if the gradients are in different directions. Issues with momentum based Gradient descent In the valley that leads to exact desired minima, there are a large number of oscillations using momentum-based GD. Because it overshoots the minima with larger steps and takes a U-turn but again overshoots so this process repeats. Which means moving with larger steps is not always good. Momentum-based GD oscillates for a large number of times in and out of the minima. To overcome this issue Nesterov accelerated Gradient Descent is used. In momentum based GD as the gradient heads to the valley(minima region), it makes a lot of U-turns(oscillations) before it converges. This problem was initially identified and responded by a researcher named Yurii Nesterov. He suggested, make the movement first by history amount(previous momentum) then calculate the temporary gradient at this point and then update the parameters. In other words, before making an update directly first it looks ahead by moving with the previous momentum then it finds what the gradient should be. This looking ahead helps NAG in finishing its job(finding the minima) quicker than momentum-based GD. Hence the oscillations are less compared to momentum based GD and also there are fewer chances of missing the minima. NAG update rule for weight parameter NAG algorithm in Python for sigmoid neuron def do_nag_gradient_descent(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b, gamma = 0, 0, 0.9 for i in range(max_epochs): dw,db = 0,0 #compute the look ahead value w = w — gamma * v_w b = b — gamma * v_b for x,y in zip(X,Y): #compute the derivatives using look ahead value dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) #Now move further in the opposite direction of that gradient w = w — eta * dw b = b — eta * db #Now update the previous momentum v_w = gamma * v_w + eta * dw v_b = gamma * v_b + eta * db Here v_w and v_b refer to v(t) and v(b) respectively. As per the update rule The update is directly proportional to the gradient(∇w). Smaller the gradient smaller the update and the gradient is directly proportional to the input. Therefore the update is dependent on the input also. Need for an adaptive learning rate For the real-time datasets, most of the features are sparse i.e. having zero values. Due to this for most of the cases, the corresponding gradient is zero and therefore the parameters update is also zero. To resonate this problem, these update should be boosted i.e. a high learning rate for sparse features. Therefore the learning rate should be adaptive for fairly sparse data. In other words, if we are dealing with sparse features then learning rate should be high whereas for dense features learning rate should be low. Adagrad, RMSProp, Adam algorithms are based on the concept of adaptive learning rate. It adopts the learning rate(η) based on the sparsity of features. So the parameters with small updates(sparse features) have high learning rate whereas the parameters with large updates(dense features) have low learning rate. Therefore adagrad uses a different learning rate for each parameter. Adagrad update rule for weight parameter v(t) accumulates the running sum of square of the gradients. Square of ∇w(t) neglects the sign of gradients. v(t) indicates accumulated gradient up to time t. Epsilon in the denominator avoids the chances of divide by zero error. So if v(t) is low (due to less update up to time t) for a parameter then the effective learning rate will be high and if v(t) is high for a parameter then effective learning rate will be less. Adagrad algorithm in Python for sigmoid neuron def do_adagrad(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) v_w += dw**2 v_b += db**2 self.w -= (eta / np.sqrt(v_w) + eps) * dw self.b -= (eta / np.sqrt(v_b) + eps) * db Disadvantage with Adagrad The learning rate decays very aggressively For parameters(especially bias) corresponding to dense features, after a few updates, the learning rate decays rapidly as the denominator grows rapidly due to the accumulation of squared gradients. So after a finite number of updates, the algorithm refuses to learn and converges slowly even if we run it for a large number of epochs. The gradient reaches to a bad minimum (close to desired minima) but not at exact minima. So adagrad results in decaying and decreasing learning rate for bias parameters. RMSProp overcomes the decaying learning rate problem of adagrad and prevents the rapid growth in v(t). Instead of accumulating squared gradients from the beginning, it accumulates the previous gradients in some portion(weight) which prevents rapid growth of v(t) and due to this the algorithm keeps learning and tries to converge. RMSProp update rule for weight parameter Here v(t) is exponentially decaying average of all the previous squared gradients. The beta parameter value is set to a similar value as the momentum term. The running average v(t) up to time t is dependent on weighted previous average gradients and current gradient. v(t) maintains (∇w(t))2 for a fixed window time. Adagrad algorithm in Python for sigmoid neuron def do_RMSProp(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) v_w = beta * v_w + (1 — beta) * dw**2 v_b = beta * v_b + (1 — beta) * db**2 self.w -= (eta / np.sqrt(v_w) + eps) * dw self.b -= (eta / np.sqrt(v_b) + eps) * db Issues with RMSProp A large number of oscillations with high learning rate or large gradient So far in Adagrad, RMSProp we were calculating different learning rates for different parameters, can we have different momentums for different parameters. Adam algorithm introduces the concept of adaptive momentum along with adaptive learning rate. Adaptive Moment Estimation (Adam) computes the exponentially decaying average of previous gradients m(t) along with an adaptive learning rate. Adam is a combined form of Momentum-based GD and RMSProp. In Momentum-based GD, previous gradients(history) are used to compute the current gradient whereas, in RMSProp previous gradients(history) are used to adjust the learning rate based on the features. Therefore Adam deals with adaptive learning rate and adaptive momentum where RMSProp ensures v(t) does not grow rapidly to avoid the chances of decaying learning rate and m(t) from Momentum-based GD ensures it calculates the exponentially decaying average of previous gradients, not the current gradient. Adam update rule for weight parameter Here m(t) and v(t) are values of the mean obtained from the first moment. Adam uses bias corrected values (uncentered variance) of gradients for update rule and these values are obtained through the second moment. The final update rule is given as Adam algorithm in Python for sigmoid neuron def do_Adam(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 m_w, m_b = 0, 0 num_updates = 0 for i in range(epochs): dw, db = 0, 0 for x, y in zip(X, Y): dw = self.grad_w(x, y) db = self.grad_b(x, y) num_updates += 1 m_w = beta1 * m_w + (1-beta1) * dw m_b = beta1 * m_b + (1-beta1) * db v_w = beta2 * v_w + (1-beta2) * dw**2 v_b = beta2 * v_b + (1-beta2) * db**2 #m_w_c, m_b_c, v_w_c and v_b_c for bias correction m_w_c = m_w / (1 — np.power(beta1, num_updates)) m_b_c = m_b / (1 — np.power(beta1, num_updates)) v_w_c = v_w / (1 — np.power(beta2, num_updates)) v_b_c = v_b / (1 — np.power(beta2, num_updates)) self.w -= (eta / np.sqrt(v_w_c) + eps) * m_w_c self.b -= (eta / np.sqrt(v_b_c) + eps) * m_b_c So in Adam unlike RMSProp fewer oscillations and it moves more deterministically in the right direction which leads to faster convergence and better optimization. In this article, I have discussed the different types of optimization algorithms and the common issues one might encounter while using each of them. Generally, Adam with mini-batch is preferred for the training of deep neural networks.
[ { "code": null, "e": 566, "s": 171, "text": "The goal of neural networks is to minimize the loss, for producing better and accurate results. In order to minimize the loss, we need to update the internal learning parameters(especially weights and biases). These parameters are updated based on some update rule/function. Generally, we think about Gradient descent as an update rule. Now two types of questions arise w.r.t parameters update." }, { "code": null, "e": 615, "s": 566, "text": "How much/what data should be used for an update?" }, { "code": null, "e": 648, "s": 615, "text": "What update rule should be used?" }, { "code": null, "e": 879, "s": 648, "text": "This post revolves around these two questions and answers in the simplest way in the context of better optimization. In this post, I will present an intuitive vision of optimization algorithms, their different types, and variants." }, { "code": null, "e": 895, "s": 879, "text": "Additional NOTE" }, { "code": null, "e": 1177, "s": 895, "text": "This article assumes that the reader has basic knowledge about the concept of the neural network, forward and backward propagation, weight initalization, activation functions, etc. In case you are not familiar then I would recommend you to follow my other articles on these topics." }, { "code": null, "e": 1251, "s": 1177, "text": "Forward propagation in neural networks — Simplified math and code version" }, { "code": null, "e": 1317, "s": 1251, "text": "Why better weight initialization is important in neural networks?" }, { "code": null, "e": 1409, "s": 1317, "text": "Analyzing different types of activation functions in neural networks — which one to prefer?" }, { "code": null, "e": 2164, "s": 1409, "text": "Optimization algorithm tries to minimize the loss(cost) by following some update rule. The loss is a mathematical function denoting the difference between the predicted value and actual value. Loss is dependent on the actual value which is derived with the help of learning parameters(weights and biases) and inputs. Therefore learning parameters are very important for better training and producing accurate results. To find out the optimal value of these parameters we need to continuously update them. There should be some update rule for this purpose. So we use various optimization algorithms to follow some update rule and each optimization algorithm has a different approach to calculate, update and find out the optimal value of model parameters." }, { "code": null, "e": 2362, "s": 2164, "text": "Based on our first question “How much data should be used for an update” optimization algorithms can be classified as Gradient Descent, Mini batch Gradient Descent, and Stochastic Gradient Descent." }, { "code": null, "e": 2602, "s": 2362, "text": "In fact, the basic algorithm is Gradient Descent. Mini-batch Gradient descent and Stochastic Gradient Descent are two different strategies based on the amount of the data taken. These two are also known as the variants of Gradient Descent." }, { "code": null, "e": 2820, "s": 2602, "text": "Gradient descent is most commonly used and popular iterative machine learning algorithm. It is also the foundation for other optimization algorithms. Gradient descent has the following update rule for weight parameter" }, { "code": null, "e": 3155, "s": 2820, "text": "Since during backpropagation for updating the parameters, the derivative of loss w.r.t. a parameter is calculated. This derivative can be dependent on more than one variable so for its calculation multiplication chain rule is used. For this purpose, a Gradient is required. A gradient is a vector indicating the direction of increase." }, { "code": null, "e": 3312, "s": 3155, "text": "For gradient calculation, we need to calculate derivatives of loss w.r.t the parameters and update the parameters in the opposite direction of the gradient." }, { "code": null, "e": 3751, "s": 3312, "text": "The above ideal convex curve image displays the weight update in the opposite direction of the gradient. As we can notice for too large and small values of weights the loss is maximum and our goal is to minimize the loss so the weights are updated. If the gradient is negative then descent(dive) towards the positive side and if the gradient is positive then descent towards the negative side until the minimal value of gradient is found." }, { "code": null, "e": 3847, "s": 3751, "text": "Algorithm for Gradient descent using a single neuron with sigmoid activation function in Python" }, { "code": null, "e": 4328, "s": 3847, "text": "def sigmoid(w,b,x): return 1.0 / (1.0 + np.exp(-w*x + b))def grad_w(w,b,x,y): fx = sigmoid(w,b,x) return (fx — y) * fx * (1-fx) * xdef grad_b(w,b,x,y): fx = sigmoid(w,b,x) return (fx — y) * fx * (1-fx)def do_gradient_descent(): w,b,eta = -2, -2, 1.0 max_epochs = 1000 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) w = w — eta * dw b = b — eta * db" }, { "code": null, "e": 4825, "s": 4328, "text": "The above animation represents how the algorithm converges after 1000 epochs. The error surface used in this animation is as per the input. This error surface is animated in 2D space. For 2D, a contour map is used where the contours represent the third dimension i.e. error. The red regions represent the high values of error, more the intensity of the red region more the error. Similarly, the blue regions represent the low values of error, less the intensity of the blue region less the error." }, { "code": null, "e": 5038, "s": 4825, "text": "Standard Gradient descent updates the parameters only after each epoch i.e. after calculating the derivatives for all the observations it updates the parameters. This phenomenon may lead to the following caveats." }, { "code": null, "e": 5205, "s": 5038, "text": "It can be very slow for very large datasets because only one-time update for each epoch so large number of epochs is required to have a substantial number of updates." }, { "code": null, "e": 5276, "s": 5205, "text": "For large datasets, the vectorization of data doesn’t fit into memory." }, { "code": null, "e": 5338, "s": 5276, "text": "For non-convex surfaces, it may only find the local minimums." }, { "code": null, "e": 5425, "s": 5338, "text": "Now let see how different variations of gradient descent can address these challenges." }, { "code": null, "e": 5603, "s": 5425, "text": "Stochastic gradient descent updates the parameters for each observation which leads to more number of updates. So it is a faster approach which helps in quicker decision making." }, { "code": null, "e": 5710, "s": 5603, "text": "Algorithm for Stochastic Gradient descent using a single neuron with sigmoid activation function in Python" }, { "code": null, "e": 5994, "s": 5710, "text": "def do_stochastic_gradient_descent(): w,b,eta = -2, -2, 1.0 max_epochs = 1000 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) w = w — eta * dw b = b — eta * db" }, { "code": null, "e": 6237, "s": 5994, "text": "Quicker updates in different directions can be noticed in this animation. Here, lots of oscillations take place which causes the updates with higher variance i.e. noisy updates. These noisy updates help in finding new and better local minima." }, { "code": null, "e": 6258, "s": 6237, "text": "Disadvantages of SGD" }, { "code": null, "e": 6339, "s": 6258, "text": "Because of the greedy approach, it only approximates (stochastics) the gradient." }, { "code": null, "e": 6429, "s": 6339, "text": "Due to frequent fluctuations, it will keep overshooting near to the desired exact minima." }, { "code": null, "e": 6511, "s": 6429, "text": "Now let see how another variant of gradient descent can address these challenges." }, { "code": null, "e": 6888, "s": 6511, "text": "Another variant of GD to address the problems of SGD, it lies in between GD and SGD. Mini-batch Gradient descent updates the parameters for a finite number of observations. These observations together are referred to a batch with some fixed size. Batch size is chosen as a multiple of 64 e.g. 64, 128, 256, etc. Many more updates take place in one epoch through Mini-batch GD." }, { "code": null, "e": 6995, "s": 6888, "text": "Algorithm for Mini-batch Gradient descent using a single neuron with sigmoid activation function in Python" }, { "code": null, "e": 7416, "s": 6995, "text": "def do_mini_batch_gradient_descent(): w,b,eta = -2, -2, 1.0 max_epochs = 1000 mini_batch_size = 3 num_of_points_seen = 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) num_of_points_seen += 1 if num_of_points_seen % mini_batch_size == 0: w = w — eta * dw b = b — eta * db" }, { "code": null, "e": 7493, "s": 7416, "text": "As we can see there are fewer oscillations in Mini-batch in contrast to SGD." }, { "code": null, "e": 7509, "s": 7493, "text": "Basic notations" }, { "code": null, "e": 7549, "s": 7509, "text": "1 epoch = one pass over the entire data" }, { "code": null, "e": 7584, "s": 7549, "text": "1 step = one update for parameters" }, { "code": null, "e": 7610, "s": 7584, "text": "N = number of data points" }, { "code": null, "e": 7630, "s": 7610, "text": "B = Mini-batch size" }, { "code": null, "e": 7658, "s": 7630, "text": "Advantages of Mini-batch GD" }, { "code": null, "e": 7732, "s": 7658, "text": "Updates are less noisy compared to SGD which leads to better convergence." }, { "code": null, "e": 7848, "s": 7732, "text": "A high number of updates in a single epoch compared to GD so less number of epochs are required for large datasets." }, { "code": null, "e": 7917, "s": 7848, "text": "Fits very well to the processor memory which makes computing faster." }, { "code": null, "e": 8277, "s": 7917, "text": "The error surface contains more sloppy as well less sloppy areas. During back propagation, there will be more update in parameters for the regions with more slope whereas less update in parameters for the regions with a gentle slope. More change in parameters leads to more change in loss, similarly less change in parameters leads to less change in the loss." }, { "code": null, "e": 8545, "s": 8277, "text": "If the parameter initialization lands in a gentle slope area then it requires a large number of epochs to navigate through these areas. It happens so because the gradient will be very small in gentle slope regions. So it moves with small baby steps in gentle regions." }, { "code": null, "e": 8703, "s": 8545, "text": "Consider a case with initialization in a flat surface as shown below where GD is used and the error is not reducing when the gradient is in the flat surface." }, { "code": null, "e": 8787, "s": 8703, "text": "Even after a large number of epochs for e.g. 10000 the algorithm is not converging." }, { "code": null, "e": 8886, "s": 8787, "text": "Due to this issue, the convergence is not achieved so easily and the learning takes too much time." }, { "code": null, "e": 8952, "s": 8886, "text": "To overcome this problem Momentum based gradient descent is used." }, { "code": null, "e": 9244, "s": 8952, "text": "Consider a case where in order to reach to your desired destination you are continuously being asked to follow the same direction and once you become confident that you are following the right direction then you start taking bigger steps and you keep getting momentum in that same direction." }, { "code": null, "e": 9469, "s": 9244, "text": "Similar to this if the gradient is in a flat surface for long term then rather than taking constant steps it should take bigger steps and keep the momentum continue. This approach is known as momentum based gradient descent." }, { "code": null, "e": 9534, "s": 9469, "text": "Momentum-based gradient descent update rule for weight parameter" }, { "code": null, "e": 9810, "s": 9534, "text": "Gamma parameter(γ) is the momentum term which indicates how much acceleration you want. Here along with the current gradient (η∇w(t)), the movement is also done according to history (γV(t−1)) so the update becomes larger which leads to faster movement and faster convergence." }, { "code": null, "e": 10013, "s": 9810, "text": "v(t) is exponentially decaying weighted sum, as t increases γV(t−1) becomes smaller and smaller i.e. this equation holds the farther updates by a small magnitude and recent updates by a large magnitude." }, { "code": null, "e": 10074, "s": 10013, "text": "Momentum-based gradient descent in Python for sigmoid neuron" }, { "code": null, "e": 10431, "s": 10074, "text": "def do_momentum_based_gradient_descent(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) v_w = gamma * v_w + eta * dw v_b = gamma * v_b + eta * db w = w — v_w b = b — v_b" }, { "code": null, "e": 10572, "s": 10431, "text": "This algorithm adds momentum in the direction of consistent gradients and cancels the momentum if the gradients are in different directions." }, { "code": null, "e": 10616, "s": 10572, "text": "Issues with momentum based Gradient descent" }, { "code": null, "e": 10905, "s": 10616, "text": "In the valley that leads to exact desired minima, there are a large number of oscillations using momentum-based GD. Because it overshoots the minima with larger steps and takes a U-turn but again overshoots so this process repeats. Which means moving with larger steps is not always good." }, { "code": null, "e": 10988, "s": 10905, "text": "Momentum-based GD oscillates for a large number of times in and out of the minima." }, { "code": null, "e": 11058, "s": 10988, "text": "To overcome this issue Nesterov accelerated Gradient Descent is used." }, { "code": null, "e": 11282, "s": 11058, "text": "In momentum based GD as the gradient heads to the valley(minima region), it makes a lot of U-turns(oscillations) before it converges. This problem was initially identified and responded by a researcher named Yurii Nesterov." }, { "code": null, "e": 11591, "s": 11282, "text": "He suggested, make the movement first by history amount(previous momentum) then calculate the temporary gradient at this point and then update the parameters. In other words, before making an update directly first it looks ahead by moving with the previous momentum then it finds what the gradient should be." }, { "code": null, "e": 11811, "s": 11591, "text": "This looking ahead helps NAG in finishing its job(finding the minima) quicker than momentum-based GD. Hence the oscillations are less compared to momentum based GD and also there are fewer chances of missing the minima." }, { "code": null, "e": 11848, "s": 11811, "text": "NAG update rule for weight parameter" }, { "code": null, "e": 11891, "s": 11848, "text": "NAG algorithm in Python for sigmoid neuron" }, { "code": null, "e": 12507, "s": 11891, "text": "def do_nag_gradient_descent(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b, gamma = 0, 0, 0.9 for i in range(max_epochs): dw,db = 0,0 #compute the look ahead value w = w — gamma * v_w b = b — gamma * v_b for x,y in zip(X,Y): #compute the derivatives using look ahead value dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) #Now move further in the opposite direction of that gradient w = w — eta * dw b = b — eta * db #Now update the previous momentum v_w = gamma * v_w + eta * dw v_b = gamma * v_b + eta * db" }, { "code": null, "e": 12561, "s": 12507, "text": "Here v_w and v_b refer to v(t) and v(b) respectively." }, { "code": null, "e": 12584, "s": 12561, "text": "As per the update rule" }, { "code": null, "e": 12790, "s": 12584, "text": "The update is directly proportional to the gradient(∇w). Smaller the gradient smaller the update and the gradient is directly proportional to the input. Therefore the update is dependent on the input also." }, { "code": null, "e": 12825, "s": 12790, "text": "Need for an adaptive learning rate" }, { "code": null, "e": 13205, "s": 12825, "text": "For the real-time datasets, most of the features are sparse i.e. having zero values. Due to this for most of the cases, the corresponding gradient is zero and therefore the parameters update is also zero. To resonate this problem, these update should be boosted i.e. a high learning rate for sparse features. Therefore the learning rate should be adaptive for fairly sparse data." }, { "code": null, "e": 13350, "s": 13205, "text": "In other words, if we are dealing with sparse features then learning rate should be high whereas for dense features learning rate should be low." }, { "code": null, "e": 13436, "s": 13350, "text": "Adagrad, RMSProp, Adam algorithms are based on the concept of adaptive learning rate." }, { "code": null, "e": 13731, "s": 13436, "text": "It adopts the learning rate(η) based on the sparsity of features. So the parameters with small updates(sparse features) have high learning rate whereas the parameters with large updates(dense features) have low learning rate. Therefore adagrad uses a different learning rate for each parameter." }, { "code": null, "e": 13772, "s": 13731, "text": "Adagrad update rule for weight parameter" }, { "code": null, "e": 14002, "s": 13772, "text": "v(t) accumulates the running sum of square of the gradients. Square of ∇w(t) neglects the sign of gradients. v(t) indicates accumulated gradient up to time t. Epsilon in the denominator avoids the chances of divide by zero error." }, { "code": null, "e": 14195, "s": 14002, "text": "So if v(t) is low (due to less update up to time t) for a parameter then the effective learning rate will be high and if v(t) is high for a parameter then effective learning rate will be less." }, { "code": null, "e": 14242, "s": 14195, "text": "Adagrad algorithm in Python for sigmoid neuron" }, { "code": null, "e": 14603, "s": 14242, "text": "def do_adagrad(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) v_w += dw**2 v_b += db**2 self.w -= (eta / np.sqrt(v_w) + eps) * dw self.b -= (eta / np.sqrt(v_b) + eps) * db" }, { "code": null, "e": 14629, "s": 14603, "text": "Disadvantage with Adagrad" }, { "code": null, "e": 14672, "s": 14629, "text": "The learning rate decays very aggressively" }, { "code": null, "e": 15177, "s": 14672, "text": "For parameters(especially bias) corresponding to dense features, after a few updates, the learning rate decays rapidly as the denominator grows rapidly due to the accumulation of squared gradients. So after a finite number of updates, the algorithm refuses to learn and converges slowly even if we run it for a large number of epochs. The gradient reaches to a bad minimum (close to desired minima) but not at exact minima. So adagrad results in decaying and decreasing learning rate for bias parameters." }, { "code": null, "e": 15280, "s": 15177, "text": "RMSProp overcomes the decaying learning rate problem of adagrad and prevents the rapid growth in v(t)." }, { "code": null, "e": 15508, "s": 15280, "text": "Instead of accumulating squared gradients from the beginning, it accumulates the previous gradients in some portion(weight) which prevents rapid growth of v(t) and due to this the algorithm keeps learning and tries to converge." }, { "code": null, "e": 15549, "s": 15508, "text": "RMSProp update rule for weight parameter" }, { "code": null, "e": 15866, "s": 15549, "text": "Here v(t) is exponentially decaying average of all the previous squared gradients. The beta parameter value is set to a similar value as the momentum term. The running average v(t) up to time t is dependent on weighted previous average gradients and current gradient. v(t) maintains (∇w(t))2 for a fixed window time." }, { "code": null, "e": 15913, "s": 15866, "text": "Adagrad algorithm in Python for sigmoid neuron" }, { "code": null, "e": 16324, "s": 15913, "text": "def do_RMSProp(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 for i in range(max_epochs): dw,db = 0,0 for x,y in zip(X,Y): dw += grad_w(w,b,x,y) db += grad_b(w,b,x,y) v_w = beta * v_w + (1 — beta) * dw**2 v_b = beta * v_b + (1 — beta) * db**2 self.w -= (eta / np.sqrt(v_w) + eps) * dw self.b -= (eta / np.sqrt(v_b) + eps) * db" }, { "code": null, "e": 16344, "s": 16324, "text": "Issues with RMSProp" }, { "code": null, "e": 16417, "s": 16344, "text": "A large number of oscillations with high learning rate or large gradient" }, { "code": null, "e": 16667, "s": 16417, "text": "So far in Adagrad, RMSProp we were calculating different learning rates for different parameters, can we have different momentums for different parameters. Adam algorithm introduces the concept of adaptive momentum along with adaptive learning rate." }, { "code": null, "e": 16868, "s": 16667, "text": "Adaptive Moment Estimation (Adam) computes the exponentially decaying average of previous gradients m(t) along with an adaptive learning rate. Adam is a combined form of Momentum-based GD and RMSProp." }, { "code": null, "e": 17372, "s": 16868, "text": "In Momentum-based GD, previous gradients(history) are used to compute the current gradient whereas, in RMSProp previous gradients(history) are used to adjust the learning rate based on the features. Therefore Adam deals with adaptive learning rate and adaptive momentum where RMSProp ensures v(t) does not grow rapidly to avoid the chances of decaying learning rate and m(t) from Momentum-based GD ensures it calculates the exponentially decaying average of previous gradients, not the current gradient." }, { "code": null, "e": 17410, "s": 17372, "text": "Adam update rule for weight parameter" }, { "code": null, "e": 17484, "s": 17410, "text": "Here m(t) and v(t) are values of the mean obtained from the first moment." }, { "code": null, "e": 17624, "s": 17484, "text": "Adam uses bias corrected values (uncentered variance) of gradients for update rule and these values are obtained through the second moment." }, { "code": null, "e": 17658, "s": 17624, "text": "The final update rule is given as" }, { "code": null, "e": 17702, "s": 17658, "text": "Adam algorithm in Python for sigmoid neuron" }, { "code": null, "e": 18553, "s": 17702, "text": "def do_Adam(): w,b,eta,max_epochs = -2, -2, 1.0, 1000 v_w, v_b = 0, 0 m_w, m_b = 0, 0 num_updates = 0 for i in range(epochs): dw, db = 0, 0 for x, y in zip(X, Y): dw = self.grad_w(x, y) db = self.grad_b(x, y) num_updates += 1 m_w = beta1 * m_w + (1-beta1) * dw m_b = beta1 * m_b + (1-beta1) * db v_w = beta2 * v_w + (1-beta2) * dw**2 v_b = beta2 * v_b + (1-beta2) * db**2 #m_w_c, m_b_c, v_w_c and v_b_c for bias correction m_w_c = m_w / (1 — np.power(beta1, num_updates)) m_b_c = m_b / (1 — np.power(beta1, num_updates)) v_w_c = v_w / (1 — np.power(beta2, num_updates)) v_b_c = v_b / (1 — np.power(beta2, num_updates)) self.w -= (eta / np.sqrt(v_w_c) + eps) * m_w_c self.b -= (eta / np.sqrt(v_b_c) + eps) * m_b_c" }, { "code": null, "e": 18716, "s": 18553, "text": "So in Adam unlike RMSProp fewer oscillations and it moves more deterministically in the right direction which leads to faster convergence and better optimization." } ]
Node.js First Application - GeeksforGeeks
13 Oct, 2021 Node.js is an open source, cross-platform server environment which executes JavaScript using V8 JavaScript Engine. Node.js helps to write front-end and back-end code in the same language. It helps to write efficient code for real-time applications. In Node.js, the applications can be written using console-based method or web-based method. Console based Node.js Application: The Node.js console-based applications are run using Node.js command prompt. Console module in Node.js provide a simple debugging console. Node.js is a global console which can be used for synchronous as well as asynchronous communication. The console.log() function is used to display output on console. This function prints output to stdout with newline. Syntax: console.log([data][, ...]); Here, data is the content to be displayed on console. Example 1: Creating a Hello World application using Node.js. Create a geeks.js file containing the following code: console.log('Hello World'); Run the file on Node.js command prompt using command node geeks.js i.e. node <file_name> .Output: Example 2: Creating a Hello World application receiving the user input. Create a gfg.js file containing the following code. console.log(process.argv.slice(2)); The process.argv is used to provide command line argument to a program. Use the slice function with 2 as its argument to get all the elements of argv that comes after its second element, i.e. the arguments the user entered The first argument is location of the Node.js binary which runs the program and the second argument is location of the file being run.Output: Web-based Node.js Application: A web-based Node.js application consists of the following three important components: Import required modules: Load Node.js modules using the require directive. Load http module and store returned HTTP instance into a variable.Syntax:var http = require("http"); var http = require("http"); Create server: Create a server to listen the client’s requests. Create server instance using createServer() method. Bind server to port 8080 using listen method associated with server instance.Syntax:http.createServer().listen(8080); http.createServer().listen(8080); Read request and return response: Read the client request made using browser or console and return the response. A function with request and response parameters is used to read client request and return response.Syntax:http.createServer(function (request, response) {...}).listen(8080); http.createServer(function (request, response) {...}).listen(8080); Example: This example create a Hello World web-based application using Node.js. Create a firstprogram.js file containing the following code. // Require http headervar http = require('http'); // Create serverhttp.createServer(function (req, res) { // HTTP Status: 200 : OK // Content Type: text/html res.writeHead(200, {'Content-Type': 'text/html'}); // Send the response body as "Hello World!" res.end('Hello World!'); }).listen(8080); Run the file on Node.js command prompt using command node firstprogram.js and type http://127.0.0.1:8080/ in a web browser to see the output.Output: Node.js-Basics Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method How to update NPM ? Difference between promise and async await in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 37201, "s": 37173, "text": "\n13 Oct, 2021" }, { "code": null, "e": 37542, "s": 37201, "text": "Node.js is an open source, cross-platform server environment which executes JavaScript using V8 JavaScript Engine. Node.js helps to write front-end and back-end code in the same language. It helps to write efficient code for real-time applications. In Node.js, the applications can be written using console-based method or web-based method." }, { "code": null, "e": 37934, "s": 37542, "text": "Console based Node.js Application: The Node.js console-based applications are run using Node.js command prompt. Console module in Node.js provide a simple debugging console. Node.js is a global console which can be used for synchronous as well as asynchronous communication. The console.log() function is used to display output on console. This function prints output to stdout with newline." }, { "code": null, "e": 37942, "s": 37934, "text": "Syntax:" }, { "code": null, "e": 37970, "s": 37942, "text": "console.log([data][, ...]);" }, { "code": null, "e": 38024, "s": 37970, "text": "Here, data is the content to be displayed on console." }, { "code": null, "e": 38139, "s": 38024, "text": "Example 1: Creating a Hello World application using Node.js. Create a geeks.js file containing the following code:" }, { "code": "console.log('Hello World'); ", "e": 38168, "s": 38139, "text": null }, { "code": null, "e": 38266, "s": 38168, "text": "Run the file on Node.js command prompt using command node geeks.js i.e. node <file_name> .Output:" }, { "code": null, "e": 38390, "s": 38266, "text": "Example 2: Creating a Hello World application receiving the user input. Create a gfg.js file containing the following code." }, { "code": "console.log(process.argv.slice(2));", "e": 38426, "s": 38390, "text": null }, { "code": null, "e": 38791, "s": 38426, "text": "The process.argv is used to provide command line argument to a program. Use the slice function with 2 as its argument to get all the elements of argv that comes after its second element, i.e. the arguments the user entered The first argument is location of the Node.js binary which runs the program and the second argument is location of the file being run.Output:" }, { "code": null, "e": 38908, "s": 38791, "text": "Web-based Node.js Application: A web-based Node.js application consists of the following three important components:" }, { "code": null, "e": 39084, "s": 38908, "text": "Import required modules: Load Node.js modules using the require directive. Load http module and store returned HTTP instance into a variable.Syntax:var http = require(\"http\");" }, { "code": null, "e": 39112, "s": 39084, "text": "var http = require(\"http\");" }, { "code": null, "e": 39346, "s": 39112, "text": "Create server: Create a server to listen the client’s requests. Create server instance using createServer() method. Bind server to port 8080 using listen method associated with server instance.Syntax:http.createServer().listen(8080);" }, { "code": null, "e": 39380, "s": 39346, "text": "http.createServer().listen(8080);" }, { "code": null, "e": 39667, "s": 39380, "text": "Read request and return response: Read the client request made using browser or console and return the response. A function with request and response parameters is used to read client request and return response.Syntax:http.createServer(function (request, response) {...}).listen(8080);" }, { "code": null, "e": 39735, "s": 39667, "text": "http.createServer(function (request, response) {...}).listen(8080);" }, { "code": null, "e": 39876, "s": 39735, "text": "Example: This example create a Hello World web-based application using Node.js. Create a firstprogram.js file containing the following code." }, { "code": "// Require http headervar http = require('http'); // Create serverhttp.createServer(function (req, res) { // HTTP Status: 200 : OK // Content Type: text/html res.writeHead(200, {'Content-Type': 'text/html'}); // Send the response body as \"Hello World!\" res.end('Hello World!'); }).listen(8080);", "e": 40199, "s": 39876, "text": null }, { "code": null, "e": 40348, "s": 40199, "text": "Run the file on Node.js command prompt using command node firstprogram.js and type http://127.0.0.1:8080/ in a web browser to see the output.Output:" }, { "code": null, "e": 40363, "s": 40348, "text": "Node.js-Basics" }, { "code": null, "e": 40370, "s": 40363, "text": "Picked" }, { "code": null, "e": 40378, "s": 40370, "text": "Node.js" }, { "code": null, "e": 40395, "s": 40378, "text": "Web Technologies" }, { "code": null, "e": 40493, "s": 40395, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40502, "s": 40493, "text": "Comments" }, { "code": null, "e": 40515, "s": 40502, "text": "Old Comments" }, { "code": null, "e": 40552, "s": 40515, "text": "Express.js express.Router() Function" }, { "code": null, "e": 40600, "s": 40552, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40633, "s": 40600, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 40653, "s": 40633, "text": "How to update NPM ?" }, { "code": null, "e": 40707, "s": 40653, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 40749, "s": 40707, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 40792, "s": 40749, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 40854, "s": 40792, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40904, "s": 40854, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
10 Examples to Understand SQL Views | by Soner Yıldırım | Towards Data Science
SQL is a programming language used to manage and maintain data stored in relational databases. A relational database consists of tables with labelled rows and columns. One of the most frequent operations with SQL is to query a database to retrieve data. A typical relational database contains many tables that are related to each other by means of shared values in a column known as foreign key. As the number of tables increases, writing queries starts to become complex. Besides, we usually need to filter or transform data while retrieving from the database. Thus, we end up writing complicated and lengthy queries to obtain the desired data. It is doable to write a complex query once or twice. However, if we need to use it many times, a more practical approach is necessary. One option is to save the query in a text or sql file and copy it whenever needed. It is fine but there is a better option which is SQL views or simply views. A view is a stored query. Views are saved in the database server so we do not have to copy them from some other file. We create a view by assigning a name to a query. Let’s start with an example so that we have an idea about how a view looks like. After that, I will elaborate on the examples and explain the views in more detail. I have created a customer and orders table with mock data. The tables contain some information about customers of a business and their orders. Here is an overview of the tables: The tables are related by the customer id (cust_id) column so we use the customer id column to join these tables. Consider a case where need to find the total order amount for each location. Here is the query that accomplished this task. #Example 1mysql> select customer.location, sum(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location;+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin | 9811.09 || Dallas | 23288.40 || Houston | 12978.33 |+----------+--------------------+ We select the location from the customer table and the sum of amount from the orders table. The tables are joined on the customer id column. The group by clause groups the entries (i.e. rows) by location. We can store this query using a view as follows: #Example 2mysql> create view totalAmount -> as -> select customer.location, sum(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location; The “create view” statement is used along with a name for the view. Then, we write the query after the “as” keyword. As you notice, creating a view does not return anything or it does not execute the select statement. The views generate a result set only when they are invoked. We can invoke views just like we query a table. Here is how it’s done: #Example 3mysql> select * from totalAmount;+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin | 9811.09 || Dallas | 23288.40 || Houston | 12978.33 |+----------+--------------------+ The example above makes the views seem like tables. In terms of querying, views can be considered as tables. However, they do not store any data. Once a view is executed, SQL retrieves the data from the tables specified inside the view. Thus, views are sometimes called virtual tables. Note: It is important to emphasize that we are using MySQL as relational database management system (RDBMS). Although the SQL syntax is mostly the same among different RDBMs, there might be small differences. We can filter a view by using the where clause. #Example 4mysql> select * from totalAmount -> where location = "Austin";+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin | 9811.09 |+----------+--------------------+ We can only filter based on the columns included in the view. For instance, the orders table has a date column but it cannot be used for filtering. The totalAmount view only refers to the location and sum of the amount. These are the only two values we can use for filtering. Let’s create another view which allows for filtering based on the date and amount columns. #Example 5mysql> create view cityOrders -> as -> select -> customer.location, -> orders.date, -> orders.amount -> from customer -> join orders -> on customer.cust_id = orders.cust_id; The cityOrders view refers to three columns which are the location from customer table and the date and amount from orders table. We can use the cityOrders view to calculate the total order amount for each location on a specific date. #Example 6mysql> select location, sum(amount) -> from cityOrders -> where date = '2020-01-31' -> group by location;+----------+-------------+| location | sum(amount) |+----------+-------------+| Austin | 77.94 || Dallas | 260.77 || Houston | 72.46 |+----------+-------------+ We can also calculate the number of orders that are higher than a specific amount for each city. #Example 7mysql> select location, count(amount) -> from cityOrders -> where amount > 20 -> group by location;+----------+---------------+| location | count(amount) |+----------+---------------+| Austin | 160 || Dallas | 383 || Houston | 205 |+----------+---------------+ Although both the totalAmount and cityOrders views refer to the amount column, we cannot use single order amounts for filtering in the totalAmount view. The reason is that the totalAmount view refers to the sum of the amounts, not single order amounts. We can update a view using the “alter view” or “create or replace view” statements. The difference is that the view must exist to use the “alter view” statement. If we are not sure if the view already exists, we should use the “create or replace view” statement. Let’s modify the cityOrders view. #Example 8mysql> alter view cityOrders -> as -> select -> customer.location, -> customer.age, -> orders.date, -> orders.amount -> from customer -> join orders -> on customer.cust_id = orders.cust_id; We have added the age column from customer table to the cityOrders view. We can now use the age for filtering or aggregation as well. The following query returns the average order amount of customers who are older than 30. It also groups the results based on location. #Example 9mysql> select location, avg(amount) -> from cityOrders -> where age > 30 -> group by location;+----------+-------------+| location | avg(amount) |+----------+-------------+| Austin | 53.740153 || Dallas | 47.069703 || Houston | 49.287771 |+----------+-------------+ If we do not need a view anymore, we can drop it. The syntax is same as dropping a table. #Example 10mysql> drop view totalAmount;Query OK, 0 rows affected (0.00 sec)mysql> select * from totalAmount;ERROR 1146 (42S02): Table 'practice.totalAmount' doesn't exist The view is an important concept for SQL. There are many advantages of using a view. The first and foremost, it simplifies complex queries. The examples we have done included joining two tables. In case of larger databases with many tables, the queries might be highly complex. Thus, views provide a more practical way. The views also save us from writing the same queries over and over. Consider we have a highly complicated routine calculation that involves multiple filtering, aggregations, and nested select statements. It is much better to have it in a view than writing the query each time. We also have more control over the access to the database using views. A table might contain sensitive information that can only be accessed by certain employees. Using views, we can grant access to only specific columns of a table. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 339, "s": 171, "text": "SQL is a programming language used to manage and maintain data stored in relational databases. A relational database consists of tables with labelled rows and columns." }, { "code": null, "e": 567, "s": 339, "text": "One of the most frequent operations with SQL is to query a database to retrieve data. A typical relational database contains many tables that are related to each other by means of shared values in a column known as foreign key." }, { "code": null, "e": 817, "s": 567, "text": "As the number of tables increases, writing queries starts to become complex. Besides, we usually need to filter or transform data while retrieving from the database. Thus, we end up writing complicated and lengthy queries to obtain the desired data." }, { "code": null, "e": 1111, "s": 817, "text": "It is doable to write a complex query once or twice. However, if we need to use it many times, a more practical approach is necessary. One option is to save the query in a text or sql file and copy it whenever needed. It is fine but there is a better option which is SQL views or simply views." }, { "code": null, "e": 1278, "s": 1111, "text": "A view is a stored query. Views are saved in the database server so we do not have to copy them from some other file. We create a view by assigning a name to a query." }, { "code": null, "e": 1442, "s": 1278, "text": "Let’s start with an example so that we have an idea about how a view looks like. After that, I will elaborate on the examples and explain the views in more detail." }, { "code": null, "e": 1620, "s": 1442, "text": "I have created a customer and orders table with mock data. The tables contain some information about customers of a business and their orders. Here is an overview of the tables:" }, { "code": null, "e": 1734, "s": 1620, "text": "The tables are related by the customer id (cust_id) column so we use the customer id column to join these tables." }, { "code": null, "e": 1858, "s": 1734, "text": "Consider a case where need to find the total order amount for each location. Here is the query that accomplished this task." }, { "code": null, "e": 2266, "s": 1858, "text": "#Example 1mysql> select customer.location, sum(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location;+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin | 9811.09 || Dallas | 23288.40 || Houston | 12978.33 |+----------+--------------------+" }, { "code": null, "e": 2471, "s": 2266, "text": "We select the location from the customer table and the sum of amount from the orders table. The tables are joined on the customer id column. The group by clause groups the entries (i.e. rows) by location." }, { "code": null, "e": 2520, "s": 2471, "text": "We can store this query using a view as follows:" }, { "code": null, "e": 2736, "s": 2520, "text": "#Example 2mysql> create view totalAmount -> as -> select customer.location, sum(orders.amount) -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location;" }, { "code": null, "e": 2853, "s": 2736, "text": "The “create view” statement is used along with a name for the view. Then, we write the query after the “as” keyword." }, { "code": null, "e": 3014, "s": 2853, "text": "As you notice, creating a view does not return anything or it does not execute the select statement. The views generate a result set only when they are invoked." }, { "code": null, "e": 3085, "s": 3014, "text": "We can invoke views just like we query a table. Here is how it’s done:" }, { "code": null, "e": 3360, "s": 3085, "text": "#Example 3mysql> select * from totalAmount;+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin | 9811.09 || Dallas | 23288.40 || Houston | 12978.33 |+----------+--------------------+" }, { "code": null, "e": 3646, "s": 3360, "text": "The example above makes the views seem like tables. In terms of querying, views can be considered as tables. However, they do not store any data. Once a view is executed, SQL retrieves the data from the tables specified inside the view. Thus, views are sometimes called virtual tables." }, { "code": null, "e": 3855, "s": 3646, "text": "Note: It is important to emphasize that we are using MySQL as relational database management system (RDBMS). Although the SQL syntax is mostly the same among different RDBMs, there might be small differences." }, { "code": null, "e": 3903, "s": 3855, "text": "We can filter a view by using the where clause." }, { "code": null, "e": 4144, "s": 3903, "text": "#Example 4mysql> select * from totalAmount -> where location = \"Austin\";+----------+--------------------+| location | sum(orders.amount) |+----------+--------------------+| Austin | 9811.09 |+----------+--------------------+" }, { "code": null, "e": 4420, "s": 4144, "text": "We can only filter based on the columns included in the view. For instance, the orders table has a date column but it cannot be used for filtering. The totalAmount view only refers to the location and sum of the amount. These are the only two values we can use for filtering." }, { "code": null, "e": 4511, "s": 4420, "text": "Let’s create another view which allows for filtering based on the date and amount columns." }, { "code": null, "e": 4725, "s": 4511, "text": "#Example 5mysql> create view cityOrders -> as -> select -> customer.location, -> orders.date, -> orders.amount -> from customer -> join orders -> on customer.cust_id = orders.cust_id;" }, { "code": null, "e": 4855, "s": 4725, "text": "The cityOrders view refers to three columns which are the location from customer table and the date and amount from orders table." }, { "code": null, "e": 4960, "s": 4855, "text": "We can use the cityOrders view to calculate the total order amount for each location on a specific date." }, { "code": null, "e": 5267, "s": 4960, "text": "#Example 6mysql> select location, sum(amount) -> from cityOrders -> where date = '2020-01-31' -> group by location;+----------+-------------+| location | sum(amount) |+----------+-------------+| Austin | 77.94 || Dallas | 260.77 || Houston | 72.46 |+----------+-------------+" }, { "code": null, "e": 5364, "s": 5267, "text": "We can also calculate the number of orders that are higher than a specific amount for each city." }, { "code": null, "e": 5679, "s": 5364, "text": "#Example 7mysql> select location, count(amount) -> from cityOrders -> where amount > 20 -> group by location;+----------+---------------+| location | count(amount) |+----------+---------------+| Austin | 160 || Dallas | 383 || Houston | 205 |+----------+---------------+" }, { "code": null, "e": 5932, "s": 5679, "text": "Although both the totalAmount and cityOrders views refer to the amount column, we cannot use single order amounts for filtering in the totalAmount view. The reason is that the totalAmount view refers to the sum of the amounts, not single order amounts." }, { "code": null, "e": 6195, "s": 5932, "text": "We can update a view using the “alter view” or “create or replace view” statements. The difference is that the view must exist to use the “alter view” statement. If we are not sure if the view already exists, we should use the “create or replace view” statement." }, { "code": null, "e": 6229, "s": 6195, "text": "Let’s modify the cityOrders view." }, { "code": null, "e": 6464, "s": 6229, "text": "#Example 8mysql> alter view cityOrders -> as -> select -> customer.location, -> customer.age, -> orders.date, -> orders.amount -> from customer -> join orders -> on customer.cust_id = orders.cust_id;" }, { "code": null, "e": 6733, "s": 6464, "text": "We have added the age column from customer table to the cityOrders view. We can now use the age for filtering or aggregation as well. The following query returns the average order amount of customers who are older than 30. It also groups the results based on location." }, { "code": null, "e": 7029, "s": 6733, "text": "#Example 9mysql> select location, avg(amount) -> from cityOrders -> where age > 30 -> group by location;+----------+-------------+| location | avg(amount) |+----------+-------------+| Austin | 53.740153 || Dallas | 47.069703 || Houston | 49.287771 |+----------+-------------+" }, { "code": null, "e": 7119, "s": 7029, "text": "If we do not need a view anymore, we can drop it. The syntax is same as dropping a table." }, { "code": null, "e": 7291, "s": 7119, "text": "#Example 10mysql> drop view totalAmount;Query OK, 0 rows affected (0.00 sec)mysql> select * from totalAmount;ERROR 1146 (42S02): Table 'practice.totalAmount' doesn't exist" }, { "code": null, "e": 7611, "s": 7291, "text": "The view is an important concept for SQL. There are many advantages of using a view. The first and foremost, it simplifies complex queries. The examples we have done included joining two tables. In case of larger databases with many tables, the queries might be highly complex. Thus, views provide a more practical way." }, { "code": null, "e": 7888, "s": 7611, "text": "The views also save us from writing the same queries over and over. Consider we have a highly complicated routine calculation that involves multiple filtering, aggregations, and nested select statements. It is much better to have it in a view than writing the query each time." }, { "code": null, "e": 8121, "s": 7888, "text": "We also have more control over the access to the database using views. A table might contain sensitive information that can only be accessed by certain employees. Using views, we can grant access to only specific columns of a table." } ]
How to use input readonly attribute in jQuery ?
03 Aug, 2021 Use jQuery methods to add the readonly attribute to the form input field. jQuery attr() Method: This method set/return attributes and values of the selected elements. If this method is used to return the attribute value, it returns the value of the first selected element.If this method is used to set attribute values, it sets one or more than one attribute/value pairs for the set of selected elements.Syntax:Return the value of an attribute:$(selector).attr(attribute) Set the attribute and value:$(selector).attr(attribute, value) Set attribute and value using a function:$(selector).attr(attribute, function(index, currentvalue)) Set multiple attributes and values:$(selector).attr({attribute:value, attribute:value, ...}) Parameters:attribute: This parameter specifies the name of the attribute.value: This parameter specifies the value of the attribute.function(index, currentvalue): This parameter specifies a function that returns the attribute value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current attribute value of selected elements. Syntax: Return the value of an attribute:$(selector).attr(attribute) $(selector).attr(attribute) Set the attribute and value:$(selector).attr(attribute, value) $(selector).attr(attribute, value) Set attribute and value using a function:$(selector).attr(attribute, function(index, currentvalue)) $(selector).attr(attribute, function(index, currentvalue)) Set multiple attributes and values:$(selector).attr({attribute:value, attribute:value, ...}) $(selector).attr({attribute:value, attribute:value, ...}) Parameters: attribute: This parameter specifies the name of the attribute. value: This parameter specifies the value of the attribute. function(index, currentvalue): This parameter specifies a function that returns the attribute value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current attribute value of selected elements. index: This parameter receives the index position of element in the set. currentValue: This parameter receives the current attribute value of selected elements. jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to set or return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements.Syntax:Return the value of an property:$(selector).prop(property) Set the property and value:$(selector).prop(property, value) Set property and value using a function:$(selector).prop(property, function(index, currentvalue)) Set multiple properties and values:$(selector).prop({property:value, property:value, ...}) Parameters:property: This parameter specifies the name of the property.value: This parameter specifies the value of the property.function(index, currentvalue): This parameter specifies a function that returns the property value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current property value of selected elements. jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to set or return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements. Syntax: Return the value of an property:$(selector).prop(property) $(selector).prop(property) Set the property and value:$(selector).prop(property, value) $(selector).prop(property, value) Set property and value using a function:$(selector).prop(property, function(index, currentvalue)) $(selector).prop(property, function(index, currentvalue)) Set multiple properties and values:$(selector).prop({property:value, property:value, ...}) $(selector).prop({property:value, property:value, ...}) Parameters: property: This parameter specifies the name of the property. value: This parameter specifies the value of the property. function(index, currentvalue): This parameter specifies a function that returns the property value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current property value of selected elements. index: This parameter receives the index position of element in the set. currentValue: This parameter receives the current property value of selected elements. Example 1: In this example the read-only attribute of form input text field is enabled by using attr() method. <!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input field </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p style = "font-size: 15px; font-weight: bold;"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input type="text" name="input_field" /> </form> <br> <button onclick = "GFG_Run()"> click here </button> <p id = "GFG_down" style = "color: green; font-size: 20px; font-weight: bold;"> </p> <script> function GFG_Run() { $('input').attr('readonly', true); document.getElementById("GFG_down").innerHTML = "Read-Only attribute enabled"; } </script> </body> </html> Output: Before click on the button: After click on the button: Example 2: In this example the read-only attribute of form input text field is enabled by using prop() method . <!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input tag </title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p style = "font-size: 15px; font-weight: bold;"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input type="text" name="input_field" /> </form> <br> <button onclick = "GFG_Run()"> click here </button> <p id = "GFG_down" style = "color: green; font-size: 20px; font-weight: bold;"> </p> <script> function GFG_Run() { $('input').prop('readonly', true); document.getElementById("GFG_down").innerHTML = "Read-Only attribute enabled"; } </script> </body> </html> Output: Before click on the button: After click on the button: 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. JavaScript JQuery Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Aug, 2021" }, { "code": null, "e": 102, "s": 28, "text": "Use jQuery methods to add the readonly attribute to the form input field." }, { "code": null, "e": 1155, "s": 102, "text": "jQuery attr() Method: This method set/return attributes and values of the selected elements. If this method is used to return the attribute value, it returns the value of the first selected element.If this method is used to set attribute values, it sets one or more than one attribute/value pairs for the set of selected elements.Syntax:Return the value of an attribute:$(selector).attr(attribute)\nSet the attribute and value:$(selector).attr(attribute, value)\nSet attribute and value using a function:$(selector).attr(attribute, function(index, currentvalue))\nSet multiple attributes and values:$(selector).attr({attribute:value, attribute:value, ...})\nParameters:attribute: This parameter specifies the name of the attribute.value: This parameter specifies the value of the attribute.function(index, currentvalue): This parameter specifies a function that returns the attribute value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current attribute value of selected elements." }, { "code": null, "e": 1163, "s": 1155, "text": "Syntax:" }, { "code": null, "e": 1225, "s": 1163, "text": "Return the value of an attribute:$(selector).attr(attribute)\n" }, { "code": null, "e": 1254, "s": 1225, "text": "$(selector).attr(attribute)\n" }, { "code": null, "e": 1318, "s": 1254, "text": "Set the attribute and value:$(selector).attr(attribute, value)\n" }, { "code": null, "e": 1354, "s": 1318, "text": "$(selector).attr(attribute, value)\n" }, { "code": null, "e": 1455, "s": 1354, "text": "Set attribute and value using a function:$(selector).attr(attribute, function(index, currentvalue))\n" }, { "code": null, "e": 1515, "s": 1455, "text": "$(selector).attr(attribute, function(index, currentvalue))\n" }, { "code": null, "e": 1609, "s": 1515, "text": "Set multiple attributes and values:$(selector).attr({attribute:value, attribute:value, ...})\n" }, { "code": null, "e": 1668, "s": 1609, "text": "$(selector).attr({attribute:value, attribute:value, ...})\n" }, { "code": null, "e": 1680, "s": 1668, "text": "Parameters:" }, { "code": null, "e": 1743, "s": 1680, "text": "attribute: This parameter specifies the name of the attribute." }, { "code": null, "e": 1803, "s": 1743, "text": "value: This parameter specifies the value of the attribute." }, { "code": null, "e": 2070, "s": 1803, "text": "function(index, currentvalue): This parameter specifies a function that returns the attribute value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current attribute value of selected elements." }, { "code": null, "e": 2143, "s": 2070, "text": "index: This parameter receives the index position of element in the set." }, { "code": null, "e": 2231, "s": 2143, "text": "currentValue: This parameter receives the current attribute value of selected elements." }, { "code": null, "e": 3266, "s": 2231, "text": "jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to set or return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements.Syntax:Return the value of an property:$(selector).prop(property)\nSet the property and value:$(selector).prop(property, value)\nSet property and value using a function:$(selector).prop(property, function(index, currentvalue))\nSet multiple properties and values:$(selector).prop({property:value, property:value, ...})\nParameters:property: This parameter specifies the name of the property.value: This parameter specifies the value of the property.function(index, currentvalue): This parameter specifies a function that returns the property value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current property value of selected elements." }, { "code": null, "e": 3592, "s": 3266, "text": "jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to set or return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements." }, { "code": null, "e": 3600, "s": 3592, "text": "Syntax:" }, { "code": null, "e": 3660, "s": 3600, "text": "Return the value of an property:$(selector).prop(property)\n" }, { "code": null, "e": 3688, "s": 3660, "text": "$(selector).prop(property)\n" }, { "code": null, "e": 3750, "s": 3688, "text": "Set the property and value:$(selector).prop(property, value)\n" }, { "code": null, "e": 3785, "s": 3750, "text": "$(selector).prop(property, value)\n" }, { "code": null, "e": 3884, "s": 3785, "text": "Set property and value using a function:$(selector).prop(property, function(index, currentvalue))\n" }, { "code": null, "e": 3943, "s": 3884, "text": "$(selector).prop(property, function(index, currentvalue))\n" }, { "code": null, "e": 4035, "s": 3943, "text": "Set multiple properties and values:$(selector).prop({property:value, property:value, ...})\n" }, { "code": null, "e": 4092, "s": 4035, "text": "$(selector).prop({property:value, property:value, ...})\n" }, { "code": null, "e": 4104, "s": 4092, "text": "Parameters:" }, { "code": null, "e": 4165, "s": 4104, "text": "property: This parameter specifies the name of the property." }, { "code": null, "e": 4224, "s": 4165, "text": "value: This parameter specifies the value of the property." }, { "code": null, "e": 4489, "s": 4224, "text": "function(index, currentvalue): This parameter specifies a function that returns the property value to set.index: This parameter receives the index position of element in the set.currentValue: This parameter receives the current property value of selected elements." }, { "code": null, "e": 4562, "s": 4489, "text": "index: This parameter receives the index position of element in the set." }, { "code": null, "e": 4649, "s": 4562, "text": "currentValue: This parameter receives the current property value of selected elements." }, { "code": null, "e": 4760, "s": 4649, "text": "Example 1: In this example the read-only attribute of form input text field is enabled by using attr() method." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input field </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p style = \"font-size: 15px; font-weight: bold;\"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input type=\"text\" name=\"input_field\" /> </form> <br> <button onclick = \"GFG_Run()\"> click here </button> <p id = \"GFG_down\" style = \"color: green; font-size: 20px; font-weight: bold;\"> </p> <script> function GFG_Run() { $('input').attr('readonly', true); document.getElementById(\"GFG_down\").innerHTML = \"Read-Only attribute enabled\"; } </script> </body> </html> ", "e": 5940, "s": 4760, "text": null }, { "code": null, "e": 5948, "s": 5940, "text": "Output:" }, { "code": null, "e": 5976, "s": 5948, "text": "Before click on the button:" }, { "code": null, "e": 6003, "s": 5976, "text": "After click on the button:" }, { "code": null, "e": 6115, "s": 6003, "text": "Example 2: In this example the read-only attribute of form input text field is enabled by using prop() method ." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> Add a readonly attribute to an input tag </title> <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p style = \"font-size: 15px; font-weight: bold;\"> The readonly attribute is added to input box on click on the button. </p> <form> Input : <input type=\"text\" name=\"input_field\" /> </form> <br> <button onclick = \"GFG_Run()\"> click here </button> <p id = \"GFG_down\" style = \"color: green; font-size: 20px; font-weight: bold;\"> </p> <script> function GFG_Run() { $('input').prop('readonly', true); document.getElementById(\"GFG_down\").innerHTML = \"Read-Only attribute enabled\"; } </script> </body> </html> ", "e": 7278, "s": 6115, "text": null }, { "code": null, "e": 7286, "s": 7278, "text": "Output:" }, { "code": null, "e": 7314, "s": 7286, "text": "Before click on the button:" }, { "code": null, "e": 7341, "s": 7314, "text": "After click on the button:" }, { "code": null, "e": 7609, "s": 7341, "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": 7620, "s": 7609, "text": "JavaScript" }, { "code": null, "e": 7627, "s": 7620, "text": "JQuery" }, { "code": null, "e": 7644, "s": 7627, "text": "Web Technologies" }, { "code": null, "e": 7671, "s": 7644, "text": "Web technologies Questions" } ]
How to create Binary File from the existing Text File?
21 Jul, 2021 In this article, we will discuss how to create a binary file from the given text file. Before proceeding to the steps, let’s have an introduction of what are text files and binary files. Text files: Text files store data in human-readable form and sequentially. Binary files: Binary files store data in the form of bits/groups of bits (bytes) in sequence. These bits’ combinations can refer to custom data. Binary files can store multiple types of data, such as images, audio, text, etc. Problem Statement: The task here is to read data from a text file and create a new binary file containing the same data in binary form. Example: Suppose there are details of customers in a file named “Custdata.txt” and the task is to create a binary file named “Customerdb” by reading data from the text file “Custdata.txt”. Each line of file “Custdata.txt” contains a record of one customer’s information. A record has 3 attributes i.e., ID, Name, and Age. Each record has a fixed length. Let us assume that “Custdata.txt” has the following data- Let the record size, the number of bytes in a record = B. If data for 3 customers is written to a disk file, then the file will contain 3 × B bytes. If there are information about the customer record’s relative position “pos” in the file, then the customer’s information can be directly read. pos* (B – 1) will be the record’s starting byte position. There is no requirement, as such, to store all values in a record in text format. The internal format can be used to directly store values. An option that is good and can be taken as a choice is to define a structure for our record. struct Customers { int ID; char name[30]; int age; } The individual elements of structure customers can now be accessed by creating a structure variable cs as: cs.ID.cs.name.cs.age. cs.ID. cs.name. cs.age. Let us look at the methods that would be required to read the text file and write in the binary file. The function required for reading is fscanf() and for writing is fwrite(). Reading: fscanf() function is used to read the text file containing the customer data. Syntax: int fscanf(FILE* streamPtr, const char* formatPtr, ...);This function reads the data from file stream and stores the values into the respective variables. Parameters of fscanf(): streamPtr: It specifies the pointer to the input file stream to read the data from. formatPtr: Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Example: %d for int, %s for string, etc. There is a need to include <cstdio> header file for using this function. Writing: fwrite() function is used in the program to write the data read from the text file to the binary file in binary form. Syntax: size_t fwrite(const void * bufPtr, size size, size_t count, FILE * ptr_OutputStream);The fwrite() function writes “count” number of objects, where size of every object is “size” bytes, to the given output stream. Parameters of write(): bufPtr: Pointer to the block of memory whose content is written (converted to a const void*). size: The size in bytes of each object to be written. count: The count of total objects to be read. ptr_OutputStream: Pointer to a file specifying the output file stream to write to. There is a need to include<cstdio> header file for using this function. Algorithm: Below is the approach for the program for reading the text file and writing the content in the binary form to a binary file. Open the input text file and the output binary file. Until the end of the text file is reached perform the following steps:Read a line from the input text file, into 3 variables using fscanf().The structure variable is set to values for elements(to write the structure variable into the output file.Write that structure variable to the output binary file using fwrite(). Read a line from the input text file, into 3 variables using fscanf(). The structure variable is set to values for elements(to write the structure variable into the output file. Write that structure variable to the output binary file using fwrite(). Close the input text file and the output binary file. Below is the C++ program for the above approach: C++ // C++ program for the above approach#include <cstdio>#include <cstring>#include <iostream>using namespace std; // Creating a structure for customersstruct Customers { int ID; char name[30]; int age;}; // Driver Codeint main(){ struct Customers cs; int rec_size; rec_size = sizeof(struct Customers); cout << "Size of record is: " << rec_size << endl; // Create File Pointers fp_input for // text file, fp_output for output // binary file FILE *fp_input, *fp_output; // Open input text file, output // binary file. // If we cannot open them, work // cannot be done, so return -1 fp_input = fopen("custdata.txt", "r"); if (fp_input == NULL) { cout << "Could not open input file" << endl; return -1; } fp_output = fopen("Customerdb", "wb"); if (fp_output == NULL) { cout << "Could not open " << "output file" << endl; return -1; } // Read one line from input text file, // into 3 variables id, n & a int id, a; char n[30]; // Count for keeping count of total // Customers Records int count = 0; cout << endl; // Read next line from input text // file until EOF is reached while (!feof(fp_input)) { // Reading the text file fscanf(fp_input, "%d %s %d ", &id, n, &a); // Increment the count by one // after reading a record count++; // Structure variable cs is set // to values to elements cs.ID = id, strcpy(cs.name, n), cs.age = a; // Write the structure variable // cs to output file fwrite(&cs, rec_size, 1, fp_output); printf( "Customer number %2d has" " data %5d %30s %3d \n", count, cs.ID, cs.name, cs.age); } cout << "Data from file read" << " and printed\n"; cout << "Database created for " << "Customers info\n"; // Count contains count of total records cout << "Total records written: " << count << endl; // Close both the files fclose(fp_input); fclose(fp_output); return 0;} Output: Size of record is: 40 Customer number 1 has data 1 Annil 22 Customer number 2 has data 2 Ram 45 Customer number 3 has data 3 Golu 25 Data from file read and printed Database created for Customers info Total records written: 3 Explanation: There were 3 records in the file “custdata.txt” that were read, printed, and saved in the “Customerdb” file in binary mode.The text file contains 3 fields in every line- ID, Name, and Age.The first line of the text file contains- 1 Annil 22 This line is read from the file, i.e, the data of ID, Name, and Age are read and their values are assigned to the variables id, n, and a respectively. Now assign the values of these 3 variables to the data members: ID, name[], and age of the structure variable cs respectively.Now using fwrite(&cs, rec_size, 1, fp_output), write one cs object of size rec_size to the binary file- ” fp_output” (binary mode).This procedure continues for all the lines of text files until the end of the file is reached. After the execution of the program ends, the file “custdata.txt” will remain as it is, as it was opened in the read mode- 1 Annil 22 2 Ram 45 3 Golu 25 This data is read line by line and written to the file “Customerdb” in binary mode. The file “Customerdb” will have the contents in binary form, which is not readable. The file, when opened normally, looks like this : C-File Handling File Handling C++ C++ Programs File Handling CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jul, 2021" }, { "code": null, "e": 215, "s": 28, "text": "In this article, we will discuss how to create a binary file from the given text file. Before proceeding to the steps, let’s have an introduction of what are text files and binary files." }, { "code": null, "e": 290, "s": 215, "text": "Text files: Text files store data in human-readable form and sequentially." }, { "code": null, "e": 516, "s": 290, "text": "Binary files: Binary files store data in the form of bits/groups of bits (bytes) in sequence. These bits’ combinations can refer to custom data. Binary files can store multiple types of data, such as images, audio, text, etc." }, { "code": null, "e": 652, "s": 516, "text": "Problem Statement: The task here is to read data from a text file and create a new binary file containing the same data in binary form." }, { "code": null, "e": 841, "s": 652, "text": "Example: Suppose there are details of customers in a file named “Custdata.txt” and the task is to create a binary file named “Customerdb” by reading data from the text file “Custdata.txt”." }, { "code": null, "e": 923, "s": 841, "text": "Each line of file “Custdata.txt” contains a record of one customer’s information." }, { "code": null, "e": 974, "s": 923, "text": "A record has 3 attributes i.e., ID, Name, and Age." }, { "code": null, "e": 1006, "s": 974, "text": "Each record has a fixed length." }, { "code": null, "e": 1064, "s": 1006, "text": "Let us assume that “Custdata.txt” has the following data-" }, { "code": null, "e": 1122, "s": 1064, "text": "Let the record size, the number of bytes in a record = B." }, { "code": null, "e": 1213, "s": 1122, "text": "If data for 3 customers is written to a disk file, then the file will contain 3 × B bytes." }, { "code": null, "e": 1357, "s": 1213, "text": "If there are information about the customer record’s relative position “pos” in the file, then the customer’s information can be directly read." }, { "code": null, "e": 1415, "s": 1357, "text": "pos* (B – 1) will be the record’s starting byte position." }, { "code": null, "e": 1648, "s": 1415, "text": "There is no requirement, as such, to store all values in a record in text format. The internal format can be used to directly store values. An option that is good and can be taken as a choice is to define a structure for our record." }, { "code": null, "e": 1714, "s": 1648, "text": "struct Customers \n{\n int ID;\n char name[30];\n int age;\n}" }, { "code": null, "e": 1821, "s": 1714, "text": "The individual elements of structure customers can now be accessed by creating a structure variable cs as:" }, { "code": null, "e": 1843, "s": 1821, "text": "cs.ID.cs.name.cs.age." }, { "code": null, "e": 1850, "s": 1843, "text": "cs.ID." }, { "code": null, "e": 1859, "s": 1850, "text": "cs.name." }, { "code": null, "e": 1867, "s": 1859, "text": "cs.age." }, { "code": null, "e": 2044, "s": 1867, "text": "Let us look at the methods that would be required to read the text file and write in the binary file. The function required for reading is fscanf() and for writing is fwrite()." }, { "code": null, "e": 2131, "s": 2044, "text": "Reading: fscanf() function is used to read the text file containing the customer data." }, { "code": null, "e": 2139, "s": 2131, "text": "Syntax:" }, { "code": null, "e": 2294, "s": 2139, "text": "int fscanf(FILE* streamPtr, const char* formatPtr, ...);This function reads the data from file stream and stores the values into the respective variables." }, { "code": null, "e": 2318, "s": 2294, "text": "Parameters of fscanf():" }, { "code": null, "e": 2402, "s": 2318, "text": "streamPtr: It specifies the pointer to the input file stream to read the data from." }, { "code": null, "e": 2588, "s": 2402, "text": "formatPtr: Pointer to a null-terminated character string that specifies how to read the input. It consists of format specifiers starting with %. Example: %d for int, %s for string, etc." }, { "code": null, "e": 2661, "s": 2588, "text": "There is a need to include <cstdio> header file for using this function." }, { "code": null, "e": 2789, "s": 2661, "text": "Writing: fwrite() function is used in the program to write the data read from the text file to the binary file in binary form. " }, { "code": null, "e": 2797, "s": 2789, "text": "Syntax:" }, { "code": null, "e": 3010, "s": 2797, "text": "size_t fwrite(const void * bufPtr, size size, size_t count, FILE * ptr_OutputStream);The fwrite() function writes “count” number of objects, where size of every object is “size” bytes, to the given output stream." }, { "code": null, "e": 3033, "s": 3010, "text": "Parameters of write():" }, { "code": null, "e": 3127, "s": 3033, "text": "bufPtr: Pointer to the block of memory whose content is written (converted to a const void*)." }, { "code": null, "e": 3181, "s": 3127, "text": "size: The size in bytes of each object to be written." }, { "code": null, "e": 3227, "s": 3181, "text": "count: The count of total objects to be read." }, { "code": null, "e": 3310, "s": 3227, "text": "ptr_OutputStream: Pointer to a file specifying the output file stream to write to." }, { "code": null, "e": 3382, "s": 3310, "text": "There is a need to include<cstdio> header file for using this function." }, { "code": null, "e": 3518, "s": 3382, "text": "Algorithm: Below is the approach for the program for reading the text file and writing the content in the binary form to a binary file." }, { "code": null, "e": 3571, "s": 3518, "text": "Open the input text file and the output binary file." }, { "code": null, "e": 3889, "s": 3571, "text": "Until the end of the text file is reached perform the following steps:Read a line from the input text file, into 3 variables using fscanf().The structure variable is set to values for elements(to write the structure variable into the output file.Write that structure variable to the output binary file using fwrite()." }, { "code": null, "e": 3960, "s": 3889, "text": "Read a line from the input text file, into 3 variables using fscanf()." }, { "code": null, "e": 4067, "s": 3960, "text": "The structure variable is set to values for elements(to write the structure variable into the output file." }, { "code": null, "e": 4139, "s": 4067, "text": "Write that structure variable to the output binary file using fwrite()." }, { "code": null, "e": 4193, "s": 4139, "text": "Close the input text file and the output binary file." }, { "code": null, "e": 4242, "s": 4193, "text": "Below is the C++ program for the above approach:" }, { "code": null, "e": 4246, "s": 4242, "text": "C++" }, { "code": "// C++ program for the above approach#include <cstdio>#include <cstring>#include <iostream>using namespace std; // Creating a structure for customersstruct Customers { int ID; char name[30]; int age;}; // Driver Codeint main(){ struct Customers cs; int rec_size; rec_size = sizeof(struct Customers); cout << \"Size of record is: \" << rec_size << endl; // Create File Pointers fp_input for // text file, fp_output for output // binary file FILE *fp_input, *fp_output; // Open input text file, output // binary file. // If we cannot open them, work // cannot be done, so return -1 fp_input = fopen(\"custdata.txt\", \"r\"); if (fp_input == NULL) { cout << \"Could not open input file\" << endl; return -1; } fp_output = fopen(\"Customerdb\", \"wb\"); if (fp_output == NULL) { cout << \"Could not open \" << \"output file\" << endl; return -1; } // Read one line from input text file, // into 3 variables id, n & a int id, a; char n[30]; // Count for keeping count of total // Customers Records int count = 0; cout << endl; // Read next line from input text // file until EOF is reached while (!feof(fp_input)) { // Reading the text file fscanf(fp_input, \"%d %s %d \", &id, n, &a); // Increment the count by one // after reading a record count++; // Structure variable cs is set // to values to elements cs.ID = id, strcpy(cs.name, n), cs.age = a; // Write the structure variable // cs to output file fwrite(&cs, rec_size, 1, fp_output); printf( \"Customer number %2d has\" \" data %5d %30s %3d \\n\", count, cs.ID, cs.name, cs.age); } cout << \"Data from file read\" << \" and printed\\n\"; cout << \"Database created for \" << \"Customers info\\n\"; // Count contains count of total records cout << \"Total records written: \" << count << endl; // Close both the files fclose(fp_input); fclose(fp_output); return 0;}", "e": 6413, "s": 4246, "text": null }, { "code": null, "e": 6421, "s": 6413, "text": "Output:" }, { "code": null, "e": 6741, "s": 6421, "text": "Size of record is: 40\n\nCustomer number 1 has data 1 Annil 22\nCustomer number 2 has data 2 Ram 45\nCustomer number 3 has data 3 Golu 25 \nData from file read and printed\nDatabase created for Customers info \nTotal records written: 3" }, { "code": null, "e": 6984, "s": 6741, "text": "Explanation: There were 3 records in the file “custdata.txt” that were read, printed, and saved in the “Customerdb” file in binary mode.The text file contains 3 fields in every line- ID, Name, and Age.The first line of the text file contains-" }, { "code": null, "e": 7016, "s": 6984, "text": " 1 Annil 22" }, { "code": null, "e": 7643, "s": 7016, "text": "This line is read from the file, i.e, the data of ID, Name, and Age are read and their values are assigned to the variables id, n, and a respectively. Now assign the values of these 3 variables to the data members: ID, name[], and age of the structure variable cs respectively.Now using fwrite(&cs, rec_size, 1, fp_output), write one cs object of size rec_size to the binary file- ” fp_output” (binary mode).This procedure continues for all the lines of text files until the end of the file is reached. After the execution of the program ends, the file “custdata.txt” will remain as it is, as it was opened in the read mode-" }, { "code": null, "e": 7754, "s": 7643, "text": " 1 Annil 22\n 2 Ram 45\n 3 Golu 25" }, { "code": null, "e": 7972, "s": 7754, "text": "This data is read line by line and written to the file “Customerdb” in binary mode. The file “Customerdb” will have the contents in binary form, which is not readable. The file, when opened normally, looks like this :" }, { "code": null, "e": 7988, "s": 7972, "text": "C-File Handling" }, { "code": null, "e": 8002, "s": 7988, "text": "File Handling" }, { "code": null, "e": 8006, "s": 8002, "text": "C++" }, { "code": null, "e": 8019, "s": 8006, "text": "C++ Programs" }, { "code": null, "e": 8033, "s": 8019, "text": "File Handling" }, { "code": null, "e": 8037, "s": 8033, "text": "CPP" } ]
Scala ListBuffer
07 Jun, 2019 A list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer.The Scala List class holds a sequenced, linear list of items. A List can be built up efficiently only from back to front. the ListBuffer object is convenient when we want to build a list from front to back. It supports efficient prepend and append operations. Once we are done creating our list, call the toList method. To convert the ListBuffer into a List, Time taken will be constant. To use ListBuffer, scala.collection.mutable.ListBuffer class is imported, an instance of ListBuffer is created. Example : var name = new ListBuffer[datatype]() // empty buffer is created var name = new ListBuffer("class", "gfg", "geeksforgeeks") In the above example, first, an empty buffer is created here datatype indicates the type of data such as integer, string. Then created a buffer with three elements, of type string. Below operation can be performed on ListBuffer – By using L += e we can appends the element e in constant time. By using e +=: L we can prepends the element e in constant time. L.toList In constant time, It returns a list with the contents of the ListBuffer . We should not use the ListBuffer once changing it to a list. Creating instance of ListBuffer: // Scala program to create a ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating object object GfG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer[String]() name += "GeeksForGeeks" name += "gfg" name += "Class" println(name) } } Output: ListBuffer(GeeksForGeeks, gfg, Class) Access element from ListBuffer: Element is accessed same as list, ListBuffer(i) is used to accessed ith index element of list. // Scala program to access element of ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer[String]() name += "GeeksForGeeks" name += "gfg" name += "Class" // Accessing 1th index element of listBuffer println(name(1)) } } Output: gfg Adding elements in ListBuffer: Add single element to the bufferListBuffer+=( element) ListBuffer+=( element) Add two or more elements (method has a varargs parameter) ListBuffer+= (element1, element2, ..., elementN ) ListBuffer+= (element1, element2, ..., elementN ) Append one or more elements (uses a varargs parameter)ListBuffer.append( elem1, elem2, ... elemN) ListBuffer.append( elem1, elem2, ... elemN) // Scala program to add element in ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer[String]() // Adding one element name += "GeeksForGeeks" // Add two or more elements name += ("gfg", "class") // Adding one or more element using append method name.append("Scala", "Article") // Printing ListBuffer println(name) } } Output: ListBuffer(GeeksForGeeks, gfg, class, Scala, Article) Deleting ListBuffer Elements: Remove one elementListBuffer-= (element) ListBuffer-= (element) Remove multiple elementsListBuffer-= (elem1, elem2, ....., elemN) ListBuffer-= (elem1, elem2, ....., elemN) // Scala program to delete element from ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer( "GeeksForGeeks", "gfg", "class", "Scala", "Article" ) // Deletes one element name -= "GeeksForGeeks" // Deletes two or more elements name -= ("gfg", "class") // Printing resultant ListBuffer println(name) } } Output: ListBuffer(Scala, Article) Deleting ListBuffer Elements using ListBuffer.remove() : The remove() method is used to delete one element by its position in the ListBuffer, or a series of elements beginning at a starting position. // Scala program for remove method, on ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer( "GeeksForGeeks", "gfg", "class", "Scala", "Article" ) // Removing 0th index element name.remove(0) // Printing resultant ListBuffer println(name) name.remove(1, 3) // Printing resultant ListBuffer println(name) } } Output: ListBuffer(gfg, class, Scala, Article) ListBuffer(gfg) scala-collection Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jun, 2019" }, { "code": null, "e": 529, "s": 53, "text": "A list is a collection which contains immutable data. List represents linked list in Scala. A List is immutable, if we need to create a list that is constantly changing, the preferred approach is to use a ListBuffer.The Scala List class holds a sequenced, linear list of items. A List can be built up efficiently only from back to front. the ListBuffer object is convenient when we want to build a list from front to back. It supports efficient prepend and append operations." }, { "code": null, "e": 769, "s": 529, "text": "Once we are done creating our list, call the toList method. To convert the ListBuffer into a List, Time taken will be constant. To use ListBuffer, scala.collection.mutable.ListBuffer class is imported, an instance of ListBuffer is created." }, { "code": null, "e": 779, "s": 769, "text": "Example :" }, { "code": null, "e": 905, "s": 779, "text": "var name = new ListBuffer[datatype]() // empty buffer is created\n\nvar name = new ListBuffer(\"class\", \"gfg\", \"geeksforgeeks\")" }, { "code": null, "e": 1086, "s": 905, "text": "In the above example, first, an empty buffer is created here datatype indicates the type of data such as integer, string. Then created a buffer with three elements, of type string." }, { "code": null, "e": 1135, "s": 1086, "text": "Below operation can be performed on ListBuffer –" }, { "code": null, "e": 1198, "s": 1135, "text": "By using L += e we can appends the element e in constant time." }, { "code": null, "e": 1263, "s": 1198, "text": "By using e +=: L we can prepends the element e in constant time." }, { "code": null, "e": 1407, "s": 1263, "text": "L.toList In constant time, It returns a list with the contents of the ListBuffer . We should not use the ListBuffer once changing it to a list." }, { "code": null, "e": 1440, "s": 1407, "text": "Creating instance of ListBuffer:" }, { "code": "// Scala program to create a ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating object object GfG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer[String]() name += \"GeeksForGeeks\" name += \"gfg\" name += \"Class\" println(name) } } ", "e": 1841, "s": 1440, "text": null }, { "code": null, "e": 1849, "s": 1841, "text": "Output:" }, { "code": null, "e": 1887, "s": 1849, "text": "ListBuffer(GeeksForGeeks, gfg, Class)" }, { "code": null, "e": 1920, "s": 1887, "text": " Access element from ListBuffer:" }, { "code": null, "e": 2015, "s": 1920, "text": "Element is accessed same as list, ListBuffer(i) is used to accessed ith index element of list." }, { "code": "// Scala program to access element of ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer[String]() name += \"GeeksForGeeks\" name += \"gfg\" name += \"Class\" // Accessing 1th index element of listBuffer println(name(1)) } } ", "e": 2495, "s": 2015, "text": null }, { "code": null, "e": 2503, "s": 2495, "text": "Output:" }, { "code": null, "e": 2507, "s": 2503, "text": "gfg" }, { "code": null, "e": 2539, "s": 2507, "text": " Adding elements in ListBuffer:" }, { "code": null, "e": 2594, "s": 2539, "text": "Add single element to the bufferListBuffer+=( element)" }, { "code": null, "e": 2617, "s": 2594, "text": "ListBuffer+=( element)" }, { "code": null, "e": 2725, "s": 2617, "text": "Add two or more elements (method has a varargs parameter) ListBuffer+= (element1, element2, ..., elementN )" }, { "code": null, "e": 2776, "s": 2725, "text": " ListBuffer+= (element1, element2, ..., elementN )" }, { "code": null, "e": 2874, "s": 2776, "text": "Append one or more elements (uses a varargs parameter)ListBuffer.append( elem1, elem2, ... elemN)" }, { "code": null, "e": 2918, "s": 2874, "text": "ListBuffer.append( elem1, elem2, ... elemN)" }, { "code": "// Scala program to add element in ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer[String]() // Adding one element name += \"GeeksForGeeks\" // Add two or more elements name += (\"gfg\", \"class\") // Adding one or more element using append method name.append(\"Scala\", \"Article\") // Printing ListBuffer println(name) } } ", "e": 3557, "s": 2918, "text": null }, { "code": null, "e": 3565, "s": 3557, "text": "Output:" }, { "code": null, "e": 3619, "s": 3565, "text": "ListBuffer(GeeksForGeeks, gfg, class, Scala, Article)" }, { "code": null, "e": 3650, "s": 3619, "text": " Deleting ListBuffer Elements:" }, { "code": null, "e": 3691, "s": 3650, "text": "Remove one elementListBuffer-= (element)" }, { "code": null, "e": 3714, "s": 3691, "text": "ListBuffer-= (element)" }, { "code": null, "e": 3780, "s": 3714, "text": "Remove multiple elementsListBuffer-= (elem1, elem2, ....., elemN)" }, { "code": null, "e": 3822, "s": 3780, "text": "ListBuffer-= (elem1, elem2, ....., elemN)" }, { "code": "// Scala program to delete element from ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer( \"GeeksForGeeks\", \"gfg\", \"class\", \"Scala\", \"Article\" ) // Deletes one element name -= \"GeeksForGeeks\" // Deletes two or more elements name -= (\"gfg\", \"class\") // Printing resultant ListBuffer println(name) } } ", "e": 4478, "s": 3822, "text": null }, { "code": null, "e": 4486, "s": 4478, "text": "Output:" }, { "code": null, "e": 4513, "s": 4486, "text": "ListBuffer(Scala, Article)" }, { "code": null, "e": 4571, "s": 4513, "text": " Deleting ListBuffer Elements using ListBuffer.remove() :" }, { "code": null, "e": 4714, "s": 4571, "text": "The remove() method is used to delete one element by its position in the ListBuffer, or a series of elements beginning at a starting position." }, { "code": "// Scala program for remove method, on ListBuffer // ListBuffer class is imported import scala.collection.mutable.ListBuffer // Creating Object object GFG { // Main Method def main(args: Array[String]) { // Instance of ListBuffer is created var name = ListBuffer( \"GeeksForGeeks\", \"gfg\", \"class\", \"Scala\", \"Article\" ) // Removing 0th index element name.remove(0) // Printing resultant ListBuffer println(name) name.remove(1, 3) // Printing resultant ListBuffer println(name) } } ", "e": 5384, "s": 4714, "text": null }, { "code": null, "e": 5392, "s": 5384, "text": "Output:" }, { "code": null, "e": 5447, "s": 5392, "text": "ListBuffer(gfg, class, Scala, Article)\nListBuffer(gfg)" }, { "code": null, "e": 5464, "s": 5447, "text": "scala-collection" }, { "code": null, "e": 5470, "s": 5464, "text": "Scala" } ]
Natural Numbers
29 Jun, 2022 Counting numbers like 1, 2, 3, 4, 5, 6 ... Basically, all integers greater than 0 are natural numbers. Fact about Natural numbers They are whole numbers (called integers), and never less than zero (i.e. positive numbers)The next possible natural number can be found by adding 1 to the current natural numberThe natural numbers are the ordinary numbers, 1, 2, 3, etc., with which we count.The number zero is sometimes considered to be a natural number. Not always because no one counts starting with zero, 0, 1, 2, 3.GCD of all other natural numbers with a prime is always one.The natural numbers can be defined formally by relating them to sets. Then, zero is the number of elements in the empty set; 1 is the number of elements in the set containing one natural number; and so on. They are whole numbers (called integers), and never less than zero (i.e. positive numbers) The next possible natural number can be found by adding 1 to the current natural number The natural numbers are the ordinary numbers, 1, 2, 3, etc., with which we count. The number zero is sometimes considered to be a natural number. Not always because no one counts starting with zero, 0, 1, 2, 3. GCD of all other natural numbers with a prime is always one. The natural numbers can be defined formally by relating them to sets. Then, zero is the number of elements in the empty set; 1 is the number of elements in the set containing one natural number; and so on. How to print sum of n natural Numbers? Using Recursion Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum(). Examples : Input : 3 Output : 6 Explanation : 1 + 2 + 3 = 6 Input : 5 Output : 15 Explanation : 1 + 2 + 3 + 4 + 5 = 15 C++ Java Python C# PHP Javascript // C++ program to find the// sum of natural numbers up// to n using recursion#include <iostream>using namespace std; // Returns sum of first// n natural numbersint recurSum(int n){ if (n <= 1) return n; return n + recurSum(n - 1);} // Driver codeint main(){ int n = 5; cout << recurSum(n); return 0;} // Java program to find the// sum of natural numbers up// to n using recursionimport java.util.*;import java.lang.*; class GFG{ // Returns sum of first // n natural numbers public static int recurSum(int n) { if (n <= 1) return n; return n + recurSum(n - 1); } // Driver code public static void main(String args[]) { int n = 5; System.out.println(recurSum(n)); }} # Python code to find sum# of natural numbers upto# n using recursion # Returns sum of first# n natural numbersdef recurSum(n): if n <= 1: return n return n + recurSum(n - 1) # Driver coden = 5print(recurSum(n)) // C# program to find the// sum of natural numbers// up to n using recursionusing System; class GFG{ // Returns sum of first // n natural numbers public static int recurSum(int n) { if (n <= 1) return n; return n + recurSum(n - 1); } // Driver code public static void Main() { int n = 5; Console.WriteLine(recurSum(n)); }} <?php// PHP program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction recurSum($n){ if ($n <= 1) return $n; return $n + recurSum($n - 1);} // Driver code$n = 5;echo(recurSum($n)); ?> <script> // JavaScript program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction recurSum(n){ if (n <= 1) return n; return n + recurSum(n - 1);} // Driver coden = 5;document.write(recurSum(n)); </script> Output : 15 Time Complexity: O(n) Auxiliary Space: O(n) Using Loop A simple solution is to do following. 1) Initialize : sum = 0 2) Run a loop from x = 1 to n and do following in loop. sum = sum + x C++ Java Python C# PHP Javascript // CPP program to find sum of first// n natural numbers.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ int sum = 0; for (int x=1; x<=n; x++) sum = sum + x; return sum;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;} // JAVA program to find sum of first// n natural numbers.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }} # PYTHON program to find sum of first# n natural numbers. # Returns sum of first n natural# numbersdef findSum(n) : sum = 0 x = 1 while x <=n : sum = sum + x x = x + 1 return sum # Driver code n = 5print findSum(n) // C# program to find sum of first// n natural numbers.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }} <?php// PHP program to find sum of first// n natural numbers. // Returns sum of first n natural// numbersfunction findSum($n){$sum = 0;for ($x = 1; $x <= $n; $x++) $sum = $sum + $x;return $sum;} // Driver code$n = 5;echo findSum($n); ?> <script>// JavaScript program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction findSum(n){let sum = 0;for (x = 1; x <= n; x++) sum = sum + x;return sum;} // Driver coden = 5;document.write(findSum(n)); // This code is contributed by sravan kumar </script> Output : 15 Time Complexity: O(n) Auxiliary Space: O(1) Using Sum of n terms formula Formula for finding sum of n natural numbers is given by n*(n+1)/2 which implies if the formula is used the program returns output faster than it would take iterating over loop or recursion. Time complexity is O(1). Referral Link Program to find sum of n natural numbers More problems related to Natural Number: Count natural numbers whose all permutations are greater than that number Sum of squares of first n natural numbers Sum of cubes of even and odd natural numbers LCM of First n Natural Numbers Sum of squares of first n natural numbers PranayRaju sravankumar8128 singghakshay rishav1329 number-theory Numbers Mathematical number-theory Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Jun, 2022" }, { "code": null, "e": 156, "s": 52, "text": "Counting numbers like 1, 2, 3, 4, 5, 6 ... Basically, all integers greater than 0 are natural numbers. " }, { "code": null, "e": 184, "s": 156, "text": "Fact about Natural numbers " }, { "code": null, "e": 836, "s": 184, "text": "They are whole numbers (called integers), and never less than zero (i.e. positive numbers)The next possible natural number can be found by adding 1 to the current natural numberThe natural numbers are the ordinary numbers, 1, 2, 3, etc., with which we count.The number zero is sometimes considered to be a natural number. Not always because no one counts starting with zero, 0, 1, 2, 3.GCD of all other natural numbers with a prime is always one.The natural numbers can be defined formally by relating them to sets. Then, zero is the number of elements in the empty set; 1 is the number of elements in the set containing one natural number; and so on." }, { "code": null, "e": 927, "s": 836, "text": "They are whole numbers (called integers), and never less than zero (i.e. positive numbers)" }, { "code": null, "e": 1015, "s": 927, "text": "The next possible natural number can be found by adding 1 to the current natural number" }, { "code": null, "e": 1097, "s": 1015, "text": "The natural numbers are the ordinary numbers, 1, 2, 3, etc., with which we count." }, { "code": null, "e": 1226, "s": 1097, "text": "The number zero is sometimes considered to be a natural number. Not always because no one counts starting with zero, 0, 1, 2, 3." }, { "code": null, "e": 1287, "s": 1226, "text": "GCD of all other natural numbers with a prime is always one." }, { "code": null, "e": 1493, "s": 1287, "text": "The natural numbers can be defined formally by relating them to sets. Then, zero is the number of elements in the empty set; 1 is the number of elements in the set containing one natural number; and so on." }, { "code": null, "e": 1534, "s": 1493, "text": "How to print sum of n natural Numbers? " }, { "code": null, "e": 1550, "s": 1534, "text": "Using Recursion" }, { "code": null, "e": 1673, "s": 1550, "text": "Given a number n, find sum of first n natural numbers. To calculate the sum, we will use a recursive function recur_sum()." }, { "code": null, "e": 1686, "s": 1673, "text": "Examples : " }, { "code": null, "e": 1795, "s": 1686, "text": "Input : 3\nOutput : 6\nExplanation : 1 + 2 + 3 = 6\n\nInput : 5\nOutput : 15\nExplanation : 1 + 2 + 3 + 4 + 5 = 15" }, { "code": null, "e": 1799, "s": 1795, "text": "C++" }, { "code": null, "e": 1804, "s": 1799, "text": "Java" }, { "code": null, "e": 1811, "s": 1804, "text": "Python" }, { "code": null, "e": 1814, "s": 1811, "text": "C#" }, { "code": null, "e": 1818, "s": 1814, "text": "PHP" }, { "code": null, "e": 1829, "s": 1818, "text": "Javascript" }, { "code": "// C++ program to find the// sum of natural numbers up// to n using recursion#include <iostream>using namespace std; // Returns sum of first// n natural numbersint recurSum(int n){ if (n <= 1) return n; return n + recurSum(n - 1);} // Driver codeint main(){ int n = 5; cout << recurSum(n); return 0;}", "e": 2152, "s": 1829, "text": null }, { "code": "// Java program to find the// sum of natural numbers up// to n using recursionimport java.util.*;import java.lang.*; class GFG{ // Returns sum of first // n natural numbers public static int recurSum(int n) { if (n <= 1) return n; return n + recurSum(n - 1); } // Driver code public static void main(String args[]) { int n = 5; System.out.println(recurSum(n)); }}", "e": 2588, "s": 2152, "text": null }, { "code": "# Python code to find sum# of natural numbers upto# n using recursion # Returns sum of first# n natural numbersdef recurSum(n): if n <= 1: return n return n + recurSum(n - 1) # Driver coden = 5print(recurSum(n))", "e": 2813, "s": 2588, "text": null }, { "code": "// C# program to find the// sum of natural numbers// up to n using recursionusing System; class GFG{ // Returns sum of first // n natural numbers public static int recurSum(int n) { if (n <= 1) return n; return n + recurSum(n - 1); } // Driver code public static void Main() { int n = 5; Console.WriteLine(recurSum(n)); }}", "e": 3208, "s": 2813, "text": null }, { "code": "<?php// PHP program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction recurSum($n){ if ($n <= 1) return $n; return $n + recurSum($n - 1);} // Driver code$n = 5;echo(recurSum($n)); ?>", "e": 3469, "s": 3208, "text": null }, { "code": "<script> // JavaScript program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction recurSum(n){ if (n <= 1) return n; return n + recurSum(n - 1);} // Driver coden = 5;document.write(recurSum(n)); </script>", "e": 3751, "s": 3469, "text": null }, { "code": null, "e": 3761, "s": 3751, "text": "Output : " }, { "code": null, "e": 3765, "s": 3761, "text": "15 " }, { "code": null, "e": 3787, "s": 3765, "text": "Time Complexity: O(n)" }, { "code": null, "e": 3809, "s": 3787, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 3820, "s": 3809, "text": "Using Loop" }, { "code": null, "e": 3859, "s": 3820, "text": "A simple solution is to do following. " }, { "code": null, "e": 3964, "s": 3859, "text": "1) Initialize : sum = 0\n2) Run a loop from x = 1 to n and \n do following in loop.\n sum = sum + x " }, { "code": null, "e": 3968, "s": 3964, "text": "C++" }, { "code": null, "e": 3973, "s": 3968, "text": "Java" }, { "code": null, "e": 3980, "s": 3973, "text": "Python" }, { "code": null, "e": 3983, "s": 3980, "text": "C#" }, { "code": null, "e": 3987, "s": 3983, "text": "PHP" }, { "code": null, "e": 3998, "s": 3987, "text": "Javascript" }, { "code": "// CPP program to find sum of first// n natural numbers.#include<iostream>using namespace std; // Returns sum of first n natural// numbersint findSum(int n){ int sum = 0; for (int x=1; x<=n; x++) sum = sum + x; return sum;} // Driver codeint main(){ int n = 5; cout << findSum(n); return 0;}", "e": 4303, "s": 3998, "text": null }, { "code": "// JAVA program to find sum of first// n natural numbers.import java.io.*; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void main(String args[]) { int n = 5; System.out.println(findSum(n)); }}", "e": 4710, "s": 4303, "text": null }, { "code": "# PYTHON program to find sum of first# n natural numbers. # Returns sum of first n natural# numbersdef findSum(n) : sum = 0 x = 1 while x <=n : sum = sum + x x = x + 1 return sum # Driver code n = 5print findSum(n)", "e": 4952, "s": 4710, "text": null }, { "code": "// C# program to find sum of first// n natural numbers.using System; class GFG{ // Returns sum of first n natural // numbers static int findSum(int n) { int sum = 0; for (int x = 1; x <= n; x++) sum = sum + x; return sum; } // Driver code public static void Main() { int n = 5; Console.Write(findSum(n)); }}", "e": 5335, "s": 4952, "text": null }, { "code": "<?php// PHP program to find sum of first// n natural numbers. // Returns sum of first n natural// numbersfunction findSum($n){$sum = 0;for ($x = 1; $x <= $n; $x++) $sum = $sum + $x;return $sum;} // Driver code$n = 5;echo findSum($n); ?>", "e": 5576, "s": 5335, "text": null }, { "code": "<script>// JavaScript program to find the// sum of natural numbers// up to n using recursion // Returns sum of first// n natural numbersfunction findSum(n){let sum = 0;for (x = 1; x <= n; x++) sum = sum + x;return sum;} // Driver coden = 5;document.write(findSum(n)); // This code is contributed by sravan kumar </script>", "e": 5901, "s": 5576, "text": null }, { "code": null, "e": 5911, "s": 5901, "text": "Output : " }, { "code": null, "e": 5914, "s": 5911, "text": "15" }, { "code": null, "e": 5936, "s": 5914, "text": "Time Complexity: O(n)" }, { "code": null, "e": 5958, "s": 5936, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5987, "s": 5958, "text": "Using Sum of n terms formula" }, { "code": null, "e": 6258, "s": 5987, "text": "Formula for finding sum of n natural numbers is given by n*(n+1)/2 which implies if the formula is used the program returns output faster than it would take iterating over loop or recursion. Time complexity is O(1). Referral Link Program to find sum of n natural numbers" }, { "code": null, "e": 6301, "s": 6258, "text": "More problems related to Natural Number: " }, { "code": null, "e": 6375, "s": 6301, "text": "Count natural numbers whose all permutations are greater than that number" }, { "code": null, "e": 6417, "s": 6375, "text": "Sum of squares of first n natural numbers" }, { "code": null, "e": 6462, "s": 6417, "text": "Sum of cubes of even and odd natural numbers" }, { "code": null, "e": 6493, "s": 6462, "text": "LCM of First n Natural Numbers" }, { "code": null, "e": 6535, "s": 6493, "text": "Sum of squares of first n natural numbers" }, { "code": null, "e": 6548, "s": 6537, "text": "PranayRaju" }, { "code": null, "e": 6564, "s": 6548, "text": "sravankumar8128" }, { "code": null, "e": 6577, "s": 6564, "text": "singghakshay" }, { "code": null, "e": 6588, "s": 6577, "text": "rishav1329" }, { "code": null, "e": 6602, "s": 6588, "text": "number-theory" }, { "code": null, "e": 6610, "s": 6602, "text": "Numbers" }, { "code": null, "e": 6623, "s": 6610, "text": "Mathematical" }, { "code": null, "e": 6637, "s": 6623, "text": "number-theory" }, { "code": null, "e": 6650, "s": 6637, "text": "Mathematical" }, { "code": null, "e": 6658, "s": 6650, "text": "Numbers" } ]
Select columns in PySpark dataframe
08 May, 2021 In this article, we will learn how to select columns in PySpark dataframe. In PySpark we can select columns using the select() function. The select() function allows us to select single or multiple columns in different formats. Syntax: dataframe_name.select( columns_names ) Note: We are specifying our path to spark directory using the findspark.init() function in order to enable our program to find the location of apache spark in our local machine. Ignore this line if you are running the program on cloud. Suppose we have our spark folder in c drive by name of spark so the function would look something like: findspark.init(‘c:/spark’). Not specifying the path sometimes may lead to py4j.protocol.Py4JError error when running the program locally. Example 1: Select single or multiple columns We can select single or multiple columns using the select() function by specifying the particular column name. Here we are using our custom dataset thus we need to specify our schema along with it in order to create the dataset. Python3 # select single and multiple columnsfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark findspark.init('c:/spark') # Initialize our datadata2 = [("Pulkit", 12, "CS32", 82, "Programming"), ("Ritika", 20, "CS32", 94, "Writing"), ("Atirikt", 4, "BB21", 78, None), ("Reshav", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # Define schemaschema = StructType([ StructField("Name", StringType(), True), StructField("Roll Number", IntegerType(), True), StructField("Class ID", StringType(), True), StructField("Marks", IntegerType(), True), StructField("Extracurricular", StringType(), True)]) # read the dataframedf = spark.createDataFrame(data=data2, schema=schema) # slelct columnsdf.select("Name", "Marks").show() # stop the sessionspark.stop() Output: Note: There are a lot of ways to specify the column names to the select() function. Here we used “column_name” to specify the column. Other ways include (All the examples as shown with reference to the above code): df.select(df.Name,df.Marks) df.select(df[“Name”],df[“Marks”]) We can use col() function from pyspark.sql.functions module to specify the particular columns Python3 from pyspark.sql.functions import col df.select(col("Name"),col("Marks")).show() Note: All the above methods will yield the same output as above Example 2: Select columns using indexing Indexing provides an easy way of accessing columns inside a dataframe. Indexing starts from 0 and has total n-1 numbers representing each column with 0 as first and n-1 as last nth column. We can use df.columns to access all the columns and use indexing to pass in the required columns inside a select function. Here is how the code will look like. We are using our custom dataset thus we need to specify our schema along with it in order to create the dataset. Python3 # select sparkfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark findspark.init('c:/spark') # Initialize our datadata2 = [("Pulkit", 12, "CS32", 82, "Programming"), ("Ritika", 20, "CS32", 94, "Writing"), ("Atirikt", 4, "BB21", 78, None), ("Reshav", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # Define schemaschema = StructType([ StructField("Name", StringType(), True), StructField("Roll Number", IntegerType(), True), StructField("Class ID", StringType(), True), StructField("Marks", IntegerType(), True), StructField("Extracurricular", StringType(), True)]) # read the dataframedf = spark.createDataFrame(data=data2, schema=schema) # select the columnsdf.select(df.columns[:4]).show() # stop sessionspark.stop() Output: Example 3: Access nested columns of a dataframe While creating a dataframe there might be a table where we have nested columns like, in a column name “Marks” we may have sub-columns of Internal or external marks, or we may have separate columns for the first middle, and last names in a column under the name. In order to access the nested columns inside a dataframe using the select() function, we can specify the sub-column with the associated column. Here we are using our custom dataset thus we need to specify our schema along with it in order to create the dataset. Python3 # findsparkfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark findspark.init('c:/spark') # initialize the datadata = [ (("Pulkit", "Dhingra"), 12, "CS32", 82, "Programming"), (("Ritika", "Pandey"), 20, "CS32", 94, "Writing"), (("Atirikt", "Sans"), 4, "BB21", 78, None), (("Reshav", None), 18, None, 56, None)] # start spark sessionspark = SparkSession.builder.appName("Student_Info").getOrCreate() # initialize the schema of the dataschema = StructType([ StructField('name', StructType([ StructField('firstname', StringType(), True), StructField('lastname', StringType(), True) ])), StructField("Roll Number", IntegerType(), True), StructField("Class ID", StringType(), True), StructField("Marks", IntegerType(), True), StructField("Extracurricular", StringType(), True)])# create a dataframedf2 = spark.createDataFrame(data=data, schema=schema) # display the schemadf2.printSchema() # select operationdf2.select("name.firstname", "name.lastname").show(truncate=False) # stop sessionspark.stop() Output: Here we can se we have a dataset of following schema We have a column name with sub columns as firstname and lastname. Now as we performed the select operation we have an output like Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 May, 2021" }, { "code": null, "e": 103, "s": 28, "text": "In this article, we will learn how to select columns in PySpark dataframe." }, { "code": null, "e": 257, "s": 103, "text": "In PySpark we can select columns using the select() function. The select() function allows us to select single or multiple columns in different formats. " }, { "code": null, "e": 304, "s": 257, "text": "Syntax: dataframe_name.select( columns_names )" }, { "code": null, "e": 782, "s": 304, "text": "Note: We are specifying our path to spark directory using the findspark.init() function in order to enable our program to find the location of apache spark in our local machine. Ignore this line if you are running the program on cloud. Suppose we have our spark folder in c drive by name of spark so the function would look something like: findspark.init(‘c:/spark’). Not specifying the path sometimes may lead to py4j.protocol.Py4JError error when running the program locally." }, { "code": null, "e": 827, "s": 782, "text": "Example 1: Select single or multiple columns" }, { "code": null, "e": 1057, "s": 827, "text": "We can select single or multiple columns using the select() function by specifying the particular column name. Here we are using our custom dataset thus we need to specify our schema along with it in order to create the dataset. " }, { "code": null, "e": 1065, "s": 1057, "text": "Python3" }, { "code": "# select single and multiple columnsfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark findspark.init('c:/spark') # Initialize our datadata2 = [(\"Pulkit\", 12, \"CS32\", 82, \"Programming\"), (\"Ritika\", 20, \"CS32\", 94, \"Writing\"), (\"Atirikt\", 4, \"BB21\", 78, None), (\"Reshav\", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # Define schemaschema = StructType([ StructField(\"Name\", StringType(), True), StructField(\"Roll Number\", IntegerType(), True), StructField(\"Class ID\", StringType(), True), StructField(\"Marks\", IntegerType(), True), StructField(\"Extracurricular\", StringType(), True)]) # read the dataframedf = spark.createDataFrame(data=data2, schema=schema) # slelct columnsdf.select(\"Name\", \"Marks\").show() # stop the sessionspark.stop()", "e": 2016, "s": 1065, "text": null }, { "code": null, "e": 2024, "s": 2016, "text": "Output:" }, { "code": null, "e": 2239, "s": 2024, "text": "Note: There are a lot of ways to specify the column names to the select() function. Here we used “column_name” to specify the column. Other ways include (All the examples as shown with reference to the above code):" }, { "code": null, "e": 2267, "s": 2239, "text": "df.select(df.Name,df.Marks)" }, { "code": null, "e": 2301, "s": 2267, "text": "df.select(df[“Name”],df[“Marks”])" }, { "code": null, "e": 2395, "s": 2301, "text": "We can use col() function from pyspark.sql.functions module to specify the particular columns" }, { "code": null, "e": 2403, "s": 2395, "text": "Python3" }, { "code": "from pyspark.sql.functions import col df.select(col(\"Name\"),col(\"Marks\")).show()", "e": 2485, "s": 2403, "text": null }, { "code": null, "e": 2549, "s": 2485, "text": "Note: All the above methods will yield the same output as above" }, { "code": null, "e": 2590, "s": 2549, "text": "Example 2: Select columns using indexing" }, { "code": null, "e": 3053, "s": 2590, "text": "Indexing provides an easy way of accessing columns inside a dataframe. Indexing starts from 0 and has total n-1 numbers representing each column with 0 as first and n-1 as last nth column. We can use df.columns to access all the columns and use indexing to pass in the required columns inside a select function. Here is how the code will look like. We are using our custom dataset thus we need to specify our schema along with it in order to create the dataset. " }, { "code": null, "e": 3061, "s": 3053, "text": "Python3" }, { "code": "# select sparkfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark findspark.init('c:/spark') # Initialize our datadata2 = [(\"Pulkit\", 12, \"CS32\", 82, \"Programming\"), (\"Ritika\", 20, \"CS32\", 94, \"Writing\"), (\"Atirikt\", 4, \"BB21\", 78, None), (\"Reshav\", 18, None, 56, None) ] # Start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # Define schemaschema = StructType([ StructField(\"Name\", StringType(), True), StructField(\"Roll Number\", IntegerType(), True), StructField(\"Class ID\", StringType(), True), StructField(\"Marks\", IntegerType(), True), StructField(\"Extracurricular\", StringType(), True)]) # read the dataframedf = spark.createDataFrame(data=data2, schema=schema) # select the columnsdf.select(df.columns[:4]).show() # stop sessionspark.stop()", "e": 3989, "s": 3061, "text": null }, { "code": null, "e": 3997, "s": 3989, "text": "Output:" }, { "code": null, "e": 4045, "s": 3997, "text": "Example 3: Access nested columns of a dataframe" }, { "code": null, "e": 4570, "s": 4045, "text": "While creating a dataframe there might be a table where we have nested columns like, in a column name “Marks” we may have sub-columns of Internal or external marks, or we may have separate columns for the first middle, and last names in a column under the name. In order to access the nested columns inside a dataframe using the select() function, we can specify the sub-column with the associated column. Here we are using our custom dataset thus we need to specify our schema along with it in order to create the dataset. " }, { "code": null, "e": 4578, "s": 4570, "text": "Python3" }, { "code": "# findsparkfrom pyspark.sql.types import StructType, StructField, StringType, IntegerType, FloatTypefrom pyspark.sql import SparkSessionimport findspark findspark.init('c:/spark') # initialize the datadata = [ ((\"Pulkit\", \"Dhingra\"), 12, \"CS32\", 82, \"Programming\"), ((\"Ritika\", \"Pandey\"), 20, \"CS32\", 94, \"Writing\"), ((\"Atirikt\", \"Sans\"), 4, \"BB21\", 78, None), ((\"Reshav\", None), 18, None, 56, None)] # start spark sessionspark = SparkSession.builder.appName(\"Student_Info\").getOrCreate() # initialize the schema of the dataschema = StructType([ StructField('name', StructType([ StructField('firstname', StringType(), True), StructField('lastname', StringType(), True) ])), StructField(\"Roll Number\", IntegerType(), True), StructField(\"Class ID\", StringType(), True), StructField(\"Marks\", IntegerType(), True), StructField(\"Extracurricular\", StringType(), True)])# create a dataframedf2 = spark.createDataFrame(data=data, schema=schema) # display the schemadf2.printSchema() # select operationdf2.select(\"name.firstname\", \"name.lastname\").show(truncate=False) # stop sessionspark.stop()", "e": 5718, "s": 4578, "text": null }, { "code": null, "e": 5726, "s": 5718, "text": "Output:" }, { "code": null, "e": 5779, "s": 5726, "text": "Here we can se we have a dataset of following schema" }, { "code": null, "e": 5909, "s": 5779, "text": "We have a column name with sub columns as firstname and lastname. Now as we performed the select operation we have an output like" }, { "code": null, "e": 5916, "s": 5909, "text": "Picked" }, { "code": null, "e": 5931, "s": 5916, "text": "Python-Pyspark" }, { "code": null, "e": 5938, "s": 5931, "text": "Python" } ]
Matplotlib.ticker.PercentFormatter class in Python
21 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.ticker.PercentFormatter class is used to format numbers as a percentage. Syntax: class matplotlib.ticker.PercentFormatter(xmax=100, decimals=None, symbol=’%’, is_latex=False) Parameters: xmax: It is a float value that determines how the number is converted into a percentage. decimals: It is either an integer value or None. It determines the number of decimal places to place after the point. If None (the default), the number will be computed automatically. symbol : It is either a string or none that gets appended to the label. is_latex: It is a boolean value. If False, reserved LaTeX characters in symbol are eliminated. Example 1: import pandas as pdimport numpy as npimport matplotlib.ticker as mtickfrom matplotlib.ticker import PercentFormatter df = pd.DataFrame(np.random.randn(100, 5)) ax = df.plot()ax.yaxis.set_major_formatter(mtick.PercentFormatter(5.0)) Output: Example 2: import matplotlib.pyplot as pltimport numpy as npimport matplotlib.ticker as mtickfrom matplotlib.ticker import PercentFormatter data = [8, 12, 15, 17, 18, 18.5]perc = np.linspace(0, 100, len(data)) fig = plt.figure(1, (7, 4))ax = fig.add_subplot(1, 1, 1) ax.plot(perc, data) xticks = mtick.PercentFormatter(0.5)ax.xaxis.set_major_formatter(xticks) plt.show() Output: Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 328, "s": 240, "text": "The matplotlib.ticker.PercentFormatter class is used to format numbers as a percentage." }, { "code": null, "e": 430, "s": 328, "text": "Syntax: class matplotlib.ticker.PercentFormatter(xmax=100, decimals=None, symbol=’%’, is_latex=False)" }, { "code": null, "e": 442, "s": 430, "text": "Parameters:" }, { "code": null, "e": 531, "s": 442, "text": "xmax: It is a float value that determines how the number is converted into a percentage." }, { "code": null, "e": 715, "s": 531, "text": "decimals: It is either an integer value or None. It determines the number of decimal places to place after the point. If None (the default), the number will be computed automatically." }, { "code": null, "e": 787, "s": 715, "text": "symbol : It is either a string or none that gets appended to the label." }, { "code": null, "e": 882, "s": 787, "text": "is_latex: It is a boolean value. If False, reserved LaTeX characters in symbol are eliminated." }, { "code": null, "e": 893, "s": 882, "text": "Example 1:" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.ticker as mtickfrom matplotlib.ticker import PercentFormatter df = pd.DataFrame(np.random.randn(100, 5)) ax = df.plot()ax.yaxis.set_major_formatter(mtick.PercentFormatter(5.0)) ", "e": 1128, "s": 893, "text": null }, { "code": null, "e": 1136, "s": 1128, "text": "Output:" }, { "code": null, "e": 1147, "s": 1136, "text": "Example 2:" }, { "code": "import matplotlib.pyplot as pltimport numpy as npimport matplotlib.ticker as mtickfrom matplotlib.ticker import PercentFormatter data = [8, 12, 15, 17, 18, 18.5]perc = np.linspace(0, 100, len(data)) fig = plt.figure(1, (7, 4))ax = fig.add_subplot(1, 1, 1) ax.plot(perc, data) xticks = mtick.PercentFormatter(0.5)ax.xaxis.set_major_formatter(xticks) plt.show()", "e": 1512, "s": 1147, "text": null }, { "code": null, "e": 1520, "s": 1512, "text": "Output:" }, { "code": null, "e": 1538, "s": 1520, "text": "Python-matplotlib" }, { "code": null, "e": 1545, "s": 1538, "text": "Python" }, { "code": null, "e": 1561, "s": 1545, "text": "Write From Home" } ]
Program for Volume and Surface Area of Cube
21 Jun, 2022 Cube is a 3-dimensional box-like figure represented in the 3-dimensional plane. Cube has 6 squared-shape equal faces. Each face meet another face at 90 degree each. Three sides of cube meet at same vertex. Examples: Input : Side of a cube = 2 Output : Area = 8 Total surface area = 24 Input : Side of a cube = 3 Output : Area = 27 Total surface area = 54 Volume: a*a*a Total Surface area: 6*a*a C++ Java Python3 C# PHP Javascript // CPP program to find area// and total surface area of cube#include <bits/stdc++.h>using namespace std; // utility functiondouble areaCube(double a){ return (a * a * a);} double surfaceCube(double a){ return (6 * a * a);} // driver functionint main(){ double a = 5; cout << "Area = " << areaCube(a) << endl; cout << "Total surface area = " << surfaceCube(a); return 0;} // Java program to find area// and total surface area of cube class GFG{ // utility function static double areaCube(double a) { return (a * a * a); } static double surfaceCube(double a) { return (6 * a * a); } // Driver code public static void main (String[] args) { double a = 5; System.out.println("Area = "+areaCube(a)); System.out.println("Total surface area = " +surfaceCube(a)); }} // This code is contributed by Anant Agarwal. # Python3 code to find area# and total surface area of cube # utility functiondef areaCube( a ): return (a * a * a) def surfaceCube( a ): return (6 * a * a) # driver functiona = 5print("Area =", areaCube(a))print("Total surface area =", surfaceCube(a)) # This code is contributed by "Sharad_Bhardwaj". // C# program to find area// and total surface area of cubeusing System; class GFG { // utility function static double areaCube(double a) { return (a * a * a); } static double surfaceCube(double a) { return (6 * a * a); } // Driver code public static void Main() { double a = 5; Console.WriteLine("Area = " + areaCube(a)); Console.WriteLine("Total surface area = " + surfaceCube(a)); }} // This code is contributed by vt_m. <?php// PHP program to find area// and total surface area of cube // utility functionfunction areaCube($a){ return ($a * $a * $a);} function surfaceCube( $a){ return (6 * $a * $a);} // driver function $a = 5; echo ("Area = "); echo(areaCube($a)); echo("\n"); echo("Total surface area = "); echo(surfaceCube($a)); // This code is contributed by vt_m.?> <script>// javascript program to find area// and total surface area of cube // utility functionfunction areaCube( a){ return (a * a * a);} function surfaceCube( a){ return (6 * a * a);} // Driver function let a = 5; document.write( "Area = " + areaCube(a) +"<br/>"); document.write( "Total surface area = " + surfaceCube(a)); // This code is contributed by gauravrajput1</script> Output: Area = 125 Total surface area = 150 Time complexity : O(1) Auxiliary Space : O(1) This article is contributed by Saloni Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Akanksha_Rai GauravRajput1 krishnav4 area-volume-programs maths-cube Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Jun, 2022" }, { "code": null, "e": 236, "s": 28, "text": "Cube is a 3-dimensional box-like figure represented in the 3-dimensional plane. Cube has 6 squared-shape equal faces. Each face meet another face at 90 degree each. Three sides of cube meet at same vertex. " }, { "code": null, "e": 248, "s": 236, "text": "Examples: " }, { "code": null, "e": 406, "s": 248, "text": "Input : Side of a cube = 2\nOutput : Area = 8\n Total surface area = 24\n\nInput : Side of a cube = 3\nOutput : Area = 27\n Total surface area = 54" }, { "code": null, "e": 450, "s": 410, "text": "Volume: a*a*a Total Surface area: 6*a*a" }, { "code": null, "e": 456, "s": 452, "text": "C++" }, { "code": null, "e": 461, "s": 456, "text": "Java" }, { "code": null, "e": 469, "s": 461, "text": "Python3" }, { "code": null, "e": 472, "s": 469, "text": "C#" }, { "code": null, "e": 476, "s": 472, "text": "PHP" }, { "code": null, "e": 487, "s": 476, "text": "Javascript" }, { "code": "// CPP program to find area// and total surface area of cube#include <bits/stdc++.h>using namespace std; // utility functiondouble areaCube(double a){ return (a * a * a);} double surfaceCube(double a){ return (6 * a * a);} // driver functionint main(){ double a = 5; cout << \"Area = \" << areaCube(a) << endl; cout << \"Total surface area = \" << surfaceCube(a); return 0;}", "e": 876, "s": 487, "text": null }, { "code": "// Java program to find area// and total surface area of cube class GFG{ // utility function static double areaCube(double a) { return (a * a * a); } static double surfaceCube(double a) { return (6 * a * a); } // Driver code public static void main (String[] args) { double a = 5; System.out.println(\"Area = \"+areaCube(a)); System.out.println(\"Total surface area = \" +surfaceCube(a)); }} // This code is contributed by Anant Agarwal.", "e": 1410, "s": 876, "text": null }, { "code": "# Python3 code to find area# and total surface area of cube # utility functiondef areaCube( a ): return (a * a * a) def surfaceCube( a ): return (6 * a * a) # driver functiona = 5print(\"Area =\", areaCube(a))print(\"Total surface area =\", surfaceCube(a)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 1718, "s": 1410, "text": null }, { "code": "// C# program to find area// and total surface area of cubeusing System; class GFG { // utility function static double areaCube(double a) { return (a * a * a); } static double surfaceCube(double a) { return (6 * a * a); } // Driver code public static void Main() { double a = 5; Console.WriteLine(\"Area = \" + areaCube(a)); Console.WriteLine(\"Total surface area = \" + surfaceCube(a)); }} // This code is contributed by vt_m.", "e": 2249, "s": 1718, "text": null }, { "code": "<?php// PHP program to find area// and total surface area of cube // utility functionfunction areaCube($a){ return ($a * $a * $a);} function surfaceCube( $a){ return (6 * $a * $a);} // driver function $a = 5; echo (\"Area = \"); echo(areaCube($a)); echo(\"\\n\"); echo(\"Total surface area = \"); echo(surfaceCube($a)); // This code is contributed by vt_m.?>", "e": 2626, "s": 2249, "text": null }, { "code": "<script>// javascript program to find area// and total surface area of cube // utility functionfunction areaCube( a){ return (a * a * a);} function surfaceCube( a){ return (6 * a * a);} // Driver function let a = 5; document.write( \"Area = \" + areaCube(a) +\"<br/>\"); document.write( \"Total surface area = \" + surfaceCube(a)); // This code is contributed by gauravrajput1</script>", "e": 3025, "s": 2626, "text": null }, { "code": null, "e": 3035, "s": 3025, "text": "Output: " }, { "code": null, "e": 3071, "s": 3035, "text": "Area = 125\nTotal surface area = 150" }, { "code": null, "e": 3117, "s": 3071, "text": "Time complexity : O(1) Auxiliary Space : O(1)" }, { "code": null, "e": 3539, "s": 3117, "text": "This article is contributed by Saloni Gupta . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 3544, "s": 3539, "text": "vt_m" }, { "code": null, "e": 3557, "s": 3544, "text": "Akanksha_Rai" }, { "code": null, "e": 3571, "s": 3557, "text": "GauravRajput1" }, { "code": null, "e": 3581, "s": 3571, "text": "krishnav4" }, { "code": null, "e": 3602, "s": 3581, "text": "area-volume-programs" }, { "code": null, "e": 3613, "s": 3602, "text": "maths-cube" }, { "code": null, "e": 3623, "s": 3613, "text": "Geometric" }, { "code": null, "e": 3642, "s": 3623, "text": "School Programming" }, { "code": null, "e": 3652, "s": 3642, "text": "Geometric" } ]
What are Widgets in Tkinter?
22 May, 2020 Tkinter is Python’s standard GUI (Graphical User Interface) package. tkinter provides us with a variety of common GUI elements which we can use to build out interface – such as buttons, menus and various kind of entry fields and display areas. We call these elements Widgets. In general, Widget is an element of Graphical User Interface (GUI) that displays/illustrates information or gives a way for the user to interact with the OS. In Tkinter , Widgets are objects ; instances of classes that represent buttons, frames, and so on. Each separate widget is a Python object. When creating a widget, you must pass its parent as a parameter to the widget creation function. The only exception is the “root” window, which is the top-level window that will contain everything else and it does not have a parent. Example : Python from tkinter import * # create root windowroot = Tk() # frame inside root windowframe = Frame(root) # geometry methodframe.pack() # button inside frame which is # inside rootbutton = Button(frame, text ='Geek') button.pack() # Tkinter event looproot.mainloop() Output : Tkinter supports the below mentioned core widgets – Creating a new widget doesn’t mean that it will appear on the screen. To display it, we need to call a special method: either grid, pack(example above), or place. Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n22 May, 2020" }, { "code": null, "e": 328, "s": 52, "text": "Tkinter is Python’s standard GUI (Graphical User Interface) package. tkinter provides us with a variety of common GUI elements which we can use to build out interface – such as buttons, menus and various kind of entry fields and display areas. We call these elements Widgets." }, { "code": null, "e": 589, "s": 328, "text": "In general, Widget is an element of Graphical User Interface (GUI) that displays/illustrates information or gives a way for the user to interact with the OS. In Tkinter , Widgets are objects ; instances of classes that represent buttons, frames, and so on. " }, { "code": null, "e": 864, "s": 589, "text": "Each separate widget is a Python object. When creating a widget, you must pass its parent as a parameter to the widget creation function. The only exception is the “root” window, which is the top-level window that will contain everything else and it does not have a parent. " }, { "code": null, "e": 875, "s": 864, "text": "Example : " }, { "code": null, "e": 882, "s": 875, "text": "Python" }, { "code": "from tkinter import * # create root windowroot = Tk() # frame inside root windowframe = Frame(root) # geometry methodframe.pack() # button inside frame which is # inside rootbutton = Button(frame, text ='Geek') button.pack() # Tkinter event looproot.mainloop() ", "e": 1270, "s": 882, "text": null }, { "code": null, "e": 1280, "s": 1270, "text": "Output : " }, { "code": null, "e": 1332, "s": 1280, "text": "Tkinter supports the below mentioned core widgets –" }, { "code": null, "e": 1496, "s": 1332, "text": "Creating a new widget doesn’t mean that it will appear on the screen. To display it, we need to call a special method: either grid, pack(example above), or place. " }, { "code": null, "e": 1511, "s": 1496, "text": "Python-tkinter" }, { "code": null, "e": 1518, "s": 1511, "text": "Python" }, { "code": null, "e": 1616, "s": 1518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1644, "s": 1616, "text": "Read JSON file using Python" }, { "code": null, "e": 1694, "s": 1644, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 1716, "s": 1694, "text": "Python map() function" }, { "code": null, "e": 1760, "s": 1716, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 1802, "s": 1760, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1824, "s": 1802, "text": "Enumerate() in Python" }, { "code": null, "e": 1859, "s": 1824, "text": "Read a file line by line in Python" }, { "code": null, "e": 1885, "s": 1859, "text": "Python String | replace()" }, { "code": null, "e": 1917, "s": 1885, "text": "How to Install PIP on Windows ?" } ]
Print numbers in sequence using thread synchronization
23 Dec, 2021 The problem is to synchronize n number of threads using pthread library. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread, ..... print n in nth thread and again repeat from thread 1 infinitely. Prerequisite : Multithreading Examples : Input : Thread count Output : 1 2 3 ... thread count 1 2 3 ... thread count 1 2 3 ... thread count .... Input : 5 Output : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 .... Below is the implementation: CPP // C code to synchronize threads#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t* cond = NULL; int threads;volatile int cnt = 0; // function to synchronize threadsvoid* foo(void* arg){ // turn is a basically to identify a thread int turn = *(int*)arg; while (1) { pthread_mutex_lock(&mutex); // cnt is used to determine which thread should // enter into critical section(printf() statement) if (turn != cnt) { // put all thread except one thread in waiting // state pthread_cond_wait(&cond[turn], &mutex); } // it's a time to print turn can have // values starting from 0. Hence + 1 printf("%d ", turn + 1); // determine which thread need to be scheduled now if (cnt < threads - 1) { cnt++; } else { cnt = 0; } // wake up next thread pthread_cond_signal(&cond[cnt]); pthread_mutex_unlock(&mutex); } return NULL;} // Driver codeint main(){ pthread_t* tid; volatile int i; int* arr; printf("\nEnter number of threads: "); scanf("%d", &threads); // allocate memory to cond (conditional variable), // thread id's and array of size threads cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t) * threads); tid = (pthread_t*)malloc(sizeof(pthread_t) * threads); arr = (int*)malloc(sizeof(int) * threads); // Initialize cond (conditional variable) for (int i = 0; i < threads; i++) { if (pthread_cond_init(&cond[i], NULL) != 0) { perror("pthread_cond_init() error"); exit(1); } } // create threads for (i = 0; i < threads; i++) { arr[i] = i; pthread_create(&tid[i], NULL, foo, (void*)&arr[i]); } // waiting for thread for (i = 0; i < threads; i++) { pthread_join(tid[i], NULL); } return 0;} Output : jeff1jeffo kalrap615 nishanthsmenon cpp-multithreading Processes & Threads C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Dec, 2021" }, { "code": null, "e": 336, "s": 52, "text": "The problem is to synchronize n number of threads using pthread library. The idea is take thread count and print 1 in first thread, print 2 in second thread, print 3 in third thread, ..... print n in nth thread and again repeat from thread 1 infinitely. Prerequisite : Multithreading" }, { "code": null, "e": 348, "s": 336, "text": "Examples : " }, { "code": null, "e": 539, "s": 348, "text": "Input : Thread count\nOutput : 1 2 3 ... thread count 1 2 3 ... thread \ncount 1 2 3 ... thread count ....\n\nInput : 5\nOutput : 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 \n1 2 3 4 5 1 2 3 4 5 ...." }, { "code": null, "e": 569, "s": 539, "text": " Below is the implementation:" }, { "code": null, "e": 573, "s": 569, "text": "CPP" }, { "code": "// C code to synchronize threads#include <pthread.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t* cond = NULL; int threads;volatile int cnt = 0; // function to synchronize threadsvoid* foo(void* arg){ // turn is a basically to identify a thread int turn = *(int*)arg; while (1) { pthread_mutex_lock(&mutex); // cnt is used to determine which thread should // enter into critical section(printf() statement) if (turn != cnt) { // put all thread except one thread in waiting // state pthread_cond_wait(&cond[turn], &mutex); } // it's a time to print turn can have // values starting from 0. Hence + 1 printf(\"%d \", turn + 1); // determine which thread need to be scheduled now if (cnt < threads - 1) { cnt++; } else { cnt = 0; } // wake up next thread pthread_cond_signal(&cond[cnt]); pthread_mutex_unlock(&mutex); } return NULL;} // Driver codeint main(){ pthread_t* tid; volatile int i; int* arr; printf(\"\\nEnter number of threads: \"); scanf(\"%d\", &threads); // allocate memory to cond (conditional variable), // thread id's and array of size threads cond = (pthread_cond_t*)malloc(sizeof(pthread_cond_t) * threads); tid = (pthread_t*)malloc(sizeof(pthread_t) * threads); arr = (int*)malloc(sizeof(int) * threads); // Initialize cond (conditional variable) for (int i = 0; i < threads; i++) { if (pthread_cond_init(&cond[i], NULL) != 0) { perror(\"pthread_cond_init() error\"); exit(1); } } // create threads for (i = 0; i < threads; i++) { arr[i] = i; pthread_create(&tid[i], NULL, foo, (void*)&arr[i]); } // waiting for thread for (i = 0; i < threads; i++) { pthread_join(tid[i], NULL); } return 0;}", "e": 2613, "s": 573, "text": null }, { "code": null, "e": 2624, "s": 2613, "text": "Output : " }, { "code": null, "e": 2637, "s": 2626, "text": "jeff1jeffo" }, { "code": null, "e": 2647, "s": 2637, "text": "kalrap615" }, { "code": null, "e": 2662, "s": 2647, "text": "nishanthsmenon" }, { "code": null, "e": 2681, "s": 2662, "text": "cpp-multithreading" }, { "code": null, "e": 2701, "s": 2681, "text": "Processes & Threads" }, { "code": null, "e": 2712, "s": 2701, "text": "C Language" }, { "code": null, "e": 2723, "s": 2712, "text": "C Programs" } ]
strdup() and strndup() functions in C/C++
23 Jun, 2022 The strdup() and strndup() functions are used to duplicate a string. strdup() : Syntax : char *strdup(const char *s); This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by s. The memory obtained is done dynamically using malloc and hence it can be freed using free(). It returns a pointer to the duplicated string s.Below is the C implementation to show the use of strdup() function in C: C // C program to demonstrate strdup()#include<stdio.h>#include<string.h> int main(){ char source[] = "GeeksForGeeks"; // A copy of source is created dynamically // and pointer to copy is returned. char* target = strdup(source); printf("%s", target); return 0;} Output: GeeksForGeeks strndup() : syntax: char *strndup(const char *s, size_t n); This function is similar to strdup(), but copies at most n bytes. Note: If s is longer than n, then only n bytes are copied, and a NULL (‘\0’) is added at the end.Below is the C implementation to show the use of strndup() function in C: C // C program to demonstrate strndup()#include<stdio.h>#include<string.h> int main(){ char source[] = "GeeksForGeeks"; // 5 bytes of source are copied to a new memory // allocated dynamically and pointer to copied // memory is returned. char* target = strndup(source, 5); printf("%s", target); return 0;} Output: Geeks Let us see the differences in a tabular form -: Its syntax is -: char *strndup( const char *str, size_t size ); It takes two parameters that are -:1.pointer to the null-terminated byte string to duplicate 2. max number of bytes to copy from str Reference: Linux man(7)This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. MattCT riusjeff koushikpmv mayank007rawa C-Library CPP-Library C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 505, "s": 54, "text": "The strdup() and strndup() functions are used to duplicate a string. strdup() : Syntax : char *strdup(const char *s); This function returns a pointer to a null-terminated byte string, which is a duplicate of the string pointed to by s. The memory obtained is done dynamically using malloc and hence it can be freed using free(). It returns a pointer to the duplicated string s.Below is the C implementation to show the use of strdup() function in C: " }, { "code": null, "e": 507, "s": 505, "text": "C" }, { "code": "// C program to demonstrate strdup()#include<stdio.h>#include<string.h> int main(){ char source[] = \"GeeksForGeeks\"; // A copy of source is created dynamically // and pointer to copy is returned. char* target = strdup(source); printf(\"%s\", target); return 0;}", "e": 787, "s": 507, "text": null }, { "code": null, "e": 796, "s": 787, "text": "Output: " }, { "code": null, "e": 810, "s": 796, "text": "GeeksForGeeks" }, { "code": null, "e": 1108, "s": 810, "text": "strndup() : syntax: char *strndup(const char *s, size_t n); This function is similar to strdup(), but copies at most n bytes. Note: If s is longer than n, then only n bytes are copied, and a NULL (‘\\0’) is added at the end.Below is the C implementation to show the use of strndup() function in C: " }, { "code": null, "e": 1110, "s": 1108, "text": "C" }, { "code": "// C program to demonstrate strndup()#include<stdio.h>#include<string.h> int main(){ char source[] = \"GeeksForGeeks\"; // 5 bytes of source are copied to a new memory // allocated dynamically and pointer to copied // memory is returned. char* target = strndup(source, 5); printf(\"%s\", target); return 0;}", "e": 1437, "s": 1110, "text": null }, { "code": null, "e": 1445, "s": 1437, "text": "Output:" }, { "code": null, "e": 1451, "s": 1445, "text": "Geeks" }, { "code": null, "e": 1499, "s": 1451, "text": "Let us see the differences in a tabular form -:" }, { "code": null, "e": 1516, "s": 1499, "text": "Its syntax is -:" }, { "code": null, "e": 1563, "s": 1516, "text": "char *strndup( const char *str, size_t size );" }, { "code": null, "e": 1656, "s": 1563, "text": "It takes two parameters that are -:1.pointer to the null-terminated byte string to duplicate" }, { "code": null, "e": 1696, "s": 1656, "text": "2. max number of bytes to copy from str" }, { "code": null, "e": 2144, "s": 1696, "text": "Reference: Linux man(7)This article is contributed by MAZHAR IMAM KHAN. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 2151, "s": 2144, "text": "MattCT" }, { "code": null, "e": 2160, "s": 2151, "text": "riusjeff" }, { "code": null, "e": 2171, "s": 2160, "text": "koushikpmv" }, { "code": null, "e": 2185, "s": 2171, "text": "mayank007rawa" }, { "code": null, "e": 2195, "s": 2185, "text": "C-Library" }, { "code": null, "e": 2207, "s": 2195, "text": "CPP-Library" }, { "code": null, "e": 2218, "s": 2207, "text": "C Language" }, { "code": null, "e": 2222, "s": 2218, "text": "C++" }, { "code": null, "e": 2226, "s": 2222, "text": "CPP" } ]
Get the First parts of a Data Set in R Programming – head() Function
30 Jun, 2020 head() function in R Language is used to get the first parts of a vector, matrix, table, data frame or function. Syntax: head(x, n) Parameters:x: specified data typesn: number of row need to be printed Example 1: # R program to illustrate# head function # Calling the head() function to # get the iris demo datasethead(iris) Output: Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa 5 5.0 3.6 1.4 0.2 setosa 6 5.4 3.9 1.7 0.4 setosa Example 2: # R program to illustrate# head function # Calling the head() function to # get the iris demo dataset in# 4 rowshead(iris, 4) Output: Sepal.Length Sepal.Width Petal.Length Petal.Width Species 1 5.1 3.5 1.4 0.2 setosa 2 4.9 3.0 1.4 0.2 setosa 3 4.7 3.2 1.3 0.2 setosa 4 4.6 3.1 1.5 0.2 setosa R DataFrame-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2020" }, { "code": null, "e": 141, "s": 28, "text": "head() function in R Language is used to get the first parts of a vector, matrix, table, data frame or function." }, { "code": null, "e": 160, "s": 141, "text": "Syntax: head(x, n)" }, { "code": null, "e": 230, "s": 160, "text": "Parameters:x: specified data typesn: number of row need to be printed" }, { "code": null, "e": 241, "s": 230, "text": "Example 1:" }, { "code": "# R program to illustrate# head function # Calling the head() function to # get the iris demo datasethead(iris)", "e": 354, "s": 241, "text": null }, { "code": null, "e": 362, "s": 354, "text": "Output:" }, { "code": null, "e": 783, "s": 362, "text": " Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n1 5.1 3.5 1.4 0.2 setosa\n2 4.9 3.0 1.4 0.2 setosa\n3 4.7 3.2 1.3 0.2 setosa\n4 4.6 3.1 1.5 0.2 setosa\n5 5.0 3.6 1.4 0.2 setosa\n6 5.4 3.9 1.7 0.4 setosa\n" }, { "code": null, "e": 794, "s": 783, "text": "Example 2:" }, { "code": "# R program to illustrate# head function # Calling the head() function to # get the iris demo dataset in# 4 rowshead(iris, 4)", "e": 921, "s": 794, "text": null }, { "code": null, "e": 929, "s": 921, "text": "Output:" }, { "code": null, "e": 1230, "s": 929, "text": " Sepal.Length Sepal.Width Petal.Length Petal.Width Species\n1 5.1 3.5 1.4 0.2 setosa\n2 4.9 3.0 1.4 0.2 setosa\n3 4.7 3.2 1.3 0.2 setosa\n4 4.6 3.1 1.5 0.2 setosa\n" }, { "code": null, "e": 1251, "s": 1230, "text": "R DataFrame-Function" }, { "code": null, "e": 1262, "s": 1251, "text": "R Language" } ]
Julia Language Introduction
16 Apr, 2020 Julia is a high-level open-source programming language, developed by a group of 4 people at MIT. Julia is a dynamic, high-performance programming language that is used to perform operations in scientific computing. Similar to R Programming Language, Julia is used for statistical computations and data analysis. Julia was built mainly because of its speed in programming, it has much faster execution as compared to Python and R.Julia provides support for big data analytics by performing complex tasks such as cloud computing and parallelism, which play a fundamental role in analyzing Big Data. To gain such features and compatibility, Julia draws upon the lineage of mathematical programming languages but also adopts much from many other popular dynamic languages, which include Perl, Python, Lua, Lisp, and Ruby. Julia has many reasons for being widely used for Data Analytics. Few of the reasons are: Easy to Start: Julia is a high-level language so it is closer to other popular programming languages like Python, C, R, etc. Thus it becomes very easy to learn Julia for anyone, especially for Python and C programmers. Open-source: Julia is fully open-source and free, hence it can be downloaded and worked upon easily. Integrated Language: Julia is built for scientific computations just like in Python, R, and MATLAB alongside it has its roots in the general-purpose programming. Faster Execution: Julia is known to be a combination of Python and C programming language. Hence, it has a very high execution speed of C as compared to Python, R, and MATLAB. Fewer Lines of Code: Julia provides the flexibility of writing fewer lines of codes as in Python. Finding a Compiler: There are various online IDEs such as TutorialsPoint, repl.it, etc. which can be used to run Julia programs without installing.Jupyter Notebook can also be used to run Julia programs offline. Here’s How to install Jupyter Notebook for Julia in Windows? Programming in Julia: Since Julia is a lot similar to other widely used languages syntactically, it is easier to code and learn in Julia. Programs can be written in Julia in any of the widely used text editors like Notepad++, gedit, etc. or on any of the text-editors. After writing the program, save the file with the .jl extension. Writing our first program:Just type in the following code after you start the interpreter. # Julia program to print Hello World # print functionprint("Hello World !") Output: Hello World [print(“Hello World!”)]: To print something on the console, print() function is used. To give a new line after the print statement, println() is used. Comments:Comments are used for explaining code and are used in a similar manner as in Python. Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple lines. Single line Comments:Syntax:# Single line comment # Single line comment Multi line comments:Syntax:#= Multi line comments =# #= Multi line comments =# There are multiple features that make Julia different from other languages. Julia is a dynamically typed language which makes it interactive to use. Julia is an open-source language and hence all source codes are easily available online. Julia can work on Python, C and Fortran libraries by directly calling them. Julia is flexible to use, because it allows writing fewer lines of codes as compared to C. Julia is just-in-time compiled and hence it can even approach the execution speed of C. Julia can handle complex data analytics very easily. Advantages:There are many advantages of Julia over Python and C. Few of them are: Julia is faster as compared to Python, because of its just-in-time(JIT) compilation. Julia is highly compatible with mathematical computations. Julia allocates memory to variables automatically, like Python. Julia is a combination of both dynamic and static typed language. Disadvantages: Julia is 1-indexed language, which means that its array indexing starts from 1, unlike other languages in which it starts from 0. This might cause problems to adopt new habits of writing codes. Julia, as compared to Python, is very new. Hence, people still prefer python over Julia. Matrices in Julia are accessed column-wise, whereas Python matrices are accessed row-wise. This can create problems in taking design decisions on how to go through matrices effectively in memory. Dictionaries in Julia are hashed differently than dictionaries in Python, which can make the execution slower in multiple cases. Application of Julia: Julia can be used for major scientific computations which involve Big Data. Julia can be used for Web Programming with the help of packages. Machine Learning computations can also be performed easily with the help of Julia. With the help of ARM support, Julia will soon be used on Android Smartphones. Julia-Basics Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Vectors in Julia Getting rounded value of a number in Julia - round() Method Manipulating matrices in Julia Reshaping array dimensions in Julia | Array reshape() Method Storing Output on a File in Julia Get number of elements of array in Julia - length() Method Exception handling in Julia Get array dimensions and size of a dimension in Julia - size() Method Creating array with repeated elements in Julia - repeat() Method Tuples in Julia
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Apr, 2020" }, { "code": null, "e": 871, "s": 53, "text": "Julia is a high-level open-source programming language, developed by a group of 4 people at MIT. Julia is a dynamic, high-performance programming language that is used to perform operations in scientific computing. Similar to R Programming Language, Julia is used for statistical computations and data analysis. Julia was built mainly because of its speed in programming, it has much faster execution as compared to Python and R.Julia provides support for big data analytics by performing complex tasks such as cloud computing and parallelism, which play a fundamental role in analyzing Big Data. To gain such features and compatibility, Julia draws upon the lineage of mathematical programming languages but also adopts much from many other popular dynamic languages, which include Perl, Python, Lua, Lisp, and Ruby." }, { "code": null, "e": 960, "s": 871, "text": "Julia has many reasons for being widely used for Data Analytics. Few of the reasons are:" }, { "code": null, "e": 1179, "s": 960, "text": "Easy to Start: Julia is a high-level language so it is closer to other popular programming languages like Python, C, R, etc. Thus it becomes very easy to learn Julia for anyone, especially for Python and C programmers." }, { "code": null, "e": 1280, "s": 1179, "text": "Open-source: Julia is fully open-source and free, hence it can be downloaded and worked upon easily." }, { "code": null, "e": 1442, "s": 1280, "text": "Integrated Language: Julia is built for scientific computations just like in Python, R, and MATLAB alongside it has its roots in the general-purpose programming." }, { "code": null, "e": 1618, "s": 1442, "text": "Faster Execution: Julia is known to be a combination of Python and C programming language. Hence, it has a very high execution speed of C as compared to Python, R, and MATLAB." }, { "code": null, "e": 1716, "s": 1618, "text": "Fewer Lines of Code: Julia provides the flexibility of writing fewer lines of codes as in Python." }, { "code": null, "e": 2414, "s": 1716, "text": "Finding a Compiler: There are various online IDEs such as TutorialsPoint, repl.it, etc. which can be used to run Julia programs without installing.Jupyter Notebook can also be used to run Julia programs offline. Here’s How to install Jupyter Notebook for Julia in Windows? Programming in Julia: Since Julia is a lot similar to other widely used languages syntactically, it is easier to code and learn in Julia. Programs can be written in Julia in any of the widely used text editors like Notepad++, gedit, etc. or on any of the text-editors. After writing the program, save the file with the .jl extension. Writing our first program:Just type in the following code after you start the interpreter." }, { "code": "# Julia program to print Hello World # print functionprint(\"Hello World !\") ", "e": 2495, "s": 2414, "text": null }, { "code": null, "e": 2503, "s": 2495, "text": "Output:" }, { "code": null, "e": 2515, "s": 2503, "text": "Hello World" }, { "code": null, "e": 2875, "s": 2515, "text": " [print(“Hello World!”)]: To print something on the console, print() function is used. To give a new line after the print statement, println() is used. Comments:Comments are used for explaining code and are used in a similar manner as in Python. Compilers ignore the comment entries and do not execute them. Comments can be of a single line or multiple lines." }, { "code": null, "e": 2925, "s": 2875, "text": "Single line Comments:Syntax:# Single line comment" }, { "code": null, "e": 2947, "s": 2925, "text": "# Single line comment" }, { "code": null, "e": 3002, "s": 2947, "text": "Multi line comments:Syntax:#=\nMulti line \ncomments \n=#" }, { "code": null, "e": 3030, "s": 3002, "text": "#=\nMulti line \ncomments \n=#" }, { "code": null, "e": 3106, "s": 3030, "text": "There are multiple features that make Julia different from other languages." }, { "code": null, "e": 3179, "s": 3106, "text": "Julia is a dynamically typed language which makes it interactive to use." }, { "code": null, "e": 3268, "s": 3179, "text": "Julia is an open-source language and hence all source codes are easily available online." }, { "code": null, "e": 3344, "s": 3268, "text": "Julia can work on Python, C and Fortran libraries by directly calling them." }, { "code": null, "e": 3435, "s": 3344, "text": "Julia is flexible to use, because it allows writing fewer lines of codes as compared to C." }, { "code": null, "e": 3523, "s": 3435, "text": "Julia is just-in-time compiled and hence it can even approach the execution speed of C." }, { "code": null, "e": 3576, "s": 3523, "text": "Julia can handle complex data analytics very easily." }, { "code": null, "e": 3659, "s": 3576, "text": " Advantages:There are many advantages of Julia over Python and C. Few of them are:" }, { "code": null, "e": 3744, "s": 3659, "text": "Julia is faster as compared to Python, because of its just-in-time(JIT) compilation." }, { "code": null, "e": 3803, "s": 3744, "text": "Julia is highly compatible with mathematical computations." }, { "code": null, "e": 3867, "s": 3803, "text": "Julia allocates memory to variables automatically, like Python." }, { "code": null, "e": 3933, "s": 3867, "text": "Julia is a combination of both dynamic and static typed language." }, { "code": null, "e": 3949, "s": 3933, "text": " Disadvantages:" }, { "code": null, "e": 4143, "s": 3949, "text": "Julia is 1-indexed language, which means that its array indexing starts from 1, unlike other languages in which it starts from 0. This might cause problems to adopt new habits of writing codes." }, { "code": null, "e": 4232, "s": 4143, "text": "Julia, as compared to Python, is very new. Hence, people still prefer python over Julia." }, { "code": null, "e": 4428, "s": 4232, "text": "Matrices in Julia are accessed column-wise, whereas Python matrices are accessed row-wise. This can create problems in taking design decisions on how to go through matrices effectively in memory." }, { "code": null, "e": 4557, "s": 4428, "text": "Dictionaries in Julia are hashed differently than dictionaries in Python, which can make the execution slower in multiple cases." }, { "code": null, "e": 4580, "s": 4557, "text": " Application of Julia:" }, { "code": null, "e": 4656, "s": 4580, "text": "Julia can be used for major scientific computations which involve Big Data." }, { "code": null, "e": 4721, "s": 4656, "text": "Julia can be used for Web Programming with the help of packages." }, { "code": null, "e": 4804, "s": 4721, "text": "Machine Learning computations can also be performed easily with the help of Julia." }, { "code": null, "e": 4882, "s": 4804, "text": "With the help of ARM support, Julia will soon be used on Android Smartphones." }, { "code": null, "e": 4897, "s": 4884, "text": "Julia-Basics" }, { "code": null, "e": 4903, "s": 4897, "text": "Julia" }, { "code": null, "e": 5001, "s": 4903, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5018, "s": 5001, "text": "Vectors in Julia" }, { "code": null, "e": 5078, "s": 5018, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 5109, "s": 5078, "text": "Manipulating matrices in Julia" }, { "code": null, "e": 5170, "s": 5109, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 5204, "s": 5170, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 5263, "s": 5204, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 5291, "s": 5263, "text": "Exception handling in Julia" }, { "code": null, "e": 5361, "s": 5291, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 5426, "s": 5361, "text": "Creating array with repeated elements in Julia - repeat() Method" } ]
Implementing Generic Graph in Java
17 Nov, 2021 Prerequisite: Generic Class We can also use them to code for Graph in Java. The Graph class is implemented using HashMap in Java. As we know HashMap contains a key and a value, we represent nodes as keys and their adjacency list in values in the graph. Illustration: An undirected and unweighted graph with 5 vertices. Adjacency Matrix is as follows: Adjacency List is as follows: Just unlikely in C++, we use <> to specify parameter types in generic class creation. Syntax: To create objects of a generic class BaseType <Type> obj = new BaseType <Type>() Note: In Parameter type, we cannot use primitives like ‘int’, ‘char’, or ‘double’. Example Java // Java program to implement Graph// with the help of Generics import java.util.*; class Graph<T> { // We use Hashmap to store the edges in the graph private Map<T, List<T> > map = new HashMap<>(); // This function adds a new vertex to the graph public void addVertex(T s) { map.put(s, new LinkedList<T>()); } // This function adds the edge // between source to destination public void addEdge(T source, T destination, boolean bidirectional) { if (!map.containsKey(source)) addVertex(source); if (!map.containsKey(destination)) addVertex(destination); map.get(source).add(destination); if (bidirectional == true) { map.get(destination).add(source); } } // This function gives the count of vertices public void getVertexCount() { System.out.println("The graph has " + map.keySet().size() + " vertex"); } // This function gives the count of edges public void getEdgesCount(boolean bidirection) { int count = 0; for (T v : map.keySet()) { count += map.get(v).size(); } if (bidirection == true) { count = count / 2; } System.out.println("The graph has " + count + " edges."); } // This function gives whether // a vertex is present or not. public void hasVertex(T s) { if (map.containsKey(s)) { System.out.println("The graph contains " + s + " as a vertex."); } else { System.out.println("The graph does not contain " + s + " as a vertex."); } } // This function gives whether an edge is present or not. public void hasEdge(T s, T d) { if (map.get(s).contains(d)) { System.out.println("The graph has an edge between " + s + " and " + d + "."); } else { System.out.println("The graph has no edge between " + s + " and " + d + "."); } } // Prints the adjancency list of each vertex. @Override public String toString() { StringBuilder builder = new StringBuilder(); for (T v : map.keySet()) { builder.append(v.toString() + ": "); for (T w : map.get(v)) { builder.append(w.toString() + " "); } builder.append("\n"); } return (builder.toString()); }} // Driver Codepublic class Main { public static void main(String args[]) { // Object of graph is created. Graph<Integer> g = new Graph<Integer>(); // edges are added. // Since the graph is bidirectional, // so boolean bidirectional is passed as true. g.addEdge(0, 1, true); g.addEdge(0, 4, true); g.addEdge(1, 2, true); g.addEdge(1, 3, true); g.addEdge(1, 4, true); g.addEdge(2, 3, true); g.addEdge(3, 4, true); // Printing the graph System.out.println("Graph:\n" + g.toString()); // Gives the no of vertices in the graph. g.getVertexCount(); // Gives the no of edges in the graph. g.getEdgesCount(true); // Tells whether the edge is present or not. g.hasEdge(3, 4); // Tells whether vertex is present or not g.hasVertex(5); }} Graph: 0: 1 4 1: 0 2 3 4 2: 1 3 3: 1 2 4 4: 0 1 3 The graph has 5 vertex The graph has 7 edges. The graph has an edge between 3 and 4. The graph does not contain 5 as a vertex. solankimayank Data Structures Graph Java Programs Data Structures Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Nov, 2021" }, { "code": null, "e": 83, "s": 54, "text": "Prerequisite: Generic Class " }, { "code": null, "e": 308, "s": 83, "text": "We can also use them to code for Graph in Java. The Graph class is implemented using HashMap in Java. As we know HashMap contains a key and a value, we represent nodes as keys and their adjacency list in values in the graph." }, { "code": null, "e": 376, "s": 308, "text": "Illustration: An undirected and unweighted graph with 5 vertices. " }, { "code": null, "e": 408, "s": 376, "text": "Adjacency Matrix is as follows:" }, { "code": null, "e": 439, "s": 408, "text": "Adjacency List is as follows:" }, { "code": null, "e": 526, "s": 439, "text": "Just unlikely in C++, we use <> to specify parameter types in generic class creation. " }, { "code": null, "e": 571, "s": 526, "text": "Syntax: To create objects of a generic class" }, { "code": null, "e": 615, "s": 571, "text": "BaseType <Type> obj = new BaseType <Type>()" }, { "code": null, "e": 698, "s": 615, "text": "Note: In Parameter type, we cannot use primitives like ‘int’, ‘char’, or ‘double’." }, { "code": null, "e": 706, "s": 698, "text": "Example" }, { "code": null, "e": 711, "s": 706, "text": "Java" }, { "code": "// Java program to implement Graph// with the help of Generics import java.util.*; class Graph<T> { // We use Hashmap to store the edges in the graph private Map<T, List<T> > map = new HashMap<>(); // This function adds a new vertex to the graph public void addVertex(T s) { map.put(s, new LinkedList<T>()); } // This function adds the edge // between source to destination public void addEdge(T source, T destination, boolean bidirectional) { if (!map.containsKey(source)) addVertex(source); if (!map.containsKey(destination)) addVertex(destination); map.get(source).add(destination); if (bidirectional == true) { map.get(destination).add(source); } } // This function gives the count of vertices public void getVertexCount() { System.out.println(\"The graph has \" + map.keySet().size() + \" vertex\"); } // This function gives the count of edges public void getEdgesCount(boolean bidirection) { int count = 0; for (T v : map.keySet()) { count += map.get(v).size(); } if (bidirection == true) { count = count / 2; } System.out.println(\"The graph has \" + count + \" edges.\"); } // This function gives whether // a vertex is present or not. public void hasVertex(T s) { if (map.containsKey(s)) { System.out.println(\"The graph contains \" + s + \" as a vertex.\"); } else { System.out.println(\"The graph does not contain \" + s + \" as a vertex.\"); } } // This function gives whether an edge is present or not. public void hasEdge(T s, T d) { if (map.get(s).contains(d)) { System.out.println(\"The graph has an edge between \" + s + \" and \" + d + \".\"); } else { System.out.println(\"The graph has no edge between \" + s + \" and \" + d + \".\"); } } // Prints the adjancency list of each vertex. @Override public String toString() { StringBuilder builder = new StringBuilder(); for (T v : map.keySet()) { builder.append(v.toString() + \": \"); for (T w : map.get(v)) { builder.append(w.toString() + \" \"); } builder.append(\"\\n\"); } return (builder.toString()); }} // Driver Codepublic class Main { public static void main(String args[]) { // Object of graph is created. Graph<Integer> g = new Graph<Integer>(); // edges are added. // Since the graph is bidirectional, // so boolean bidirectional is passed as true. g.addEdge(0, 1, true); g.addEdge(0, 4, true); g.addEdge(1, 2, true); g.addEdge(1, 3, true); g.addEdge(1, 4, true); g.addEdge(2, 3, true); g.addEdge(3, 4, true); // Printing the graph System.out.println(\"Graph:\\n\" + g.toString()); // Gives the no of vertices in the graph. g.getVertexCount(); // Gives the no of edges in the graph. g.getEdgesCount(true); // Tells whether the edge is present or not. g.hasEdge(3, 4); // Tells whether vertex is present or not g.hasVertex(5); }}", "e": 4293, "s": 711, "text": null }, { "code": null, "e": 4476, "s": 4293, "text": "Graph:\n0: 1 4 \n1: 0 2 3 4 \n2: 1 3 \n3: 1 2 4 \n4: 0 1 3 \n\nThe graph has 5 vertex\nThe graph has 7 edges.\nThe graph has an edge between 3 and 4.\nThe graph does not contain 5 as a vertex." }, { "code": null, "e": 4492, "s": 4478, "text": "solankimayank" }, { "code": null, "e": 4508, "s": 4492, "text": "Data Structures" }, { "code": null, "e": 4514, "s": 4508, "text": "Graph" }, { "code": null, "e": 4528, "s": 4514, "text": "Java Programs" }, { "code": null, "e": 4544, "s": 4528, "text": "Data Structures" }, { "code": null, "e": 4550, "s": 4544, "text": "Graph" } ]
Create a green button (success) with Bootstrap
Use the .btn-success class in Bootstrap to create a green button that indicates success Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <p>Click below if you want to know the result of successful students:</p> <button type = "button" class = "btn btn-success">Submit</button> </body> </html>
[ { "code": null, "e": 1275, "s": 1187, "text": "Use the .btn-success class in Bootstrap to create a green button that indicates success" }, { "code": null, "e": 1285, "s": 1275, "text": "Live Demo" }, { "code": null, "e": 1866, "s": 1285, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\"\n href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>Click below if you want to know the result of successful students:</p>\n <button type = \"button\" class = \"btn btn-success\">Submit</button>\n </body>\n</html>" } ]
Unordered Sets in C++ Standard Template Library
11 May, 2022 An unordered_set is implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set takes constant time O(1) on an average which can go up to linear time O(n) in worst case which depends on the internally used hash function, but practically they perform very well and generally provide a constant time lookup operation. The unordered_set can contain key of any type – predefined or user-defined data structure but when we define the key of type user define the type, we need to specify our comparison function according to which keys will be compared. Sets vs Unordered Sets Set is an ordered sequence of unique keys whereas unordered_set is a set in which key can be stored in any order, so unordered. Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal). The time complexity of set operations is O(log n) while for unordered_set, it is O(1). Methods on Unordered Sets: For unordered_set many functions are defined among which most used are the size and empty for capacity, find for searching a key, insert and erase for modification. The Unordered_set allows only unique keys, for duplicate keys unordered_multiset should be used. Example of declaration, find, insert and iteration in unordered_set is given below : CPP // C++ program to demonstrate various function of unordered_set#include <bits/stdc++.h>using namespace std; int main(){ // declaring set for storing string data-type unordered_set <string> stringSet ; // inserting various string, same string will be stored // once in set stringSet.insert("code") ; stringSet.insert("in") ; stringSet.insert("c++") ; stringSet.insert("is") ; stringSet.insert("fast") ; string key = "slow" ; // find returns end iterator if key is not found, // else it returns iterator to that key if (stringSet.find(key) == stringSet.end()) cout << key << " not found" << endl << endl ; else cout << "Found " << key << endl << endl ; key = "c++"; if (stringSet.find(key) == stringSet.end()) cout << key << " not found\n" ; else cout << "Found " << key << endl ; // now iterating over whole set and printing its // content cout << "\nAll elements : "; unordered_set<string> :: iterator itr; for (itr = stringSet.begin(); itr != stringSet.end(); itr++) cout << (*itr) << endl;} Output: slow not found Found c++ All elements : is fast c++ in code find, insert and erase take constant amount of time on average. The find() function returns an iterator to end() if key is not there in set, otherwise an iterator to the key position is returned. The iterator works as a pointer to the key values so that we can get the key by dereferencing them using * operator. A practical problem based on unordered_set – Given an array(list) of integers, find all the duplicates among them. Input : arr[] = {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5} Output : Duplicate item are : 5 2 1 Below is C++ solution using unordered_set. CPP // C++ program to find duplicate from an array using// unordered_set#include <bits/stdc++.h>using namespace std; // Print duplicates in arr[0..n-1] using unordered_setvoid printDuplicates(int arr[], int n){ // declaring unordered sets for checking and storing // duplicates unordered_set<int> intSet; unordered_set<int> duplicate; // looping through array elements for (int i = 0; i < n; i++) { // if element is not there then insert that if (intSet.find(arr[i]) == intSet.end()) intSet.insert(arr[i]); // if element is already there then insert into // duplicate set else duplicate.insert(arr[i]); } // printing the result cout << "Duplicate item are : "; unordered_set<int> :: iterator itr; // iterator itr loops from begin() till end() for (itr = duplicate.begin(); itr != duplicate.end(); itr++) cout << *itr << " ";} // Driver codeint main(){ int arr[] = {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5}; int n = sizeof(arr) / sizeof(int); printDuplicates(arr, n); return 0;} Output : Duplicate item are : 5 1 2 Methods of unordered_set: insert()– Insert a new {element} in the unordered_set container. begin()– Return an iterator pointing to the first element in the unordered_set container. end()– Returns an iterator pointing to the past-the-end-element. count()– Count occurrences of a particular element in an unordered_set container. find()– Search for an element in the container. clear()– Removes all of the elements from an unordered_set and empties it. cbegin()– Return a const_iterator pointing to the first element in the unordered_set container. cend()– Return a const_iterator pointing to past-the-end element in the unordered_set container or in one of it’s bucket. bucket_size()– Returns the total number of elements present in a specific bucket in an unordered_set container. erase()– Remove either a single element or a range of elements ranging from start(inclusive) to end(exclusive). size()– Return the number of elements in the unordered_set container. swap()– Exchange values of two unordered_set containers. emplace()– Insert an element in an unordered_set container. max_size()– Returns maximum number of elements that an unordered_set container can hold. empty()– Check if an unordered_set container is empty or not. equal_range– Returns range that includes all elements equal to given value. operator= – Copies (or moves) an unordered_set to another unordered_set and unordered_set::operator= is the corresponding operator function. hash_function() – This hash function is a unary function which takes asingle argument only and returns a unique value of type size_t based on it. reserve()– Used to request capacity change of unordered_set. bucket()– Returns the bucket number of a specific element. bucket_count() – Returns the total number of buckets present in an unordered_set container. load_factor()– Returns the current load factor in the unordered_set container. rehash()– Set the number of buckets in the container of unordered_set to given size or more. max_load_factor()– Returns(Or sets) the current maximum load factor of the unordered set container. emplace_hint()– Inserts a new element in the unordered_set only if the value to be inserted is unique, with a given hint. == operator – The ‘==’ is an operator in C++ STL performs equality comparison operation between two unordered sets and unordered_set::operator== is the corresponding operator function for the same. key_eq()– Returns a boolean value according to the comparison. It returns the key equivalence comparison predicate used by the unordered_set. operator!=– The != is a relational operator in C++ STL which compares the equality and inequality between unordered_set containers. max_bucket_count() – Find the maximum number of buckets that unordered_set can have. Recent articles on unordered_setThis article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sai Harish Pathuri NerdCaps siddharthx_07 ashissingh640 ravi_42 unknownfool iampratikangre vaasugupta01 cpp-containers-library cpp-unordered_set cpp-unordered_set-functions STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2022" }, { "code": null, "e": 702, "s": 52, "text": "An unordered_set is implemented using a hash table where keys are hashed into indices of a hash table so that the insertion is always randomized. All operations on the unordered_set takes constant time O(1) on an average which can go up to linear time O(n) in worst case which depends on the internally used hash function, but practically they perform very well and generally provide a constant time lookup operation. The unordered_set can contain key of any type – predefined or user-defined data structure but when we define the key of type user define the type, we need to specify our comparison function according to which keys will be compared." }, { "code": null, "e": 1458, "s": 702, "text": "Sets vs Unordered Sets Set is an ordered sequence of unique keys whereas unordered_set is a set in which key can be stored in any order, so unordered. Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal). The time complexity of set operations is O(log n) while for unordered_set, it is O(1). Methods on Unordered Sets: For unordered_set many functions are defined among which most used are the size and empty for capacity, find for searching a key, insert and erase for modification. The Unordered_set allows only unique keys, for duplicate keys unordered_multiset should be used. Example of declaration, find, insert and iteration in unordered_set is given below :" }, { "code": null, "e": 1462, "s": 1458, "text": "CPP" }, { "code": "// C++ program to demonstrate various function of unordered_set#include <bits/stdc++.h>using namespace std; int main(){ // declaring set for storing string data-type unordered_set <string> stringSet ; // inserting various string, same string will be stored // once in set stringSet.insert(\"code\") ; stringSet.insert(\"in\") ; stringSet.insert(\"c++\") ; stringSet.insert(\"is\") ; stringSet.insert(\"fast\") ; string key = \"slow\" ; // find returns end iterator if key is not found, // else it returns iterator to that key if (stringSet.find(key) == stringSet.end()) cout << key << \" not found\" << endl << endl ; else cout << \"Found \" << key << endl << endl ; key = \"c++\"; if (stringSet.find(key) == stringSet.end()) cout << key << \" not found\\n\" ; else cout << \"Found \" << key << endl ; // now iterating over whole set and printing its // content cout << \"\\nAll elements : \"; unordered_set<string> :: iterator itr; for (itr = stringSet.begin(); itr != stringSet.end(); itr++) cout << (*itr) << endl;}", "e": 2573, "s": 1462, "text": null }, { "code": null, "e": 2582, "s": 2573, "text": "Output: " }, { "code": null, "e": 2645, "s": 2582, "text": "slow not found\n\nFound c++\n\nAll elements : \nis\nfast\nc++\nin\ncode" }, { "code": null, "e": 3074, "s": 2645, "text": "find, insert and erase take constant amount of time on average. The find() function returns an iterator to end() if key is not there in set, otherwise an iterator to the key position is returned. The iterator works as a pointer to the key values so that we can get the key by dereferencing them using * operator. A practical problem based on unordered_set – Given an array(list) of integers, find all the duplicates among them. " }, { "code": null, "e": 3165, "s": 3074, "text": "Input : arr[] = {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5}\nOutput : Duplicate item are : 5 2 1 " }, { "code": null, "e": 3209, "s": 3165, "text": "Below is C++ solution using unordered_set. " }, { "code": null, "e": 3213, "s": 3209, "text": "CPP" }, { "code": "// C++ program to find duplicate from an array using// unordered_set#include <bits/stdc++.h>using namespace std; // Print duplicates in arr[0..n-1] using unordered_setvoid printDuplicates(int arr[], int n){ // declaring unordered sets for checking and storing // duplicates unordered_set<int> intSet; unordered_set<int> duplicate; // looping through array elements for (int i = 0; i < n; i++) { // if element is not there then insert that if (intSet.find(arr[i]) == intSet.end()) intSet.insert(arr[i]); // if element is already there then insert into // duplicate set else duplicate.insert(arr[i]); } // printing the result cout << \"Duplicate item are : \"; unordered_set<int> :: iterator itr; // iterator itr loops from begin() till end() for (itr = duplicate.begin(); itr != duplicate.end(); itr++) cout << *itr << \" \";} // Driver codeint main(){ int arr[] = {1, 5, 2, 1, 4, 3, 1, 7, 2, 8, 9, 5}; int n = sizeof(arr) / sizeof(int); printDuplicates(arr, n); return 0;}", "e": 4309, "s": 3213, "text": null }, { "code": null, "e": 4319, "s": 4309, "text": "Output : " }, { "code": null, "e": 4347, "s": 4319, "text": "Duplicate item are : 5 1 2 " }, { "code": null, "e": 4375, "s": 4347, "text": "Methods of unordered_set: " }, { "code": null, "e": 4440, "s": 4375, "text": "insert()– Insert a new {element} in the unordered_set container." }, { "code": null, "e": 4530, "s": 4440, "text": "begin()– Return an iterator pointing to the first element in the unordered_set container." }, { "code": null, "e": 4595, "s": 4530, "text": "end()– Returns an iterator pointing to the past-the-end-element." }, { "code": null, "e": 4677, "s": 4595, "text": "count()– Count occurrences of a particular element in an unordered_set container." }, { "code": null, "e": 4725, "s": 4677, "text": "find()– Search for an element in the container." }, { "code": null, "e": 4800, "s": 4725, "text": "clear()– Removes all of the elements from an unordered_set and empties it." }, { "code": null, "e": 4896, "s": 4800, "text": "cbegin()– Return a const_iterator pointing to the first element in the unordered_set container." }, { "code": null, "e": 5018, "s": 4896, "text": "cend()– Return a const_iterator pointing to past-the-end element in the unordered_set container or in one of it’s bucket." }, { "code": null, "e": 5130, "s": 5018, "text": "bucket_size()– Returns the total number of elements present in a specific bucket in an unordered_set container." }, { "code": null, "e": 5242, "s": 5130, "text": "erase()– Remove either a single element or a range of elements ranging from start(inclusive) to end(exclusive)." }, { "code": null, "e": 5312, "s": 5242, "text": "size()– Return the number of elements in the unordered_set container." }, { "code": null, "e": 5369, "s": 5312, "text": "swap()– Exchange values of two unordered_set containers." }, { "code": null, "e": 5429, "s": 5369, "text": "emplace()– Insert an element in an unordered_set container." }, { "code": null, "e": 5518, "s": 5429, "text": "max_size()– Returns maximum number of elements that an unordered_set container can hold." }, { "code": null, "e": 5580, "s": 5518, "text": "empty()– Check if an unordered_set container is empty or not." }, { "code": null, "e": 5656, "s": 5580, "text": "equal_range– Returns range that includes all elements equal to given value." }, { "code": null, "e": 5797, "s": 5656, "text": "operator= – Copies (or moves) an unordered_set to another unordered_set and unordered_set::operator= is the corresponding operator function." }, { "code": null, "e": 5943, "s": 5797, "text": "hash_function() – This hash function is a unary function which takes asingle argument only and returns a unique value of type size_t based on it." }, { "code": null, "e": 6004, "s": 5943, "text": "reserve()– Used to request capacity change of unordered_set." }, { "code": null, "e": 6063, "s": 6004, "text": "bucket()– Returns the bucket number of a specific element." }, { "code": null, "e": 6155, "s": 6063, "text": "bucket_count() – Returns the total number of buckets present in an unordered_set container." }, { "code": null, "e": 6234, "s": 6155, "text": "load_factor()– Returns the current load factor in the unordered_set container." }, { "code": null, "e": 6327, "s": 6234, "text": "rehash()– Set the number of buckets in the container of unordered_set to given size or more." }, { "code": null, "e": 6427, "s": 6327, "text": "max_load_factor()– Returns(Or sets) the current maximum load factor of the unordered set container." }, { "code": null, "e": 6549, "s": 6427, "text": "emplace_hint()– Inserts a new element in the unordered_set only if the value to be inserted is unique, with a given hint." }, { "code": null, "e": 6747, "s": 6549, "text": "== operator – The ‘==’ is an operator in C++ STL performs equality comparison operation between two unordered sets and unordered_set::operator== is the corresponding operator function for the same." }, { "code": null, "e": 6889, "s": 6747, "text": "key_eq()– Returns a boolean value according to the comparison. It returns the key equivalence comparison predicate used by the unordered_set." }, { "code": null, "e": 7021, "s": 6889, "text": "operator!=– The != is a relational operator in C++ STL which compares the equality and inequality between unordered_set containers." }, { "code": null, "e": 7106, "s": 7021, "text": "max_bucket_count() – Find the maximum number of buckets that unordered_set can have." }, { "code": null, "e": 7311, "s": 7106, "text": "Recent articles on unordered_setThis article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7330, "s": 7311, "text": "Sai Harish Pathuri" }, { "code": null, "e": 7339, "s": 7330, "text": "NerdCaps" }, { "code": null, "e": 7353, "s": 7339, "text": "siddharthx_07" }, { "code": null, "e": 7367, "s": 7353, "text": "ashissingh640" }, { "code": null, "e": 7375, "s": 7367, "text": "ravi_42" }, { "code": null, "e": 7387, "s": 7375, "text": "unknownfool" }, { "code": null, "e": 7402, "s": 7387, "text": "iampratikangre" }, { "code": null, "e": 7415, "s": 7402, "text": "vaasugupta01" }, { "code": null, "e": 7438, "s": 7415, "text": "cpp-containers-library" }, { "code": null, "e": 7456, "s": 7438, "text": "cpp-unordered_set" }, { "code": null, "e": 7484, "s": 7456, "text": "cpp-unordered_set-functions" }, { "code": null, "e": 7488, "s": 7484, "text": "STL" }, { "code": null, "e": 7499, "s": 7488, "text": "C Language" }, { "code": null, "e": 7503, "s": 7499, "text": "C++" }, { "code": null, "e": 7507, "s": 7503, "text": "STL" }, { "code": null, "e": 7511, "s": 7507, "text": "CPP" } ]
How to hide elements in responsive layout using CSS ?
11 Oct, 2019 CSS can be used to hide or display elements of the page. This can be used in a responsive website to show certain elements that are only possible to interact with a larger screen size for a good user experience. Media queries are the technique introduced in CSS3 to help to design responsive websites. A media query has two parts, one is the optional media type which helps to describe the general class of devices that the media query will work. The other one is the media feature which describe specific characteristics of device where the page is to be displayed. These can be tested for their value to accordingly change the behavior of the contents of the page. The media type used here is screen, which is used with the ‘only’ keyword so that the media query only affects the selected screens. The media feature can be changed based on the width. For example, it can be used with the width media feature. This can be modified to change when the width is set to a particular value like using the min-width and max-width. Other supported media features can be used to check for values that help in a responsive website. Syntax: // Check if the height is at least 600px@media only screen and (min-width: 600px) { .large { display: block; }} In this example, the elements are hide by setting the ‘display’ property to ‘none’. The media queries contain classes that will set the display property to blockExample: <!DOCTYPE html><html> <head> <title> How to hide elements in responsive layout using CSS? </title> <style> .box { margin: 20px; border: 1px dotted; height: 100px; width: 100px; background-color: lightgreen; display: none; } /* Check if the screen size is at least 600px */ @media only screen and (min-width: 600px) { .lg { display: block; } } /* check if the screen size is at least 400px */ @media only screen and (min-width: 400px) { .md { display: block; } } /* check if the screen size is at least 100px */ @media only screen and (min-width: 100px) { .sm { display: block; } } </style></head> <body> <h1> Hiding elements in responsive layout using CSS? </h1> <div class="box lg"> This is only visible on large devices </div> <div class="box md"> This is only visible on medium and large devices </div> <div class="box sm"> This is only visible on smaller, medium and large devices </div></body> </html> Output: When the screen size is at least 600px: When the screen size is at least 400px: When the screen size is at least 100px: CSS-Misc Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 240, "s": 28, "text": "CSS can be used to hide or display elements of the page. This can be used in a responsive website to show certain elements that are only possible to interact with a larger screen size for a good user experience." }, { "code": null, "e": 695, "s": 240, "text": "Media queries are the technique introduced in CSS3 to help to design responsive websites. A media query has two parts, one is the optional media type which helps to describe the general class of devices that the media query will work. The other one is the media feature which describe specific characteristics of device where the page is to be displayed. These can be tested for their value to accordingly change the behavior of the contents of the page." }, { "code": null, "e": 1152, "s": 695, "text": "The media type used here is screen, which is used with the ‘only’ keyword so that the media query only affects the selected screens. The media feature can be changed based on the width. For example, it can be used with the width media feature. This can be modified to change when the width is set to a particular value like using the min-width and max-width. Other supported media features can be used to check for values that help in a responsive website." }, { "code": null, "e": 1160, "s": 1152, "text": "Syntax:" }, { "code": "// Check if the height is at least 600px@media only screen and (min-width: 600px) { .large { display: block; }}", "e": 1285, "s": 1160, "text": null }, { "code": null, "e": 1455, "s": 1285, "text": "In this example, the elements are hide by setting the ‘display’ property to ‘none’. The media queries contain classes that will set the display property to blockExample:" }, { "code": "<!DOCTYPE html><html> <head> <title> How to hide elements in responsive layout using CSS? </title> <style> .box { margin: 20px; border: 1px dotted; height: 100px; width: 100px; background-color: lightgreen; display: none; } /* Check if the screen size is at least 600px */ @media only screen and (min-width: 600px) { .lg { display: block; } } /* check if the screen size is at least 400px */ @media only screen and (min-width: 400px) { .md { display: block; } } /* check if the screen size is at least 100px */ @media only screen and (min-width: 100px) { .sm { display: block; } } </style></head> <body> <h1> Hiding elements in responsive layout using CSS? </h1> <div class=\"box lg\"> This is only visible on large devices </div> <div class=\"box md\"> This is only visible on medium and large devices </div> <div class=\"box sm\"> This is only visible on smaller, medium and large devices </div></body> </html>", "e": 2751, "s": 1455, "text": null }, { "code": null, "e": 2759, "s": 2751, "text": "Output:" }, { "code": null, "e": 2799, "s": 2759, "text": "When the screen size is at least 600px:" }, { "code": null, "e": 2839, "s": 2799, "text": "When the screen size is at least 400px:" }, { "code": null, "e": 2879, "s": 2839, "text": "When the screen size is at least 100px:" }, { "code": null, "e": 2888, "s": 2879, "text": "CSS-Misc" }, { "code": null, "e": 2895, "s": 2888, "text": "Picked" }, { "code": null, "e": 2899, "s": 2895, "text": "CSS" }, { "code": null, "e": 2916, "s": 2899, "text": "Web Technologies" }, { "code": null, "e": 2943, "s": 2916, "text": "Web technologies Questions" } ]
Python | Count the array elements with factors less than or equal to the factors of given x
12 Jun, 2022 Given an array, the task is to count the elements of array whose factors are less than the given number x. Examples: Input: arr = [2, 12, 4, 6], x = 6 Output: 2 factors of x = 6 is [1, 2, 3] factors of arr[0] = 2 is [1] factors of arr[1] = 12 is [1, 2, 3, 4] factors of arr[2] = 4 is [1, 2] factors of arr[3] = 6 is [1, 2, 3] so only arr[0] and arr[2] are the answer. Approach: Find out factors of all the elements and that of given xand after that compare all of them if factors of elements are less than that of factors of x, then increment the count. Below is the implementation of above problem – Python3 from math import ceil, sqrt # function to count the factors of an arraydef factorscount(x): count = 0 for i in range(1,ceil(sqrt(x))): if x%i==i: count+=1 else: count+=2 return count def Totalcount(arr, x): # count of factors of given x count_fac = factorscount(x) # store the count of each factors arr_fac = [factorscount(i) for i in arr] ans = 0 for i in arr_fac: # if factors count of element of array is #small than that of given number if i<count_fac: ans+=1 return ans # Driver code arr = [2,12,4,6]x = 6print(Totalcount(arr, x)) 2 Time Complexity: O(√x+n√k) where n is the size of the array, x is the given number, and k is the maximum element in the array.Auxiliary Space: O(n) pushpeshrajdx01 math Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2022" }, { "code": null, "e": 145, "s": 28, "text": "Given an array, the task is to count the elements of array whose factors are less than the given number x. Examples:" }, { "code": null, "e": 396, "s": 145, "text": "Input: arr = [2, 12, 4, 6], x = 6 Output: 2 factors of x = 6 is [1, 2, 3] factors of arr[0] = 2 is [1] factors of arr[1] = 12 is [1, 2, 3, 4] factors of arr[2] = 4 is [1, 2] factors of arr[3] = 6 is [1, 2, 3] so only arr[0] and arr[2] are the answer." }, { "code": null, "e": 630, "s": 396, "text": "Approach: Find out factors of all the elements and that of given xand after that compare all of them if factors of elements are less than that of factors of x, then increment the count. Below is the implementation of above problem – " }, { "code": null, "e": 638, "s": 630, "text": "Python3" }, { "code": "from math import ceil, sqrt # function to count the factors of an arraydef factorscount(x): count = 0 for i in range(1,ceil(sqrt(x))): if x%i==i: count+=1 else: count+=2 return count def Totalcount(arr, x): # count of factors of given x count_fac = factorscount(x) # store the count of each factors arr_fac = [factorscount(i) for i in arr] ans = 0 for i in arr_fac: # if factors count of element of array is #small than that of given number if i<count_fac: ans+=1 return ans # Driver code arr = [2,12,4,6]x = 6print(Totalcount(arr, x))", "e": 1295, "s": 638, "text": null }, { "code": null, "e": 1297, "s": 1295, "text": "2" }, { "code": null, "e": 1445, "s": 1297, "text": "Time Complexity: O(√x+n√k) where n is the size of the array, x is the given number, and k is the maximum element in the array.Auxiliary Space: O(n)" }, { "code": null, "e": 1461, "s": 1445, "text": "pushpeshrajdx01" }, { "code": null, "e": 1466, "s": 1461, "text": "math" }, { "code": null, "e": 1473, "s": 1466, "text": "Python" }, { "code": null, "e": 1571, "s": 1473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1603, "s": 1571, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1630, "s": 1603, "text": "Python Classes and Objects" }, { "code": null, "e": 1651, "s": 1630, "text": "Python OOPs Concepts" }, { "code": null, "e": 1674, "s": 1651, "text": "Introduction To PYTHON" }, { "code": null, "e": 1730, "s": 1674, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1761, "s": 1730, "text": "Python | os.path.join() method" }, { "code": null, "e": 1803, "s": 1761, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1845, "s": 1803, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1884, "s": 1845, "text": "Python | Get unique values from a list" } ]
Python program to change values in a Dictionary
08 Dec, 2020 Given a dictionary in Python, the task is to write a Python program to change the value in one of the key-value pairs. This article discusses mechanisms to do this effectively. Examples: Input: {'hari': 1, 'dita': 2} Output: {'hari': 1, 'dita': 4} Input: {'hari': 1, 'dita': 2} Output: {'hari': 3, 'dita': 5} Method 1 In this we refer to the key of the value to be changed and supply it with a new value. Example: Python3 # declaring dictionarydict = {'hari': 1, 'dita': 2} # original dictionaryprint("initial dictionary-", dict) # changing the key value from 2 to 4dict['dita'] = 4 # dictionary after updateprint("dictionary after modification-", dict) Output: initial dictionary- {‘hari’: 1, ‘dita’: 2} dictionary after modification- {‘hari’: 1, ‘dita’: 4} Method 2: In this method we use zip() function, which aggregates the iterable and combines them into a tuple form. Example: Python3 # declaring dictionarydict1 = {'hari': 1, 'dita': 2} # original dictionaryprint("initial dictionary-", dict1) # list of values which will replace the values of dict1list1 = [3, 5] # this preserves the keys and modifies the valuesdict1 = dict(zip(list(dict1.keys()), list1)) # modified dictionaryprint("dictionary after modification-", dict1) Output: initial dictionary- {‘hari’: 1, ‘dita’: 2} dictionary after modification- {‘hari’: 3, ‘dita’: 5} Python dictionary-programs Technical Scripter 2020 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Dec, 2020" }, { "code": null, "e": 205, "s": 28, "text": "Given a dictionary in Python, the task is to write a Python program to change the value in one of the key-value pairs. This article discusses mechanisms to do this effectively." }, { "code": null, "e": 215, "s": 205, "text": "Examples:" }, { "code": null, "e": 338, "s": 215, "text": "Input: {'hari': 1, 'dita': 2}\nOutput: {'hari': 1, 'dita': 4}\n\nInput: {'hari': 1, 'dita': 2}\nOutput: {'hari': 3, 'dita': 5}" }, { "code": null, "e": 347, "s": 338, "text": "Method 1" }, { "code": null, "e": 434, "s": 347, "text": "In this we refer to the key of the value to be changed and supply it with a new value." }, { "code": null, "e": 443, "s": 434, "text": "Example:" }, { "code": null, "e": 451, "s": 443, "text": "Python3" }, { "code": "# declaring dictionarydict = {'hari': 1, 'dita': 2} # original dictionaryprint(\"initial dictionary-\", dict) # changing the key value from 2 to 4dict['dita'] = 4 # dictionary after updateprint(\"dictionary after modification-\", dict)", "e": 687, "s": 451, "text": null }, { "code": null, "e": 695, "s": 687, "text": "Output:" }, { "code": null, "e": 739, "s": 695, "text": "initial dictionary- {‘hari’: 1, ‘dita’: 2} " }, { "code": null, "e": 793, "s": 739, "text": "dictionary after modification- {‘hari’: 1, ‘dita’: 4}" }, { "code": null, "e": 804, "s": 793, "text": "Method 2: " }, { "code": null, "e": 909, "s": 804, "text": "In this method we use zip() function, which aggregates the iterable and combines them into a tuple form." }, { "code": null, "e": 918, "s": 909, "text": "Example:" }, { "code": null, "e": 926, "s": 918, "text": "Python3" }, { "code": "# declaring dictionarydict1 = {'hari': 1, 'dita': 2} # original dictionaryprint(\"initial dictionary-\", dict1) # list of values which will replace the values of dict1list1 = [3, 5] # this preserves the keys and modifies the valuesdict1 = dict(zip(list(dict1.keys()), list1)) # modified dictionaryprint(\"dictionary after modification-\", dict1)", "e": 1272, "s": 926, "text": null }, { "code": null, "e": 1280, "s": 1272, "text": "Output:" }, { "code": null, "e": 1324, "s": 1280, "text": "initial dictionary- {‘hari’: 1, ‘dita’: 2} " }, { "code": null, "e": 1378, "s": 1324, "text": "dictionary after modification- {‘hari’: 3, ‘dita’: 5}" }, { "code": null, "e": 1405, "s": 1378, "text": "Python dictionary-programs" }, { "code": null, "e": 1429, "s": 1405, "text": "Technical Scripter 2020" }, { "code": null, "e": 1436, "s": 1429, "text": "Python" }, { "code": null, "e": 1452, "s": 1436, "text": "Python Programs" }, { "code": null, "e": 1471, "s": 1452, "text": "Technical Scripter" }, { "code": null, "e": 1569, "s": 1471, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1601, "s": 1569, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1628, "s": 1601, "text": "Python Classes and Objects" }, { "code": null, "e": 1649, "s": 1628, "text": "Python OOPs Concepts" }, { "code": null, "e": 1672, "s": 1649, "text": "Introduction To PYTHON" }, { "code": null, "e": 1703, "s": 1672, "text": "Python | os.path.join() method" }, { "code": null, "e": 1725, "s": 1703, "text": "Defaultdict in Python" }, { "code": null, "e": 1764, "s": 1725, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1802, "s": 1764, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1839, "s": 1802, "text": "Python Program for Fibonacci numbers" } ]
Box Plot in Python using Matplotlib
08 Mar, 2022 A Box Plot is also known as Whisker plot is created to display the summary of the set of data values having properties like minimum, first quartile, median, third quartile and maximum. In the box plot, a box is created from the first quartile to the third quartile, a vertical line is also there which goes through the box at the median. Here x-axis denotes the data to be plotted while the y-axis shows the frequency distribution. The matplotlib.pyplot module of matplotlib library provides boxplot() function with the help of which we can create box plots. Syntax: matplotlib.pyplot.boxplot(data, notch=None, vert=None, patch_artist=None, widths=None) Parameters: The data values given to the ax.boxplot() method can be a Numpy array or Python list or Tuple of arrays. Let us create the box plot by using numpy.random.normal() to create some random data, it takes mean, standard deviation, and the desired number of values as arguments. Example: Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetnp.random.seed(10)data = np.random.normal(100, 20, 200) fig = plt.figure(figsize =(10, 7)) # Creating plotplt.boxplot(data) # show plotplt.show() Output: The matplotlib.pyplot.boxplot() provides endless customization possibilities to the box plot. The notch = True attribute creates the notch format to the box plot, patch_artist = True fills the boxplot with colors, we can set different colors to different boxes.The vert = 0 attribute creates horizontal box plot. labels takes same dimensions as the number data sets. Example 1: Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetnp.random.seed(10) data_1 = np.random.normal(100, 10, 200)data_2 = np.random.normal(90, 20, 200)data_3 = np.random.normal(80, 30, 200)data_4 = np.random.normal(70, 40, 200)data = [data_1, data_2, data_3, data_4] fig = plt.figure(figsize =(10, 7)) # Creating axes instanceax = fig.add_axes([0, 0, 1, 1]) # Creating plotbp = ax.boxplot(data) # show plotplt.show() Output: Example 2: Let’s try to modify the above plot with some of the customizations: Python3 # Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetnp.random.seed(10)data_1 = np.random.normal(100, 10, 200)data_2 = np.random.normal(90, 20, 200)data_3 = np.random.normal(80, 30, 200)data_4 = np.random.normal(70, 40, 200)data = [data_1, data_2, data_3, data_4] fig = plt.figure(figsize =(10, 7))ax = fig.add_subplot(111) # Creating axes instancebp = ax.boxplot(data, patch_artist = True, notch ='True', vert = 0) colors = ['#0000FF', '#00FF00', '#FFFF00', '#FF00FF'] for patch, color in zip(bp['boxes'], colors): patch.set_facecolor(color) # changing color and linewidth of# whiskersfor whisker in bp['whiskers']: whisker.set(color ='#8B008B', linewidth = 1.5, linestyle =":") # changing color and linewidth of# capsfor cap in bp['caps']: cap.set(color ='#8B008B', linewidth = 2) # changing color and linewidth of# mediansfor median in bp['medians']: median.set(color ='red', linewidth = 3) # changing style of fliersfor flier in bp['fliers']: flier.set(marker ='D', color ='#e7298a', alpha = 0.5) # x-axis labelsax.set_yticklabels(['data_1', 'data_2', 'data_3', 'data_4']) # Adding titleplt.title("Customized box plot") # Removing top axes and right axes# ticksax.get_xaxis().tick_bottom()ax.get_yaxis().tick_left() # show plotplt.show() Output: clintra aaronxyliu Python-matplotlib 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 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 Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Mar, 2022" }, { "code": null, "e": 484, "s": 52, "text": "A Box Plot is also known as Whisker plot is created to display the summary of the set of data values having properties like minimum, first quartile, median, third quartile and maximum. In the box plot, a box is created from the first quartile to the third quartile, a vertical line is also there which goes through the box at the median. Here x-axis denotes the data to be plotted while the y-axis shows the frequency distribution." }, { "code": null, "e": 611, "s": 484, "text": "The matplotlib.pyplot module of matplotlib library provides boxplot() function with the help of which we can create box plots." }, { "code": null, "e": 620, "s": 611, "text": "Syntax: " }, { "code": null, "e": 707, "s": 620, "text": "matplotlib.pyplot.boxplot(data, notch=None, vert=None, patch_artist=None, widths=None)" }, { "code": null, "e": 720, "s": 707, "text": "Parameters: " }, { "code": null, "e": 993, "s": 720, "text": "The data values given to the ax.boxplot() method can be a Numpy array or Python list or Tuple of arrays. Let us create the box plot by using numpy.random.normal() to create some random data, it takes mean, standard deviation, and the desired number of values as arguments." }, { "code": null, "e": 1004, "s": 993, "text": "Example: " }, { "code": null, "e": 1012, "s": 1004, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetnp.random.seed(10)data = np.random.normal(100, 20, 200) fig = plt.figure(figsize =(10, 7)) # Creating plotplt.boxplot(data) # show plotplt.show()", "e": 1245, "s": 1012, "text": null }, { "code": null, "e": 1254, "s": 1245, "text": "Output: " }, { "code": null, "e": 1621, "s": 1254, "text": "The matplotlib.pyplot.boxplot() provides endless customization possibilities to the box plot. The notch = True attribute creates the notch format to the box plot, patch_artist = True fills the boxplot with colors, we can set different colors to different boxes.The vert = 0 attribute creates horizontal box plot. labels takes same dimensions as the number data sets." }, { "code": null, "e": 1633, "s": 1621, "text": "Example 1: " }, { "code": null, "e": 1641, "s": 1633, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetnp.random.seed(10) data_1 = np.random.normal(100, 10, 200)data_2 = np.random.normal(90, 20, 200)data_3 = np.random.normal(80, 30, 200)data_4 = np.random.normal(70, 40, 200)data = [data_1, data_2, data_3, data_4] fig = plt.figure(figsize =(10, 7)) # Creating axes instanceax = fig.add_axes([0, 0, 1, 1]) # Creating plotbp = ax.boxplot(data) # show plotplt.show()", "e": 2090, "s": 1641, "text": null }, { "code": null, "e": 2099, "s": 2090, "text": "Output: " }, { "code": null, "e": 2179, "s": 2099, "text": "Example 2: Let’s try to modify the above plot with some of the customizations: " }, { "code": null, "e": 2187, "s": 2179, "text": "Python3" }, { "code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetnp.random.seed(10)data_1 = np.random.normal(100, 10, 200)data_2 = np.random.normal(90, 20, 200)data_3 = np.random.normal(80, 30, 200)data_4 = np.random.normal(70, 40, 200)data = [data_1, data_2, data_3, data_4] fig = plt.figure(figsize =(10, 7))ax = fig.add_subplot(111) # Creating axes instancebp = ax.boxplot(data, patch_artist = True, notch ='True', vert = 0) colors = ['#0000FF', '#00FF00', '#FFFF00', '#FF00FF'] for patch, color in zip(bp['boxes'], colors): patch.set_facecolor(color) # changing color and linewidth of# whiskersfor whisker in bp['whiskers']: whisker.set(color ='#8B008B', linewidth = 1.5, linestyle =\":\") # changing color and linewidth of# capsfor cap in bp['caps']: cap.set(color ='#8B008B', linewidth = 2) # changing color and linewidth of# mediansfor median in bp['medians']: median.set(color ='red', linewidth = 3) # changing style of fliersfor flier in bp['fliers']: flier.set(marker ='D', color ='#e7298a', alpha = 0.5) # x-axis labelsax.set_yticklabels(['data_1', 'data_2', 'data_3', 'data_4']) # Adding titleplt.title(\"Customized box plot\") # Removing top axes and right axes# ticksax.get_xaxis().tick_bottom()ax.get_yaxis().tick_left() # show plotplt.show()", "e": 3609, "s": 2187, "text": null }, { "code": null, "e": 3618, "s": 3609, "text": "Output: " }, { "code": null, "e": 3628, "s": 3620, "text": "clintra" }, { "code": null, "e": 3639, "s": 3628, "text": "aaronxyliu" }, { "code": null, "e": 3657, "s": 3639, "text": "Python-matplotlib" }, { "code": null, "e": 3664, "s": 3657, "text": "Python" }, { "code": null, "e": 3762, "s": 3664, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3780, "s": 3762, "text": "Python Dictionary" }, { "code": null, "e": 3822, "s": 3780, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3844, "s": 3822, "text": "Enumerate() in Python" }, { "code": null, "e": 3879, "s": 3844, "text": "Read a file line by line in Python" }, { "code": null, "e": 3905, "s": 3879, "text": "Python String | replace()" }, { "code": null, "e": 3937, "s": 3905, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3966, "s": 3937, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3993, "s": 3966, "text": "Python Classes and Objects" }, { "code": null, "e": 4014, "s": 3993, "text": "Python OOPs Concepts" } ]
Mongoose | save() Function
20 May, 2020 The save() function is used to save the document to the database. Using this function, new documents can be added to the database. Installation of mongoose module: You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter 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 mongoose module. You can install this package by using this command.npm install mongoose npm install mongoose After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose npm version mongoose 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 const mongoose = require('mongoose'); // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks',{ useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User',{ name: { type: String }, age: { type: Number }}); var new_user = new User({ name: 'Manish', age:34}) new_user.save(function(err,result){ if (err){ console.log(err); } else{ console.log(result) }}) Steps to run the program: The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see in the database that the new_user is saved as shown below: The project structure will look like this: Make sure you have installed mongoose module using following command:npm install mongoose npm install mongoose Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below: Run index.js file using below command:node index.js node index.js After the function is executed, You can see in the database that the new_user is saved as shown below: So this is how you can use the mongoose save() function which saves the document to the database. Using this function, new documents can be added to the database. Mongoose MongoDB Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Spring Boot JpaRepository with Example Mongoose Populate() Method MongoDB - db.collection.Find() Method Aggregation in MongoDB MongoDB - Check the existence of the fields in the specified collection How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method
[ { "code": null, "e": 52, "s": 24, "text": "\n20 May, 2020" }, { "code": null, "e": 183, "s": 52, "text": "The save() function is used to save the document to the database. Using this function, new documents can be added to the database." }, { "code": null, "e": 216, "s": 183, "text": "Installation of mongoose module:" }, { "code": null, "e": 612, "s": 216, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongooseAfter installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongooseAfter 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": 735, "s": 612, "text": "You can visit the link to Install mongoose module. You can install this package by using this command.npm install mongoose" }, { "code": null, "e": 756, "s": 735, "text": "npm install mongoose" }, { "code": null, "e": 883, "s": 756, "text": "After installing mongoose module, you can check your mongoose version in command prompt using the command.npm version mongoose" }, { "code": null, "e": 904, "s": 883, "text": "npm version mongoose" }, { "code": null, "e": 1052, "s": 904, "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": 1066, "s": 1052, "text": "node index.js" }, { "code": null, "e": 1085, "s": 1066, "text": "Filename: index.js" }, { "code": "const mongoose = require('mongoose'); // Database Connectionmongoose.connect('mongodb://127.0.0.1:27017/geeksforgeeks',{ useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true}); // User modelconst User = mongoose.model('User',{ name: { type: String }, age: { type: Number }}); var new_user = new User({ name: 'Manish', age:34}) new_user.save(function(err,result){ if (err){ console.log(err); } else{ console.log(result) }})", "e": 1576, "s": 1085, "text": null }, { "code": null, "e": 1602, "s": 1576, "text": "Steps to run the program:" }, { "code": null, "e": 2068, "s": 1602, "text": "The project structure will look like this:Make sure you have installed mongoose module using following command:npm install mongooseBelow is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:Run index.js file using below command:node index.jsAfter the function is executed, You can see in the database that the new_user is saved as shown below:" }, { "code": null, "e": 2111, "s": 2068, "text": "The project structure will look like this:" }, { "code": null, "e": 2201, "s": 2111, "text": "Make sure you have installed mongoose module using following command:npm install mongoose" }, { "code": null, "e": 2222, "s": 2201, "text": "npm install mongoose" }, { "code": null, "e": 2404, "s": 2222, "text": "Below is the sample data in the database before the function is executed, You can use any GUI tool or terminal to see the database, like we have used Robo3T GUI tool as shown below:" }, { "code": null, "e": 2456, "s": 2404, "text": "Run index.js file using below command:node index.js" }, { "code": null, "e": 2470, "s": 2456, "text": "node index.js" }, { "code": null, "e": 2573, "s": 2470, "text": "After the function is executed, You can see in the database that the new_user is saved as shown below:" }, { "code": null, "e": 2736, "s": 2573, "text": "So this is how you can use the mongoose save() function which saves the document to the database. Using this function, new documents can be added to the database." }, { "code": null, "e": 2745, "s": 2736, "text": "Mongoose" }, { "code": null, "e": 2753, "s": 2745, "text": "MongoDB" }, { "code": null, "e": 2761, "s": 2753, "text": "Node.js" }, { "code": null, "e": 2778, "s": 2761, "text": "Web Technologies" }, { "code": null, "e": 2876, "s": 2778, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2915, "s": 2876, "text": "Spring Boot JpaRepository with Example" }, { "code": null, "e": 2942, "s": 2915, "text": "Mongoose Populate() Method" }, { "code": null, "e": 2980, "s": 2942, "text": "MongoDB - db.collection.Find() Method" }, { "code": null, "e": 3003, "s": 2980, "text": "Aggregation in MongoDB" }, { "code": null, "e": 3075, "s": 3003, "text": "MongoDB - Check the existence of the fields in the specified collection" }, { "code": null, "e": 3123, "s": 3075, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3156, "s": 3123, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3189, "s": 3156, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 3246, "s": 3189, "text": "How to install the previous version of node.js and npm ?" } ]
R - Vectors
Vectors are the most basic R data objects and there are six types of atomic vectors. They are logical, integer, double, complex, character and raw. Even when you write just one value in R, it becomes a vector of length 1 and belongs to one of the above vector types. # Atomic vector of type character. print("abc"); # Atomic vector of type double. print(12.5) # Atomic vector of type integer. print(63L) # Atomic vector of type logical. print(TRUE) # Atomic vector of type complex. print(2+3i) # Atomic vector of type raw. print(charToRaw('hello')) When we execute the above code, it produces the following result − [1] "abc" [1] 12.5 [1] 63 [1] TRUE [1] 2+3i [1] 68 65 6c 6c 6f Using colon operator with numeric data # Creating a sequence from 5 to 13. v <- 5:13 print(v) # Creating a sequence from 6.6 to 12.6. v <- 6.6:12.6 print(v) # If the final element specified does not belong to the sequence then it is discarded. v <- 3.8:11.4 print(v) When we execute the above code, it produces the following result − [1] 5 6 7 8 9 10 11 12 13 [1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6 [1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8 Using sequence (Seq.) operator # Create vector with elements from 5 to 9 incrementing by 0.4. print(seq(5, 9, by = 0.4)) When we execute the above code, it produces the following result − [1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0 Using the c() function The non-character values are coerced to character type if one of the elements is a character. # The logical and numeric values are converted to characters. s <- c('apple','red',5,TRUE) print(s) When we execute the above code, it produces the following result − [1] "apple" "red" "5" "TRUE" Elements of a Vector are accessed using indexing. The [ ] brackets are used for indexing. Indexing starts with position 1. Giving a negative value in the index drops that element from result.TRUE, FALSE or 0 and 1 can also be used for indexing. # Accessing vector elements using position. t <- c("Sun","Mon","Tue","Wed","Thurs","Fri","Sat") u <- t[c(2,3,6)] print(u) # Accessing vector elements using logical indexing. v <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)] print(v) # Accessing vector elements using negative indexing. x <- t[c(-2,-5)] print(x) # Accessing vector elements using 0/1 indexing. y <- t[c(0,0,0,0,0,0,1)] print(y) When we execute the above code, it produces the following result − [1] "Mon" "Tue" "Fri" [1] "Sun" "Fri" [1] "Sun" "Tue" "Wed" "Fri" "Sat" [1] "Sun" Two vectors of same length can be added, subtracted, multiplied or divided giving the result as a vector output. # Create two vectors. v1 <- c(3,8,4,5,0,11) v2 <- c(4,11,0,8,1,2) # Vector addition. add.result <- v1+v2 print(add.result) # Vector subtraction. sub.result <- v1-v2 print(sub.result) # Vector multiplication. multi.result <- v1*v2 print(multi.result) # Vector division. divi.result <- v1/v2 print(divi.result) When we execute the above code, it produces the following result − [1] 7 19 4 13 1 13 [1] -1 -3 4 -3 -1 9 [1] 12 88 0 40 0 22 [1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000 If we apply arithmetic operations to two vectors of unequal length, then the elements of the shorter vector are recycled to complete the operations. v1 <- c(3,8,4,5,0,11) v2 <- c(4,11) # V2 becomes c(4,11,4,11,4,11) add.result <- v1+v2 print(add.result) sub.result <- v1-v2 print(sub.result) When we execute the above code, it produces the following result − [1] 7 19 8 16 4 22 [1] -1 -3 0 -6 -4 0 Elements in a vector can be sorted using the sort() function. v <- c(3,8,4,5,0,11, -9, 304) # Sort the elements of the vector. sort.result <- sort(v) print(sort.result) # Sort the elements in the reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result) # Sorting character vectors. v <- c("Red","Blue","yellow","violet") sort.result <- sort(v) print(sort.result) # Sorting character vectors in reverse order. revsort.result <- sort(v, decreasing = TRUE) print(revsort.result) When we execute the above code, it produces the following result − [1] -9 0 3 4 5 8 11 304 [1] 304 11 8 5 4 3 0 -9 [1] "Blue" "Red" "violet" "yellow" [1] "yellow" "violet" "Red" "Blue"
[ { "code": null, "e": 2684, "s": 2536, "text": "Vectors are the most basic R data objects and there are six types of atomic vectors. They are logical, integer, double, complex, character and raw." }, { "code": null, "e": 2803, "s": 2684, "text": "Even when you write just one value in R, it becomes a vector of length 1 and belongs to one of the above vector types." }, { "code": null, "e": 3090, "s": 2803, "text": "# Atomic vector of type character.\nprint(\"abc\");\n\n# Atomic vector of type double.\nprint(12.5)\n\n# Atomic vector of type integer.\nprint(63L)\n\n# Atomic vector of type logical.\nprint(TRUE)\n\n# Atomic vector of type complex.\nprint(2+3i)\n\n# Atomic vector of type raw.\nprint(charToRaw('hello'))" }, { "code": null, "e": 3157, "s": 3090, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 3221, "s": 3157, "text": "[1] \"abc\"\n[1] 12.5\n[1] 63\n[1] TRUE\n[1] 2+3i\n[1] 68 65 6c 6c 6f\n" }, { "code": null, "e": 3260, "s": 3221, "text": "Using colon operator with numeric data" }, { "code": null, "e": 3490, "s": 3260, "text": "# Creating a sequence from 5 to 13.\nv <- 5:13\nprint(v)\n\n# Creating a sequence from 6.6 to 12.6.\nv <- 6.6:12.6\nprint(v)\n\n# If the final element specified does not belong to the sequence then it is discarded.\nv <- 3.8:11.4\nprint(v)" }, { "code": null, "e": 3557, "s": 3490, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 3672, "s": 3557, "text": "[1] 5 6 7 8 9 10 11 12 13\n[1] 6.6 7.6 8.6 9.6 10.6 11.6 12.6\n[1] 3.8 4.8 5.8 6.8 7.8 8.8 9.8 10.8\n" }, { "code": null, "e": 3703, "s": 3672, "text": "Using sequence (Seq.) operator" }, { "code": null, "e": 3793, "s": 3703, "text": "# Create vector with elements from 5 to 9 incrementing by 0.4.\nprint(seq(5, 9, by = 0.4))" }, { "code": null, "e": 3860, "s": 3793, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 3909, "s": 3860, "text": "[1] 5.0 5.4 5.8 6.2 6.6 7.0 7.4 7.8 8.2 8.6 9.0\n" }, { "code": null, "e": 3932, "s": 3909, "text": "Using the c() function" }, { "code": null, "e": 4026, "s": 3932, "text": "The non-character values are coerced to character type if one of the elements is a character." }, { "code": null, "e": 4126, "s": 4026, "text": "# The logical and numeric values are converted to characters.\ns <- c('apple','red',5,TRUE)\nprint(s)" }, { "code": null, "e": 4193, "s": 4126, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 4230, "s": 4193, "text": "[1] \"apple\" \"red\" \"5\" \"TRUE\" \n" }, { "code": null, "e": 4475, "s": 4230, "text": "Elements of a Vector are accessed using indexing. The [ ] brackets are used for indexing. Indexing starts with position 1. Giving a negative value in the index drops that element from result.TRUE, FALSE or 0 and 1 can also be used for indexing." }, { "code": null, "e": 4873, "s": 4475, "text": "# Accessing vector elements using position.\nt <- c(\"Sun\",\"Mon\",\"Tue\",\"Wed\",\"Thurs\",\"Fri\",\"Sat\")\nu <- t[c(2,3,6)]\nprint(u)\n\n# Accessing vector elements using logical indexing.\nv <- t[c(TRUE,FALSE,FALSE,FALSE,FALSE,TRUE,FALSE)]\nprint(v)\n\n# Accessing vector elements using negative indexing.\nx <- t[c(-2,-5)]\nprint(x)\n\n# Accessing vector elements using 0/1 indexing.\ny <- t[c(0,0,0,0,0,0,1)]\nprint(y)" }, { "code": null, "e": 4940, "s": 4873, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 5023, "s": 4940, "text": "[1] \"Mon\" \"Tue\" \"Fri\"\n[1] \"Sun\" \"Fri\"\n[1] \"Sun\" \"Tue\" \"Wed\" \"Fri\" \"Sat\"\n[1] \"Sun\"\n" }, { "code": null, "e": 5136, "s": 5023, "text": "Two vectors of same length can be added, subtracted, multiplied or divided giving the result as a vector output." }, { "code": null, "e": 5449, "s": 5136, "text": "# Create two vectors.\nv1 <- c(3,8,4,5,0,11)\nv2 <- c(4,11,0,8,1,2)\n\n# Vector addition.\nadd.result <- v1+v2\nprint(add.result)\n\n# Vector subtraction.\nsub.result <- v1-v2\nprint(sub.result)\n\n# Vector multiplication.\nmulti.result <- v1*v2\nprint(multi.result)\n\n# Vector division.\ndivi.result <- v1/v2\nprint(divi.result)" }, { "code": null, "e": 5516, "s": 5449, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 5647, "s": 5516, "text": "[1] 7 19 4 13 1 13\n[1] -1 -3 4 -3 -1 9\n[1] 12 88 0 40 0 22\n[1] 0.7500000 0.7272727 Inf 0.6250000 0.0000000 5.5000000\n" }, { "code": null, "e": 5796, "s": 5647, "text": "If we apply arithmetic operations to two vectors of unequal length, then the elements of the shorter vector are recycled to complete the operations." }, { "code": null, "e": 5941, "s": 5796, "text": "v1 <- c(3,8,4,5,0,11)\nv2 <- c(4,11)\n# V2 becomes c(4,11,4,11,4,11)\n\nadd.result <- v1+v2\nprint(add.result)\n\nsub.result <- v1-v2\nprint(sub.result)" }, { "code": null, "e": 6008, "s": 5941, "text": "When we execute the above code, it produces the following result −" }, { "code": null, "e": 6053, "s": 6008, "text": "[1] 7 19 8 16 4 22\n[1] -1 -3 0 -6 -4 0\n" }, { "code": null, "e": 6115, "s": 6053, "text": "Elements in a vector can be sorted using the sort() function." }, { "code": null, "e": 6558, "s": 6115, "text": "v <- c(3,8,4,5,0,11, -9, 304)\n\n# Sort the elements of the vector.\nsort.result <- sort(v)\nprint(sort.result)\n\n# Sort the elements in the reverse order.\nrevsort.result <- sort(v, decreasing = TRUE)\nprint(revsort.result)\n\n# Sorting character vectors.\nv <- c(\"Red\",\"Blue\",\"yellow\",\"violet\")\nsort.result <- sort(v)\nprint(sort.result)\n\n# Sorting character vectors in reverse order.\nrevsort.result <- sort(v, decreasing = TRUE)\nprint(revsort.result)" }, { "code": null, "e": 6625, "s": 6558, "text": "When we execute the above code, it produces the following result −" } ]